CombinedText stringlengths 4 3.42M |
|---|
pub mod framed;
pub mod server;
pub mod proto;
pub mod client;
pub mod shortcut;
pub static STANDALONE_ADDRESS: &'static str = "STANDALONE";
default runtime string for standalone address
pub mod framed;
pub mod server;
pub mod proto;
pub mod client;
pub mod shortcut;
pub static STANDALONE_ADDRESS: &'static str = "STANDALONE";
lazy_static! {
pub static ref STANDALONE_ADDRESS_STRING: String = String::from(STANDALONE_ADDRESS);
} |
use std::thread::sleep;
use std::time::{Instant, Duration};
use rand::random;
use kvproto::pdpb;
use super::node::new_node_cluster;
use super::server::new_server_cluster;
use super::cluster::{Cluster, Simulator};
use super::transport_simulate::Isolate;
fn wait_down_peers<T: Simulator>(cluster: &Cluster<T>, count: u64) -> u64 {
let begin = Instant::now();
for _ in 1..100 {
if cluster.get_down_peers().len() != count as usize {
sleep(Duration::from_millis(100));
} else {
break;
}
}
begin.elapsed().as_secs()
}
fn check_down_seconds(peer: &pdpb::PeerStats, secs: u64) {
debug!("down {} secs {}", peer.get_down_seconds(), secs);
assert!(peer.get_down_seconds() <= secs);
}
fn test_leader_down_and_become_leader_again<T: Simulator>(cluster: &mut Cluster<T>, count: u64) {
// Isolate node.
let node = cluster.leader_of_region(1).unwrap();
let node_id = node.get_id();
cluster.add_send_filter(Isolate::new(node_id));
// Kill another node.
let next_id = if node_id < count {
node_id + 1
} else {
1
};
cluster.stop_node(next_id);
let secs = wait_down_peers(cluster, 2);
// Check node and another are down.
let down_peers = cluster.get_down_peers();
check_down_seconds(down_peers.get(&node_id).unwrap(), secs);
check_down_seconds(down_peers.get(&next_id).unwrap(), secs);
// Restart node and sleep a few seconds.
let sleep_secs = 3;
cluster.clear_send_filters();
wait_down_peers(cluster, 1);
sleep(Duration::from_secs(sleep_secs));
// Wait node to become leader again.
loop {
cluster.transfer_leader(1, node.clone());
if let Some(peer) = cluster.leader_of_region(1) {
if peer.get_id() == node_id {
break;
}
}
sleep(Duration::from_millis(100));
}
wait_down_peers(cluster, 1);
// Ensure that node will not reuse the previous peer heartbeats.
let prev_secs = cluster.get_down_peers().get(&next_id).unwrap().get_down_seconds();
for _ in 1..100 {
let down_secs = cluster.get_down_peers().get(&next_id).unwrap().get_down_seconds();
if down_secs != prev_secs {
assert!(down_secs < sleep_secs);
break;
}
sleep(Duration::from_millis(100));
}
}
fn test_down_peers<T: Simulator>(cluster: &mut Cluster<T>, count: u64) {
cluster.cfg.raft_store.max_peer_down_duration = Duration::from_millis(100);
cluster.run();
// Kill 1, 3
cluster.stop_node(1);
cluster.stop_node(3);
let secs = wait_down_peers(cluster, 2);
// Check 1, 3 are down.
let down_peers = cluster.get_down_peers();
check_down_seconds(down_peers.get(&1).unwrap(), secs);
check_down_seconds(down_peers.get(&3).unwrap(), secs);
// Restart 1, 3
cluster.run_node(1);
cluster.run_node(3);
wait_down_peers(cluster, 0);
for _ in 0..3 {
let n = random::<u64>() % count + 1;
// kill n.
cluster.stop_node(n);
let secs = wait_down_peers(cluster, 1);
// Check i is down and others are not down.
for i in 1..(count + 1) {
match cluster.get_down_peers().get(&i) {
Some(peer) => {
assert_eq!(i, n);
check_down_seconds(peer, secs);
}
None => assert!(i != n),
}
}
// Restart n.
cluster.run_node(n);
wait_down_peers(cluster, 0);
}
test_leader_down_and_become_leader_again(cluster, count);
}
#[test]
fn test_node_down_peers() {
let mut cluster = new_node_cluster(0, 5);
test_down_peers(&mut cluster, 5);
}
#[test]
fn test_server_down_peers() {
let mut cluster = new_server_cluster(0, 5);
test_down_peers(&mut cluster, 5);
}
tests: fix test_down_peers. (#922)
use std::thread::sleep;
use std::time::{Instant, Duration};
use rand::random;
use kvproto::pdpb;
use super::node::new_node_cluster;
use super::server::new_server_cluster;
use super::cluster::{Cluster, Simulator};
use super::transport_simulate::Isolate;
fn wait_down_peers<T: Simulator>(cluster: &Cluster<T>, count: u64) -> u64 {
let begin = Instant::now();
for _ in 1..100 {
if cluster.get_down_peers().len() != count as usize {
sleep(Duration::from_millis(100));
} else {
break;
}
}
begin.elapsed().as_secs()
}
fn check_down_seconds(peer: &pdpb::PeerStats, secs: u64) {
debug!("down {} secs {}", peer.get_down_seconds(), secs);
assert!(peer.get_down_seconds() <= secs);
}
fn test_leader_down_and_become_leader_again<T: Simulator>(cluster: &mut Cluster<T>, count: u64) {
// Isolate node.
let node = cluster.leader_of_region(1).unwrap();
let node_id = node.get_id();
cluster.add_send_filter(Isolate::new(node_id));
// Kill another node.
let next_id = if node_id < count {
node_id + 1
} else {
1
};
cluster.stop_node(next_id);
// Check node and another are down.
let secs = wait_down_peers(cluster, 2);
let down_peers = cluster.get_down_peers();
debug!("down_peers: {:?}", down_peers);
check_down_seconds(down_peers.get(&node_id).unwrap(), secs);
check_down_seconds(down_peers.get(&next_id).unwrap(), secs);
// Restart node and sleep a few seconds.
let sleep_secs = 3;
cluster.clear_send_filters();
wait_down_peers(cluster, 1);
sleep(Duration::from_secs(sleep_secs));
// Wait node to become leader again.
loop {
cluster.transfer_leader(1, node.clone());
if let Some(peer) = cluster.leader_of_region(1) {
if peer.get_id() == node_id {
break;
}
}
sleep(Duration::from_millis(100));
}
wait_down_peers(cluster, 1);
// Ensure that node will not reuse the previous peer heartbeats.
let prev_secs = cluster.get_down_peers().get(&next_id).unwrap().get_down_seconds();
for _ in 1..100 {
let down_secs = cluster.get_down_peers().get(&next_id).unwrap().get_down_seconds();
if down_secs != prev_secs {
assert!(down_secs < sleep_secs);
break;
}
sleep(Duration::from_millis(100));
}
}
fn test_down_peers<T: Simulator>(cluster: &mut Cluster<T>, count: u64) {
cluster.cfg.raft_store.max_peer_down_duration = Duration::from_millis(500);
cluster.run();
// Kill 1, 3
cluster.stop_node(1);
cluster.stop_node(3);
let secs = wait_down_peers(cluster, 2);
// Check 1, 3 are down.
let down_peers = cluster.get_down_peers();
check_down_seconds(down_peers.get(&1).unwrap(), secs);
check_down_seconds(down_peers.get(&3).unwrap(), secs);
// Restart 1, 3
cluster.run_node(1);
cluster.run_node(3);
wait_down_peers(cluster, 0);
for _ in 0..3 {
let n = random::<u64>() % count + 1;
// kill n.
cluster.stop_node(n);
let secs = wait_down_peers(cluster, 1);
// Check i is down and others are not down.
for i in 1..(count + 1) {
match cluster.get_down_peers().get(&i) {
Some(peer) => {
assert_eq!(i, n);
check_down_seconds(peer, secs);
}
None => assert!(i != n),
}
}
// Restart n.
cluster.run_node(n);
wait_down_peers(cluster, 0);
}
test_leader_down_and_become_leader_again(cluster, count);
}
#[test]
fn test_node_down_peers() {
let mut cluster = new_node_cluster(0, 5);
test_down_peers(&mut cluster, 5);
}
#[test]
fn test_server_down_peers() {
let mut cluster = new_server_cluster(0, 5);
test_down_peers(&mut cluster, 5);
}
|
macro_rules! alloc_node {
($s:ident, $n:expr) => {{
let new_index = $s.vm.borrow_mut().alloc($n);
$s.get_epiq(new_index)
}}
}
mod primitive;
use std::rc::Rc;
use std::cell::RefCell;
use core::*;
use printer::*;
const DEGUGGING_NOW: bool = false;
const UNIT_INDX: usize = 0;
pub struct Walker {
vm: Rc<RefCell<Heliqs>>,
}
impl Walker {
pub fn new(vm: Rc<RefCell<Heliqs>>) -> Walker {
Walker { vm: vm, }
}
pub fn walk(&self) {
println!("\n");
let entry = self.get_entry_node();
let result = self.walk_internal(entry.clone(), 0);
// 変化があればentryを変更する
if result.0 != entry.0 {
self.vm.borrow_mut().set_entry(result.0);
}
}
fn get_entry_node(&self) -> Node<Rc<Epiq>> {
if let Some(node) = self.vm.borrow().entry().map(|entry| self.get_epiq(entry)) {
node
} else {
panic!("entryが正しく取得できませんでした");
}
}
fn walk_internal<'a>(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "walk_internal", input.0);
let Node(_, piq) = input.clone();
match *piq {
Epiq::Eval(p, q) => self.eval(p, q, nest_level),
Epiq::Lpiq(p, q) => self.walk_piq(input, ":", p, q, nest_level),
Epiq::Appl(p, q) => self.walk_piq(input, "!", p, q, nest_level),
Epiq::Rslv(p, q) => self.walk_piq(input, "@", p, q, nest_level),
Epiq::Cond(p, q) => self.walk_piq(input, "?", p, q, nest_level),
Epiq::Envn(p, q) => self.walk_piq(input, "%", p, q, nest_level),
Epiq::Bind(p, q) => self.walk_piq(input, "#", p, q, nest_level),
Epiq::Lmbd(p, q) => self.walk_piq(input, r"\", p, q, nest_level),
Epiq::Tpiq{ref o, p, q} => self.walk_piq(input, o, p, q, nest_level),
_ => input,
}
}
fn walk_piq(&self, input: Node<Rc<Epiq>>, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// pとq両方をwalkしてみて、
// 結果が両方とも変わらなければそのまま返す、
// そうでなければ新しくpiqを作って返す
let p_node = self.get_epiq(p);
let q_node = self.get_epiq(q);
let p_result = self.walk_internal(p_node, nest_level + 1);
let q_result = self.walk_internal(q_node, nest_level + 1);
if p_result.0 == p && q_result.0 == q {
input
} else {
self.walk_piq_internal(o, p_result.0, q_result.0)
}
}
fn walk_piq_internal(&self, o: &str, p: NodeId, q: NodeId) -> Node<Rc<Epiq>> {
let new_epiq = match o {
":" => Epiq::Lpiq(p, q),
"!" => Epiq::Appl(p, q),
"@" => Epiq::Rslv(p, q),
"?" => Epiq::Cond(p, q),
"%" => Epiq::Envn(p, q),
"#" => Epiq::Bind(p, q),
r"\" => Epiq::Lmbd(p, q),
_ => Epiq::Tpiq{o: o.to_string(), p, q},
};
let mut borrow_mut_vm = self.vm.borrow_mut();
let new_epiq_index = borrow_mut_vm.alloc(new_epiq);
self.get_epiq(new_epiq_index)
}
fn eval_internal<'a>(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_internal", input.0);
let Node(input_index, piq) = input.clone();
match *piq {
Epiq::Unit |
Epiq::Tval |
Epiq::Fval |
Epiq::Uit8(_) |
Epiq::Name(_) |
Epiq::Text(_) |
Epiq::Lpiq(..) => input,
Epiq::Eval(p, q) => self.eval(p, q, nest_level), // こっちはあまり通らないかもしれない
Epiq::Appl(p, q) => self.eval_apply(input, p, q, nest_level),
Epiq::Rslv(p, q) => self.eval_resolve(p, q, nest_level),
Epiq::Cond(p, q) => self.eval_condition(input, input_index, "?", p, q, nest_level),
Epiq::Envn(..) => self.eval_environment(input),
Epiq::Bind(p, q) => self.eval_bind(p, q, nest_level),
Epiq::Accs(p, q) => self.eval_access(input, p, q, nest_level),
Epiq::Lmbd(..) => self.eval_lambda_direct(input),
Epiq::Prim(_) => self.eval_primitive_direct(input),
Epiq::Tpiq{ref o, p, q} => self.eval_tpiq(o, p, q, nest_level),
Epiq::Mpiq{ref o, p, q} => self.eval_mpiq(o, p, q, nest_level),
_ => panic!("eval_internal: 無効なEpiq"),
}
}
fn eval(&self, _p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// ひとまずpは無視
// そのまま返すとNG
let q_node = self.get_epiq(q);
let result = self.eval_internal(q_node, nest_level + 1);
self.log_piq(nest_level, "eval: eval完前", q);
self.log_piq(nest_level, "eval: eval完後", result.0);
result
}
fn eval_apply(&self, input: Node<Rc<Epiq>>, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// p: lambda q:arguments
let lambda_node = self.get_epiq(p);
let walked_lambda_box = self.walk_internal(lambda_node, nest_level + 1);
let walked_lambda_piq = walked_lambda_box.1;
let args_node = self.get_epiq(q);
let args = self.walk_internal(args_node, nest_level + 1);
self.log_piq(nest_level, "args: ", args.0);
match *walked_lambda_piq {
Epiq::Lmbd(lambda_env, lambda_body) => {
self.eval_lambda(input, lambda_env, lambda_body, args, nest_level)
},
Epiq::Prim(ref n) => self.eval_primitive(input, args, n, nest_level),
_ => {
panic!("関数部分がlambdaでもprimでもないのでエラー");
},
}
}
fn eval_resolve(&self, _p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// p: 用途未定。ひとまず無視
// q: シンボルというか名前
let node = self.get_epiq(q);
let result = self.walk_internal(node, nest_level + 1);
if let Epiq::Name(ref n) = *result.1 {
let vm = self.vm.borrow();
match vm.resolve(n) {
Some(Some(res)) => res.clone().clone(),
_ => {
panic!("resolve時に指定されたキーが見つからない: {:?}", n);
},
}
} else {
panic!("resolve時のキーがNameじゃないのでエラー");
}
}
fn eval_environment(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
// ひとまずNoneを返しておく
// 本来は中身もwalkしてから返すべき?
input
}
fn eval_bind(&self, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
let result;
if let Some((n, walked_q_val)) = {
let p_val = self.get_epiq(p);
let walked_p_val = self.walk_internal(p_val, nest_level + 1);
if let Epiq::Name(ref n) = *walked_p_val.1 {
let q_val = self.get_epiq(q);
let result = self.walk_internal(q_val, nest_level + 1);
let walked_q_val = result.0;
Some((n.clone(), walked_q_val.clone()))
} else {
None
}
} {
// println!("#.p is Name");
result = {
// println!("borrow_mut: {:?}", 3);
self.vm.borrow_mut().define(n.as_ref(), walked_q_val);
// println!("borrow_mut: {:?}", 4);
let new_index = UNIT_INDX; // self.vm.borrow_mut().alloc(Epiq::Unit);
self.get_epiq(new_index)
};
result
} else {
panic!("#.p is not Name");
}
}
/// 直接lambdaをevalした時('> |\)に通る(現在、基本的には何もしない)
/// 一方、eval_lambda()はapplyを通して呼ばれる
fn eval_lambda_direct(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
// TODO: 一つ目の環境の中身はひとまず無視する
// qのリストだけを逐次実行して、勝手に最後の値をwalkしてから返却するようにする
// ただ、そもそも、blockをevalしても、何も変化はないはず。
input
}
/// applyを通して呼ばれる
/// 一方、eval_lambda_direct()は直接lambdaをevalした時('> |\)に通る
fn eval_lambda(&self, input: Node<Rc<Epiq>>,
env: usize, body: usize, args: Node<Rc<Epiq>>,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_lambda", input.0);
// 1. 環境を作成する
let walked_env_box = self.walked_node(env, nest_level);
if let Epiq::Envn(_, symbols) = *walked_env_box.1 {
let params = self.get_epiq(symbols);
self.vm.borrow_mut().extend();
self.assign_arguments(params, args, nest_level);
} else {
panic!("apply envがTpiqではありません");
}
// 2. 関数本体をwalkを挟んでから返す
// TODO: walkにするとLambdaをそのまま返してしまうので、マクロのような扱いになる
// 実行したければevalしてから返す、
// しかしできればマクロ展開・関数適用を両方ともこの中でやってしまいたい。。。
// 今のところはひとまず関数適用しておく(普通にevalを通す)
let body_node = self.get_epiq(body);
let evaled_body = self.eval_internal(body_node, nest_level + 1);
// 3. 環境フレームを削除する
self.vm.borrow_mut().pop();
self.log_piq(nest_level, "apply 正常終了: ", evaled_body.0);
evaled_body
}
/// 直接Primをevalした時に通る(現在、基本的には何もしない)
/// 一方、eval_primitive()はapplyを通して呼ばれる
fn eval_primitive_direct(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
/*
println!("primitive");
// まずは引き算
Result::MakeEpiq(Some(Epiq::Uit8(3)))
*/
// と思ったけど、これはapplyから呼ばれるので、ここを通ることはなさそう
// println!("Primはapplyから呼ばれるので、ここを通ることはなさそう");
// Result::MakeEpiq(None)
input
}
/// applyを通して呼ばれる
/// 一方、eval_primitive_direct()は直接Primをevalした時に通る
fn eval_primitive(&self, input: Node<Rc<Epiq>>, args: Node<Rc<Epiq>>, n: &str, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_primitive", input.0);
match n.as_ref() {
"decr" => self.decrement(args),
"plus" => self.plus(args),
"minus" => self.minus(args),
"print" => self.print(args),
"ltoreq" => self.le_or_eq_nmbr(args),
"concat" => self.concat(args),
"eq" => {
let first = self.pval(args.clone());
match *first.1 {
Epiq::Uit8(n1) => self.eq_nmbr(args),
Epiq::Text(ref text1) => self.eq_text(args),
Epiq::Unit => {
let rest = self.qval(args);
let second = self.pval(rest);
let new_epiq = if *second.1 == Epiq::Unit { Epiq::Tval } else { Epiq::Fval };
alloc_node!(self, new_epiq)
}
_ => {
panic!("primitive 1つ目の引数の型は数値/文字列のみだが違反している, {:?}", self.printer_printed(first.0));
},
}
},
_ => {
panic!("Primitive関数名が想定外なのでエラー");
},
}
}
fn eval_access(&self, input: Node<Rc<Epiq>>,
p: usize, q: usize,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_access", input.0);
// p: レシーバ
// q: アクセッサ
let Node(_, p_reciever) = self.walk_internal(self.get_epiq(p), nest_level + 1);
let Node(_, q_accessor) = self.walk_internal(self.get_epiq(q), nest_level + 1);
// レシーバの種類によってできることが変わる
match *p_reciever {
Epiq::Lpiq(p, q) => {
// Lpiqならば、pとqが使える、それ以外は無理
if let Epiq::Name(ref n) = *q_accessor {
match n.as_ref() {
"o" => alloc_node!(self, Epiq::Text(":".to_string())),
"p" => {
let p_node = self.get_epiq(p);
self.walk_internal(p_node, nest_level + 1)
},
"q" => {
let q_node = self.get_epiq(q);
self.walk_internal(q_node, nest_level + 1)
},
_ => {
self.log("Lpiqならばpとq以外はエラー");
input
},
}
} else {
panic!("アクセッサがNameではないのでエラー");
}
},
Epiq::Tpiq{ref o,p,q} => {
// Lpiqならば、pとqが使える、それ以外は無理
if let Epiq::Name(ref n) = *q_accessor {
match n.as_ref() {
"o" => alloc_node!(self, Epiq::Text(o.to_string())),
"p" => {
let p_node = self.get_epiq(p);
self.walk_internal(p_node, nest_level + 1)
},
"q" => {
let q_node = self.get_epiq(q);
self.walk_internal(q_node, nest_level + 1)
},
_ => {
self.log("Tpiqならばoとpとq以外はエラー");
input
},
}
} else {
panic!("アクセッサがNameではないのでエラー");
}
},
_ => {
panic!("{:?}.{:?}は現在取得できません", *p_reciever, *q_accessor);
},
}
}
fn eval_condition(&self, input: Node<Rc<Epiq>>, input_index: usize,
o: &str, p: usize, q: usize,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_condition", input.0);
// p: ^T or ^F(他の値の評価はひとまず考えない)
// q: Lpiq、^Tならpを返し、^Fならqを返す
let p_condition = self.get_epiq(p);
// 条件節をwalk
// println!("condition: {:?}", "条件節をwalk");
let walked_condition = self.walk_internal(p_condition.clone(), nest_level + 1);
// 値がwalk後に変化していたら付け替える
if walked_condition.0 == p_condition.0 {
let mut vm = self.vm.borrow_mut();
let node_mut = vm.get_epiq_mut(input_index);
node_mut.1 = Rc::new(Epiq::Tpiq{o:o.to_string(), p:walked_condition.0, q:q});
// println!("{:?} -> ({} {:?}){}condition eval後付け替え", *input.1, input_index, walked_condition_node.1, " ".repeat(lvl));
}
let result_piq = self.get_epiq(q);
match *walked_condition.1 {
Epiq::Tval => {
let p_node = self.pval(result_piq);
self.walk_internal(p_node, nest_level + 1)
},
Epiq::Fval => {
let q_node = self.qval(result_piq);
self.walk_internal(q_node, nest_level + 1)
},
_ => {
panic!("condtion 評価結果は^Tか^Fだが{:?}なのでエラー", walked_condition.1);
},
}
}
fn eval_list(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_list", input.0);
let current_node = self.pval(input.clone());
let evaled_current_node = self.eval_internal(current_node, nest_level + 1);
let next = self.qval(input);
if let Epiq::Unit = *next.1 {
// リストの最後なので評価の結果を返す
evaled_current_node
} else {
// 次の項目へ
self.eval_list(next, nest_level + 1)
}
}
fn assign_arguments(&self, parameters_node: Node<Rc<Epiq>>, arguments_node: Node<Rc<Epiq>>, nest_level: u32) {
// arguments_piqはリストのはずなので、一つ一つ回して定義していく
self.log_piq(nest_level, "assign_arguments", parameters_node.0);
let content_node = self.pval(arguments_node.clone());
let next_args_node = self.qval(arguments_node);
let param_node = self.pval(parameters_node.clone());
let next_params_node = self.qval(parameters_node);
let mut symbol_string = "";
if let Epiq::Name(ref s) = *param_node.1 {
symbol_string = s;
} else {
// 文字列じゃない場合は初期値があるとか、
// 他の可能性があるが今は実装しない
}
self.vm.borrow_mut().define(symbol_string, content_node.0);
// paramsとargs、両方のリストを回していくが、
// ループの基準となるのはargs。
// paramsが途中でなくなっても知らん。
if *next_args_node.1 == Epiq::Unit {
// 最後なので終了
return;
}
// 次にいく
self.assign_arguments(next_params_node, next_args_node, nest_level
);
}
fn eval_tpiq(&self, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// call macro
let macrocro = match self.vm.borrow().resolve("macro") {
Some(Some(res)) => res.clone().clone(),
_ => {
panic!("resolve時に指定されたキーが見つからない: {:?}", "macro");
},
};
let arg1 = self.vm.borrow_mut().alloc(Epiq::Text(o.to_string()));
let arg2_node = self.get_epiq(p);
let arg3_node = self.get_epiq(q);
let args_last = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg3_node.0, UNIT_INDX));
let args_second = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg2_node.0, args_last));
let args_first = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg1, args_second));
let appl = self.vm.borrow_mut().alloc(Epiq::Appl(macrocro.0, args_first));
let appl_node = self.get_epiq(appl);
let macro_result = self.eval_internal(appl_node, nest_level + 1);
macro_result
}
fn eval_mpiq(&self, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
match o.as_ref() {
">" => {
// ^> リストのeval
// リストの要素それぞれをevalする
// pは-1だとして処理する(最後の項目の評価結果が最終的な結果となる)
let eval_list_node = self.get_epiq(q);
let result = self.eval_list(eval_list_node, nest_level + 1);
// println!("eval_list result: {:?}", result);
result
},
_ => panic!("Epiq::Mpiqは>のみ"),
}
}
fn walked_node(&self, i: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
let node = self.get_epiq(i);
self.walk_internal(node, nest_level + 1)
}
fn pval(&self, piq: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
if let Epiq::Lpiq(p, _) = *piq.1 {
self.get_epiq(p)
} else {
let from = self.printer_printed(piq.0);
panic!("{:?}からpvalは取り出せません", from);
}
}
fn qval(&self, piq: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
if let Epiq::Lpiq(_, q) = *piq.1 {
self.get_epiq(q)
} else {
let from = self.printer_printed(piq.0);
panic!("{:?}からqvalは取り出せません", from);
}
}
// walker内でEpiqを読み取り用で取得するためのヘルパー
// cloneしているのは多分しかたない
fn get_epiq(&self, i: usize) -> Node<Rc<Epiq>> {
let vm = self.vm.borrow();
let &Node(index, ref rc_epiq) = vm.get_epiq(i);
Node(index, rc_epiq.clone())
}
fn log_piq(&self, lvl: u32, comment: &str, i: usize) {
if DEGUGGING_NOW {
println!("{}{} {:?}", " ".repeat((lvl * 2) as usize), comment, self.printer_printed(i));
}
}
fn log(&self, s: &str) {
if DEGUGGING_NOW {
panic!("{:?}", s)
// println!("{:?}", s);
}
}
fn printer_printed(&self, i: NodeId) -> String {
let printer = Printer::new(self.vm.clone());
printer.print_aexp(i, 0)
}
}
refactor eval_access()
macro_rules! alloc_node {
($s:ident, $n:expr) => {{
let new_index = $s.vm.borrow_mut().alloc($n);
$s.get_epiq(new_index)
}}
}
macro_rules! unwrap_name {
($s:ident, $e:expr) => {{
match *$e.1 {
Epiq::Name(ref t) => t,
_ => {
let from = $s.printer_printed($e.0);
panic!("{:?}からnameは取り出せません", from);
},
}
}}
}
mod primitive;
use std::rc::Rc;
use std::cell::RefCell;
use core::*;
use printer::*;
const DEGUGGING_NOW: bool = false;
const UNIT_INDX: usize = 0;
pub struct Walker {
vm: Rc<RefCell<Heliqs>>,
}
impl Walker {
pub fn new(vm: Rc<RefCell<Heliqs>>) -> Walker {
Walker { vm: vm, }
}
pub fn walk(&self) {
println!("\n");
let entry = self.get_entry_node();
let result = self.walk_internal(entry.clone(), 0);
// 変化があればentryを変更する
if result.0 != entry.0 {
self.vm.borrow_mut().set_entry(result.0);
}
}
fn get_entry_node(&self) -> Node<Rc<Epiq>> {
if let Some(node) = self.vm.borrow().entry().map(|entry| self.get_epiq(entry)) {
node
} else {
panic!("entryが正しく取得できませんでした");
}
}
fn walk_internal<'a>(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "walk_internal", input.0);
let Node(_, piq) = input.clone();
match *piq {
Epiq::Eval(p, q) => self.eval(p, q, nest_level),
Epiq::Lpiq(p, q) => self.walk_piq(input, ":", p, q, nest_level),
Epiq::Appl(p, q) => self.walk_piq(input, "!", p, q, nest_level),
Epiq::Rslv(p, q) => self.walk_piq(input, "@", p, q, nest_level),
Epiq::Cond(p, q) => self.walk_piq(input, "?", p, q, nest_level),
Epiq::Envn(p, q) => self.walk_piq(input, "%", p, q, nest_level),
Epiq::Bind(p, q) => self.walk_piq(input, "#", p, q, nest_level),
Epiq::Lmbd(p, q) => self.walk_piq(input, r"\", p, q, nest_level),
Epiq::Tpiq{ref o, p, q} => self.walk_piq(input, o, p, q, nest_level),
_ => input,
}
}
fn walk_piq(&self, input: Node<Rc<Epiq>>, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// pとq両方をwalkしてみて、
// 結果が両方とも変わらなければそのまま返す、
// そうでなければ新しくpiqを作って返す
let p_node = self.get_epiq(p);
let q_node = self.get_epiq(q);
let p_result = self.walk_internal(p_node, nest_level + 1);
let q_result = self.walk_internal(q_node, nest_level + 1);
if p_result.0 == p && q_result.0 == q {
input
} else {
self.walk_piq_internal(o, p_result.0, q_result.0)
}
}
fn walk_piq_internal(&self, o: &str, p: NodeId, q: NodeId) -> Node<Rc<Epiq>> {
let new_epiq = match o {
":" => Epiq::Lpiq(p, q),
"!" => Epiq::Appl(p, q),
"@" => Epiq::Rslv(p, q),
"?" => Epiq::Cond(p, q),
"%" => Epiq::Envn(p, q),
"#" => Epiq::Bind(p, q),
r"\" => Epiq::Lmbd(p, q),
_ => Epiq::Tpiq{o: o.to_string(), p, q},
};
let mut borrow_mut_vm = self.vm.borrow_mut();
let new_epiq_index = borrow_mut_vm.alloc(new_epiq);
self.get_epiq(new_epiq_index)
}
fn eval_internal<'a>(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_internal", input.0);
let Node(input_index, piq) = input.clone();
match *piq {
Epiq::Unit |
Epiq::Tval |
Epiq::Fval |
Epiq::Uit8(_) |
Epiq::Name(_) |
Epiq::Text(_) |
Epiq::Lpiq(..) => input,
Epiq::Eval(p, q) => self.eval(p, q, nest_level), // こっちはあまり通らないかもしれない
Epiq::Appl(p, q) => self.eval_apply(input, p, q, nest_level),
Epiq::Rslv(p, q) => self.eval_resolve(p, q, nest_level),
Epiq::Cond(p, q) => self.eval_condition(input, input_index, "?", p, q, nest_level),
Epiq::Envn(..) => self.eval_environment(input),
Epiq::Bind(p, q) => self.eval_bind(p, q, nest_level),
Epiq::Accs(p, q) => self.eval_access(input, p, q, nest_level),
Epiq::Lmbd(..) => self.eval_lambda_direct(input),
Epiq::Prim(_) => self.eval_primitive_direct(input),
Epiq::Tpiq{ref o, p, q} => self.eval_tpiq(o, p, q, nest_level),
Epiq::Mpiq{ref o, p, q} => self.eval_mpiq(o, p, q, nest_level),
_ => panic!("eval_internal: 無効なEpiq"),
}
}
fn eval(&self, _p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// ひとまずpは無視
// そのまま返すとNG
let q_node = self.get_epiq(q);
let result = self.eval_internal(q_node, nest_level + 1);
self.log_piq(nest_level, "eval: eval完前", q);
self.log_piq(nest_level, "eval: eval完後", result.0);
result
}
fn eval_apply(&self, input: Node<Rc<Epiq>>, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// p: lambda q:arguments
let lambda_node = self.get_epiq(p);
let walked_lambda_box = self.walk_internal(lambda_node, nest_level + 1);
let walked_lambda_piq = walked_lambda_box.1;
let args_node = self.get_epiq(q);
let args = self.walk_internal(args_node, nest_level + 1);
self.log_piq(nest_level, "args: ", args.0);
match *walked_lambda_piq {
Epiq::Lmbd(lambda_env, lambda_body) => {
self.eval_lambda(input, lambda_env, lambda_body, args, nest_level)
},
Epiq::Prim(ref n) => self.eval_primitive(input, args, n, nest_level),
_ => {
panic!("関数部分がlambdaでもprimでもないのでエラー");
},
}
}
fn eval_resolve(&self, _p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// p: 用途未定。ひとまず無視
// q: シンボルというか名前
let node = self.get_epiq(q);
let result = self.walk_internal(node, nest_level + 1);
if let Epiq::Name(ref n) = *result.1 {
let vm = self.vm.borrow();
match vm.resolve(n) {
Some(Some(res)) => res.clone().clone(),
_ => {
panic!("resolve時に指定されたキーが見つからない: {:?}", n);
},
}
} else {
panic!("resolve時のキーがNameじゃないのでエラー");
}
}
fn eval_environment(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
// ひとまずNoneを返しておく
// 本来は中身もwalkしてから返すべき?
input
}
fn eval_bind(&self, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
let result;
if let Some((n, walked_q_val)) = {
let p_val = self.get_epiq(p);
let walked_p_val = self.walk_internal(p_val, nest_level + 1);
if let Epiq::Name(ref n) = *walked_p_val.1 {
let q_val = self.get_epiq(q);
let result = self.walk_internal(q_val, nest_level + 1);
let walked_q_val = result.0;
Some((n.clone(), walked_q_val.clone()))
} else {
None
}
} {
// println!("#.p is Name");
result = {
// println!("borrow_mut: {:?}", 3);
self.vm.borrow_mut().define(n.as_ref(), walked_q_val);
// println!("borrow_mut: {:?}", 4);
let new_index = UNIT_INDX; // self.vm.borrow_mut().alloc(Epiq::Unit);
self.get_epiq(new_index)
};
result
} else {
panic!("#.p is not Name");
}
}
/// 直接lambdaをevalした時('> |\)に通る(現在、基本的には何もしない)
/// 一方、eval_lambda()はapplyを通して呼ばれる
fn eval_lambda_direct(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
// TODO: 一つ目の環境の中身はひとまず無視する
// qのリストだけを逐次実行して、勝手に最後の値をwalkしてから返却するようにする
// ただ、そもそも、blockをevalしても、何も変化はないはず。
input
}
/// applyを通して呼ばれる
/// 一方、eval_lambda_direct()は直接lambdaをevalした時('> |\)に通る
fn eval_lambda(&self, input: Node<Rc<Epiq>>,
env: usize, body: usize, args: Node<Rc<Epiq>>,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_lambda", input.0);
// 1. 環境を作成する
let walked_env_box = self.walked_node(env, nest_level);
if let Epiq::Envn(_, symbols) = *walked_env_box.1 {
let params = self.get_epiq(symbols);
self.vm.borrow_mut().extend();
self.assign_arguments(params, args, nest_level);
} else {
panic!("apply envがTpiqではありません");
}
// 2. 関数本体をwalkを挟んでから返す
// TODO: walkにするとLambdaをそのまま返してしまうので、マクロのような扱いになる
// 実行したければevalしてから返す、
// しかしできればマクロ展開・関数適用を両方ともこの中でやってしまいたい。。。
// 今のところはひとまず関数適用しておく(普通にevalを通す)
let body_node = self.get_epiq(body);
let evaled_body = self.eval_internal(body_node, nest_level + 1);
// 3. 環境フレームを削除する
self.vm.borrow_mut().pop();
self.log_piq(nest_level, "apply 正常終了: ", evaled_body.0);
evaled_body
}
/// 直接Primをevalした時に通る(現在、基本的には何もしない)
/// 一方、eval_primitive()はapplyを通して呼ばれる
fn eval_primitive_direct(&self, input: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
// println!("primitive");
input
}
/// applyを通して呼ばれる
/// 一方、eval_primitive_direct()は直接Primをevalした時に通る
fn eval_primitive(&self, input: Node<Rc<Epiq>>, args: Node<Rc<Epiq>>, n: &str, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_primitive", input.0);
match n.as_ref() {
"decr" => self.decrement(args),
"plus" => self.plus(args),
"minus" => self.minus(args),
"print" => self.print(args),
"ltoreq" => self.le_or_eq_nmbr(args),
"concat" => self.concat(args),
"eq" => {
let first = self.pval(args.clone());
match *first.1 {
Epiq::Uit8(n1) => self.eq_nmbr(args),
Epiq::Text(ref text1) => self.eq_text(args),
Epiq::Unit => {
let rest = self.qval(args);
let second = self.pval(rest);
let new_epiq = if *second.1 == Epiq::Unit { Epiq::Tval } else { Epiq::Fval };
alloc_node!(self, new_epiq)
}
_ => {
panic!("primitive 1つ目の引数の型は数値/文字列のみだが違反している, {:?}", self.printer_printed(first.0));
},
}
},
_ => {
panic!("Primitive関数名が想定外なのでエラー");
},
}
}
fn eval_access(&self, input: Node<Rc<Epiq>>, p: usize, q: usize,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_access", input.0);
// p: レシーバ q: アクセッサ
let p_reciever = self.walked_node(p, nest_level);
let q_accessor = self.walked_node(q, nest_level);
// レシーバの種類によってできることが変わる
match *p_reciever.1 {
Epiq::Lpiq(p, q) => {
// Lpiqならば、pとqのみが使える
let n = unwrap_name!(self, q_accessor);
match n.as_ref() {
"p" => self.walked_node(p, nest_level),
"q" => self.walked_node(q, nest_level),
_ => panic!("Lpiqならばpとq以外はエラー"),
}
},
Epiq::Tpiq{ref o,p,q} => {
// Tpiqならば、pとqが使える
let n = unwrap_name!(self, q_accessor);
match n.as_ref() {
"o" => alloc_node!(self, Epiq::Text(o.to_string())),
"p" => self.walked_node(p, nest_level),
"q" => self.walked_node(q, nest_level),
_ => panic!("Tpiqならばoとpとq以外はエラー"),
}
},
_ => panic!("{:?}に{:?}というアクセッサはありません", *p_reciever.1, *q_accessor.1),
}
}
fn eval_condition(&self, input: Node<Rc<Epiq>>, input_index: usize,
o: &str, p: usize, q: usize,
nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_condition", input.0);
// p: ^T or ^F(他の値の評価はひとまず考えない)
// q: Lpiq、^Tならpを返し、^Fならqを返す
let p_condition = self.get_epiq(p);
// 条件節をwalk
// println!("condition: {:?}", "条件節をwalk");
let walked_condition = self.walk_internal(p_condition.clone(), nest_level + 1);
// 値がwalk後に変化していたら付け替える
if walked_condition.0 == p_condition.0 {
let mut vm = self.vm.borrow_mut();
let node_mut = vm.get_epiq_mut(input_index);
node_mut.1 = Rc::new(Epiq::Tpiq{o:o.to_string(), p:walked_condition.0, q:q});
// println!("{:?} -> ({} {:?}){}condition eval後付け替え", *input.1, input_index, walked_condition_node.1, " ".repeat(lvl));
}
let result_piq = self.get_epiq(q);
match *walked_condition.1 {
Epiq::Tval => {
let p_node = self.pval(result_piq);
self.walk_internal(p_node, nest_level + 1)
},
Epiq::Fval => {
let q_node = self.qval(result_piq);
self.walk_internal(q_node, nest_level + 1)
},
_ => {
panic!("condtion 評価結果は^Tか^Fだが{:?}なのでエラー", walked_condition.1);
},
}
}
fn eval_list(&self, input: Node<Rc<Epiq>>, nest_level: u32) -> Node<Rc<Epiq>> {
self.log_piq(nest_level, "eval_list", input.0);
let current_node = self.pval(input.clone());
let evaled_current_node = self.eval_internal(current_node, nest_level + 1);
let next = self.qval(input);
if let Epiq::Unit = *next.1 {
// リストの最後なので評価の結果を返す
evaled_current_node
} else {
// 次の項目へ
self.eval_list(next, nest_level + 1)
}
}
fn assign_arguments(&self, parameters_node: Node<Rc<Epiq>>, arguments_node: Node<Rc<Epiq>>, nest_level: u32) {
// arguments_piqはリストのはずなので、一つ一つ回して定義していく
self.log_piq(nest_level, "assign_arguments", parameters_node.0);
let content_node = self.pval(arguments_node.clone());
let next_args_node = self.qval(arguments_node);
let param_node = self.pval(parameters_node.clone());
let next_params_node = self.qval(parameters_node);
let mut symbol_string = "";
if let Epiq::Name(ref s) = *param_node.1 {
symbol_string = s;
} else {
// 文字列じゃない場合は初期値があるとか、
// 他の可能性があるが今は実装しない
}
self.vm.borrow_mut().define(symbol_string, content_node.0);
// paramsとargs、両方のリストを回していくが、
// ループの基準となるのはargs。
// paramsが途中でなくなっても知らん。
if *next_args_node.1 == Epiq::Unit {
// 最後なので終了
return;
}
// 次にいく
self.assign_arguments(next_params_node, next_args_node, nest_level
);
}
fn eval_tpiq(&self, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
// call macro
let macrocro = match self.vm.borrow().resolve("macro") {
Some(Some(res)) => res.clone().clone(),
_ => {
panic!("resolve時に指定されたキーが見つからない: {:?}", "macro");
},
};
let arg1 = self.vm.borrow_mut().alloc(Epiq::Text(o.to_string()));
let arg2_node = self.get_epiq(p);
let arg3_node = self.get_epiq(q);
let args_last = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg3_node.0, UNIT_INDX));
let args_second = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg2_node.0, args_last));
let args_first = self.vm.borrow_mut().alloc(Epiq::Lpiq(arg1, args_second));
let appl = self.vm.borrow_mut().alloc(Epiq::Appl(macrocro.0, args_first));
let appl_node = self.get_epiq(appl);
let macro_result = self.eval_internal(appl_node, nest_level + 1);
macro_result
}
fn eval_mpiq(&self, o: &str, p: NodeId, q: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
match o.as_ref() {
">" => {
// ^> リストのeval
// リストの要素それぞれをevalする
// pは-1だとして処理する(最後の項目の評価結果が最終的な結果となる)
let eval_list_node = self.get_epiq(q);
let result = self.eval_list(eval_list_node, nest_level + 1);
// println!("eval_list result: {:?}", result);
result
},
_ => panic!("Epiq::Mpiqは>のみ"),
}
}
fn walked_node(&self, i: NodeId, nest_level: u32) -> Node<Rc<Epiq>> {
let node = self.get_epiq(i);
self.walk_internal(node, nest_level + 1)
}
fn pval(&self, piq: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
if let Epiq::Lpiq(p, _) = *piq.1 {
self.get_epiq(p)
} else {
let from = self.printer_printed(piq.0);
panic!("{:?}からpvalは取り出せません", from);
}
}
fn qval(&self, piq: Node<Rc<Epiq>>) -> Node<Rc<Epiq>> {
if let Epiq::Lpiq(_, q) = *piq.1 {
self.get_epiq(q)
} else {
let from = self.printer_printed(piq.0);
panic!("{:?}からqvalは取り出せません", from);
}
}
// walker内でEpiqを読み取り用で取得するためのヘルパー
// cloneしているのは多分しかたない
fn get_epiq(&self, i: usize) -> Node<Rc<Epiq>> {
let vm = self.vm.borrow();
let &Node(index, ref rc_epiq) = vm.get_epiq(i);
Node(index, rc_epiq.clone())
}
fn log_piq(&self, lvl: u32, comment: &str, i: usize) {
if DEGUGGING_NOW {
println!("{}{} {:?}", " ".repeat((lvl * 2) as usize), comment, self.printer_printed(i));
}
}
fn log(&self, s: &str) {
if DEGUGGING_NOW {
panic!("{:?}", s)
// println!("{:?}", s);
}
}
fn printer_printed(&self, i: NodeId) -> String {
let printer = Printer::new(self.vm.clone());
printer.print_aexp(i, 0)
}
}
|
// Copyright (C) 2019 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0
use crypto_hash::{Algorithm, Hasher};
use hex;
use pkg_schema::{objects, Object};
use std::{
fs::File,
io::{BufReader, Read, Write},
path::Path,
};
#[derive(PartialEq, Debug)]
pub(crate) enum Status {
Missing,
Incomplete,
Corrupted,
Ready,
}
impl_object_info!(objects::Copy);
impl_object_info!(objects::Flash);
impl_object_info!(objects::Imxkobs);
impl_object_info!(objects::Tarball);
impl_object_info!(objects::Ubifs);
impl_object_info!(objects::Raw);
impl_object_info!(objects::Test);
impl_object_for_object_types!(Copy, Flash, Imxkobs, Tarball, Ubifs, Raw, Test);
pub(crate) trait Info {
fn status(&self, download_dir: &Path) -> Result<Status, failure::Error> {
let object = download_dir.join(self.sha256sum());
if !object.exists() {
return Ok(Status::Missing);
}
if object.metadata()?.len() < self.len() {
return Ok(Status::Incomplete);
}
let mut buf = [0; 1024];
let mut reader = BufReader::new(File::open(object)?);
let mut hasher = Hasher::new(Algorithm::SHA256);
loop {
let len = reader.read(&mut buf)?;
hasher.write_all(&buf[..len])?;
if len == 0 {
break;
}
}
if hex::encode(hasher.finish()) != self.sha256sum() {
println!("{:?} {:?}", &self.sha256sum(), hex::encode(hasher.finish()));
return Ok(Status::Corrupted);
}
Ok(Status::Ready)
}
fn filename(&self) -> &str;
fn len(&self) -> u64;
fn sha256sum(&self) -> &str;
}
updatehub: Remove print when object is found to be corrupted
Signed-off-by: Jonathas-Conceicao <33cd5f63a6435f6b1365c76100ff4a5652c45928@ossystems.com.br>
// Copyright (C) 2019 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0
use crypto_hash::{Algorithm, Hasher};
use hex;
use pkg_schema::{objects, Object};
use std::{
fs::File,
io::{BufReader, Read, Write},
path::Path,
};
#[derive(PartialEq, Debug)]
pub(crate) enum Status {
Missing,
Incomplete,
Corrupted,
Ready,
}
impl_object_info!(objects::Copy);
impl_object_info!(objects::Flash);
impl_object_info!(objects::Imxkobs);
impl_object_info!(objects::Tarball);
impl_object_info!(objects::Ubifs);
impl_object_info!(objects::Raw);
impl_object_info!(objects::Test);
impl_object_for_object_types!(Copy, Flash, Imxkobs, Tarball, Ubifs, Raw, Test);
pub(crate) trait Info {
fn status(&self, download_dir: &Path) -> Result<Status, failure::Error> {
let object = download_dir.join(self.sha256sum());
if !object.exists() {
return Ok(Status::Missing);
}
if object.metadata()?.len() < self.len() {
return Ok(Status::Incomplete);
}
let mut buf = [0; 1024];
let mut reader = BufReader::new(File::open(object)?);
let mut hasher = Hasher::new(Algorithm::SHA256);
loop {
let len = reader.read(&mut buf)?;
hasher.write_all(&buf[..len])?;
if len == 0 {
break;
}
}
if hex::encode(hasher.finish()) != self.sha256sum() {
return Ok(Status::Corrupted);
}
Ok(Status::Ready)
}
fn filename(&self) -> &str;
fn len(&self) -> u64;
fn sha256sum(&self) -> &str;
}
|
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use std::sync::Arc;
use buffer::BufferSlice;
use buffer::sys::UnsafeBuffer;
use command_buffer::states_manager::StatesManager;
use device::Queue;
use memory::Content;
use sync::AccessFlagBits;
use sync::Fence;
use sync::PipelineStages;
use sync::Semaphore;
/// Trait for objects that represent either a buffer or a slice of a buffer.
pub unsafe trait Buffer {
/// Returns the inner information about this buffer.
fn inner(&self) -> BufferInner;
#[inline]
fn size(&self) -> usize {
self.inner().buffer.size()
}
#[inline]
fn as_buffer_slice(&self) -> BufferSlice<Self::Content, &Self> where Self: Sized + TypedBuffer {
BufferSlice::from(self)
}
#[inline]
fn into_buffer_slice(self) -> BufferSlice<Self::Content, Self> where Self: Sized + TypedBuffer {
BufferSlice::from(self)
}
}
#[derive(Copy, Clone, Debug)]
pub struct BufferInner<'a> {
pub buffer: &'a UnsafeBuffer,
pub offset: usize
}
unsafe impl<'a, B: ?Sized> Buffer for &'a B where B: Buffer + 'a {
#[inline]
fn inner(&self) -> BufferInner {
(**self).inner()
}
#[inline]
fn size(&self) -> usize {
(**self).size()
}
}
unsafe impl<B: ?Sized> Buffer for Arc<B> where B: Buffer {
#[inline]
fn inner(&self) -> BufferInner {
(**self).inner()
}
#[inline]
fn size(&self) -> usize {
(**self).size()
}
}
/// Extension trait for `Buffer`. Types that implement this can be used in a `StdCommandBuffer`.
///
/// Each buffer and image used in a `StdCommandBuffer` have an associated state which is
/// represented by the `CommandListState` associated type of this trait. You can make multiple
/// buffers or images share the same state by making `is_same` return true.
pub unsafe trait TrackedBuffer<States = StatesManager>: Buffer {
/// Returns a new state that corresponds to the moment after a slice of the buffer has been
/// used in the pipeline. The parameters indicate in which way it has been used.
///
/// If the transition should result in a pipeline barrier, then it must be returned by this
/// function.
// TODO: what should be the behavior if `num_command` is equal to the `num_command` of a
// previous transition?
fn transition(&self, states: &mut States, num_command: usize, offset: usize, size: usize,
write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>;
/// Function called when the command buffer builder is turned into a real command buffer.
///
/// This function can return an additional pipeline barrier that will be applied at the end
/// of the command buffer.
fn finish(&self, in_s: &mut States, out: &mut States) -> Option<PipelineBarrierRequest>;
/// Called right before the command buffer is submitted.
// TODO: function should be unsafe because it must be guaranteed that a cb is submitted
fn on_submit<F>(&self, states: &States, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>;
}
/// Requests that a pipeline barrier is created.
pub struct PipelineBarrierRequest {
/// The number of the command after which the barrier should be placed. Must usually match
/// the number that was passed to the previous call to `transition`, or 0 if the buffer hasn't
/// been used yet.
pub after_command_num: usize,
/// The source pipeline stages of the transition.
pub source_stage: PipelineStages,
/// The destination pipeline stages of the transition.
pub destination_stages: PipelineStages,
/// If true, the pipeliner barrier is by region. There is literaly no reason to pass `false`
/// here, but it is included just in case.
pub by_region: bool,
/// An optional memory barrier. See the docs of `PipelineMemoryBarrierRequest`.
pub memory_barrier: Option<PipelineMemoryBarrierRequest>,
}
/// Requests that a memory barrier is created as part of the pipeline barrier.
///
/// By default, a pipeline barrier only guarantees that the source operations are executed before
/// the destination operations, but it doesn't make memory writes made by source operations visible
/// to the destination operations. In order to make so, you have to add a memory barrier.
///
/// The memory barrier always concerns the buffer that is currently being processed. You can't add
/// a memory barrier that concerns another resource.
pub struct PipelineMemoryBarrierRequest {
/// Offset of start of the range to flush.
pub offset: isize,
/// Size of the range to flush.
pub size: usize,
/// Source accesses.
pub source_access: AccessFlagBits,
/// Destination accesses.
pub destination_access: AccessFlagBits,
}
pub struct SubmitInfos {
pub pre_semaphore: Option<(Arc<Semaphore>, PipelineStages)>,
pub post_semaphore: Option<Arc<Semaphore>>,
pub pre_barrier: Option<PipelineBarrierRequest>,
pub post_barrier: Option<PipelineBarrierRequest>,
}
unsafe impl<B:? Sized, S> TrackedBuffer<S> for Arc<B> where B: TrackedBuffer<S> {
#[inline]
fn transition(&self, states: &mut S, num_command: usize, offset: usize,
size: usize, write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>
{
(**self).transition(states, num_command, offset, size, write, stage, access)
}
#[inline]
fn finish(&self, i: &mut S, o: &mut S) -> Option<PipelineBarrierRequest> {
(**self).finish(i, o)
}
#[inline]
fn on_submit<F>(&self, states: &S, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>
{
(**self).on_submit(states, queue, fence)
}
}
unsafe impl<'a, B: ?Sized, S> TrackedBuffer<S> for &'a B where B: TrackedBuffer<S> + 'a {
#[inline]
fn transition(&self, states: &mut S, num_command: usize, offset: usize,
size: usize, write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>
{
(**self).transition(states, num_command, offset, size, write, stage, access)
}
#[inline]
fn finish(&self, i: &mut S, o: &mut S) -> Option<PipelineBarrierRequest> {
(**self).finish(i, o)
}
#[inline]
fn on_submit<F>(&self, states: &S, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>
{
(**self).on_submit(states, queue, fence)
}
}
pub unsafe trait TypedBuffer: Buffer {
type Content: ?Sized + 'static;
#[inline]
fn len(&self) -> usize where Self::Content: Content {
self.size() / <Self::Content as Content>::indiv_size()
}
}
unsafe impl<B: ?Sized> TypedBuffer for Arc<B> where B: TypedBuffer {
type Content = B::Content;
}
unsafe impl<'a, B: ?Sized + 'a> TypedBuffer for &'a B where B: TypedBuffer {
type Content = B::Content;
}
Move len() from TypedBuffer to Buffer
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use std::sync::Arc;
use buffer::BufferSlice;
use buffer::sys::UnsafeBuffer;
use command_buffer::states_manager::StatesManager;
use device::Queue;
use memory::Content;
use sync::AccessFlagBits;
use sync::Fence;
use sync::PipelineStages;
use sync::Semaphore;
/// Trait for objects that represent either a buffer or a slice of a buffer.
pub unsafe trait Buffer {
/// Returns the inner information about this buffer.
fn inner(&self) -> BufferInner;
#[inline]
fn size(&self) -> usize {
self.inner().buffer.size()
}
#[inline]
fn len(&self) -> usize where Self: TypedBuffer, Self::Content: Content {
self.size() / <Self::Content as Content>::indiv_size()
}
#[inline]
fn as_buffer_slice(&self) -> BufferSlice<Self::Content, &Self> where Self: Sized + TypedBuffer {
BufferSlice::from(self)
}
#[inline]
fn into_buffer_slice(self) -> BufferSlice<Self::Content, Self> where Self: Sized + TypedBuffer {
BufferSlice::from(self)
}
}
#[derive(Copy, Clone, Debug)]
pub struct BufferInner<'a> {
pub buffer: &'a UnsafeBuffer,
pub offset: usize
}
unsafe impl<'a, B: ?Sized> Buffer for &'a B where B: Buffer + 'a {
#[inline]
fn inner(&self) -> BufferInner {
(**self).inner()
}
#[inline]
fn size(&self) -> usize {
(**self).size()
}
}
unsafe impl<B: ?Sized> Buffer for Arc<B> where B: Buffer {
#[inline]
fn inner(&self) -> BufferInner {
(**self).inner()
}
#[inline]
fn size(&self) -> usize {
(**self).size()
}
}
/// Extension trait for `Buffer`. Types that implement this can be used in a `StdCommandBuffer`.
///
/// Each buffer and image used in a `StdCommandBuffer` have an associated state which is
/// represented by the `CommandListState` associated type of this trait. You can make multiple
/// buffers or images share the same state by making `is_same` return true.
pub unsafe trait TrackedBuffer<States = StatesManager>: Buffer {
/// Returns a new state that corresponds to the moment after a slice of the buffer has been
/// used in the pipeline. The parameters indicate in which way it has been used.
///
/// If the transition should result in a pipeline barrier, then it must be returned by this
/// function.
// TODO: what should be the behavior if `num_command` is equal to the `num_command` of a
// previous transition?
fn transition(&self, states: &mut States, num_command: usize, offset: usize, size: usize,
write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>;
/// Function called when the command buffer builder is turned into a real command buffer.
///
/// This function can return an additional pipeline barrier that will be applied at the end
/// of the command buffer.
fn finish(&self, in_s: &mut States, out: &mut States) -> Option<PipelineBarrierRequest>;
/// Called right before the command buffer is submitted.
// TODO: function should be unsafe because it must be guaranteed that a cb is submitted
fn on_submit<F>(&self, states: &States, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>;
}
/// Requests that a pipeline barrier is created.
pub struct PipelineBarrierRequest {
/// The number of the command after which the barrier should be placed. Must usually match
/// the number that was passed to the previous call to `transition`, or 0 if the buffer hasn't
/// been used yet.
pub after_command_num: usize,
/// The source pipeline stages of the transition.
pub source_stage: PipelineStages,
/// The destination pipeline stages of the transition.
pub destination_stages: PipelineStages,
/// If true, the pipeliner barrier is by region. There is literaly no reason to pass `false`
/// here, but it is included just in case.
pub by_region: bool,
/// An optional memory barrier. See the docs of `PipelineMemoryBarrierRequest`.
pub memory_barrier: Option<PipelineMemoryBarrierRequest>,
}
/// Requests that a memory barrier is created as part of the pipeline barrier.
///
/// By default, a pipeline barrier only guarantees that the source operations are executed before
/// the destination operations, but it doesn't make memory writes made by source operations visible
/// to the destination operations. In order to make so, you have to add a memory barrier.
///
/// The memory barrier always concerns the buffer that is currently being processed. You can't add
/// a memory barrier that concerns another resource.
pub struct PipelineMemoryBarrierRequest {
/// Offset of start of the range to flush.
pub offset: isize,
/// Size of the range to flush.
pub size: usize,
/// Source accesses.
pub source_access: AccessFlagBits,
/// Destination accesses.
pub destination_access: AccessFlagBits,
}
pub struct SubmitInfos {
pub pre_semaphore: Option<(Arc<Semaphore>, PipelineStages)>,
pub post_semaphore: Option<Arc<Semaphore>>,
pub pre_barrier: Option<PipelineBarrierRequest>,
pub post_barrier: Option<PipelineBarrierRequest>,
}
unsafe impl<B:? Sized, S> TrackedBuffer<S> for Arc<B> where B: TrackedBuffer<S> {
#[inline]
fn transition(&self, states: &mut S, num_command: usize, offset: usize,
size: usize, write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>
{
(**self).transition(states, num_command, offset, size, write, stage, access)
}
#[inline]
fn finish(&self, i: &mut S, o: &mut S) -> Option<PipelineBarrierRequest> {
(**self).finish(i, o)
}
#[inline]
fn on_submit<F>(&self, states: &S, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>
{
(**self).on_submit(states, queue, fence)
}
}
unsafe impl<'a, B: ?Sized, S> TrackedBuffer<S> for &'a B where B: TrackedBuffer<S> + 'a {
#[inline]
fn transition(&self, states: &mut S, num_command: usize, offset: usize,
size: usize, write: bool, stage: PipelineStages, access: AccessFlagBits)
-> Option<PipelineBarrierRequest>
{
(**self).transition(states, num_command, offset, size, write, stage, access)
}
#[inline]
fn finish(&self, i: &mut S, o: &mut S) -> Option<PipelineBarrierRequest> {
(**self).finish(i, o)
}
#[inline]
fn on_submit<F>(&self, states: &S, queue: &Arc<Queue>, fence: F) -> SubmitInfos
where F: FnOnce() -> Arc<Fence>
{
(**self).on_submit(states, queue, fence)
}
}
pub unsafe trait TypedBuffer: Buffer {
type Content: ?Sized + 'static;
}
unsafe impl<B: ?Sized> TypedBuffer for Arc<B> where B: TypedBuffer {
type Content = B::Content;
}
unsafe impl<'a, B: ?Sized + 'a> TypedBuffer for &'a B where B: TypedBuffer {
type Content = B::Content;
}
|
//! Link between Vulkan and a window and/or the screen.
//!
//! In order to draw on the screen or a window, you have to use two steps:
//!
//! - Create a `Surface` object that represents the location where the image will show up.
//! - Create a `Swapchain` using that `Surface`.
//!
//! Creating a surface can be done with only an `Instance` object. However creating a swapchain
//! requires a `Device` object.
//!
//! Once you have a swapchain, you can retreive `Image` objects from it and draw to them. However
//! due to double-buffering or other caching mechanism, the rendering will not automatically be
//! shown on screen. In order to show the output on screen, you have to *present* the swapchain
//! by using the method with the same name.
//!
//! # Extensions
//!
//! Theses capabilities depend on some extensions:
//!
//! - `VK_KHR_surface`
//! - `VK_KHR_swapchain`
//! - `VK_KHR_display`
//! - `VK_KHR_display_swapchain`
//! - `VK_KHR_xlib_surface`
//! - `VK_KHR_xcb_surface`
//! - `VK_KHR_wayland_surface`
//! - `VK_KHR_mir_surface`
//! - `VK_KHR_android_surface`
//! - `VK_KHR_win32_surface`
//!
use std::ffi::CStr;
use std::ptr;
use std::sync::Arc;
use std::vec::IntoIter;
use instance::PhysicalDevice;
use memory::MemorySourceChunk;
use check_errors;
use OomError;
use VulkanObject;
use VulkanPointers;
use vk;
pub use self::surface::Capabilities;
pub use self::surface::Surface;
pub use self::surface::PresentMode;
pub use self::surface::SurfaceTransform;
pub use self::surface::CompositeAlpha;
pub use self::surface::ColorSpace;
pub use self::swapchain::Swapchain;
pub use self::swapchain::AcquireError;
mod surface;
mod swapchain;
// TODO: extract this to a `display` module and solve the visibility problems
/// ?
// TODO: plane capabilities
pub struct DisplayPlane {
device: PhysicalDevice,
index: u32,
properties: vk::DisplayPlanePropertiesKHR,
supported_displays: Vec<vk::DisplayKHR>,
}
impl DisplayPlane {
/// Enumerates all the display planes that are available on a given physical device.
pub fn enumerate(device: &PhysicalDevice) -> Result<IntoIter<DisplayPlane>, OomError> {
let vk = device.instance().pointers();
let num = unsafe {
let mut num: u32 = 0;
try!(check_errors(vk.GetPhysicalDeviceDisplayPlanePropertiesKHR(device.internal_object(),
&mut num, ptr::null_mut())));
num
};
let planes: Vec<vk::DisplayPlanePropertiesKHR> = unsafe {
let mut planes = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetPhysicalDeviceDisplayPlanePropertiesKHR(device.internal_object(),
&mut num,
planes.as_mut_ptr())));
planes.set_len(num as usize);
planes
};
Ok(planes.into_iter().enumerate().map(|(index, prop)| {
let num = unsafe {
let mut num: u32 = 0;
check_errors(vk.GetDisplayPlaneSupportedDisplaysKHR(device.internal_object(), index as u32,
&mut num, ptr::null_mut())).unwrap(); // TODO: shouldn't unwrap
num
};
let supported_displays: Vec<vk::DisplayKHR> = unsafe {
let mut displays = Vec::with_capacity(num as usize);
let mut num = num;
check_errors(vk.GetDisplayPlaneSupportedDisplaysKHR(device.internal_object(),
index as u32, &mut num,
displays.as_mut_ptr())).unwrap(); // TODO: shouldn't unwrap
displays.set_len(num as usize);
displays
};
DisplayPlane {
device: device.clone(),
index: index as u32,
properties: prop,
supported_displays: supported_displays,
}
}).collect::<Vec<_>>().into_iter())
}
/// Returns true if this plane supports the given display.
#[inline]
pub fn supports(&self, display: &Display) -> bool {
// making sure that the physical device is the same
if self.device.internal_object() != display.device.internal_object() {
return false;
}
self.supported_displays.iter().find(|&&d| d == display.internal_object()).is_some()
}
}
/// Represents a monitor connected to a physical device.
#[derive(Clone)]
pub struct Display {
device: PhysicalDevice,
properties: Arc<vk::DisplayPropertiesKHR>, // TODO: Arc because struct isn't clone
}
impl Display {
/// Enumerates all the displays that are available on a given physical device.
pub fn enumerate(device: &PhysicalDevice) -> Result<IntoIter<Display>, OomError> {
let vk = device.instance().pointers();
let num = unsafe {
let mut num = 0;
try!(check_errors(vk.GetPhysicalDeviceDisplayPropertiesKHR(device.internal_object(),
&mut num, ptr::null_mut())));
num
};
let displays: Vec<vk::DisplayPropertiesKHR> = unsafe {
let mut displays = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetPhysicalDeviceDisplayPropertiesKHR(device.internal_object(),
&mut num,
displays.as_mut_ptr())));
displays.set_len(num as usize);
displays
};
Ok(displays.into_iter().map(|prop| {
Display {
device: device.clone(),
properties: Arc::new(prop),
}
}).collect::<Vec<_>>().into_iter())
}
/// Returns the name of the display.
#[inline]
pub fn name(&self) -> &str {
unsafe {
CStr::from_ptr(self.properties.displayName).to_str()
.expect("non UTF-8 characters in display name")
}
}
/// Returns the physical resolution of the display.
#[inline]
pub fn physical_resolution(&self) -> [u32; 2] {
let ref r = self.properties.physicalResolution;
[r.width, r.height]
}
/// Returns a list of all modes available on this display.
pub fn display_modes(&self) -> Result<IntoIter<DisplayMode>, OomError> {
let vk = self.device.instance().pointers();
let num = unsafe {
let mut num = 0;
try!(check_errors(vk.GetDisplayModePropertiesKHR(self.device.internal_object(),
self.properties.display,
&mut num, ptr::null_mut())));
num
};
let modes: Vec<vk::DisplayModePropertiesKHR> = unsafe {
let mut modes = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetDisplayModePropertiesKHR(self.device.internal_object(),
self.properties.display, &mut num,
modes.as_mut_ptr())));
modes.set_len(num as usize);
modes
};
Ok(modes.into_iter().map(|mode| {
DisplayMode {
display: self.clone(),
display_mode: mode.displayMode,
parameters: mode.parameters,
}
}).collect::<Vec<_>>().into_iter())
}
}
unsafe impl VulkanObject for Display {
type Object = vk::DisplayKHR;
#[inline]
fn internal_object(&self) -> vk::DisplayKHR {
self.properties.display
}
}
/// Represents a mode on a specific display.
pub struct DisplayMode {
display: Display,
display_mode: vk::DisplayModeKHR,
parameters: vk::DisplayModeParametersKHR,
}
impl DisplayMode {
/*pub fn new(display: &Display) -> Result<Arc<DisplayMode>, OomError> {
let vk = instance.pointers();
let parameters = vk::DisplayModeParametersKHR {
visibleRegion: vk::Extent2D { width: , height: },
refreshRate: ,
};
let display_mode = {
let infos = vk::DisplayModeCreateInfoKHR {
sType: vk::STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR,
pNext: ptr::null(),
flags: 0, // reserved
parameters: parameters,
};
let mut output = mem::uninitialized();
try!(check_errors(vk.CreateDisplayModeKHR(display.device.internal_object(),
display.display, &infos, ptr::null(),
&mut output)));
output
};
Ok(Arc::new(DisplayMode {
instance: display.device.instance().clone(),
display_mode: display_mode,
parameters: ,
}))
}*/
/// Returns the display corresponding to this mode.
#[inline]
pub fn display(&self) -> &Display {
&self.display
}
/// Returns the dimensions of the region that is visible on the monitor.
#[inline]
pub fn visible_region(&self) -> [u32; 2] {
let ref d = self.parameters.visibleRegion;
[d.width, d.height]
}
/// Returns the refresh rate of this mode.
#[inline]
pub fn refresh_rate(&self) -> u32 {
self.parameters.refreshRate
}
}
Fix missing export
//! Link between Vulkan and a window and/or the screen.
//!
//! In order to draw on the screen or a window, you have to use two steps:
//!
//! - Create a `Surface` object that represents the location where the image will show up.
//! - Create a `Swapchain` using that `Surface`.
//!
//! Creating a surface can be done with only an `Instance` object. However creating a swapchain
//! requires a `Device` object.
//!
//! Once you have a swapchain, you can retreive `Image` objects from it and draw to them. However
//! due to double-buffering or other caching mechanism, the rendering will not automatically be
//! shown on screen. In order to show the output on screen, you have to *present* the swapchain
//! by using the method with the same name.
//!
//! # Extensions
//!
//! Theses capabilities depend on some extensions:
//!
//! - `VK_KHR_surface`
//! - `VK_KHR_swapchain`
//! - `VK_KHR_display`
//! - `VK_KHR_display_swapchain`
//! - `VK_KHR_xlib_surface`
//! - `VK_KHR_xcb_surface`
//! - `VK_KHR_wayland_surface`
//! - `VK_KHR_mir_surface`
//! - `VK_KHR_android_surface`
//! - `VK_KHR_win32_surface`
//!
use std::ffi::CStr;
use std::ptr;
use std::sync::Arc;
use std::vec::IntoIter;
use instance::PhysicalDevice;
use memory::MemorySourceChunk;
use check_errors;
use OomError;
use VulkanObject;
use VulkanPointers;
use vk;
pub use self::surface::Capabilities;
pub use self::surface::Surface;
pub use self::surface::PresentMode;
pub use self::surface::SurfaceTransform;
pub use self::surface::CompositeAlpha;
pub use self::surface::ColorSpace;
pub use self::swapchain::Swapchain;
pub use self::swapchain::SwapchainAllocatedChunk;
pub use self::swapchain::AcquireError;
mod surface;
mod swapchain;
// TODO: extract this to a `display` module and solve the visibility problems
/// ?
// TODO: plane capabilities
pub struct DisplayPlane {
device: PhysicalDevice,
index: u32,
properties: vk::DisplayPlanePropertiesKHR,
supported_displays: Vec<vk::DisplayKHR>,
}
impl DisplayPlane {
/// Enumerates all the display planes that are available on a given physical device.
pub fn enumerate(device: &PhysicalDevice) -> Result<IntoIter<DisplayPlane>, OomError> {
let vk = device.instance().pointers();
let num = unsafe {
let mut num: u32 = 0;
try!(check_errors(vk.GetPhysicalDeviceDisplayPlanePropertiesKHR(device.internal_object(),
&mut num, ptr::null_mut())));
num
};
let planes: Vec<vk::DisplayPlanePropertiesKHR> = unsafe {
let mut planes = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetPhysicalDeviceDisplayPlanePropertiesKHR(device.internal_object(),
&mut num,
planes.as_mut_ptr())));
planes.set_len(num as usize);
planes
};
Ok(planes.into_iter().enumerate().map(|(index, prop)| {
let num = unsafe {
let mut num: u32 = 0;
check_errors(vk.GetDisplayPlaneSupportedDisplaysKHR(device.internal_object(), index as u32,
&mut num, ptr::null_mut())).unwrap(); // TODO: shouldn't unwrap
num
};
let supported_displays: Vec<vk::DisplayKHR> = unsafe {
let mut displays = Vec::with_capacity(num as usize);
let mut num = num;
check_errors(vk.GetDisplayPlaneSupportedDisplaysKHR(device.internal_object(),
index as u32, &mut num,
displays.as_mut_ptr())).unwrap(); // TODO: shouldn't unwrap
displays.set_len(num as usize);
displays
};
DisplayPlane {
device: device.clone(),
index: index as u32,
properties: prop,
supported_displays: supported_displays,
}
}).collect::<Vec<_>>().into_iter())
}
/// Returns true if this plane supports the given display.
#[inline]
pub fn supports(&self, display: &Display) -> bool {
// making sure that the physical device is the same
if self.device.internal_object() != display.device.internal_object() {
return false;
}
self.supported_displays.iter().find(|&&d| d == display.internal_object()).is_some()
}
}
/// Represents a monitor connected to a physical device.
#[derive(Clone)]
pub struct Display {
device: PhysicalDevice,
properties: Arc<vk::DisplayPropertiesKHR>, // TODO: Arc because struct isn't clone
}
impl Display {
/// Enumerates all the displays that are available on a given physical device.
pub fn enumerate(device: &PhysicalDevice) -> Result<IntoIter<Display>, OomError> {
let vk = device.instance().pointers();
let num = unsafe {
let mut num = 0;
try!(check_errors(vk.GetPhysicalDeviceDisplayPropertiesKHR(device.internal_object(),
&mut num, ptr::null_mut())));
num
};
let displays: Vec<vk::DisplayPropertiesKHR> = unsafe {
let mut displays = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetPhysicalDeviceDisplayPropertiesKHR(device.internal_object(),
&mut num,
displays.as_mut_ptr())));
displays.set_len(num as usize);
displays
};
Ok(displays.into_iter().map(|prop| {
Display {
device: device.clone(),
properties: Arc::new(prop),
}
}).collect::<Vec<_>>().into_iter())
}
/// Returns the name of the display.
#[inline]
pub fn name(&self) -> &str {
unsafe {
CStr::from_ptr(self.properties.displayName).to_str()
.expect("non UTF-8 characters in display name")
}
}
/// Returns the physical resolution of the display.
#[inline]
pub fn physical_resolution(&self) -> [u32; 2] {
let ref r = self.properties.physicalResolution;
[r.width, r.height]
}
/// Returns a list of all modes available on this display.
pub fn display_modes(&self) -> Result<IntoIter<DisplayMode>, OomError> {
let vk = self.device.instance().pointers();
let num = unsafe {
let mut num = 0;
try!(check_errors(vk.GetDisplayModePropertiesKHR(self.device.internal_object(),
self.properties.display,
&mut num, ptr::null_mut())));
num
};
let modes: Vec<vk::DisplayModePropertiesKHR> = unsafe {
let mut modes = Vec::with_capacity(num as usize);
let mut num = num;
try!(check_errors(vk.GetDisplayModePropertiesKHR(self.device.internal_object(),
self.properties.display, &mut num,
modes.as_mut_ptr())));
modes.set_len(num as usize);
modes
};
Ok(modes.into_iter().map(|mode| {
DisplayMode {
display: self.clone(),
display_mode: mode.displayMode,
parameters: mode.parameters,
}
}).collect::<Vec<_>>().into_iter())
}
}
unsafe impl VulkanObject for Display {
type Object = vk::DisplayKHR;
#[inline]
fn internal_object(&self) -> vk::DisplayKHR {
self.properties.display
}
}
/// Represents a mode on a specific display.
pub struct DisplayMode {
display: Display,
display_mode: vk::DisplayModeKHR,
parameters: vk::DisplayModeParametersKHR,
}
impl DisplayMode {
/*pub fn new(display: &Display) -> Result<Arc<DisplayMode>, OomError> {
let vk = instance.pointers();
let parameters = vk::DisplayModeParametersKHR {
visibleRegion: vk::Extent2D { width: , height: },
refreshRate: ,
};
let display_mode = {
let infos = vk::DisplayModeCreateInfoKHR {
sType: vk::STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR,
pNext: ptr::null(),
flags: 0, // reserved
parameters: parameters,
};
let mut output = mem::uninitialized();
try!(check_errors(vk.CreateDisplayModeKHR(display.device.internal_object(),
display.display, &infos, ptr::null(),
&mut output)));
output
};
Ok(Arc::new(DisplayMode {
instance: display.device.instance().clone(),
display_mode: display_mode,
parameters: ,
}))
}*/
/// Returns the display corresponding to this mode.
#[inline]
pub fn display(&self) -> &Display {
&self.display
}
/// Returns the dimensions of the region that is visible on the monitor.
#[inline]
pub fn visible_region(&self) -> [u32; 2] {
let ref d = self.parameters.visibleRegion;
[d.width, d.height]
}
/// Returns the refresh rate of this mode.
#[inline]
pub fn refresh_rate(&self) -> u32 {
self.parameters.refreshRate
}
}
|
use time::SteadyTime;
// Halo server is just an IP, port, and the time it last sent a packet.
pub struct HaloServer {
pub ip: String,
pub port: u16,
pub last_alive: SteadyTime
}
// This converts it to ip:port.
impl ToString for HaloServer {
fn to_string(&self) -> String {
return self.ip.clone() + ":" + &(self.port.to_string());
}
}
// Equality against a (ip: &str, port: u16) tuple
impl<'a> PartialEq<(&'a str, u16)> for HaloServer {
fn eq(&self, other: &(&'a str, u16)) -> bool {
let (ip, port) = *other;
self.ip == ip && self.port == port
}
}
Less hassle / possibly more efficient to use tuples .0/1
use time::SteadyTime;
// Halo server is just an IP, port, and the time it last sent a packet.
pub struct HaloServer {
pub ip: String,
pub port: u16,
pub last_alive: SteadyTime
}
// This converts it to ip:port.
impl ToString for HaloServer {
fn to_string(&self) -> String {
return self.ip.clone() + ":" + &(self.port.to_string());
}
}
// Equality against a (ip: &str, port: u16) tuple
impl<'a> PartialEq<(&'a str, u16)> for HaloServer {
fn eq(&self, other: &(&'a str, u16)) -> bool {
self.ip == other.0 && self.port == other.1
}
}
|
// * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <ben@beneills.com>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
mod mode;
#[macro_use]
extern crate uucore;
use clap::{crate_version, App, Arg, ArgMatches};
use file_diff::diff;
use filetime::{set_file_times, FileTime};
use uucore::backup_control::{self, BackupMode};
use uucore::entries::{grp2gid, usr2uid};
use uucore::perms::{wrap_chgrp, wrap_chown, Verbosity};
use libc::{getegid, geteuid};
use std::fs;
use std::fs::File;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
const DEFAULT_STRIP_PROGRAM: &str = "strip";
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
backup_mode: BackupMode,
suffix: String,
owner: String,
group: String,
verbose: bool,
preserve_timestamps: bool,
compare: bool,
strip: bool,
strip_program: String,
create_leading: bool,
target_dir: Option<String>,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction {
/// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_NO_ARG: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATE_LEADING: &str = "create-leading";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = uu_app().usage(&usage[..]).get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
pub fn uu_app() -> App<'static, 'static> {
App::new(executable!())
.version(crate_version!())
.about(ABOUT)
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("make a backup of each existing destination file")
.takes_value(true)
.require_equals(true)
.min_values(0)
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_NO_ARG)
.short("b")
.help("like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATE_LEADING)
.short("D")
.help("create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("set group ownership, instead of process's current group")
.value_name("GROUP")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("set ownership (super-user only)")
.value_name("OWNER")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("strip symbol tables (no action Windows)")
)
.arg(
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("program used to strip binaries (no action Windows)")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("override the usual backup suffix")
.value_name("SUFFIX")
.takes_value(true)
.min_values(1)
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true).min_values(1))
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present(OPT_DIRECTORY) {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
let x = matches.value_of(OPT_MODE).ok_or(1)?;
Some(mode::parse(x, considering_dir).map_err(|err| {
show_error!("Invalid mode string: {}", err);
1
})?)
} else {
None
};
let target_dir = matches.value_of(OPT_TARGET_DIRECTORY).map(|d| d.to_owned());
Ok(Behavior {
main_function,
specified_mode,
backup_mode: backup_control::determine_backup_mode(
matches.is_present(OPT_BACKUP_NO_ARG) || matches.is_present(OPT_BACKUP),
matches.value_of(OPT_BACKUP),
),
suffix: backup_control::determine_backup_suffix(matches.value_of(OPT_SUFFIX)),
owner: matches.value_of(OPT_OWNER).unwrap_or("").to_string(),
group: matches.value_of(OPT_GROUP).unwrap_or("").to_string(),
verbose: matches.is_present(OPT_VERBOSE),
preserve_timestamps: matches.is_present(OPT_PRESERVE_TIMESTAMPS),
compare: matches.is_present(OPT_COMPARE),
strip: matches.is_present(OPT_STRIP),
strip_program: String::from(
matches
.value_of(OPT_STRIP_PROGRAM)
.unwrap_or(DEFAULT_STRIP_PROGRAM),
),
create_leading: matches.is_present(OPT_CREATE_LEADING),
target_dir,
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for path in paths.iter().map(Path::new) {
// if the path already exist, don't try to create it again
if !path.exists() {
// Differently than the primary functionality (MainFunction::Standard), the directory
// functionality should create all ancestors (or components) of a directory regardless
// of the presence of the "-D" flag.
// NOTE: the GNU "install" sets the expected mode only for the target directory. All
// created ancestor directories will have the default mode. Hence it is safe to use
// fs::create_dir_all and then only modify the target's dir mode.
if let Err(e) = fs::create_dir_all(path) {
show_error!("{}: {}", path.display(), e);
all_successful = false;
continue;
}
if b.verbose {
show_error!("creating directory '{}'", path.display());
}
}
if mode::chmod(path, b.mode()).is_err() {
all_successful = false;
continue;
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(mut paths: Vec<String>, b: Behavior) -> i32 {
let target: PathBuf = b
.target_dir
.clone()
.unwrap_or_else(|| paths.pop().unwrap())
.into();
let sources = &paths.iter().map(PathBuf::from).collect::<Vec<_>>();
if sources.len() > 1 || (target.exists() && target.is_dir()) {
copy_files_into_dir(sources, &target, &b)
} else {
if let Some(parent) = target.parent() {
if !parent.exists() && b.create_leading {
if let Err(e) = fs::create_dir_all(parent) {
show_error!("failed to create {}: {}", parent.display(), e);
return 1;
}
if mode::chmod(parent, b.mode()).is_err() {
show_error!("failed to chmod {}", parent.display());
return 1;
}
}
}
if target.is_file() || is_new_file_path(&target) {
copy_file_to_file(&sources[0], &target, &b)
} else {
show_error!(
"invalid target {}: No such file or directory",
target.display()
);
1
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> i32 {
if !target_dir.is_dir() {
show_error!("target '{}' is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
if !sourcepath.exists() {
show_error!(
"cannot stat '{}': No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
if sourcepath.is_dir() {
show_error!("omitting directory '{}'", sourcepath.display());
all_successful = false;
continue;
}
let mut targetpath = target_dir.to_path_buf();
let filename = sourcepath.components().last().unwrap();
targetpath.push(filename);
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &Path, target: &Path, b: &Behavior) -> i32 {
if copy(file, target, b).is_err() {
1
} else {
0
}
}
/// Copy one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
#[allow(clippy::cognitive_complexity)]
fn copy(from: &Path, to: &Path, b: &Behavior) -> Result<(), ()> {
if b.compare && !need_copy(from, to, b) {
return Ok(());
}
// Declare the path here as we may need it for the verbose output below.
let mut backup_path = None;
// Perform backup, if any, before overwriting 'to'
//
// The codes actually making use of the backup process don't seem to agree
// on how best to approach the issue. (mv and ln, for example)
if to.exists() {
backup_path = backup_control::get_backup_path(b.backup_mode, to, &b.suffix);
if let Some(ref backup_path) = backup_path {
// TODO!!
if let Err(err) = fs::rename(to, backup_path) {
show_error!(
"install: cannot backup file '{}' to '{}': {}",
to.display(),
backup_path.display(),
err
);
return Err(());
}
}
}
if from.to_string_lossy() == "/dev/null" {
/* workaround a limitation of fs::copy
* https://github.com/rust-lang/rust/issues/79390
*/
if let Err(err) = File::create(to) {
show_error!(
"install: cannot install '{}' to '{}': {}",
from.display(),
to.display(),
err
);
return Err(());
}
} else if let Err(err) = fs::copy(from, to) {
show_error!(
"cannot install '{}' to '{}': {}",
from.display(),
to.display(),
err
);
return Err(());
}
if b.strip && cfg!(not(windows)) {
match Command::new(&b.strip_program).arg(to).output() {
Ok(o) => {
if !o.status.success() {
crash!(
1,
"strip program failed: {}",
String::from_utf8(o.stderr).unwrap_or_default()
);
}
}
Err(e) => crash!(1, "strip program execution failed: {}", e),
}
}
if mode::chmod(to, b.mode()).is_err() {
return Err(());
}
if !b.owner.is_empty() {
let meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let owner_id = match usr2uid(&b.owner) {
Ok(g) => g,
_ => crash!(1, "no such user: {}", b.owner),
};
let gid = meta.gid();
match wrap_chown(
to,
&meta,
Some(owner_id),
Some(gid),
false,
Verbosity::Normal,
) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
}
}
Err(e) => show_error!("{}", e),
}
}
if !b.group.is_empty() {
let meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let group_id = match grp2gid(&b.group) {
Ok(g) => g,
_ => crash!(1, "no such group: {}", b.group),
};
match wrap_chgrp(to, &meta, group_id, false, Verbosity::Normal) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
}
}
Err(e) => show_error!("{}", e),
}
}
if b.preserve_timestamps {
let meta = match fs::metadata(from) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let modified_time = FileTime::from_last_modification_time(&meta);
let accessed_time = FileTime::from_last_access_time(&meta);
match set_file_times(to, accessed_time, modified_time) {
Ok(_) => {}
Err(e) => show_error!("{}", e),
}
}
if b.verbose {
print!("'{}' -> '{}'", from.display(), to.display());
match backup_path {
Some(path) => println!(" (backup: '{}')", path.display()),
None => println!(),
}
}
Ok(())
}
/// Return true if a file is necessary to copy. This is the case when:
/// - _from_ or _to_ is nonexistent;
/// - either file has a sticky bit or set[ug]id bit, or the user specified one;
/// - either file isn't a regular file;
/// - the sizes of _from_ and _to_ differ;
/// - _to_'s owner differs from intended; or
/// - the contents of _from_ and _to_ differ.
///
/// # Parameters
///
/// _from_ and _to_, if existent, must be non-directories.
///
/// # Errors
///
/// Crashes the program if a nonexistent owner or group is specified in _b_.
///
fn need_copy(from: &Path, to: &Path, b: &Behavior) -> bool {
let from_meta = match fs::metadata(from) {
Ok(meta) => meta,
Err(_) => return true,
};
let to_meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(_) => return true,
};
// setuid || setgid || sticky
let extra_mode: u32 = 0o7000;
if b.specified_mode.unwrap_or(0) & extra_mode != 0
|| from_meta.mode() & extra_mode != 0
|| to_meta.mode() & extra_mode != 0
{
return true;
}
if !from_meta.is_file() || !to_meta.is_file() {
return true;
}
if from_meta.len() != to_meta.len() {
return true;
}
// TODO: if -P (#1809) and from/to contexts mismatch, return true.
if !b.owner.is_empty() {
let owner_id = match usr2uid(&b.owner) {
Ok(id) => id,
_ => crash!(1, "no such user: {}", b.owner),
};
if owner_id != to_meta.uid() {
return true;
}
} else if !b.group.is_empty() {
let group_id = match grp2gid(&b.group) {
Ok(id) => id,
_ => crash!(1, "no such group: {}", b.group),
};
if group_id != to_meta.gid() {
return true;
}
} else {
#[cfg(not(target_os = "windows"))]
unsafe {
if to_meta.uid() != geteuid() || to_meta.gid() != getegid() {
return true;
}
}
}
if !diff(from.to_str().unwrap(), to.to_str().unwrap()) {
return true;
}
false
}
install: Adapt to modified backup mode determination
// * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <ben@beneills.com>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
mod mode;
#[macro_use]
extern crate uucore;
use clap::{crate_version, App, Arg, ArgMatches};
use file_diff::diff;
use filetime::{set_file_times, FileTime};
use uucore::backup_control::{self, BackupMode};
use uucore::entries::{grp2gid, usr2uid};
use uucore::perms::{wrap_chgrp, wrap_chown, Verbosity};
use libc::{getegid, geteuid};
use std::fs;
use std::fs::File;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
const DEFAULT_STRIP_PROGRAM: &str = "strip";
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
backup_mode: BackupMode,
suffix: String,
owner: String,
group: String,
verbose: bool,
preserve_timestamps: bool,
compare: bool,
strip: bool,
strip_program: String,
create_leading: bool,
target_dir: Option<String>,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction {
/// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_NO_ARG: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATE_LEADING: &str = "create-leading";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = uu_app().usage(&usage[..]).get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
pub fn uu_app() -> App<'static, 'static> {
App::new(executable!())
.version(crate_version!())
.about(ABOUT)
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("make a backup of each existing destination file")
.takes_value(true)
.require_equals(true)
.min_values(0)
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_NO_ARG)
.short("b")
.help("like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATE_LEADING)
.short("D")
.help("create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("set group ownership, instead of process's current group")
.value_name("GROUP")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("set ownership (super-user only)")
.value_name("OWNER")
.takes_value(true)
)
.arg(
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("strip symbol tables (no action Windows)")
)
.arg(
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("program used to strip binaries (no action Windows)")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("override the usual backup suffix")
.value_name("SUFFIX")
.takes_value(true)
.min_values(1)
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true).min_values(1))
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present(OPT_DIRECTORY) {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
let x = matches.value_of(OPT_MODE).ok_or(1)?;
Some(mode::parse(x, considering_dir).map_err(|err| {
show_error!("Invalid mode string: {}", err);
1
})?)
} else {
None
};
let backup_mode = backup_control::determine_backup_mode(
matches.is_present(OPT_BACKUP_NO_ARG),
matches.is_present(OPT_BACKUP),
matches.value_of(OPT_BACKUP),
);
let backup_mode = match backup_mode {
Err(err) => {
show_usage_error!("{}", err);
return Err(1);
}
Ok(mode) => mode,
};
let target_dir = matches.value_of(OPT_TARGET_DIRECTORY).map(|d| d.to_owned());
Ok(Behavior {
main_function,
specified_mode,
backup_mode,
suffix: backup_control::determine_backup_suffix(matches.value_of(OPT_SUFFIX)),
owner: matches.value_of(OPT_OWNER).unwrap_or("").to_string(),
group: matches.value_of(OPT_GROUP).unwrap_or("").to_string(),
verbose: matches.is_present(OPT_VERBOSE),
preserve_timestamps: matches.is_present(OPT_PRESERVE_TIMESTAMPS),
compare: matches.is_present(OPT_COMPARE),
strip: matches.is_present(OPT_STRIP),
strip_program: String::from(
matches
.value_of(OPT_STRIP_PROGRAM)
.unwrap_or(DEFAULT_STRIP_PROGRAM),
),
create_leading: matches.is_present(OPT_CREATE_LEADING),
target_dir,
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for path in paths.iter().map(Path::new) {
// if the path already exist, don't try to create it again
if !path.exists() {
// Differently than the primary functionality (MainFunction::Standard), the directory
// functionality should create all ancestors (or components) of a directory regardless
// of the presence of the "-D" flag.
// NOTE: the GNU "install" sets the expected mode only for the target directory. All
// created ancestor directories will have the default mode. Hence it is safe to use
// fs::create_dir_all and then only modify the target's dir mode.
if let Err(e) = fs::create_dir_all(path) {
show_error!("{}: {}", path.display(), e);
all_successful = false;
continue;
}
if b.verbose {
show_error!("creating directory '{}'", path.display());
}
}
if mode::chmod(path, b.mode()).is_err() {
all_successful = false;
continue;
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(mut paths: Vec<String>, b: Behavior) -> i32 {
let target: PathBuf = b
.target_dir
.clone()
.unwrap_or_else(|| paths.pop().unwrap())
.into();
let sources = &paths.iter().map(PathBuf::from).collect::<Vec<_>>();
if sources.len() > 1 || (target.exists() && target.is_dir()) {
copy_files_into_dir(sources, &target, &b)
} else {
if let Some(parent) = target.parent() {
if !parent.exists() && b.create_leading {
if let Err(e) = fs::create_dir_all(parent) {
show_error!("failed to create {}: {}", parent.display(), e);
return 1;
}
if mode::chmod(parent, b.mode()).is_err() {
show_error!("failed to chmod {}", parent.display());
return 1;
}
}
}
if target.is_file() || is_new_file_path(&target) {
copy_file_to_file(&sources[0], &target, &b)
} else {
show_error!(
"invalid target {}: No such file or directory",
target.display()
);
1
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> i32 {
if !target_dir.is_dir() {
show_error!("target '{}' is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
if !sourcepath.exists() {
show_error!(
"cannot stat '{}': No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
if sourcepath.is_dir() {
show_error!("omitting directory '{}'", sourcepath.display());
all_successful = false;
continue;
}
let mut targetpath = target_dir.to_path_buf();
let filename = sourcepath.components().last().unwrap();
targetpath.push(filename);
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &Path, target: &Path, b: &Behavior) -> i32 {
if copy(file, target, b).is_err() {
1
} else {
0
}
}
/// Copy one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
#[allow(clippy::cognitive_complexity)]
fn copy(from: &Path, to: &Path, b: &Behavior) -> Result<(), ()> {
if b.compare && !need_copy(from, to, b) {
return Ok(());
}
// Declare the path here as we may need it for the verbose output below.
let mut backup_path = None;
// Perform backup, if any, before overwriting 'to'
//
// The codes actually making use of the backup process don't seem to agree
// on how best to approach the issue. (mv and ln, for example)
if to.exists() {
backup_path = backup_control::get_backup_path(b.backup_mode, to, &b.suffix);
if let Some(ref backup_path) = backup_path {
// TODO!!
if let Err(err) = fs::rename(to, backup_path) {
show_error!(
"install: cannot backup file '{}' to '{}': {}",
to.display(),
backup_path.display(),
err
);
return Err(());
}
}
}
if from.to_string_lossy() == "/dev/null" {
/* workaround a limitation of fs::copy
* https://github.com/rust-lang/rust/issues/79390
*/
if let Err(err) = File::create(to) {
show_error!(
"install: cannot install '{}' to '{}': {}",
from.display(),
to.display(),
err
);
return Err(());
}
} else if let Err(err) = fs::copy(from, to) {
show_error!(
"cannot install '{}' to '{}': {}",
from.display(),
to.display(),
err
);
return Err(());
}
if b.strip && cfg!(not(windows)) {
match Command::new(&b.strip_program).arg(to).output() {
Ok(o) => {
if !o.status.success() {
crash!(
1,
"strip program failed: {}",
String::from_utf8(o.stderr).unwrap_or_default()
);
}
}
Err(e) => crash!(1, "strip program execution failed: {}", e),
}
}
if mode::chmod(to, b.mode()).is_err() {
return Err(());
}
if !b.owner.is_empty() {
let meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let owner_id = match usr2uid(&b.owner) {
Ok(g) => g,
_ => crash!(1, "no such user: {}", b.owner),
};
let gid = meta.gid();
match wrap_chown(
to,
&meta,
Some(owner_id),
Some(gid),
false,
Verbosity::Normal,
) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
}
}
Err(e) => show_error!("{}", e),
}
}
if !b.group.is_empty() {
let meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let group_id = match grp2gid(&b.group) {
Ok(g) => g,
_ => crash!(1, "no such group: {}", b.group),
};
match wrap_chgrp(to, &meta, group_id, false, Verbosity::Normal) {
Ok(n) => {
if !n.is_empty() {
show_error!("{}", n);
}
}
Err(e) => show_error!("{}", e),
}
}
if b.preserve_timestamps {
let meta = match fs::metadata(from) {
Ok(meta) => meta,
Err(f) => crash!(1, "{}", f.to_string()),
};
let modified_time = FileTime::from_last_modification_time(&meta);
let accessed_time = FileTime::from_last_access_time(&meta);
match set_file_times(to, accessed_time, modified_time) {
Ok(_) => {}
Err(e) => show_error!("{}", e),
}
}
if b.verbose {
print!("'{}' -> '{}'", from.display(), to.display());
match backup_path {
Some(path) => println!(" (backup: '{}')", path.display()),
None => println!(),
}
}
Ok(())
}
/// Return true if a file is necessary to copy. This is the case when:
/// - _from_ or _to_ is nonexistent;
/// - either file has a sticky bit or set[ug]id bit, or the user specified one;
/// - either file isn't a regular file;
/// - the sizes of _from_ and _to_ differ;
/// - _to_'s owner differs from intended; or
/// - the contents of _from_ and _to_ differ.
///
/// # Parameters
///
/// _from_ and _to_, if existent, must be non-directories.
///
/// # Errors
///
/// Crashes the program if a nonexistent owner or group is specified in _b_.
///
fn need_copy(from: &Path, to: &Path, b: &Behavior) -> bool {
let from_meta = match fs::metadata(from) {
Ok(meta) => meta,
Err(_) => return true,
};
let to_meta = match fs::metadata(to) {
Ok(meta) => meta,
Err(_) => return true,
};
// setuid || setgid || sticky
let extra_mode: u32 = 0o7000;
if b.specified_mode.unwrap_or(0) & extra_mode != 0
|| from_meta.mode() & extra_mode != 0
|| to_meta.mode() & extra_mode != 0
{
return true;
}
if !from_meta.is_file() || !to_meta.is_file() {
return true;
}
if from_meta.len() != to_meta.len() {
return true;
}
// TODO: if -P (#1809) and from/to contexts mismatch, return true.
if !b.owner.is_empty() {
let owner_id = match usr2uid(&b.owner) {
Ok(id) => id,
_ => crash!(1, "no such user: {}", b.owner),
};
if owner_id != to_meta.uid() {
return true;
}
} else if !b.group.is_empty() {
let group_id = match grp2gid(&b.group) {
Ok(id) => id,
_ => crash!(1, "no such group: {}", b.group),
};
if group_id != to_meta.gid() {
return true;
}
} else {
#[cfg(not(target_os = "windows"))]
unsafe {
if to_meta.uid() != geteuid() || to_meta.gid() != getegid() {
return true;
}
}
}
if !diff(from.to_str().unwrap(), to.to_str().unwrap()) {
return true;
}
false
}
|
extern crate x11;
extern crate libc;
use std::ffi;
use std::process::Command;
use std::boxed::Box;
use x11::xlib;
use super::WindowManager;
use super::workspace::Workspaces;
use super::layout;
#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
pub key: u64,
pub mask: u32,
}
impl KeyBind {
pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
let mut mask = 0;
let mut sym = 0;
for key in tokens {
match *key {
"$mod" => mask = mask | mod_key,
"Shift" => mask = mask | xlib::ShiftMask,
"Ctrl" => mask = mask | xlib::ControlMask,
"Mod1" => mask = mask | xlib::Mod1Mask,
"Mod2" => mask = mask | xlib::Mod2Mask,
"Mod3" => mask = mask | xlib::Mod3Mask,
"Mod4" => mask = mask | xlib::Mod4Mask,
"Mod5" => mask = mask | xlib::Mod5Mask,
_ => {
let tmp = ffi::CString::new(*key).unwrap();
unsafe{
sym = xlib::XStringToKeysym(tmp.as_ptr());
}
}
}
}
println!("bind {} {}", mask, sym);
KeyBind {
mask: mask,
key: sym
}
}
}
pub trait Handler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int);
}
pub struct ExecHandler {
pub cmd: Command
}
pub struct LayoutHandler {
layout_type: layout::Type,
}
/// switch to another workspace
pub struct WorkspaceHandler {
pub key: char,
}
impl Handler for WorkspaceHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
debug!("handle workspace");
workspaces.switch_current(self.key, display);
}
}
impl Handler for ExecHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
debug!("handle exec");
self.cmd.spawn();
}
}
impl Handler for LayoutHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
debug!("handle layout");
let current = workspaces.current();
let t = self.layout_type.clone();
current.change_layout(t);
current.config(display, screen_num);
}
}
impl LayoutHandler {
pub fn new(layout: layout::Type) -> LayoutHandler{
LayoutHandler {
layout_type: layout
}
}
}
impl ExecHandler {
pub fn new(tokens: &[&str]) -> ExecHandler {
let (name, args) = tokens.split_at(1);
let mut cmd = Command::new(name[0]);
for arg in args {
println!("{}", arg);
cmd.arg(arg);
}
let handler = ExecHandler {
cmd: cmd,
};
handler
}
}
use Window, Display
extern crate x11;
extern crate libc;
use std::ffi;
use std::process::Command;
use std::boxed::Box;
use x11::xlib;
use x11::xlib::{ Display, Window };
use super::WindowManager;
use super::workspace::Workspaces;
use super::layout;
#[derive(Hash, Eq, PartialEq, Debug)]
pub struct KeyBind {
pub key: u64,
pub mask: u32,
}
impl KeyBind {
pub fn build(mod_key: u32, tokens: &[&str]) -> KeyBind {
let mut mask = 0;
let mut sym = 0;
for key in tokens {
match *key {
"$mod" => mask = mask | mod_key,
"Shift" => mask = mask | xlib::ShiftMask,
"Ctrl" => mask = mask | xlib::ControlMask,
"Mod1" => mask = mask | xlib::Mod1Mask,
"Mod2" => mask = mask | xlib::Mod2Mask,
"Mod3" => mask = mask | xlib::Mod3Mask,
"Mod4" => mask = mask | xlib::Mod4Mask,
"Mod5" => mask = mask | xlib::Mod5Mask,
_ => {
let tmp = ffi::CString::new(*key).unwrap();
unsafe{
sym = xlib::XStringToKeysym(tmp.as_ptr());
}
}
}
}
println!("bind {} {}", mask, sym);
KeyBind {
mask: mask,
key: sym
}
}
}
pub trait Handler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int);
}
pub struct ExecHandler {
pub cmd: Command
}
pub struct LayoutHandler {
layout_type: layout::Type,
}
/// switch to another workspace
pub struct WorkspaceHandler {
pub key: char,
}
impl Handler for WorkspaceHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
debug!("handle workspace");
workspaces.switch_current(self.key, display);
}
}
impl Handler for ExecHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut Display, screen_num: libc::c_int) {
debug!("handle exec");
self.cmd.spawn();
}
}
impl Handler for LayoutHandler {
fn handle(&mut self, workspaces: &mut Workspaces, display: *mut xlib::Display, screen_num: libc::c_int) {
debug!("handle layout");
let current = workspaces.current();
let t = self.layout_type.clone();
current.change_layout(t);
current.config(display, screen_num);
}
}
impl LayoutHandler {
pub fn new(layout: layout::Type) -> LayoutHandler{
LayoutHandler {
layout_type: layout
}
}
}
impl ExecHandler {
pub fn new(tokens: &[&str]) -> ExecHandler {
let (name, args) = tokens.split_at(1);
let mut cmd = Command::new(name[0]);
for arg in args {
println!("{}", arg);
cmd.arg(arg);
}
let handler = ExecHandler {
cmd: cmd,
};
handler
}
}
|
extern crate common;
extern crate rand;
use common::*;
use common::Projection::*;
use common::Turn::*;
use common::Value::*;
use common::PiecesLeft::*;
use common::Highlighted::*;
use common::Participant::*;
use std::default::Default;
use rand::{Rng, SeedableRng, StdRng};
use std::collections::hash_map::Entry::Occupied;
#[cfg(debug_assertions)]
#[no_mangle]
pub fn new_state() -> State {
println!("debug on");
let seed: &[_] = &[42];
let rng: StdRng = SeedableRng::from_seed(seed);
make_state(rng)
}
#[cfg(not(debug_assertions))]
#[no_mangle]
pub fn new_state() -> State {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|dur| dur.as_secs())
.unwrap_or(42);
println!("{}", timestamp);
let seed: &[_] = &[timestamp as usize];
let rng: StdRng = SeedableRng::from_seed(seed);
make_state(rng)
}
fn deal(state: &mut State) -> Option<Card> {
deal_parts(&mut state.deck, &mut state.pile, &mut state.rng)
}
fn deal_parts(deck: &mut Vec<Card>, pile: &mut Vec<Card>, rng: &mut StdRng) -> Option<Card> {
//reshuffle if we run out of cards.
if deck.len() == 0 {
if cfg!(debug_assertions) {
println!("reshuffle");
}
if pile.len() == 0 {
if cfg!(debug_assertions) {
println!("========= empty pile");
}
return None;
}
for card in pile.drain(..) {
deck.push(card);
}
rng.shuffle(deck.as_mut_slice());
};
deck.pop()
}
fn make_state(mut rng: StdRng) -> State {
let mut deck = Card::all_values();
rng.shuffle(deck.as_mut_slice());
debug_assert!(deck.len() > MAX_PLAYERS * 3, "Not enough cards!");
let cpu_players_count = rng.gen_range(1, MAX_PLAYERS);
let mut pile = Vec::new();
let player_hand;
let mut cpu_hands;
{
let deck_ref = &mut deck;
let pile_ref = &mut pile;
let rng_ref = &mut rng;
player_hand = vec![
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
];
cpu_hands = Vec::new();
for _ in 0..cpu_players_count {
cpu_hands.push(vec![
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
]);
}
}
let mut colour_deck = PieceColour::all_values();
rng.shuffle(colour_deck.as_mut_slice());
debug_assert!(
colour_deck.len() >= MAX_PLAYERS,
"Not enough piece colours!"
);
let player_stash = Stash::full(colour_deck.pop().unwrap());
let mut cpu_stashes = Vec::new();
for _ in 0..cpu_players_count {
cpu_stashes.push(Stash::full(colour_deck.pop().unwrap()));
}
let state = State {
rng,
cam_x: 0.0,
cam_y: 0.0,
zoom: f32::powi(1.25, 8),
board: HashMap::new(),
mouse_pos: (400.0, 300.0),
window_wh: (INITIAL_WINDOW_WIDTH as _, INITIAL_WINDOW_HEIGHT as _),
ui_context: UIContext::new(),
mouse_held: false,
turn: DrawUntilNumberCard,
deck,
pile: Vec::new(),
player_hand,
cpu_hands,
stashes: Stashes {
player_stash,
cpu_stashes,
},
hud_alpha: 1.0,
highlighted: PlayerOccupation,
message: Default::default(),
};
state
}
#[derive(Debug)]
enum Action {
SelectPiece((i8, i8), usize),
SelectSpace((i8, i8)),
PageBack((i8, i8)),
PageForward((i8, i8)),
SelectCardFromHand(usize),
NoAction,
}
use Action::*;
const FADE_RATE: f32 = 1.0 / 24.0;
const TRANSLATION_SCALE: f32 = 0.0625;
#[no_mangle]
//returns true if quit requested
pub fn update_and_render(p: &Platform, state: &mut State, events: &mut Vec<Event>) -> bool {
let mut mouse_pressed = false;
let mut mouse_released = false;
let mut right_mouse_pressed = false;
//let mut right_mouse_released = false;
let mut escape_pressed = false;
for event in events {
if cfg!(debug_assertions) {
match *event {
Event::MouseMove(_) => {}
_ => println!("{:?}", *event),
}
}
match *event {
Event::Quit | Event::KeyDown(Keycode::F10) => {
return true;
}
Event::KeyDown(Keycode::Escape) => {
escape_pressed = true;
}
Event::KeyDown(Keycode::Space) => if cfg!(debug_assertions) {
add_random_board_card(state);
},
Event::KeyDown(Keycode::R) => if cfg!(debug_assertions) {
state.board.clear();
},
Event::KeyDown(Keycode::C) => if cfg!(debug_assertions) {
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
},
Event::KeyDown(Keycode::V) => if cfg!(debug_assertions) {
(p.set_verts)(get_vert_vecs());
},
Event::KeyDown(Keycode::M) => if cfg!(debug_assertions) {
state.message = Message {
text: "Test Message".to_owned(),
timeout: 1500,
}
},
Event::KeyDown(Keycode::Up) => {
state.cam_y += state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Down) => {
state.cam_y -= state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Right) => {
state.cam_x += state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Left) => {
state.cam_x -= state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Num0) => {
state.cam_x = 0.0;
state.cam_y = 0.0;
state.zoom = 1.0;
}
Event::KeyDown(Keycode::W) => {
state.zoom *= 1.25;
}
Event::KeyDown(Keycode::S) => {
state.zoom /= 1.25;
if state.zoom == 0.0 {
state.zoom = std::f32::MIN_POSITIVE / TRANSLATION_SCALE;
}
}
Event::MouseMove((x, y)) => {
state.mouse_pos = (x as f32, y as f32);
}
Event::LeftMouseDown => {
mouse_pressed = true;
}
Event::LeftMouseUp => {
mouse_released = true;
}
Event::RightMouseDown => {
right_mouse_pressed = true;
}
Event::RightMouseUp => {
//right_mouse_released = true;
}
Event::WindowSize((w, h)) => {
state.window_wh = (w as f32, h as f32);
println!("{}", state.window_wh.0 / state.window_wh.1);
}
_ => {}
}
}
if mouse_released != mouse_pressed {
if mouse_released {
state.mouse_held = false;
} else {
state.mouse_held = true;
}
}
let mouse_button_state = ButtonState {
pressed: mouse_pressed,
released: mouse_released,
held: state.mouse_held,
};
state.ui_context.frame_init();
state.hud_alpha += if state.mouse_pos.1 / state.window_wh.1 > HUD_LINE {
FADE_RATE
} else {
-FADE_RATE
};
state.hud_alpha = clamp(state.hud_alpha, 0.0, 1.0);
let aspect_ratio = state.window_wh.0 / state.window_wh.1;
let mouse_x = center((state.mouse_pos.0) / state.window_wh.0);
let mouse_y = -center(((state.mouse_pos.1) / state.window_wh.1));
let (view, inverse_view) = {
let near = 0.5;
let far = 1024.0;
let scale = state.zoom * near;
let top = scale;
let bottom = -top;
let right = aspect_ratio * scale;
let left = -right;
let projection = get_projection(&ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: Perspective,
// projection: Orthographic,
});
let inverse_projection = get_projection(&ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: InversePerspective,
// projection: InverseOrthographic,
});
let camera = scale_translation(1.0, state.cam_x, state.cam_y);
let inverse_camera = inverse_scale_translation(1.0, state.cam_x, state.cam_y);
let view = mat4x4_mul(&camera, &projection);
let inverse_view = mat4x4_mul(&inverse_projection, &inverse_camera);
(view, inverse_view)
};
let (world_mouse_x, world_mouse_y, _, _) =
mat4x4_vector_mul_divide(&inverse_view, mouse_x, mouse_y, 0.0, 1.0);
let mut action = NoAction;
for (
grid_coords,
&Space {
card,
ref pieces,
offset: space_offset,
},
) in state.board.iter()
{
let (card_x, card_y, rotated) = get_card_spec(grid_coords);
let card_matrix = get_card_matrix(&view, (card_x, card_y, rotated));
let card_id = card_id(*grid_coords);
let mut card_texture_spec = card.texture_spec();
let (card_mouse_x, card_mouse_y) = (world_mouse_x - card_x, world_mouse_y - card_y);
let on_card = if rotated {
(card_mouse_x).abs() <= 1.0 && (card_mouse_y).abs() <= CARD_RATIO
} else {
(card_mouse_x).abs() <= CARD_RATIO && (card_mouse_y).abs() <= 1.0
};
let button_outcome = button_logic(
&mut state.ui_context,
Button {
id: card_id,
pointer_inside: on_card,
state: mouse_button_state,
},
);
if button_outcome.clicked {
action = SelectSpace(grid_coords.clone());
} else {
let highlight = if let MoveSelect(piece_pickup_coords, _, _) = state.turn {
let valid_targets = get_valid_move_targets(&state.board, piece_pickup_coords);
valid_targets.contains(&grid_coords)
} else {
match state.highlighted {
PlayerOccupation => {
is_occupied_by(&state.board, grid_coords, state.stashes.player_stash.colour)
}
NoHighlighting => false,
}
};
match (button_outcome.draw_state, highlight) {
(_, true) | (Hover, _) => {
card_texture_spec.5 = -0.5;
card_texture_spec.7 = -0.5;
}
(Pressed, false) => {
card_texture_spec.5 = -0.5;
card_texture_spec.6 = -0.5;
}
_ => {}
}
draw_card(p, card_matrix, card_texture_spec);
}
for (i, piece) in pieces.into_iter().enumerate() {
if i < space_offset as _ || i > (space_offset + PIECES_PER_PAGE - 1) as _ {
continue;
}
let (x, y) = card_relative_piece_coords(i);
let half_piece_scale = piece_scale(piece);
debug_assert!(i <= 255);
let piece_id = piece_id(card_id, i as u8);
let mut piece_texture_spec = piece_texture_spec(piece);
let on_piece = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(x, y),
half_piece_scale,
rotated,
);
let button_outcome = match state.turn {
Move | Grow | ConvertSlashDemolish => button_logic(
&mut state.ui_context,
Button {
id: piece_id,
pointer_inside: on_piece,
state: mouse_button_state,
},
),
_ => Default::default(),
};
if button_outcome.clicked {
action = SelectPiece(grid_coords.clone(), i);
} else {
match button_outcome.draw_state {
Pressed => {
piece_texture_spec.5 = 1.5;
piece_texture_spec.6 = 1.5;
piece_texture_spec.7 = 1.5;
}
Hover => {
piece_texture_spec.5 = -1.5;
piece_texture_spec.6 = -1.5;
piece_texture_spec.7 = -1.5;
}
Inactive => {}
}
draw_piece(p, card_matrix, piece, x, y, piece_texture_spec);
};
}
if pieces.len() > PIECES_PER_PAGE as _ {
let scale = 0.125;
let x_offset_amount = 15.0 / 32.0;
let y_offset_amount = (ARROW_SIZE + 2.5) / (T_S * scale);
let forward_x = CARD_RATIO - x_offset_amount;
let forward_y = -(1.0 - y_offset_amount);
let forward_arrow_matrix = mat4x4_mul(
&scale_translation(scale, forward_x, forward_y),
&card_matrix,
);
let mut forward_arrow_texture_spec = (
420.0 / T_S,
895.0 / T_S,
ARROW_SIZE / T_S,
ARROW_SIZE / T_S,
0,
0.0,
0.0,
0.0,
0.0,
);
let mut backward_arrow_texture_spec = forward_arrow_texture_spec.clone();
if pieces.len() > (space_offset * PIECES_PER_PAGE) as _ {
let on_forward = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(forward_x, forward_y),
scale,
rotated,
);
let forward_button_outcome = button_logic(
&mut state.ui_context,
Button {
id: arrow_id(card_id, true),
pointer_inside: on_forward,
state: mouse_button_state,
},
);
if forward_button_outcome.clicked {
action = PageForward(*grid_coords);
} else {
match forward_button_outcome.draw_state {
Pressed => {
forward_arrow_texture_spec.5 = 1.5;
forward_arrow_texture_spec.6 = 1.5;
}
Hover => {
forward_arrow_texture_spec.5 = -1.5;
forward_arrow_texture_spec.7 = -1.5;
}
Inactive => {}
}
};
(p.draw_textured_poly_with_matrix)(
forward_arrow_matrix,
SQUARE_POLY_INDEX,
forward_arrow_texture_spec,
0,
);
}
if space_offset > 0 {
let backward_x = -CARD_RATIO + x_offset_amount;
let backward_y = forward_y;
let mut backward_camera_matrix = scale_translation(-scale, backward_x, backward_y);
backward_camera_matrix[5] *= -1.0;
let backward_arrow_matrix = mat4x4_mul(&backward_camera_matrix, &card_matrix);
let on_backward = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(backward_x, backward_y),
scale,
rotated,
);
let backward_button_outcome = button_logic(
&mut state.ui_context,
Button {
id: arrow_id(card_id, false),
pointer_inside: on_backward,
state: mouse_button_state,
},
);
if backward_button_outcome.clicked {
action = PageBack(*grid_coords);
} else {
match backward_button_outcome.draw_state {
Pressed => {
backward_arrow_texture_spec.5 = 1.5;
backward_arrow_texture_spec.6 = 1.5;
}
Hover => {
backward_arrow_texture_spec.5 = -1.5;
backward_arrow_texture_spec.7 = -1.5;
}
Inactive => {}
}
};
(p.draw_textured_poly_with_matrix)(
backward_arrow_matrix,
SQUARE_POLY_INDEX,
backward_arrow_texture_spec,
0,
);
}
}
}
if state.turn == SelectTurnOption {
let top_row = [
(DrawThree, "Draw"),
(Grow, "Grow"),
(Spawn, "Spawn"),
(Build, "Build"),
];
let top_row_len = top_row.len();
for i in 0..top_row_len {
let (target_turn, label) = top_row[i];
if turn_options_button(
p,
&mut state.ui_context,
label,
(-0.75 + i as f32 * 0.5, 0.875),
(600 + i) as _,
(mouse_x, mouse_y),
mouse_button_state,
) {
state.turn = target_turn;
};
}
let bottom_row = [
(Move, "Move"),
(ConvertSlashDemolish, "Convert/Demolish"),
(Fly, "Fly"),
(Hatch, "Hatch"),
];
for i in 0..bottom_row.len() {
let (target_turn, label) = bottom_row[i];
if turn_options_button(
p,
&mut state.ui_context,
label,
(-0.75 + i as f32 * 0.5, 11.0 / 16.0),
(600 + top_row_len + i) as _,
(mouse_x, mouse_y),
mouse_button_state,
) {
if target_turn == ConvertSlashDemolish {
state.message = Message {
text: "Choose a piece to target.".to_owned(),
timeout: WARNING_TIMEOUT,
};
} else if target_turn == Fly {
state.message = Message {
text: "Choose an Ace from your hand to discard.".to_owned(),
timeout: WARNING_TIMEOUT,
};
}
state.turn = target_turn;
};
}
}
match draw_hud(
p,
state,
aspect_ratio,
(mouse_x, mouse_y),
mouse_button_state,
) {
NoAction => {}
otherwise => {
action = otherwise;
}
};
match action {
PageBack(space_coords) => if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.offset = space.offset.saturating_sub(PIECES_PER_PAGE);
},
PageForward(space_coords) => if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.offset = space.offset.saturating_add(PIECES_PER_PAGE);
},
_ => {}
}
if cfg!(debug_assertions) {
match action {
NoAction => {}
_ => {
println!("{:?}", action);
}
}
}
{
let power_blocks = power_blocks(&state.board);
// There is a way to have two winners: A player can move
// a piece from a contesed area to another whihc gives them a power block,
//while also leaving the contested block to another player.
//AFAICT that is the maximum possble though.
let mut winners = (None, None);
for block in power_blocks {
if let Some(controller) = single_controller(&state.stashes, &state.board, block) {
winners = match winners {
(None, None) => (Some(controller), None),
(Some(winner), _) | (_, Some(winner)) if winner == controller => winners,
(Some(_), Some(second_winner)) => {
debug_assert!(second_winner == controller, "Three winners?!");
winners
}
(Some(winner), None) => (Some(winner), Some(controller)),
(None, Some(mistake)) => (None, Some(mistake)),
};
}
}
if let Some(winner) = winners.0 {
state.turn = if winners.1 == Some(Player) {
//player gets top billing
Over(Player, Some(winner))
} else {
Over(winner, winners.1)
};
}
}
let t = state.turn;
match state.turn {
DrawUntilNumberCard => {
if !state.player_hand.iter().any(|c| c.is_number()) {
state.turn = RevealHand(Player);
} else {
for i in 0..state.cpu_hands.len() {
let hand = &state.cpu_hands[i];
if !hand.iter().any(|c| c.is_number()) {
state.turn = RevealHand(Cpu(i));
break;
}
}
}
if let DrawUntilNumberCard = state.turn {
state.turn = WhoStarts;
}
}
RevealHand(participant) => {
{
let hand = match participant {
Player => &state.player_hand,
Cpu(i) => &state.cpu_hands[i],
};
let card_scale = 1.0;
let half_hand_len = (hand.len() / 2) as isize;
for (i, card) in hand.iter().enumerate() {
let (card_x, card_y) = ((i as isize - half_hand_len) as f32 / 2.0, 0.0);
let hand_camera_matrix = [
card_scale,
0.0,
0.0,
0.0,
0.0,
card_scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
let card_matrix = mat4x4_mul(&hand_camera_matrix, &view);
draw_card(p, card_matrix, card.texture_spec());
}
}
//TODO should the CPU players remember the revealed cards?
if mouse_button_state.pressed {
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
for i in 0..state.cpu_hands.len() {
if let Some(card) = deal(state) {
state.cpu_hands[i].push(card);
}
}
state.turn = DrawUntilNumberCard;
}
}
WhoStarts => {
if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
let mut cpu_cards_vec = Vec::new();
'hands: for hand in state.cpu_hands.iter_mut() {
//TODO is there a reason for this not to be the first one?
for i in 0..hand.len() {
if hand[i].is_number() {
cpu_cards_vec.push(hand.remove(i));
continue 'hands;
}
}
}
debug_assert!(state.cpu_hands.len() == cpu_cards_vec.len());
let mut cpu_cards = [None; MAX_PLAYERS - 1];
for i in 0..cpu_cards_vec.len() {
cpu_cards[i] = Some(cpu_cards_vec[i]);
}
let player_card = state.player_hand.remove(index);
let first = {
let mut pairs = vec![(Player, player_card)];
for i in 0..cpu_cards_vec.len() {
pairs.push((Cpu(i), cpu_cards_vec[i]));
}
//reverse it so the player wins ties
pairs
.iter()
.rev()
.max_by_key(|&&(_, c)| c.value.number_value())
.unwrap()
.0
};
let starter_cards = StarterCards {
player_card,
cpu_cards,
first,
};
state.turn = FirstRound(starter_cards, first);
}
}
}
FirstRound(starter_cards, mut current_participant) => {
loop {
match current_participant {
Player => {
state.turn = FirstRoundPlayer(starter_cards);
break;
}
Cpu(i) => {
let possible_targets = set_to_vec(first_round_targets(&state.board));
//TODO should we try to make a power block? or avoid one?
if let Some(key) = state.rng.choose(&possible_targets) {
let stash = &mut state.stashes.cpu_stashes[i];
let space_and_piece_available =
stash[Pips::One] != NoneLeft && state.board.get(key).is_none();
debug_assert!(space_and_piece_available);
if space_and_piece_available {
if let Some(card) = starter_cards.cpu_cards[i] {
let mut space = Space::new(card);
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
}
state.board.insert(*key, space);
}
}
}
}
}
current_participant =
next_participant(cpu_player_count(state), current_participant);
if current_participant == starter_cards.first {
state.turn = CpuTurn(Some(current_participant));
break;
}
}
}
FirstRoundPlayer(starter_cards) => {
let possible_targets = first_round_targets(&state.board);
let target_space_coords = place_card(
p,
state,
&view,
&possible_targets,
starter_cards.player_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
if let Some(key) = target_space_coords {
let cpu_player_count = cpu_player_count(state);
let stash = &mut state.stashes.player_stash;
let space_and_piece_available =
stash[Pips::One] != NoneLeft && state.board.get(&key).is_none();
debug_assert!(space_and_piece_available);
if space_and_piece_available {
let mut space = Space::new(starter_cards.player_card);
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
}
state.board.insert(key, space);
}
let next_participant = next_participant(cpu_player_count, Player);
if next_participant == starter_cards.first {
state.turn = CpuTurn(Some(next_participant));
} else {
state.turn = FirstRound(starter_cards, next_participant);
}
}
}
DrawInitialCard => {
//TODO drawing sound effect or other indication?
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
state.turn = SelectTurnOption;
}
SelectTurnOption => {
state.highlighted = NoHighlighting;
state.message.timeout = 0;
}
DrawThree => {
//TODO drawing sound effect or other indication?
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
state.turn = Discard;
}
Grow => if let SelectPiece(space_coords, piece_index) = action {
match grow_if_available(
space_coords,
piece_index,
&mut state.board,
&mut state.stashes.player_stash,
) {
Ok(true) => {
state.turn = Discard;
}
Ok(false) => {}
Err(message) => {
state.message = message;
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
Spawn => {
state.highlighted = PlayerOccupation;
if let SelectSpace(key) = action {
match spawn_if_possible(&mut state.board, &key, &mut state.stashes.player_stash) {
Ok(true) => {
state.turn = Discard;
}
Ok(false) => {}
Err(message) => {
state.message = message;
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
Build => {
state.highlighted = PlayerOccupation;
if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
state.turn = BuildSelect(state.player_hand.remove(index), index);
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
BuildSelect(held_card, old_index) => {
let build_targets =
get_all_build_targets_set(&state.board, state.stashes.player_stash.colour);
let target_space_coords = place_card(
p,
state,
&view,
&build_targets,
held_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
if let Some(key) = target_space_coords {
if build_targets.contains(&key) {
state.board.insert(
key,
Space {
card: held_card,
..Default::default()
},
);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
} else if build_targets.len() == 0 {
state.message = Message {
text: "You can't Build because you don't occupy a space on the edge!"
.to_owned(),
timeout: WARNING_TIMEOUT,
};
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
}
}
Move => if let SelectPiece(space_coords, piece_index) = action {
if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
if let Some(piece) = space.pieces.remove(piece_index) {
state.turn = MoveSelect(space_coords, piece_index, piece);
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
MoveSelect(space_coords, piece_index, piece) => {
draw_piece(
p,
view,
piece,
world_mouse_x,
world_mouse_y,
piece_texture_spec(piece),
);
let close_enough_grid_coords =
get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let button_outcome = if close_enough_grid_coords.is_some() {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: mouse_button_state,
},
)
} else {
Default::default()
};
let target_space_coords = if button_outcome.clicked {
close_enough_grid_coords
} else {
None
};
if let Some(key) = target_space_coords {
let valid_targets = get_valid_move_targets(&state.board, space_coords);
if valid_targets.contains(&key) {
if let Occupied(mut entry) = state.board.entry(key) {
let mut space = entry.get_mut();
//shpuld this be an insert at 0 so the new piece is clearly visible?
space.pieces.push(piece);
}
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.pieces.insert(piece_index, piece);
}
state.turn = SelectTurnOption;
}
}
ConvertSlashDemolish => if let SelectPiece(space_coords, piece_index) = action {
let valid_targets =
occupied_by_or_adjacent_spaces(&state.board, state.stashes.player_stash.colour);
if valid_targets.contains(&space_coords) {
state.turn =
ConvertSlashDemolishDiscard(space_coords, piece_index, None, None, None);
} else {
let text =
"You must target a piece at most one space away from your pieces.".to_owned();
state.message = Message {
text,
timeout: WARNING_TIMEOUT,
};
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
) => {
if let Some(space) = state.board.get(&space_coords) {
if let Some(piece) = space.pieces.get(piece_index) {
let pips_needed = u8::from(piece.pips);
let hand = &state.player_hand;
let (pips_selected, smallest_card_value) = match (
card_index_1.and_then(|i| hand.get(i)),
card_index_2.and_then(|i| hand.get(i)),
card_index_3.and_then(|i| hand.get(i)),
) {
(None, None, None) => (0, 0),
(Some(&card), None, None) |
(None, Some(&card), None) |
(None, None, Some(&card)) => {
let v = pip_value(&card);
(v, v)
}
(Some(&card1), Some(&card2), None) |
(None, Some(&card1), Some(&card2)) |
(Some(&card1), None, Some(&card2)) => {
let v1 = pip_value(&card1);
let v2 = pip_value(&card2);
(v1 + v2, std::cmp::min(v1, v2))
}
(Some(&card1), Some(&card2), Some(&card3)) => {
let v1 = pip_value(&card1);
let v2 = pip_value(&card2);
let v3 = pip_value(&card3);
(v1 + v2 + v3, std::cmp::min(v1, std::cmp::min(v2, v3)))
}
};
state.turn = if pips_selected >= pips_needed &&
smallest_card_value > pips_selected - pips_needed
{
state.message.timeout = 0;
ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
pips_selected - pips_needed,
)
} else {
if pips_selected >= pips_needed &&
smallest_card_value <= pips_selected - pips_needed
{
state.message = Message {
text: "You cannot discard redundant face cards to get extra draws"
.to_owned(),
timeout: WARNING_TIMEOUT,
}
}
if let SelectCardFromHand(index) = action {
match (
card_index_1.and_then(|i| hand.get(i)),
card_index_2.and_then(|i| hand.get(i)),
card_index_3.and_then(|i| hand.get(i)),
) {
(Some(_), Some(_), Some(_)) => state.turn,
(Some(_), Some(_), _) => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
card_index_2,
Some(index),
),
(Some(_), _, _) => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
Some(index),
None,
),
_ => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
Some(index),
None,
None,
),
}
} else {
state.turn
}
};
}
};
if right_mouse_pressed || escape_pressed {
state.turn = match state.turn {
ConvertSlashDemolishDiscard(_, _, None, None, None) => ConvertSlashDemolish,
_ => ConvertSlashDemolishDiscard(space_coords, piece_index, None, None, None),
};
} else {
state.message = Message {
text: "Choose which face card(s) to discard from your hand.".to_owned(),
timeout: WARNING_TIMEOUT,
};
}
}
ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
) => {
debug_assert!(cards_owed <= 2);
let hand = &mut state.player_hand;
let stashes = &mut state.stashes;
if let Some(space) = state.board.get_mut(&space_coords) {
let can_convert = if let Some(piece) = space.pieces.get(piece_index) {
let stash = &stashes.player_stash;
match piece.pips {
Pips::One => stash[Pips::One] != NoneLeft,
Pips::Two => stash[Pips::One] != NoneLeft || stash[Pips::Two] != NoneLeft,
Pips::Three => {
stash[Pips::One] != NoneLeft || stash[Pips::Two] != NoneLeft ||
stash[Pips::Three] != NoneLeft
}
}
} else {
false
};
if can_convert &&
turn_options_button(
p,
&mut state.ui_context,
"Convert",
(-0.25, 0.875),
700,
(mouse_x, mouse_y),
mouse_button_state,
) {
state.turn = ConvertSelect(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
);
} else if !can_convert ||
turn_options_button(
p,
&mut state.ui_context,
"Demolish",
(0.25, 0.875),
701,
(mouse_x, mouse_y),
mouse_button_state,
) {
if let Some(piece) = space.pieces.remove(piece_index) {
stashes[piece.colour].add(piece);
}
let pile = &mut state.pile;
card_index_1.map(|i| pile.push(hand.remove(i)));
card_index_2.map(|i| pile.push(hand.remove(i)));
card_index_3.map(|i| pile.push(hand.remove(i)));
for _ in 0..cards_owed {
if let Some(card) = deal_parts(&mut state.deck, pile, &mut state.rng) {
hand.push(card);
}
}
state.turn = Discard;
};
};
if right_mouse_pressed || escape_pressed {
state.turn = ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
);
}
}
ConvertSelect(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
) => if let Some(space) = state.board.get_mut(&space_coords) {
if let Some(piece) = space.pieces.get_mut(piece_index) {
let stash_colour = state.stashes.player_stash.colour;
let (has_one, has_two, has_three) = {
let stash = &state.stashes[stash_colour];
(
stash[Pips::One] != NoneLeft,
stash[Pips::Two] != NoneLeft,
stash[Pips::Three] != NoneLeft,
)
};
let mut selected_pips = None;
if has_one && piece.pips == Pips::One {
selected_pips = Some(Pips::One);
}
if !has_one && has_two && piece.pips == Pips::Two {
selected_pips = Some(Pips::Two);
}
if !has_one && !has_two && has_three && piece.pips == Pips::Three {
selected_pips = Some(Pips::Three);
}
if has_one && piece.pips > Pips::One &&
turn_options_button(
p,
&mut state.ui_context,
"Small",
(-2.0 / 3.0, 0.875),
700,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::One);
}
if has_two && piece.pips >= Pips::Two &&
turn_options_button(
p,
&mut state.ui_context,
"Medium",
(0.0, 0.875),
701,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::Two);
}
if has_three && piece.pips >= Pips::Three &&
turn_options_button(
p,
&mut state.ui_context,
"Large",
(2.0 / 3.0, 0.875),
702,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::Three);
}
if let Some(pips) = selected_pips {
if pips <= piece.pips {
if let Some(stash_piece) = state.stashes[stash_colour].remove(pips) {
state.stashes[piece.colour].add(*piece);
*piece = stash_piece;
let hand = &mut state.player_hand;
let pile = &mut state.pile;
card_index_1.map(|i| pile.push(hand.remove(i)));
card_index_2.map(|i| pile.push(hand.remove(i)));
card_index_3.map(|i| pile.push(hand.remove(i)));
for _ in 0..cards_owed {
if let Some(card) =
deal_parts(&mut state.deck, pile, &mut state.rng)
{
hand.push(card);
}
}
state.turn = Discard;
}
}
}
}
},
Fly => {
state.highlighted = PlayerOccupation;
if let Some(only_ace_index) = get_only_ace_index(&state.player_hand) {
state.turn =
FlySelectCarpet(state.player_hand.remove(only_ace_index), only_ace_index);
} else if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
if card.value == Ace {
true
} else {
state.message = Message {
text: "That card is not an Ace!".to_owned(),
timeout: WARNING_TIMEOUT,
};
false
}
} else {
false
};
if valid_target {
state.turn = FlySelectCarpet(state.player_hand.remove(index), index);
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
FlySelectCarpet(ace, old_index) => if let SelectSpace(key) = action {
if is_space_movable(&state.board, &key) {
if let Some(space) = state.board.remove(&key) {
state.turn = FlySelect(key, space, ace, old_index);
state.message.timeout = 0;
}
} else {
state.message = Message {
text: "Moving that card leaves a section of cards completely detached!"
.to_owned(),
timeout: WARNING_TIMEOUT,
}
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, ace);
state.turn = SelectTurnOption;
} else {
state.message = Message {
text: "Choose which card on the board to move.".to_owned(),
timeout: WARNING_TIMEOUT,
};
},
FlySelect(old_coords, space, ace, old_index) => {
let Space {
card,
pieces,
offset: space_offset,
} = space;
let fly_from_targets = fly_from_targets(&state.board, &old_coords);
for grid_coords in fly_from_targets.iter() {
let card_matrix = get_card_matrix(&view, get_card_spec(grid_coords));
draw_empty_space(p, card_matrix);
}
let close_enough_grid_coords =
get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let in_place = close_enough_grid_coords.is_some();
let card_spec =
if in_place && fly_from_targets.contains(&close_enough_grid_coords.unwrap()) {
get_card_spec(&close_enough_grid_coords.unwrap())
} else {
(world_mouse_x, world_mouse_y, false)
};
let card_matrix = get_card_matrix(&view, card_spec);
let button_outcome = if in_place {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: mouse_button_state,
},
)
} else {
Default::default()
};
draw_card(p, card_matrix, card.texture_spec());
for (i, piece) in pieces.into_iter().enumerate() {
if i < space_offset as _ || i > (space_offset + PIECES_PER_PAGE) as _ {
continue;
}
let (x, y) = card_relative_piece_coords(i);
draw_piece(p, card_matrix, piece, x, y, piece_texture_spec(piece));
}
let target_space_coords = if button_outcome.clicked {
close_enough_grid_coords
} else {
None
};
if let Some(key) = target_space_coords {
if fly_from_targets.contains(&key) {
state.board.insert(key, space);
state.pile.push(ace);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.board.insert(old_coords, space);
state.player_hand.insert(old_index, ace);
state.turn = SelectTurnOption;
}
}
Hatch => {
if let SelectCardFromHand(index) = action {
//this assumes no pyramids have been duplicated
let no_pieces_on_board = state.stashes.player_stash.is_full();
if no_pieces_on_board {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
state.turn = HatchSelect(state.player_hand.remove(index), index);
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
HatchSelect(held_card, old_index) => {
let hatch_targets = get_all_hatch_targets_set(&state.board);
let target_space_coords = place_card(
p,
state,
&view,
&hatch_targets,
held_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
debug_assert!(state.stashes.player_stash.is_full());
if let Some(key) = target_space_coords {
if hatch_targets.contains(&key) {
let mut pieces: SpacePieces = Default::default();
if let Some(piece) = state.stashes.player_stash.remove(Pips::One) {
pieces.push(piece);
}
state.board.insert(
key,
Space {
card: held_card,
pieces,
..Default::default()
},
);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
}
}
Discard => {
state.highlighted = NoHighlighting;
if state.player_hand.len() > 6 {
if let SelectCardFromHand(index) = action {
state.pile.push(state.player_hand.remove(index));
} else {
state.message = Message {
text: "Discard down to six cards".to_owned(),
timeout: 1000,
};
}
} else {
state.turn = CpuTurn(None);
};
}
CpuTurn(set_participant) => {
let cpu_player_count = cpu_player_count(state);
let mut current_participant =
set_participant.unwrap_or(next_participant(cpu_player_count, Player));
while current_participant != Player {
println!("current_participant: {:?}", current_participant);
let (hand, colour, stashes) = match current_participant {
Player => {
debug_assert!(false, "Attempting to take player's turn");
(
&mut state.player_hand,
state.stashes.player_stash.colour,
&mut state.stashes,
)
}
Cpu(i) => (
&mut state.cpu_hands[i],
state.stashes.cpu_stashes[i].colour,
&mut state.stashes,
),
};
let rng = &mut state.rng;
//DrawInitialCard
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
let mut possible_plan: Option<Plan> =
get_plan(&state.board, stashes, &hand, rng, colour);
'turn: loop {
//TODO better "AI". Evaluate every use of rng in this match statement
let turn_option = if let Some(plan) = possible_plan {
if cfg!(debug_assertions) {
println!("plan is {:?}", plan);
}
match plan {
Plan::Fly(_) | Plan::FlySpecific(_, _) => 6,
Plan::ConvertSlashDemolish(_, _) => 5,
Plan::Move(_) => 4,
Plan::Hatch(_) => 7,
}
} else {
if cfg!(debug_assertions) {
let x = rng.gen_range(0, 8);
println!("randomly chose {:?}", x);
x
} else {
rng.gen_range(0, 8)
}
};
match turn_option {
1 => {
//Grow
let chosen_piece = {
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i)
{
let possible_piece_index =
state.board.get(&space_coords).and_then(|space| {
let own_pieces = space
.pieces
.filtered_indicies(|p| p.colour == colour);
rng.choose(&own_pieces).map(|&i| i)
});
possible_piece_index
.map(|piece_index| (space_coords, piece_index))
} else {
None
}
};
if let Some((space_coords, piece_index)) = chosen_piece {
match grow_if_available(
space_coords,
piece_index,
&mut state.board,
&mut stashes[colour],
) {
Ok(true) => {
break 'turn;
}
_ => {}
}
}
}
2 => {
//Spawn
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i) {
match spawn_if_possible(
&mut state.board,
&space_coords,
&mut stashes[colour],
) {
Ok(true) => {
break 'turn;
}
_ => {}
}
}
}
3 => {
//Build
let mut number_cards: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.is_number())
.map(|(i, _)| i)
.collect();
//the cpu's choices should be a function of the rng
number_cards.sort();
if let Some(&card_index) = rng.choose(&number_cards) {
let build_targets = get_all_build_targets(&state.board, colour);
if let Some(&key) = rng.choose(&build_targets) {
state.board.insert(
key,
Space {
card: hand.remove(card_index),
..Default::default()
},
);
break 'turn;
}
}
}
4 => {
//Move
let chosen_piece = if let Some(Plan::Move(target)) = possible_plan {
let adjacent_keys: Vec<_> = {
let mut adjacent_keys : Vec<_> = FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + target.0, y + target.1))
.collect();
rng.shuffle(&mut adjacent_keys);
adjacent_keys
};
let mut result = None;
for key in adjacent_keys.iter() {
if let Some(space) = state.board.get(key) {
let own_pieces =
space.pieces.filtered_indicies(|p| p.colour == colour);
if let Some(piece_index) = own_pieces.last() {
result = Some((*key, *piece_index));
break;
}
}
}
if result.is_some() {
result
} else {
possible_plan = None;
None
}
} else {
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i)
{
let possible_piece_index =
state.board.get(&space_coords).and_then(|space| {
let own_pieces = space
.pieces
.filtered_indicies(|p| p.colour == colour);
rng.choose(&own_pieces).map(|&i| i)
});
possible_piece_index
.map(|piece_index| (space_coords, piece_index))
} else {
None
}
};
if let Some((space_coords, piece_index)) = chosen_piece {
let possible_target_space_coords =
if let Some(Plan::Move(target)) = possible_plan {
Some(target)
} else {
let valid_targets = set_to_vec(
get_valid_move_targets(&state.board, space_coords),
);
rng.choose(&valid_targets).map(|&i| i)
};
if let Some(target_space_coords) = possible_target_space_coords {
let possible_piece = if let Occupied(mut source_entry) =
state.board.entry(space_coords)
{
let mut source_space = source_entry.get_mut();
source_space.pieces.remove(piece_index)
} else {
None
};
if let Some(piece) = possible_piece {
if let Occupied(mut target_entry) =
state.board.entry(target_space_coords)
{
let mut target_space = target_entry.get_mut();
//shpuld this be an insert at 0
//so the new piece is clearly visible?
target_space.pieces.push(piece);
break 'turn;
}
}
}
}
}
5 => {
//Convert/Demolish
let chosen_enemy_pieces = {
let spaces: Vec<(i8, i8)> =
occupied_by_or_adjacent_spaces(&state.board, colour);
let mut result: Vec<
((i8, i8), usize),
> = vec![];
if let Some(Plan::ConvertSlashDemolish(space_coords, piece_index))
= possible_plan {
if let Some(space) = state.board.get(&space_coords) {
if space.pieces.get(piece_index).is_some() {
result = vec![(space_coords, piece_index)];
}
}
}
if result.len() == 0 {
let mut pieces = Vec::new();
let mut colours = active_colours(stashes);
colours.sort_by_key(|c| stashes[*c].used_count());
colours.retain(|c| *c != colour);
for &target_colour in colours.pop().iter() {
for key in spaces.iter() {
if let Some(space) = state.board.get(key) {
pieces.extend(
space
.pieces
.filtered_indicies(
|piece| piece.colour == target_colour,
)
.iter()
.filter_map(|&i| {
space
.pieces
.get(i)
.map(|p| ((*key, i), p.pips))
}),
);
}
}
}
let stash = &stashes[colour];
let mut available_sizes = Pips::all_values();
available_sizes.retain(|&pips| stash[pips] != NoneLeft);
type Pair = (((i8, i8), usize), Pips);
let (convertable, not_convertable): (Vec<Pair>, Vec<Pair>) =
pieces.iter().partition(|&&(_, pips)|
available_sizes.contains(&pips)
);
result = convertable
.iter()
.chain(not_convertable.iter())
.map(|pair| pair.0)
.collect();
}
result
};
for (space_coords, piece_index) in chosen_enemy_pieces {
if let Some(space) = state.board.get_mut(&space_coords) {
if let Some(piece) = space.pieces.get(piece_index).clone() {
let pips_needed = u8::from(piece.pips);
let selections = {
//TODO we might want to save particular cards to make a
// power block etc.
let mut card_choices :Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| !c.is_number())
.collect();
card_choices.sort_by(|&(_, a), &(_, b)| {
pip_value(&a).cmp(&pip_value(&b))
});
let mut selected_indicies = Vec::new();
let mut pips_selected = 0;
let mut smallest_card_value = 255;
while let Some((index, card)) = card_choices.pop() {
selected_indicies.push(index);
pips_selected += pip_value(card);
smallest_card_value = std::cmp::min(
smallest_card_value,
pip_value(card),
);
if pips_selected >= pips_needed {
break;
}
}
if pips_selected >= pips_needed &&
smallest_card_value > pips_selected - pips_needed
{
let can_convert = match piece.pips {
Pips::One => {
stashes[colour][Pips::One] != NoneLeft
}
Pips::Two => {
stashes[colour][Pips::One] != NoneLeft ||
stashes[colour][Pips::Two] != NoneLeft
}
Pips::Three => {
stashes[colour][Pips::One] != NoneLeft ||
stashes[colour][Pips::Two] !=
NoneLeft ||
stashes[colour][Pips::Three] != NoneLeft
}
};
Some((
selected_indicies,
can_convert,
pips_selected - pips_needed,
))
} else {
possible_plan = None;
None
}
};
//TODO You very rarely might want to demolish instead of
//convert to save a piece in your stash for a future turn
match selections {
Some((selected_indicies, true, cards_owed)) => {
//Convert
for &pips in
vec![Pips::Three, Pips::Two, Pips::One].iter()
{
if pips <= piece.pips {
if let Some(stash_piece) =
stashes[colour].remove(pips)
{
if let Some(old_piece) =
space.pieces.get_mut(piece_index)
{
stashes[old_piece.colour]
.add(*old_piece);
*old_piece = stash_piece;
for i in selected_indicies {
state.pile.push(hand.remove(i));
}
for _ in 0..cards_owed {
if let Some(card) = deal_parts(
&mut state.deck,
&mut state.pile,
rng,
) {
hand.push(card);
}
}
break 'turn;
}
}
}
}
}
Some((selected_indicies, false, cards_owed)) => {
//Demolish
if let Some(piece) =
space.pieces.remove(piece_index)
{
stashes[piece.colour].add(piece);
}
for i in selected_indicies {
state.pile.push(hand.remove(i));
}
for _ in 0..cards_owed {
if let Some(card) = deal_parts(
&mut state.deck,
&mut state.pile,
rng,
) {
hand.push(card);
}
}
break 'turn;
}
_ => {}
};
}
};
}
}
6 => {
//Fly
let ace_indicies: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.value == Ace)
.map(|(i, _)| i)
.collect();
if ace_indicies.len() == 0 {
possible_plan = None;
continue 'turn;
}
let board = &mut state.board;
let chosen_space = {
match possible_plan {
Some(Plan::Fly(target)) |
Some(Plan::FlySpecific(_, target)) => {
if board.contains_key(&target) {
board.remove(&target).map(|space| (target, space))
} else {
possible_plan = None;
None
}
}
_ => {
let spaces = get_all_spaces_occupied_by(board, colour);
rng.choose(&spaces).and_then(
|key| if is_space_movable(board, key) {
board.remove(key).map(|space| (*key, space))
} else {
None
},
)
}
}
};
if let Some((old_coords, space)) = chosen_space {
let target_space_coords: Option<
(i8, i8),
> = if let Some(Plan::FlySpecific(source, _)) = possible_plan {
if let None = board.get(&source) {
Some(source)
} else {
debug_assert!(false, "Bad Plan::FlySpecific!");
None
}
} else {
let fly_from_targets = fly_from_targets(&board, &old_coords);
//TODO if there is a Fly Plan then place
//it as far away as possible
//or in a place that helps the cpu player
rng.choose(&fly_from_targets).cloned()
};
if let Some(key) = target_space_coords {
if let Some(ace_index) = rng.choose(&ace_indicies) {
state.pile.push(hand.remove(*ace_index));
board.insert(key, space);
break 'turn;
}
}
}
}
7 => {
//Hatch
let stash = &mut stashes[colour];
let no_pieces_on_board = stash.is_full();
if no_pieces_on_board {
let mut number_cards: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.is_number())
.map(|(i, _)| i)
.collect();
number_cards.sort();
if let Some(&card_index) = rng.choose(&number_cards) {
let target_space_coords =
if let Some(Plan::Hatch(target)) = possible_plan {
Some(target)
} else {
let mut hatch_targets: Vec<
(i8, i8),
> = get_all_hatch_targets(&state.board)
.iter()
.cloned()
.collect();
hatch_targets.sort();
rng.choose(&hatch_targets).cloned()
};
if let Some(key) = target_space_coords {
let mut pieces: SpacePieces = Default::default();
if let Some(piece) = stash.remove(Pips::One) {
pieces.push(piece);
}
state.board.insert(
key,
Space {
card: hand.remove(card_index),
pieces,
..Default::default()
},
);
break 'turn;
}
}
}
}
_ => {
//DrawThree
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
break 'turn;
}
}
}
current_participant = next_participant(cpu_player_count, current_participant);
}
state.turn = DrawInitialCard;
}
Over(winner, possible_second_winner) => {
fn win_message(participant: Participant) -> String {
match participant {
Player => "You win".to_owned(),
Cpu(i) => format!("Cpu {} wins", i),
}
}
let text = format!("{}!", win_message(winner));
draw_outlined_text(
p,
&text,
(0.0, 0.875),
1.0,
36.0,
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
);
if let Some(second_winner) = possible_second_winner {
draw_outlined_text(
p,
&format!("{} as well!", win_message(second_winner)),
(0.0, 0.75),
1.0,
36.0,
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
);
}
}
};
//draw the hud here so the layering is correct
(p.draw_layer)(1, state.hud_alpha);
//draw the message over top of everything
if state.message.timeout > 0 {
let message_location = (0.0, -((HUD_LINE * 2.0) - 1.0) + 0.125);
let alpha = if state.message.timeout > 512 {
1.0
} else {
state.message.timeout as f32 / 512.0
};
let outline_colour = [0.0, 0.0, 0.0, alpha];
let boosted_alpha = if alpha * 2.0 >= 1.0 { 1.0 } else { alpha * 2.0 };
let middle_alpha = if boosted_alpha >= alpha {
boosted_alpha
} else {
alpha
};
let middle_colour = [1.0, 1.0, 1.0, middle_alpha];
draw_outlined_text(
p,
&state.message.text,
message_location,
1.0,
24.0,
middle_colour,
outline_colour,
);
state.message.timeout = state.message.timeout.saturating_sub(16);
}
if cfg!(debug_assertions) {
if t != state.turn {
println!("{:?}", state.turn);
}
}
match state.turn {
DrawUntilNumberCard |
FirstRound(_, _) |
DrawInitialCard |
SelectTurnOption |
Discard |
CpuTurn(_) |
Over(_, _) => if escape_pressed {
return true;
},
_ => {}
};
if cfg!(debug_assertions) {
fn diff<T: Copy + PartialEq>(a: &Vec<T>, b: &Vec<T>) -> Vec<T> {
let mut diff = Vec::new();
let (shorter, longer) = if a.len() > b.len() {
(&b, &a)
} else {
(&a, &b)
};
for i in 0..longer.len() {
match (shorter.get(i), longer.get(i)) {
(Some(c1), Some(c2)) if c1 == c2 => {}
(Some(_), Some(c2)) => {
diff.push(*c2);
}
(Some(c), None) | (None, Some(c)) => {
diff.push(*c);
}
(None, None) => {}
}
}
diff
}
////////////////////
// card check //
////////////////////
let mut all_cards = Vec::new();
all_cards.extend(state.player_hand.iter().cloned());
for hand in state.cpu_hands.iter() {
all_cards.extend(hand.iter().cloned());
}
all_cards.extend(state.deck.iter().cloned());
all_cards.extend(state.pile.iter().cloned());
let mut over_okay = false;
match state.turn {
FirstRound(starter_cards, _) | FirstRoundPlayer(starter_cards) => {
all_cards.push(starter_cards.player_card.clone());
for possible_card in starter_cards.cpu_cards.iter() {
if let Some(card) = *possible_card {
all_cards.push(card);
}
}
over_okay = true;
}
BuildSelect(card, _) | FlySelectCarpet(card, _) | HatchSelect(card, _) => {
all_cards.push(card);
}
FlySelect(_, space, card, _) => {
all_cards.push(space.card);
all_cards.push(card);
}
_ => {}
}
for space in state.board.values() {
all_cards.push(space.card.clone());
}
all_cards.sort();
let fresh_deck = Card::all_values();
if over_okay {
assert!(all_cards.len() >= fresh_deck.len());
} else {
assert_eq!(
all_cards,
fresh_deck,
"
all_cards.len():{:?}
fresh_deck.len():{:?}
diff :{:?}",
all_cards.len(),
fresh_deck.len(),
diff(&all_cards, &fresh_deck)
);
}
////////////////////
// piece check //
////////////////////
let colours = active_colours(&state.stashes);
let mut all_pieces = Vec::new();
for &colour in colours.iter() {
let stash = &state.stashes[colour];
for pips in Pips::all_values() {
match stash[pips] {
NoneLeft => {}
OneLeft => {
all_pieces.push(Piece { colour, pips });
}
TwoLeft => {
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
}
ThreeLeft => {
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
}
}
}
}
for space in state.board.values() {
for piece in space.pieces.clone().into_iter() {
all_pieces.push(piece);
}
}
match state.turn {
MoveSelect(_, _, piece) => {
all_pieces.push(piece);
}
FlySelect(_, space, _, _) => for piece in space.pieces.clone().into_iter() {
all_pieces.push(piece);
},
_ => {}
}
all_pieces.sort();
let mut one_of_each = Piece::all_values();
one_of_each.retain(|p| colours.contains(&p.colour));
let mut expected = Vec::new();
for piece in one_of_each {
expected.push(piece);
expected.push(piece);
expected.push(piece);
}
assert_eq!(
all_pieces,
expected,
"
all_pieces.len():{:?}
expected.len():{:?}
diff :{:?}",
all_pieces.len(),
expected.len(),
diff(&all_pieces, &expected)
);
}
false
}
fn occupied_by_or_adjacent_spaces(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
let mut set = get_all_spaces_occupied_by_set(board, colour);
let initial_keys: Vec<(i8, i8)> = set.iter().cloned().collect();
for key in initial_keys {
set.extend(
FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + key.0, y + key.1)),
);
}
set_to_vec(set)
}
//a cheesy way to do an outline
fn draw_outlined_text(
p: &Platform,
text: &str,
location: (f32, f32),
screen_width_percentage: f32,
scale: f32,
middle_colour: [f32; 4],
outline_colour: [f32; 4],
) {
//let's just lineraly extrapolate from what worked before!
let outline_scale = scale * 24.5 / 24.0;
let outline_offset = 1.0 / (512.0 * 24.0);
(p.draw_text)(
text,
(location.0 + outline_offset, location.1 - outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 - outline_offset, location.1 + outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 - outline_offset, location.1 - outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 + outline_offset, location.1 + outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
location,
screen_width_percentage,
scale,
middle_colour,
0,
);
}
const HUD_LINE: f32 = 0.675;
const WARNING_TIMEOUT: u32 = 2500;
fn place_card(
p: &Platform,
state: &mut State,
view: &[f32; 16],
targets: &HashSet<(i8, i8)>,
card: Card,
(world_mouse_x, world_mouse_y): (f32, f32),
button_state: ButtonState,
) -> Option<(i8, i8)> {
for grid_coords in targets.iter() {
let card_matrix = get_card_matrix(&view, get_card_spec(grid_coords));
draw_empty_space(p, card_matrix);
}
let close_enough_grid_coords = get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let in_place = close_enough_grid_coords.is_some();
let card_spec = if in_place && targets.contains(&close_enough_grid_coords.unwrap()) {
get_card_spec(&close_enough_grid_coords.unwrap())
} else {
(world_mouse_x, world_mouse_y, false)
};
let card_matrix = get_card_matrix(&view, card_spec);
let button_outcome = if in_place {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: button_state,
},
)
} else {
Default::default()
};
draw_card(p, card_matrix, card.texture_spec());
if button_outcome.clicked {
close_enough_grid_coords
} else {
None
}
}
fn cpu_player_count(state: &State) -> usize {
state.cpu_hands.len()
}
fn next_participant(cpu_player_count: usize, participant: Participant) -> Participant {
match participant {
Player => Cpu(0),
Cpu(i) => if i >= cpu_player_count - 1 {
Player
} else {
Cpu(i + 1)
},
}
}
fn pip_value(card: &Card) -> u8 {
match card.value {
Ace | Jack /* | Joker*/ => 1,
Queen => 2,
King => 3,
//this value ensures the set of cards will be rejected
_ => 0,
}
}
fn turn_options_button(
p: &Platform,
context: &mut UIContext,
label: &str,
(x, y): (f32, f32),
id: UiId,
(mouse_x, mouse_y): (f32, f32),
state: ButtonState,
) -> bool {
let mut texture_spec = (
3.0 * CARD_TEXTURE_WIDTH,
4.0 * CARD_TEXTURE_HEIGHT + (4.0 * TOOLTIP_TEXTURE_HEIGHT_OFFSET),
TOOLTIP_TEXTURE_WIDTH,
TOOLTIP_TEXTURE_HEIGHT,
0,
0.0,
0.0,
0.0,
0.0,
);
let camera = scale_translation(0.0625, x, y);
let inverse_camera = inverse_scale_translation(0.0625, x, y);
let (box_mouse_x, box_mouse_y, _, _) =
mat4x4_vector_mul(&inverse_camera, mouse_x, mouse_y, 0.0, 1.0);
let pointer_inside = box_mouse_x.abs() <= TOOLTIP_RATIO && box_mouse_y.abs() <= 1.0;
let button_outcome = button_logic(
context,
Button {
id,
pointer_inside,
state,
},
);
match button_outcome.draw_state {
Pressed => {
texture_spec.5 = -0.5;
texture_spec.6 = -0.5;
}
Hover => {
texture_spec.5 = -0.5;
texture_spec.7 = -0.5;
}
Inactive => {}
}
(p.draw_textured_poly_with_matrix)(camera, 2, texture_spec, 0);
let font_scale = if label.len() > 8 { 18.0 } else { 24.0 };
(p.draw_text)(label, (x, y), 1.0, font_scale, [1.0; 4], 0);
button_outcome.clicked
}
fn get_only_ace_index(hand: &Vec<Card>) -> Option<usize> {
let mut result = None;
for (i, card) in hand.iter().enumerate() {
if card.value == Ace {
if result.is_none() {
result = Some(i);
} else {
return None;
}
}
}
result
}
fn spawn_if_possible(
board: &mut Board,
key: &(i8, i8),
stash: &mut Stash,
) -> Result<bool, Message> {
if stash[Pips::One] == NoneLeft {
return Err(Message {
text: "You are out of small pyramids!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
if is_occupied_by(board, key, stash.colour) {
if let Some(mut space) = board.get_mut(key) {
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
return Ok(true);
}
}
}
Ok(false)
}
fn is_occupied_by(board: &Board, grid_coords: &(i8, i8), colour: PieceColour) -> bool {
if let Some(space) = board.get(grid_coords) {
space_occupied_by(space, colour)
} else {
false
}
}
fn space_occupied_by(space: &Space, colour: PieceColour) -> bool {
space.pieces.any(|piece| piece.colour == colour)
}
fn grow_if_available(
space_coords: (i8, i8),
piece_index: usize,
board: &mut Board,
stash: &mut Stash,
) -> Result<bool, Message> {
if let Occupied(mut entry) = board.entry(space_coords) {
let mut space = entry.get_mut();
if let Some(piece) = space.pieces.get_mut(piece_index) {
if piece.colour == stash.colour {
match piece.pips {
Pips::One | Pips::Two => {
if let Some(larger_piece) = stash.remove(piece.pips.higher()) {
let temp = piece.clone();
*piece = larger_piece;
stash.add(temp);
return Ok(true);
}
}
Pips::Three => {
return Err(Message {
text: "That pyramid is already maximum size!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
}
} else {
return Err(Message {
text: "You cannot grow another player's piece!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
}
}
Ok(false)
}
const PIECES_PER_PAGE: u8 = 4;
fn point_in_square_on_card(
(point_x, point_y): (f32, f32),
(box_center_x, box_center_y): (f32, f32),
square_size: f32,
rotated: bool,
) -> bool {
if rotated {
//swapping x and y and inverting y is equivalent to rotation by 90 degrees
//This trick appears to only works with a square
(-point_y - box_center_x).abs() <= square_size &&
(point_x - box_center_y).abs() <= square_size
} else {
(point_x - box_center_x).abs() <= square_size &&
(point_y - box_center_y).abs() <= square_size
}
}
const ARROW_SIZE: f32 = 15.0;
fn scale_translation(scale: f32, x_offest: f32, y_offset: f32) -> [f32; 16] {
[
scale,
0.0,
0.0,
0.0,
0.0,
scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
x_offest,
y_offset,
0.0,
1.0,
]
}
fn inverse_scale_translation(scale: f32, x_offest: f32, y_offset: f32) -> [f32; 16] {
scale_translation(1.0 / scale, -x_offest / scale, -y_offset / scale)
}
fn get_close_enough_grid_coords(world_mouse_x: f32, world_mouse_y: f32) -> Option<(i8, i8)> {
let closest_grid_coords = from_world_coords((world_mouse_x, world_mouse_y));
let rotated = card_is_rotated(&closest_grid_coords);
let (center_x, center_y) = to_world_coords(closest_grid_coords);
let (x_distance, y_distance) = (
f32::abs(center_x - world_mouse_x),
f32::abs(center_y - world_mouse_y),
);
let in_bounds = if rotated {
x_distance < CARD_LONG_RADIUS && y_distance < CARD_SHORT_RADIUS
} else {
x_distance < CARD_SHORT_RADIUS && y_distance < CARD_LONG_RADIUS
};
if in_bounds {
Some(closest_grid_coords)
} else {
None
}
}
const CARD_LONG_RADIUS: f32 = 1.0;
const CARD_SHORT_RADIUS: f32 = CARD_RATIO;
type CardSpec = (f32, f32, bool);
fn get_card_spec(grid_coords: &(i8, i8)) -> CardSpec {
let (card_x, card_y) = to_world_coords(*grid_coords);
let rotated = card_is_rotated(grid_coords);
(card_x, card_y, rotated)
}
use std::collections::HashSet;
fn get_valid_move_targets(board: &Board, (x, y): (i8, i8)) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
result
}
fn get_all_build_targets(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
set_to_vec(get_all_build_targets_set(board, colour))
}
fn get_all_build_targets_set(board: &Board, colour: PieceColour) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
let occupied_spaces = get_all_spaces_occupied_by_set(board, colour);
for &(x, y) in occupied_spaces.iter() {
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
result
}
fn get_all_hatch_targets(board: &Board) -> Vec<(i8, i8)> {
set_to_vec(get_all_hatch_targets_set(board))
}
fn get_all_hatch_targets_set(board: &Board) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
for &(x, y) in board.keys() {
for &(dx, dy) in EIGHT_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
result
}
fn get_all_spaces_occupied_by(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
set_to_vec(get_all_spaces_occupied_by_set(board, colour))
}
fn set_to_vec(set: HashSet<(i8, i8)>) -> Vec<(i8, i8)> {
let mut result: Vec<_> = set.iter().cloned().collect();
//we want the chosen results to be a function only our rng, not the HashSet's internal one
result.sort();
result
}
fn get_all_spaces_occupied_by_set(board: &Board, colour: PieceColour) -> HashSet<(i8, i8)> {
board
.iter()
.filter_map(|(key, space)| if space_occupied_by(space, colour) {
Some(*key)
} else {
None
})
.collect()
}
fn card_is_rotated(grid_coords: &(i8, i8)) -> bool {
(grid_coords.0 + grid_coords.1) % 2 == 0
}
fn card_relative_piece_coords(index: usize) -> (f32, f32) {
match index % 4 {
0 => (0.35, 0.5),
1 => (-0.35, 0.5),
2 => (-0.35, -0.5),
3 => (0.35, -0.5),
_ => (0.0, 0.0),
}
}
fn draw_piece(
p: &Platform,
card_matrix: [f32; 16],
piece: Piece,
x: f32,
y: f32,
piece_texture_spec: TextureSpec,
) {
let scale = piece_scale(piece);
let piece_matrix = scale_translation(scale, x, y);
(p.draw_textured_poly_with_matrix)(
mat4x4_mul(&piece_matrix, &card_matrix),
SQUARE_POLY_INDEX,
piece_texture_spec,
0,
);
}
fn single_controller(stashes: &Stashes, board: &Board, block: Block) -> Option<Participant> {
if let Some(pieces_array) = block_to_pieces(board, block) {
let mut participant_iter = pieces_array
.iter()
.map(|pieces| controller(stashes, pieces));
let possible_particpants: [Option<Participant>; 3] = [
participant_iter.next().and_then(id),
participant_iter.next().and_then(id),
participant_iter.next().and_then(id),
];
match (
possible_particpants[0],
possible_particpants[1],
possible_particpants[2],
) {
(Some(p1), Some(p2), Some(p3)) if p1 == p2 && p2 == p3 => Some(p1),
_ => None,
}
} else {
None
}
}
fn controller(stashes: &Stashes, pieces: &SpacePieces) -> Option<Participant> {
let mut possible_colour = None;
for piece in pieces.into_iter() {
if let Some(colour) = possible_colour {
if colour != piece.colour {
return None;
}
} else {
possible_colour = Some(piece.colour);
}
}
possible_colour.and_then(|colour| if stashes.player_stash.colour == colour {
Some(Player)
} else {
for i in 0..stashes.cpu_stashes.len() {
if stashes.cpu_stashes[i].colour == colour {
return Some(Cpu(i));
}
}
None
})
}
#[derive(Clone, Copy, Debug)]
enum Block {
Horizontal(i8, (i8, i8, i8)),
Vertical(i8, (i8, i8, i8)),
UpRight(i8, i8),
UpLeft(i8, i8),
DownLeft(i8, i8),
DownRight(i8, i8),
}
use Block::*;
fn power_blocks(board: &Board) -> Vec<Block> {
let mut result = Vec::new();
for &(x, y) in board.keys() {
let horizontal = Horizontal(y, (x - 1, x, x + 1));
if is_power_block(board, horizontal) {
result.push(horizontal);
}
let vertical = Vertical(x, (y - 1, y, y + 1));
if is_power_block(board, vertical) {
result.push(vertical);
}
let up_right = UpRight(x, y);
if is_power_block(board, up_right) {
result.push(up_right);
}
let up_left = UpLeft(x, y);
if is_power_block(board, up_left) {
result.push(up_left);
}
let down_right = DownRight(x, y);
if is_power_block(board, down_right) {
result.push(down_right);
}
let down_left = DownLeft(x, y);
if is_power_block(board, down_left) {
result.push(down_left);
}
}
result
}
#[derive(Clone, Copy, Debug)]
struct CompletableBlock {
keys: [(i8, i8); 2],
completion: Completion,
}
#[derive(Clone, Copy, Debug)]
enum Completion {
Unique(Suit, Value),
ValueMatch(Value),
SuitedEnds(Suit, (Value, Value)),
}
use Completion::*;
fn completable_power_block(board: &Board, block: Block) -> Option<CompletableBlock> {
if let Some((keys, mut cards)) = block_to_two_cards_and_a_blank(board, block) {
cards.sort();
match (cards[0], cards[1]) {
(Card { value: v1, .. }, Card { value: v2, .. })
if v1.is_number() && v2.is_number() && v1 == v2 =>
{
Some(CompletableBlock {
keys,
completion: ValueMatch(v1),
})
}
(
Card {
value: v1,
suit: s1,
},
Card {
value: v2,
suit: s2,
},
) if v1.is_number() && v2.is_number() && s1 == s2 =>
{
let v1_f32 = f32::from(v1);
let v2_f32 = f32::from(v2);
if v1_f32 + 1.0 == v2_f32 {
match (v1.lower_number(), v2.higher_number()) {
(Some(low), Some(high)) => Some(CompletableBlock {
keys,
completion: SuitedEnds(s1, (low, high)),
}),
(Some(v), _) | (_, Some(v)) => Some(CompletableBlock {
keys,
completion: Unique(s1, v),
}),
(None, None) => None,
}
} else if v1_f32 + 2.0 == v2_f32 {
v1.higher_number().map(|v| {
CompletableBlock {
keys,
completion: Unique(s1, v),
}
})
} else {
None
}
}
_ => None,
}
} else {
None
}
}
fn block_to_two_cards_and_a_blank(
board: &Board,
block: Block,
) -> Option<([(i8, i8); 2], [Card; 2])> {
let coords = block_to_coords(block);
let mut pairs_iter = coords
.iter()
.map(|key| board.get(key).map(|s| (*key, s.card)));
let possible_pairs: [Option<((i8, i8), Card)>; 3] = [
pairs_iter.next().and_then(id),
pairs_iter.next().and_then(id),
pairs_iter.next().and_then(id),
];
match (possible_pairs[0], possible_pairs[1], possible_pairs[2]) {
(Some(p1), Some(p2), _) | (Some(p1), _, Some(p2)) | (_, Some(p1), Some(p2)) => {
Some(([p1.0, p2.0], [p1.1, p2.1]))
}
_ => None,
}
}
fn completable_power_blocks(board: &Board) -> Vec<CompletableBlock> {
let mut result = Vec::new();
for &(x, y) in board.keys() {
let horizontal = Horizontal(y, (x - 1, x, x + 1));
if let Some(completable) = completable_power_block(board, horizontal) {
result.push(completable);
}
let vertical = Vertical(x, (y - 1, y, y + 1));
if let Some(completable) = completable_power_block(board, vertical) {
result.push(completable);
}
let up_right = UpRight(x, y);
if let Some(completable) = completable_power_block(board, up_right) {
result.push(completable);
}
let up_left = UpLeft(x, y);
if let Some(completable) = completable_power_block(board, up_left) {
result.push(completable);
}
let down_right = DownRight(x, y);
if let Some(completable) = completable_power_block(board, down_right) {
result.push(completable);
}
let down_left = DownLeft(x, y);
if let Some(completable) = completable_power_block(board, down_left) {
result.push(completable);
}
}
result
}
fn block_to_coords(block: Block) -> [(i8, i8); 3] {
match block {
Horizontal(y, (x_minus_1, x, x_plus_1)) => [(x_minus_1, y), (x, y), (x_plus_1, y)],
Vertical(x, (y_minus_1, y, y_plus_1)) => [(x, y_minus_1), (x, y), (x, y_plus_1)],
UpRight(x, y) => [(x, y + 1), (x, y), (x + 1, y)],
UpLeft(x, y) => [(x, y + 1), (x, y), (x - 1, y)],
DownLeft(x, y) => [(x, y - 1), (x, y), (x - 1, y)],
DownRight(x, y) => [(x, y - 1), (x, y), (x + 1, y)],
}
}
/// The identity function.
fn id<T>(x: T) -> T {
x
}
fn block_to_cards(board: &Board, block: Block) -> Option<[Card; 3]> {
let coords = block_to_coords(block);
let mut cards_iter = coords.iter().map(|key| board.get(key).map(|s| s.card));
let possible_cards: [Option<Card>; 3] = [
cards_iter.next().and_then(id),
cards_iter.next().and_then(id),
cards_iter.next().and_then(id),
];
match (possible_cards[0], possible_cards[1], possible_cards[2]) {
(Some(c1), Some(c2), Some(c3)) => Some([c1, c2, c3]),
_ => None,
}
}
fn block_to_pieces(board: &Board, block: Block) -> Option<[SpacePieces; 3]> {
let coords = block_to_coords(block);
let mut coords_iter = coords
.iter()
.map(|key| board.get(key).map(|s| (*s).pieces.clone()));
let possible_pieces: [Option<SpacePieces>; 3] = [
coords_iter.next().and_then(id),
coords_iter.next().and_then(id),
coords_iter.next().and_then(id),
];
match (possible_pieces[0], possible_pieces[1], possible_pieces[2]) {
(Some(p1), Some(p2), Some(p3)) => Some([p1, p2, p3]),
_ => None,
}
}
fn is_power_block(board: &Board, block: Block) -> bool {
if let Some(mut cards) = block_to_cards(board, block) {
cards.sort();
match (cards[0], cards[1], cards[2]) {
(Card { value: v1, .. }, Card { value: v2, .. }, Card { value: v3, .. })
if v1.is_number() && v2.is_number() && v3.is_number() && v1 == v2 && v2 == v3 =>
{
true
}
(
Card {
value: v1,
suit: s1,
},
Card {
value: v2,
suit: s2,
},
Card {
value: v3,
suit: s3,
},
) if v1.is_number() && v2.is_number() && v3.is_number() && s1 == s2 && s2 == s3 =>
{
f32::from(v1) + 1.0 == f32::from(v2) && f32::from(v2) + 1.0 == f32::from(v3)
}
_ => false,
}
} else {
false
}
}
fn draw_card(p: &Platform, card_matrix: [f32; 16], texture_spec: TextureSpec) {
(p.draw_textured_poly_with_matrix)(card_matrix, CARD_POLY_INDEX, texture_spec, 0);
}
fn draw_empty_space(p: &Platform, card_matrix: [f32; 16]) {
(p.draw_textured_poly_with_matrix)(
card_matrix,
CARD_POLY_INDEX,
(
4.0 * CARD_TEXTURE_WIDTH,
4.0 * CARD_TEXTURE_HEIGHT,
CARD_TEXTURE_WIDTH,
CARD_TEXTURE_HEIGHT,
0,
0.0,
0.0,
0.0,
0.0,
),
0,
);
}
fn get_card_matrix(view: &[f32; 16], (card_x, card_y, rotated): CardSpec) -> [f32; 16] {
let angle = if rotated {
std::f32::consts::FRAC_PI_2
} else {
0.0
};
let world_matrix = [
f32::cos(angle),
-f32::sin(angle),
0.0,
0.0,
f32::sin(angle),
f32::cos(angle),
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
mat4x4_mul(&world_matrix, view)
}
fn draw_hud(
p: &Platform,
state: &mut State,
aspect_ratio: f32,
(mouse_x, mouse_y): (f32, f32),
mouse_button_state: ButtonState,
) -> Action {
let mut result = NoAction;
let layer = 1;
let near = 0.5;
let far = 1024.0;
let scale = 8.0;
let top = scale;
let bottom = -top;
let right = aspect_ratio * scale;
let left = -right;
let half_height = scale * 2.0;
let half_width = half_height * aspect_ratio;
let projection_spec = ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: Perspective,
// projection: Orthographic,
};
let hud_view = get_projection(&projection_spec);
let inverse_hud_view = get_projection(&projection_spec.inverse());
let (hud_mouse_x, hud_mouse_y, _, _) =
mat4x4_vector_mul_divide(&inverse_hud_view, mouse_x, mouse_y, 0.0, 1.0);
let card_scale = 3.0;
let hand_length = state.player_hand.len();
let mut card_coords = vec![(0.0, 0.0); hand_length];
let mut selected_index = None;
for i in (0..hand_length).rev() {
let (card_x, card_y) = (-half_width * (13.0 - i as f32) / 16.0, -half_height * 0.75);
card_coords[i] = (card_x, card_y);
if selected_index.is_none() {
let (card_mouse_x, card_mouse_y) = (hud_mouse_x - card_x, hud_mouse_y - card_y);
let on_card = (card_mouse_x).abs() <= CARD_RATIO * card_scale &&
(card_mouse_y).abs() <= card_scale;
if on_card {
selected_index = Some(i);
}
}
}
for (i, card) in state.player_hand.iter().enumerate() {
let (card_x, card_y) = card_coords[i];
let hand_camera_matrix = [
card_scale,
0.0,
0.0,
0.0,
0.0,
card_scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
let card_matrix = mat4x4_mul(&hand_camera_matrix, &hud_view);
let pointer_inside = match state.turn {
Build | Hatch | WhoStarts => card.is_number() && selected_index == Some(i),
ConvertSlashDemolishDiscard(_, _, _, _, _) => {
!card.is_number() && selected_index == Some(i)
}
Fly => card.value == Ace && selected_index == Some(i),
Discard => selected_index == Some(i),
_ => false,
};
let button_outcome = button_logic(
&mut state.ui_context,
Button {
id: (250 + i) as _,
pointer_inside,
state: mouse_button_state,
},
);
let mut texture_spec = card.texture_spec();
if button_outcome.clicked {
result = SelectCardFromHand(i);
} else {
match button_outcome.draw_state {
Pressed => {
texture_spec.5 = -0.5;
texture_spec.6 = -0.5;
}
Hover => {
texture_spec.5 = -0.5;
texture_spec.7 = -0.5;
}
Inactive => {}
}
}
(p.draw_textured_poly_with_matrix)(card_matrix, CARD_POLY_INDEX, texture_spec, layer);
}
let (stash_x, stash_y) = (half_width * 0.75, -half_height * 25.0 / 32.0);
let stash_camera_matrix = [
3.0,
0.0,
0.0,
0.0,
0.0,
3.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
stash_x,
stash_y,
0.0,
1.0,
];
let stash_matrix = mat4x4_mul(&stash_camera_matrix, &hud_view);
draw_stash(p, stash_matrix, &state.stashes.player_stash, layer);
result
}
fn draw_stash(p: &Platform, matrix: [f32; 16], stash: &Stash, layer: usize) {
let pips_vec = vec![Pips::Three, Pips::Two, Pips::One];
for (pile_index, &pips) in pips_vec.iter().enumerate() {
let poly_index = match pips {
Pips::One => 3,
Pips::Two => 4,
Pips::Three => 5,
};
let piece = Piece {
colour: stash.colour,
pips,
};
let scale = piece_scale(piece) * 2.0;
for i in 0..u8::from(stash[pips]) {
//this includes a 90 degree rotation
let camera_matrix = [
0.0,
scale,
0.0,
0.0,
-scale,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
(pile_index as f32 * 1.5) - (0.625 / scale),
(i as f32 * scale) + (pile_index as f32 * -15.0 / 64.0),
0.0,
1.0,
];
let texture_spec = stash_piece_texture_spec(&piece);
(p.draw_textured_poly_with_matrix)(
mat4x4_mul(&camera_matrix, &matrix),
poly_index,
texture_spec,
layer,
);
}
}
}
#[derive(Copy, Clone, Debug)]
struct Button {
id: UiId,
pointer_inside: bool,
state: ButtonState,
}
#[derive(Copy, Clone, Debug)]
struct ButtonState {
pressed: bool,
released: bool,
held: bool,
}
#[derive(Copy, Clone, Debug)]
struct ButtonOutcome {
clicked: bool,
draw_state: DrawState,
}
impl Default for ButtonOutcome {
fn default() -> Self {
ButtonOutcome {
clicked: false,
draw_state: Inactive,
}
}
}
#[derive(Copy, Clone, Debug)]
enum DrawState {
Pressed,
Hover,
Inactive,
}
use DrawState::*;
///This function handles the logic for a given button and returns wheter it was clicked
///and the state of the button so it can be drawn properly elsestate of the button so
///it can be drawn properly elsewhere
fn button_logic(context: &mut UIContext, button: Button) -> ButtonOutcome {
/// In order for this to work properly `context.frame_init();`
/// must be called at the start of each frame, before this function is called
let mut clicked = false;
let inside = button.pointer_inside;
let id = button.id;
if context.active == id {
if button.state.released {
clicked = context.hot == id && inside;
context.set_not_active();
}
} else if context.hot == id {
if button.state.pressed {
context.set_active(id);
}
}
if inside {
context.set_next_hot(id);
}
let draw_state = if context.active == id && (button.state.held || button.state.pressed) {
Pressed
} else if context.hot == id {
Hover
} else {
Inactive
};
ButtonOutcome {
clicked,
draw_state,
}
}
//map [0,1] to [-1,1]
fn center(x: f32) -> f32 {
x * 2.0 - 1.0
}
const LARGEST_PIECE_TEXTURE_SIZE: f32 = 65.0 / T_S;
fn piece_scale(piece: Piece) -> f32 {
piece_size(piece) * 5.0
}
fn piece_size(piece: Piece) -> f32 {
match piece.pips {
Pips::One => 33.0 / T_S,
Pips::Two => 49.0 / T_S,
Pips::Three => LARGEST_PIECE_TEXTURE_SIZE,
}
}
fn piece_texture_spec(piece: Piece) -> TextureSpec {
let size = piece_size(piece);
let (x, y) = match piece.pips {
Pips::One => (114.0 / T_S, 792.0 / T_S),
Pips::Two => (65.0 / T_S, 776.0 / T_S),
Pips::Three => (0.0, 760.0 / T_S),
};
let colour_offset = LARGEST_PIECE_TEXTURE_SIZE * f32::from(piece.colour);
(
x,
y + colour_offset,
size,
size,
i32::from(piece.colour),
0.0,
0.0,
0.0,
0.0,
)
}
fn stash_piece_texture_spec(piece: &Piece) -> TextureSpec {
let (x, y) = match piece.pips {
Pips::One => (320.0 / T_S, 792.0 / T_S),
Pips::Two => (246.0 / T_S, 776.0 / T_S),
Pips::Three => (148.0 / T_S, 760.0 / T_S),
};
let (w, h) = match piece.pips {
Pips::One => (STASH_ONE_PIP_WIDTH / T_S, STASH_ONE_PIP_HEIGHT / T_S),
Pips::Two => (STASH_TWO_PIP_WIDTH / T_S, STASH_TWO_PIP_HEIGHT / T_S),
Pips::Three => (STASH_THREE_PIP_WIDTH / T_S, STASH_THREE_PIP_HEIGHT / T_S),
};
let colour_offset = LARGEST_PIECE_TEXTURE_SIZE * f32::from(piece.colour);
(
x,
y + colour_offset,
w,
h,
i32::from(piece.colour),
0.0,
0.0,
0.0,
0.0,
)
}
fn to_world_coords((grid_x, grid_y): (i8, i8)) -> (f32, f32) {
(grid_x as f32 * 2.0, grid_y as f32 * 2.0)
}
fn from_world_coords((world_x, world_y): (f32, f32)) -> (i8, i8) {
((world_x / 2.0).round() as i8, (world_y / 2.0).round() as i8)
}
fn add_random_board_card(state: &mut State) {
state.board.insert(
(state.rng.gen_range(-10, 10), state.rng.gen_range(-10, 10)),
state.rng.gen(),
);
}
const CARD_POLY_INDEX: usize = 0;
const SQUARE_POLY_INDEX: usize = 1;
const CARD_RATIO: f32 = CARD_TEXTURE_PIXEL_WIDTH / CARD_TEXTURE_PIXEL_HEIGHT;
const TOOLTIP_RATIO: f32 = TOOLTIP_TEXTURE_PIXEL_WIDTH / TOOLTIP_TEXTURE_PIXEL_HEIGHT;
const STASH_ONE_PIP_WIDTH: f32 = 49.0;
const STASH_ONE_PIP_HEIGHT: f32 = 33.0;
const STASH_TWO_PIP_WIDTH: f32 = 73.0;
const STASH_TWO_PIP_HEIGHT: f32 = 49.0;
const STASH_THREE_PIP_WIDTH: f32 = 97.0;
const STASH_THREE_PIP_HEIGHT: f32 = 65.0;
const STASH_ONE_PIP_RATIO: f32 = STASH_ONE_PIP_WIDTH / STASH_ONE_PIP_HEIGHT;
const STASH_TWO_PIP_RATIO: f32 = STASH_TWO_PIP_WIDTH / STASH_TWO_PIP_HEIGHT;
const STASH_THREE_PIP_RATIO: f32 = STASH_THREE_PIP_WIDTH / STASH_THREE_PIP_HEIGHT;
//These are the verticies of the polygons which can be drawn.
//The index refers to the index of the inner vector within the outer vecton.
#[cfg_attr(rustfmt, rustfmt_skip)]
#[no_mangle]
pub fn get_vert_vecs() -> Vec<Vec<f32>> {
vec![
//Card
vec![
-CARD_RATIO, 1.0,
-CARD_RATIO, -1.0,
CARD_RATIO, -1.0,
CARD_RATIO, 1.0,
],
//Square
vec![
-1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
1.0, 1.0,
],
//Tooltip
vec![
-TOOLTIP_RATIO, 1.0,
-TOOLTIP_RATIO, -1.0,
TOOLTIP_RATIO, -1.0,
TOOLTIP_RATIO, 1.0,
],
//one pip stash
vec![
-STASH_ONE_PIP_RATIO, 1.0,
-STASH_ONE_PIP_RATIO, -1.0,
STASH_ONE_PIP_RATIO, -1.0,
STASH_ONE_PIP_RATIO, 1.0,
],
//two pip stash
vec![
-STASH_TWO_PIP_RATIO, 1.0,
-STASH_TWO_PIP_RATIO, -1.0,
STASH_TWO_PIP_RATIO, -1.0,
STASH_TWO_PIP_RATIO, 1.0,
],
//three pip stash
vec![
-STASH_THREE_PIP_RATIO, 1.0,
-STASH_THREE_PIP_RATIO, -1.0,
STASH_THREE_PIP_RATIO, -1.0,
STASH_THREE_PIP_RATIO, 1.0,
],
]
}
fn clamp(current: f32, min: f32, max: f32) -> f32 {
if current > max {
max
} else if current < min {
min
} else {
current
}
}
fn first_round_targets(board: &Board) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
if board.len() == 0 {
result.insert((0, 0));
} else {
let full_spaces = board.keys();
for &(x, y) in full_spaces {
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
}
result
}
fn active_colours(stashes: &Stashes) -> Vec<PieceColour> {
let mut colours = Vec::new();
colours.push(stashes.player_stash.colour);
for stash in stashes.cpu_stashes.iter() {
colours.push(stash.colour);
}
colours
}
#[derive(Copy, Clone, Debug)]
enum Plan {
Fly((i8, i8)),
FlySpecific((i8, i8), (i8, i8)),
ConvertSlashDemolish((i8, i8), usize),
Move((i8, i8)),
Hatch((i8, i8)),
}
fn get_plan(
board: &Board,
stashes: &Stashes,
hand: &Vec<Card>,
rng: &mut StdRng,
colour: PieceColour,
) -> Option<Plan> {
let power_blocks = power_blocks(board);
let disruption_targets = {
let mut completable_power_blocks = completable_power_blocks(board);
completable_power_blocks.retain(|completable| {
let has_card_to_complete: bool = match completable.completion {
Unique(suit, value) => hand.contains(&Card { suit, value }),
ValueMatch(v) => hand.iter().any(|c| v == c.value),
SuitedEnds(suit, (v1, v2)) => {
hand.contains(&Card { suit, value: v1 }) ||
hand.contains(&Card { suit, value: v2 })
}
};
!has_card_to_complete
});
let mut power_block_targets: Vec<(i8, i8)> = power_blocks
.iter()
.cloned()
.flat_map(|block| block_to_coords(block).to_vec().into_iter())
.collect();
power_block_targets.sort();
power_block_targets.dedup();
rng.shuffle(&mut power_block_targets);
let mut completable_power_block_targets: Vec<(i8, i8)> = completable_power_blocks
.iter()
.flat_map(|completable| completable.keys.iter().cloned())
.collect();
completable_power_block_targets.sort();
completable_power_block_targets.dedup();
rng.shuffle(&mut completable_power_block_targets);
let disruption_targets: Vec<(i8, i8)> = power_block_targets
.into_iter()
.chain(completable_power_block_targets)
.collect();
disruption_targets
};
let has_ace = hand.iter().filter(|c| c.value == Ace).count() > 0;
for target in disruption_targets {
if let Some(space) = board.get(&target) {
//It's contested enough if it won't be taken for at least one round.
let contested_enough = {
let counts = PieceColour::all_values()
.into_iter()
.map(|c| space.pieces.filtered_indicies(|p| p.colour == c).len());
counts.filter(|&n| n >= 2).count() >= 2
};
if contested_enough {
continue;
}
} else {
continue;
}
let occupys_target = is_occupied_by(&board, &target, colour);
if occupys_target && has_ace {
return Some(Plan::Fly(target));
} else {
let adjacent_keys: Vec<_> = {
let mut adjacent_keys: Vec<_> = FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + target.0, y + target.1))
.collect();
rng.shuffle(&mut adjacent_keys);
adjacent_keys
};
let adjacent_to_target = adjacent_keys
.iter()
.any(|key| is_occupied_by(&board, key, colour));
if adjacent_to_target || occupys_target {
let highest_pip_target: Option<u8> =
hand.iter()
.fold(None, |acc, card| match (acc, pip_value(&card)) {
(Some(prev), pip_value) => Some(prev.saturating_add(pip_value)),
(None, pip_value) if pip_value == 0 => None,
(None, pip_value) => Some(pip_value),
});
if let Some(pip_max) = highest_pip_target {
let possible_target_piece = board.get(&target).and_then(|space| {
let other_player_pieces = space.pieces.filtered_indicies(
|p| p.colour != colour && u8::from(p.pips) <= pip_max,
);
//TODO how should we pick which colour to target?
rng.choose(&other_player_pieces).cloned()
});
if let Some(target_piece) = possible_target_piece {
return Some(Plan::ConvertSlashDemolish(target, target_piece));
}
}
};
if adjacent_to_target {
return Some(Plan::Move(target));
} else if stashes[colour].is_full() {
let possible_plan = adjacent_keys
.iter()
.find(|key| !board.contains_key(key))
.map(|target_blank| Plan::Hatch(*target_blank));
if possible_plan.is_some() {
return possible_plan;
}
}
//Try to fly next to the target
if has_ace {
let mut occupied_spaces = get_all_spaces_occupied_by(board, colour);
//We filter out these spaces so the cpu player doesn't
//waste an Ace flying somehere that doesn't change the situation
//TODO check this works on overlapping power blocks
let undesired_coords: HashSet<(i8, i8)> = power_blocks
.iter()
.map(|block| block_to_coords(*block))
.filter(|coords| coords.iter().any(|key| *key == target))
.flat_map(|coords| coords.to_vec().into_iter())
.collect();
if undesired_coords.len() > 0 {
occupied_spaces.retain(|coord| !undesired_coords.contains(coord))
}
let adjacent_empty_spaces: Vec<_> = adjacent_keys
.iter()
.filter(|key| board.get(key).is_none())
.collect();
//Find suggested place to fly from
for source_coord in occupied_spaces.iter() {
let possible_targets = fly_from_targets(board, source_coord);
for target_coord in adjacent_empty_spaces.iter() {
if possible_targets.contains(target_coord) {
return Some(Plan::FlySpecific(*source_coord, **target_coord));
}
}
}
}
};
}
None
}
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
#[cfg(test)]
mod plan_tests {
use ::*;
use common::PieceColour::*;
use common::Suit::*;
fn green_vertical_power_block_board() -> Board {
let mut board = HashMap::new();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(
0,
Piece {
colour: Green,
pips: Pips::One,
},
);
pieces.insert(
1,
Piece {
colour: Green,
pips: Pips::One,
},
);
board.insert(
(0, 0),
Space {
card: Card {
suit: Clubs,
value: Two,
},
pieces,
offset: 0,
},
);
}
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(
0,
Piece {
colour: Green,
pips: Pips::One,
},
);
board.insert(
(0, 1),
Space {
card: Card {
suit: Spades,
value: Two,
},
pieces,
offset: 0,
},
);
}
{
let pieces: SpacePieces = Default::default();
board.insert(
(0, -1),
Space {
card: Card {
suit: Diamonds,
value: Two,
},
pieces,
offset: 0,
},
);
}
board
}
#[cfg_attr(rustfmt, rustfmt_skip)]
quickcheck! {
fn move_in_and_hope(seed: usize) -> bool {
let seed_slice: &[_] = &[seed];
let mut rng: StdRng = SeedableRng::from_seed(seed_slice);
let mut board = green_vertical_power_block_board();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(0, Piece {
colour: Red,
pips: Pips::One,
});
board.insert((-1,0), Space {
card: Card {
suit: Hearts,
value: Ten,
},
pieces,
offset: 0,
});
}
let player_stash = Stash {
colour: Green,
one_pip: NoneLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let red_stash = Stash {
colour: Red,
one_pip: TwoLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let stashes = Stashes {
player_stash,
cpu_stashes: vec![red_stash],
};
let hand = vec![];
let plan = get_plan(&board, &stashes, &hand, &mut rng, Red);
if let Some(Plan::Move((0,0))) = plan {
true
} else {
false
}
}
fn fly_towards(seed: usize) -> bool {
let seed_slice: &[_] = &[seed];
let mut rng: StdRng = SeedableRng::from_seed(seed_slice);
let mut board = green_vertical_power_block_board();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(0, Piece {
colour: Red,
pips: Pips::One,
});
board.insert((-1,2), Space {
card: Card {
suit: Hearts,
value: Ten,
},
pieces,
offset: 0,
});
}
let player_stash = Stash {
colour: Green,
one_pip: NoneLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let red_stash = Stash {
colour: Red,
one_pip: TwoLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let stashes = Stashes {
player_stash,
cpu_stashes: vec![red_stash],
};
let hand = vec![Card {value: Ace, suit:Spades}];
let plan = get_plan(&board, &stashes, &hand, &mut rng, Red);
if let Some(Plan::FlySpecific((-1,2),_)) = plan {
true
} else {
false
}
}
}
}
don't fly for no reason
Signed-off-by: Ryan1729 <94d48eb26deaf2479098821c91f188298c441e83@gmail.com>
extern crate common;
extern crate rand;
use common::*;
use common::Projection::*;
use common::Turn::*;
use common::Value::*;
use common::PiecesLeft::*;
use common::Highlighted::*;
use common::Participant::*;
use std::default::Default;
use rand::{Rng, SeedableRng, StdRng};
use std::collections::hash_map::Entry::Occupied;
#[cfg(debug_assertions)]
#[no_mangle]
pub fn new_state() -> State {
println!("debug on");
let seed: &[_] = &[42];
let rng: StdRng = SeedableRng::from_seed(seed);
make_state(rng)
}
#[cfg(not(debug_assertions))]
#[no_mangle]
pub fn new_state() -> State {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|dur| dur.as_secs())
.unwrap_or(42);
println!("{}", timestamp);
let seed: &[_] = &[timestamp as usize];
let rng: StdRng = SeedableRng::from_seed(seed);
make_state(rng)
}
fn deal(state: &mut State) -> Option<Card> {
deal_parts(&mut state.deck, &mut state.pile, &mut state.rng)
}
fn deal_parts(deck: &mut Vec<Card>, pile: &mut Vec<Card>, rng: &mut StdRng) -> Option<Card> {
//reshuffle if we run out of cards.
if deck.len() == 0 {
if cfg!(debug_assertions) {
println!("reshuffle");
}
if pile.len() == 0 {
if cfg!(debug_assertions) {
println!("========= empty pile");
}
return None;
}
for card in pile.drain(..) {
deck.push(card);
}
rng.shuffle(deck.as_mut_slice());
};
deck.pop()
}
fn make_state(mut rng: StdRng) -> State {
let mut deck = Card::all_values();
rng.shuffle(deck.as_mut_slice());
debug_assert!(deck.len() > MAX_PLAYERS * 3, "Not enough cards!");
let cpu_players_count = rng.gen_range(1, MAX_PLAYERS);
let mut pile = Vec::new();
let player_hand;
let mut cpu_hands;
{
let deck_ref = &mut deck;
let pile_ref = &mut pile;
let rng_ref = &mut rng;
player_hand = vec![
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
];
cpu_hands = Vec::new();
for _ in 0..cpu_players_count {
cpu_hands.push(vec![
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
deal_parts(deck_ref, pile_ref, rng_ref).unwrap(),
]);
}
}
let mut colour_deck = PieceColour::all_values();
rng.shuffle(colour_deck.as_mut_slice());
debug_assert!(
colour_deck.len() >= MAX_PLAYERS,
"Not enough piece colours!"
);
let player_stash = Stash::full(colour_deck.pop().unwrap());
let mut cpu_stashes = Vec::new();
for _ in 0..cpu_players_count {
cpu_stashes.push(Stash::full(colour_deck.pop().unwrap()));
}
let state = State {
rng,
cam_x: 0.0,
cam_y: 0.0,
zoom: f32::powi(1.25, 8),
board: HashMap::new(),
mouse_pos: (400.0, 300.0),
window_wh: (INITIAL_WINDOW_WIDTH as _, INITIAL_WINDOW_HEIGHT as _),
ui_context: UIContext::new(),
mouse_held: false,
turn: DrawUntilNumberCard,
deck,
pile: Vec::new(),
player_hand,
cpu_hands,
stashes: Stashes {
player_stash,
cpu_stashes,
},
hud_alpha: 1.0,
highlighted: PlayerOccupation,
message: Default::default(),
};
state
}
#[derive(Debug)]
enum Action {
SelectPiece((i8, i8), usize),
SelectSpace((i8, i8)),
PageBack((i8, i8)),
PageForward((i8, i8)),
SelectCardFromHand(usize),
NoAction,
}
use Action::*;
const FADE_RATE: f32 = 1.0 / 24.0;
const TRANSLATION_SCALE: f32 = 0.0625;
#[no_mangle]
//returns true if quit requested
pub fn update_and_render(p: &Platform, state: &mut State, events: &mut Vec<Event>) -> bool {
let mut mouse_pressed = false;
let mut mouse_released = false;
let mut right_mouse_pressed = false;
//let mut right_mouse_released = false;
let mut escape_pressed = false;
for event in events {
if cfg!(debug_assertions) {
match *event {
Event::MouseMove(_) => {}
_ => println!("{:?}", *event),
}
}
match *event {
Event::Quit | Event::KeyDown(Keycode::F10) => {
return true;
}
Event::KeyDown(Keycode::Escape) => {
escape_pressed = true;
}
Event::KeyDown(Keycode::Space) => if cfg!(debug_assertions) {
add_random_board_card(state);
},
Event::KeyDown(Keycode::R) => if cfg!(debug_assertions) {
state.board.clear();
},
Event::KeyDown(Keycode::C) => if cfg!(debug_assertions) {
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
},
Event::KeyDown(Keycode::V) => if cfg!(debug_assertions) {
(p.set_verts)(get_vert_vecs());
},
Event::KeyDown(Keycode::M) => if cfg!(debug_assertions) {
state.message = Message {
text: "Test Message".to_owned(),
timeout: 1500,
}
},
Event::KeyDown(Keycode::Up) => {
state.cam_y += state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Down) => {
state.cam_y -= state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Right) => {
state.cam_x += state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Left) => {
state.cam_x -= state.zoom * TRANSLATION_SCALE;
}
Event::KeyDown(Keycode::Num0) => {
state.cam_x = 0.0;
state.cam_y = 0.0;
state.zoom = 1.0;
}
Event::KeyDown(Keycode::W) => {
state.zoom *= 1.25;
}
Event::KeyDown(Keycode::S) => {
state.zoom /= 1.25;
if state.zoom == 0.0 {
state.zoom = std::f32::MIN_POSITIVE / TRANSLATION_SCALE;
}
}
Event::MouseMove((x, y)) => {
state.mouse_pos = (x as f32, y as f32);
}
Event::LeftMouseDown => {
mouse_pressed = true;
}
Event::LeftMouseUp => {
mouse_released = true;
}
Event::RightMouseDown => {
right_mouse_pressed = true;
}
Event::RightMouseUp => {
//right_mouse_released = true;
}
Event::WindowSize((w, h)) => {
state.window_wh = (w as f32, h as f32);
println!("{}", state.window_wh.0 / state.window_wh.1);
}
_ => {}
}
}
if mouse_released != mouse_pressed {
if mouse_released {
state.mouse_held = false;
} else {
state.mouse_held = true;
}
}
let mouse_button_state = ButtonState {
pressed: mouse_pressed,
released: mouse_released,
held: state.mouse_held,
};
state.ui_context.frame_init();
state.hud_alpha += if state.mouse_pos.1 / state.window_wh.1 > HUD_LINE {
FADE_RATE
} else {
-FADE_RATE
};
state.hud_alpha = clamp(state.hud_alpha, 0.0, 1.0);
let aspect_ratio = state.window_wh.0 / state.window_wh.1;
let mouse_x = center((state.mouse_pos.0) / state.window_wh.0);
let mouse_y = -center(((state.mouse_pos.1) / state.window_wh.1));
let (view, inverse_view) = {
let near = 0.5;
let far = 1024.0;
let scale = state.zoom * near;
let top = scale;
let bottom = -top;
let right = aspect_ratio * scale;
let left = -right;
let projection = get_projection(&ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: Perspective,
// projection: Orthographic,
});
let inverse_projection = get_projection(&ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: InversePerspective,
// projection: InverseOrthographic,
});
let camera = scale_translation(1.0, state.cam_x, state.cam_y);
let inverse_camera = inverse_scale_translation(1.0, state.cam_x, state.cam_y);
let view = mat4x4_mul(&camera, &projection);
let inverse_view = mat4x4_mul(&inverse_projection, &inverse_camera);
(view, inverse_view)
};
let (world_mouse_x, world_mouse_y, _, _) =
mat4x4_vector_mul_divide(&inverse_view, mouse_x, mouse_y, 0.0, 1.0);
let mut action = NoAction;
for (
grid_coords,
&Space {
card,
ref pieces,
offset: space_offset,
},
) in state.board.iter()
{
let (card_x, card_y, rotated) = get_card_spec(grid_coords);
let card_matrix = get_card_matrix(&view, (card_x, card_y, rotated));
let card_id = card_id(*grid_coords);
let mut card_texture_spec = card.texture_spec();
let (card_mouse_x, card_mouse_y) = (world_mouse_x - card_x, world_mouse_y - card_y);
let on_card = if rotated {
(card_mouse_x).abs() <= 1.0 && (card_mouse_y).abs() <= CARD_RATIO
} else {
(card_mouse_x).abs() <= CARD_RATIO && (card_mouse_y).abs() <= 1.0
};
let button_outcome = button_logic(
&mut state.ui_context,
Button {
id: card_id,
pointer_inside: on_card,
state: mouse_button_state,
},
);
if button_outcome.clicked {
action = SelectSpace(grid_coords.clone());
} else {
let highlight = if let MoveSelect(piece_pickup_coords, _, _) = state.turn {
let valid_targets = get_valid_move_targets(&state.board, piece_pickup_coords);
valid_targets.contains(&grid_coords)
} else {
match state.highlighted {
PlayerOccupation => {
is_occupied_by(&state.board, grid_coords, state.stashes.player_stash.colour)
}
NoHighlighting => false,
}
};
match (button_outcome.draw_state, highlight) {
(_, true) | (Hover, _) => {
card_texture_spec.5 = -0.5;
card_texture_spec.7 = -0.5;
}
(Pressed, false) => {
card_texture_spec.5 = -0.5;
card_texture_spec.6 = -0.5;
}
_ => {}
}
draw_card(p, card_matrix, card_texture_spec);
}
for (i, piece) in pieces.into_iter().enumerate() {
if i < space_offset as _ || i > (space_offset + PIECES_PER_PAGE - 1) as _ {
continue;
}
let (x, y) = card_relative_piece_coords(i);
let half_piece_scale = piece_scale(piece);
debug_assert!(i <= 255);
let piece_id = piece_id(card_id, i as u8);
let mut piece_texture_spec = piece_texture_spec(piece);
let on_piece = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(x, y),
half_piece_scale,
rotated,
);
let button_outcome = match state.turn {
Move | Grow | ConvertSlashDemolish => button_logic(
&mut state.ui_context,
Button {
id: piece_id,
pointer_inside: on_piece,
state: mouse_button_state,
},
),
_ => Default::default(),
};
if button_outcome.clicked {
action = SelectPiece(grid_coords.clone(), i);
} else {
match button_outcome.draw_state {
Pressed => {
piece_texture_spec.5 = 1.5;
piece_texture_spec.6 = 1.5;
piece_texture_spec.7 = 1.5;
}
Hover => {
piece_texture_spec.5 = -1.5;
piece_texture_spec.6 = -1.5;
piece_texture_spec.7 = -1.5;
}
Inactive => {}
}
draw_piece(p, card_matrix, piece, x, y, piece_texture_spec);
};
}
if pieces.len() > PIECES_PER_PAGE as _ {
let scale = 0.125;
let x_offset_amount = 15.0 / 32.0;
let y_offset_amount = (ARROW_SIZE + 2.5) / (T_S * scale);
let forward_x = CARD_RATIO - x_offset_amount;
let forward_y = -(1.0 - y_offset_amount);
let forward_arrow_matrix = mat4x4_mul(
&scale_translation(scale, forward_x, forward_y),
&card_matrix,
);
let mut forward_arrow_texture_spec = (
420.0 / T_S,
895.0 / T_S,
ARROW_SIZE / T_S,
ARROW_SIZE / T_S,
0,
0.0,
0.0,
0.0,
0.0,
);
let mut backward_arrow_texture_spec = forward_arrow_texture_spec.clone();
if pieces.len() > (space_offset * PIECES_PER_PAGE) as _ {
let on_forward = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(forward_x, forward_y),
scale,
rotated,
);
let forward_button_outcome = button_logic(
&mut state.ui_context,
Button {
id: arrow_id(card_id, true),
pointer_inside: on_forward,
state: mouse_button_state,
},
);
if forward_button_outcome.clicked {
action = PageForward(*grid_coords);
} else {
match forward_button_outcome.draw_state {
Pressed => {
forward_arrow_texture_spec.5 = 1.5;
forward_arrow_texture_spec.6 = 1.5;
}
Hover => {
forward_arrow_texture_spec.5 = -1.5;
forward_arrow_texture_spec.7 = -1.5;
}
Inactive => {}
}
};
(p.draw_textured_poly_with_matrix)(
forward_arrow_matrix,
SQUARE_POLY_INDEX,
forward_arrow_texture_spec,
0,
);
}
if space_offset > 0 {
let backward_x = -CARD_RATIO + x_offset_amount;
let backward_y = forward_y;
let mut backward_camera_matrix = scale_translation(-scale, backward_x, backward_y);
backward_camera_matrix[5] *= -1.0;
let backward_arrow_matrix = mat4x4_mul(&backward_camera_matrix, &card_matrix);
let on_backward = on_card &&
point_in_square_on_card(
(card_mouse_x, card_mouse_y),
(backward_x, backward_y),
scale,
rotated,
);
let backward_button_outcome = button_logic(
&mut state.ui_context,
Button {
id: arrow_id(card_id, false),
pointer_inside: on_backward,
state: mouse_button_state,
},
);
if backward_button_outcome.clicked {
action = PageBack(*grid_coords);
} else {
match backward_button_outcome.draw_state {
Pressed => {
backward_arrow_texture_spec.5 = 1.5;
backward_arrow_texture_spec.6 = 1.5;
}
Hover => {
backward_arrow_texture_spec.5 = -1.5;
backward_arrow_texture_spec.7 = -1.5;
}
Inactive => {}
}
};
(p.draw_textured_poly_with_matrix)(
backward_arrow_matrix,
SQUARE_POLY_INDEX,
backward_arrow_texture_spec,
0,
);
}
}
}
if state.turn == SelectTurnOption {
let top_row = [
(DrawThree, "Draw"),
(Grow, "Grow"),
(Spawn, "Spawn"),
(Build, "Build"),
];
let top_row_len = top_row.len();
for i in 0..top_row_len {
let (target_turn, label) = top_row[i];
if turn_options_button(
p,
&mut state.ui_context,
label,
(-0.75 + i as f32 * 0.5, 0.875),
(600 + i) as _,
(mouse_x, mouse_y),
mouse_button_state,
) {
state.turn = target_turn;
};
}
let bottom_row = [
(Move, "Move"),
(ConvertSlashDemolish, "Convert/Demolish"),
(Fly, "Fly"),
(Hatch, "Hatch"),
];
for i in 0..bottom_row.len() {
let (target_turn, label) = bottom_row[i];
if turn_options_button(
p,
&mut state.ui_context,
label,
(-0.75 + i as f32 * 0.5, 11.0 / 16.0),
(600 + top_row_len + i) as _,
(mouse_x, mouse_y),
mouse_button_state,
) {
if target_turn == ConvertSlashDemolish {
state.message = Message {
text: "Choose a piece to target.".to_owned(),
timeout: WARNING_TIMEOUT,
};
} else if target_turn == Fly {
state.message = Message {
text: "Choose an Ace from your hand to discard.".to_owned(),
timeout: WARNING_TIMEOUT,
};
}
state.turn = target_turn;
};
}
}
match draw_hud(
p,
state,
aspect_ratio,
(mouse_x, mouse_y),
mouse_button_state,
) {
NoAction => {}
otherwise => {
action = otherwise;
}
};
match action {
PageBack(space_coords) => if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.offset = space.offset.saturating_sub(PIECES_PER_PAGE);
},
PageForward(space_coords) => if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.offset = space.offset.saturating_add(PIECES_PER_PAGE);
},
_ => {}
}
if cfg!(debug_assertions) {
match action {
NoAction => {}
_ => {
println!("{:?}", action);
}
}
}
{
let power_blocks = power_blocks(&state.board);
// There is a way to have two winners: A player can move
// a piece from a contesed area to another whihc gives them a power block,
//while also leaving the contested block to another player.
//AFAICT that is the maximum possble though.
let mut winners = (None, None);
for block in power_blocks {
if let Some(controller) = single_controller(&state.stashes, &state.board, block) {
winners = match winners {
(None, None) => (Some(controller), None),
(Some(winner), _) | (_, Some(winner)) if winner == controller => winners,
(Some(_), Some(second_winner)) => {
debug_assert!(second_winner == controller, "Three winners?!");
winners
}
(Some(winner), None) => (Some(winner), Some(controller)),
(None, Some(mistake)) => (None, Some(mistake)),
};
}
}
if let Some(winner) = winners.0 {
state.turn = if winners.1 == Some(Player) {
//player gets top billing
Over(Player, Some(winner))
} else {
Over(winner, winners.1)
};
}
}
let t = state.turn;
match state.turn {
DrawUntilNumberCard => {
if !state.player_hand.iter().any(|c| c.is_number()) {
state.turn = RevealHand(Player);
} else {
for i in 0..state.cpu_hands.len() {
let hand = &state.cpu_hands[i];
if !hand.iter().any(|c| c.is_number()) {
state.turn = RevealHand(Cpu(i));
break;
}
}
}
if let DrawUntilNumberCard = state.turn {
state.turn = WhoStarts;
}
}
RevealHand(participant) => {
{
let hand = match participant {
Player => &state.player_hand,
Cpu(i) => &state.cpu_hands[i],
};
let card_scale = 1.0;
let half_hand_len = (hand.len() / 2) as isize;
for (i, card) in hand.iter().enumerate() {
let (card_x, card_y) = ((i as isize - half_hand_len) as f32 / 2.0, 0.0);
let hand_camera_matrix = [
card_scale,
0.0,
0.0,
0.0,
0.0,
card_scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
let card_matrix = mat4x4_mul(&hand_camera_matrix, &view);
draw_card(p, card_matrix, card.texture_spec());
}
}
//TODO should the CPU players remember the revealed cards?
if mouse_button_state.pressed {
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
for i in 0..state.cpu_hands.len() {
if let Some(card) = deal(state) {
state.cpu_hands[i].push(card);
}
}
state.turn = DrawUntilNumberCard;
}
}
WhoStarts => {
if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
let mut cpu_cards_vec = Vec::new();
'hands: for hand in state.cpu_hands.iter_mut() {
//TODO is there a reason for this not to be the first one?
for i in 0..hand.len() {
if hand[i].is_number() {
cpu_cards_vec.push(hand.remove(i));
continue 'hands;
}
}
}
debug_assert!(state.cpu_hands.len() == cpu_cards_vec.len());
let mut cpu_cards = [None; MAX_PLAYERS - 1];
for i in 0..cpu_cards_vec.len() {
cpu_cards[i] = Some(cpu_cards_vec[i]);
}
let player_card = state.player_hand.remove(index);
let first = {
let mut pairs = vec![(Player, player_card)];
for i in 0..cpu_cards_vec.len() {
pairs.push((Cpu(i), cpu_cards_vec[i]));
}
//reverse it so the player wins ties
pairs
.iter()
.rev()
.max_by_key(|&&(_, c)| c.value.number_value())
.unwrap()
.0
};
let starter_cards = StarterCards {
player_card,
cpu_cards,
first,
};
state.turn = FirstRound(starter_cards, first);
}
}
}
FirstRound(starter_cards, mut current_participant) => {
loop {
match current_participant {
Player => {
state.turn = FirstRoundPlayer(starter_cards);
break;
}
Cpu(i) => {
let possible_targets = set_to_vec(first_round_targets(&state.board));
//TODO should we try to make a power block? or avoid one?
if let Some(key) = state.rng.choose(&possible_targets) {
let stash = &mut state.stashes.cpu_stashes[i];
let space_and_piece_available =
stash[Pips::One] != NoneLeft && state.board.get(key).is_none();
debug_assert!(space_and_piece_available);
if space_and_piece_available {
if let Some(card) = starter_cards.cpu_cards[i] {
let mut space = Space::new(card);
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
}
state.board.insert(*key, space);
}
}
}
}
}
current_participant =
next_participant(cpu_player_count(state), current_participant);
if current_participant == starter_cards.first {
state.turn = CpuTurn(Some(current_participant));
break;
}
}
}
FirstRoundPlayer(starter_cards) => {
let possible_targets = first_round_targets(&state.board);
let target_space_coords = place_card(
p,
state,
&view,
&possible_targets,
starter_cards.player_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
if let Some(key) = target_space_coords {
let cpu_player_count = cpu_player_count(state);
let stash = &mut state.stashes.player_stash;
let space_and_piece_available =
stash[Pips::One] != NoneLeft && state.board.get(&key).is_none();
debug_assert!(space_and_piece_available);
if space_and_piece_available {
let mut space = Space::new(starter_cards.player_card);
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
}
state.board.insert(key, space);
}
let next_participant = next_participant(cpu_player_count, Player);
if next_participant == starter_cards.first {
state.turn = CpuTurn(Some(next_participant));
} else {
state.turn = FirstRound(starter_cards, next_participant);
}
}
}
DrawInitialCard => {
//TODO drawing sound effect or other indication?
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
state.turn = SelectTurnOption;
}
SelectTurnOption => {
state.highlighted = NoHighlighting;
state.message.timeout = 0;
}
DrawThree => {
//TODO drawing sound effect or other indication?
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
if let Some(card) = deal(state) {
state.player_hand.push(card);
}
state.turn = Discard;
}
Grow => if let SelectPiece(space_coords, piece_index) = action {
match grow_if_available(
space_coords,
piece_index,
&mut state.board,
&mut state.stashes.player_stash,
) {
Ok(true) => {
state.turn = Discard;
}
Ok(false) => {}
Err(message) => {
state.message = message;
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
Spawn => {
state.highlighted = PlayerOccupation;
if let SelectSpace(key) = action {
match spawn_if_possible(&mut state.board, &key, &mut state.stashes.player_stash) {
Ok(true) => {
state.turn = Discard;
}
Ok(false) => {}
Err(message) => {
state.message = message;
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
Build => {
state.highlighted = PlayerOccupation;
if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
state.turn = BuildSelect(state.player_hand.remove(index), index);
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
BuildSelect(held_card, old_index) => {
let build_targets =
get_all_build_targets_set(&state.board, state.stashes.player_stash.colour);
let target_space_coords = place_card(
p,
state,
&view,
&build_targets,
held_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
if let Some(key) = target_space_coords {
if build_targets.contains(&key) {
state.board.insert(
key,
Space {
card: held_card,
..Default::default()
},
);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
} else if build_targets.len() == 0 {
state.message = Message {
text: "You can't Build because you don't occupy a space on the edge!"
.to_owned(),
timeout: WARNING_TIMEOUT,
};
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
}
}
Move => if let SelectPiece(space_coords, piece_index) = action {
if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
if let Some(piece) = space.pieces.remove(piece_index) {
state.turn = MoveSelect(space_coords, piece_index, piece);
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
MoveSelect(space_coords, piece_index, piece) => {
draw_piece(
p,
view,
piece,
world_mouse_x,
world_mouse_y,
piece_texture_spec(piece),
);
let close_enough_grid_coords =
get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let button_outcome = if close_enough_grid_coords.is_some() {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: mouse_button_state,
},
)
} else {
Default::default()
};
let target_space_coords = if button_outcome.clicked {
close_enough_grid_coords
} else {
None
};
if let Some(key) = target_space_coords {
let valid_targets = get_valid_move_targets(&state.board, space_coords);
if valid_targets.contains(&key) {
if let Occupied(mut entry) = state.board.entry(key) {
let mut space = entry.get_mut();
//shpuld this be an insert at 0 so the new piece is clearly visible?
space.pieces.push(piece);
}
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
if let Occupied(mut entry) = state.board.entry(space_coords) {
let mut space = entry.get_mut();
space.pieces.insert(piece_index, piece);
}
state.turn = SelectTurnOption;
}
}
ConvertSlashDemolish => if let SelectPiece(space_coords, piece_index) = action {
let valid_targets =
occupied_by_or_adjacent_spaces(&state.board, state.stashes.player_stash.colour);
if valid_targets.contains(&space_coords) {
state.turn =
ConvertSlashDemolishDiscard(space_coords, piece_index, None, None, None);
} else {
let text =
"You must target a piece at most one space away from your pieces.".to_owned();
state.message = Message {
text,
timeout: WARNING_TIMEOUT,
};
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
},
ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
) => {
if let Some(space) = state.board.get(&space_coords) {
if let Some(piece) = space.pieces.get(piece_index) {
let pips_needed = u8::from(piece.pips);
let hand = &state.player_hand;
let (pips_selected, smallest_card_value) = match (
card_index_1.and_then(|i| hand.get(i)),
card_index_2.and_then(|i| hand.get(i)),
card_index_3.and_then(|i| hand.get(i)),
) {
(None, None, None) => (0, 0),
(Some(&card), None, None) |
(None, Some(&card), None) |
(None, None, Some(&card)) => {
let v = pip_value(&card);
(v, v)
}
(Some(&card1), Some(&card2), None) |
(None, Some(&card1), Some(&card2)) |
(Some(&card1), None, Some(&card2)) => {
let v1 = pip_value(&card1);
let v2 = pip_value(&card2);
(v1 + v2, std::cmp::min(v1, v2))
}
(Some(&card1), Some(&card2), Some(&card3)) => {
let v1 = pip_value(&card1);
let v2 = pip_value(&card2);
let v3 = pip_value(&card3);
(v1 + v2 + v3, std::cmp::min(v1, std::cmp::min(v2, v3)))
}
};
state.turn = if pips_selected >= pips_needed &&
smallest_card_value > pips_selected - pips_needed
{
state.message.timeout = 0;
ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
pips_selected - pips_needed,
)
} else {
if pips_selected >= pips_needed &&
smallest_card_value <= pips_selected - pips_needed
{
state.message = Message {
text: "You cannot discard redundant face cards to get extra draws"
.to_owned(),
timeout: WARNING_TIMEOUT,
}
}
if let SelectCardFromHand(index) = action {
match (
card_index_1.and_then(|i| hand.get(i)),
card_index_2.and_then(|i| hand.get(i)),
card_index_3.and_then(|i| hand.get(i)),
) {
(Some(_), Some(_), Some(_)) => state.turn,
(Some(_), Some(_), _) => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
card_index_2,
Some(index),
),
(Some(_), _, _) => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
card_index_1,
Some(index),
None,
),
_ => ConvertSlashDemolishDiscard(
space_coords,
piece_index,
Some(index),
None,
None,
),
}
} else {
state.turn
}
};
}
};
if right_mouse_pressed || escape_pressed {
state.turn = match state.turn {
ConvertSlashDemolishDiscard(_, _, None, None, None) => ConvertSlashDemolish,
_ => ConvertSlashDemolishDiscard(space_coords, piece_index, None, None, None),
};
} else {
state.message = Message {
text: "Choose which face card(s) to discard from your hand.".to_owned(),
timeout: WARNING_TIMEOUT,
};
}
}
ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
) => {
debug_assert!(cards_owed <= 2);
let hand = &mut state.player_hand;
let stashes = &mut state.stashes;
if let Some(space) = state.board.get_mut(&space_coords) {
let can_convert = if let Some(piece) = space.pieces.get(piece_index) {
let stash = &stashes.player_stash;
match piece.pips {
Pips::One => stash[Pips::One] != NoneLeft,
Pips::Two => stash[Pips::One] != NoneLeft || stash[Pips::Two] != NoneLeft,
Pips::Three => {
stash[Pips::One] != NoneLeft || stash[Pips::Two] != NoneLeft ||
stash[Pips::Three] != NoneLeft
}
}
} else {
false
};
if can_convert &&
turn_options_button(
p,
&mut state.ui_context,
"Convert",
(-0.25, 0.875),
700,
(mouse_x, mouse_y),
mouse_button_state,
) {
state.turn = ConvertSelect(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
);
} else if !can_convert ||
turn_options_button(
p,
&mut state.ui_context,
"Demolish",
(0.25, 0.875),
701,
(mouse_x, mouse_y),
mouse_button_state,
) {
if let Some(piece) = space.pieces.remove(piece_index) {
stashes[piece.colour].add(piece);
}
let pile = &mut state.pile;
card_index_1.map(|i| pile.push(hand.remove(i)));
card_index_2.map(|i| pile.push(hand.remove(i)));
card_index_3.map(|i| pile.push(hand.remove(i)));
for _ in 0..cards_owed {
if let Some(card) = deal_parts(&mut state.deck, pile, &mut state.rng) {
hand.push(card);
}
}
state.turn = Discard;
};
};
if right_mouse_pressed || escape_pressed {
state.turn = ConvertSlashDemolishWhich(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
);
}
}
ConvertSelect(
space_coords,
piece_index,
card_index_1,
card_index_2,
card_index_3,
cards_owed,
) => if let Some(space) = state.board.get_mut(&space_coords) {
if let Some(piece) = space.pieces.get_mut(piece_index) {
let stash_colour = state.stashes.player_stash.colour;
let (has_one, has_two, has_three) = {
let stash = &state.stashes[stash_colour];
(
stash[Pips::One] != NoneLeft,
stash[Pips::Two] != NoneLeft,
stash[Pips::Three] != NoneLeft,
)
};
let mut selected_pips = None;
if has_one && piece.pips == Pips::One {
selected_pips = Some(Pips::One);
}
if !has_one && has_two && piece.pips == Pips::Two {
selected_pips = Some(Pips::Two);
}
if !has_one && !has_two && has_three && piece.pips == Pips::Three {
selected_pips = Some(Pips::Three);
}
if has_one && piece.pips > Pips::One &&
turn_options_button(
p,
&mut state.ui_context,
"Small",
(-2.0 / 3.0, 0.875),
700,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::One);
}
if has_two && piece.pips >= Pips::Two &&
turn_options_button(
p,
&mut state.ui_context,
"Medium",
(0.0, 0.875),
701,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::Two);
}
if has_three && piece.pips >= Pips::Three &&
turn_options_button(
p,
&mut state.ui_context,
"Large",
(2.0 / 3.0, 0.875),
702,
(mouse_x, mouse_y),
mouse_button_state,
) {
selected_pips = Some(Pips::Three);
}
if let Some(pips) = selected_pips {
if pips <= piece.pips {
if let Some(stash_piece) = state.stashes[stash_colour].remove(pips) {
state.stashes[piece.colour].add(*piece);
*piece = stash_piece;
let hand = &mut state.player_hand;
let pile = &mut state.pile;
card_index_1.map(|i| pile.push(hand.remove(i)));
card_index_2.map(|i| pile.push(hand.remove(i)));
card_index_3.map(|i| pile.push(hand.remove(i)));
for _ in 0..cards_owed {
if let Some(card) =
deal_parts(&mut state.deck, pile, &mut state.rng)
{
hand.push(card);
}
}
state.turn = Discard;
}
}
}
}
},
Fly => {
state.highlighted = PlayerOccupation;
if let Some(only_ace_index) = get_only_ace_index(&state.player_hand) {
state.turn =
FlySelectCarpet(state.player_hand.remove(only_ace_index), only_ace_index);
} else if let SelectCardFromHand(index) = action {
let valid_target = if let Some(card) = state.player_hand.get(index) {
if card.value == Ace {
true
} else {
state.message = Message {
text: "That card is not an Ace!".to_owned(),
timeout: WARNING_TIMEOUT,
};
false
}
} else {
false
};
if valid_target {
state.turn = FlySelectCarpet(state.player_hand.remove(index), index);
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
FlySelectCarpet(ace, old_index) => if let SelectSpace(key) = action {
if is_space_movable(&state.board, &key) {
if let Some(space) = state.board.remove(&key) {
state.turn = FlySelect(key, space, ace, old_index);
state.message.timeout = 0;
}
} else {
state.message = Message {
text: "Moving that card leaves a section of cards completely detached!"
.to_owned(),
timeout: WARNING_TIMEOUT,
}
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, ace);
state.turn = SelectTurnOption;
} else {
state.message = Message {
text: "Choose which card on the board to move.".to_owned(),
timeout: WARNING_TIMEOUT,
};
},
FlySelect(old_coords, space, ace, old_index) => {
let Space {
card,
pieces,
offset: space_offset,
} = space;
let fly_from_targets = fly_from_targets(&state.board, &old_coords);
for grid_coords in fly_from_targets.iter() {
let card_matrix = get_card_matrix(&view, get_card_spec(grid_coords));
draw_empty_space(p, card_matrix);
}
let close_enough_grid_coords =
get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let in_place = close_enough_grid_coords.is_some();
let card_spec =
if in_place && fly_from_targets.contains(&close_enough_grid_coords.unwrap()) {
get_card_spec(&close_enough_grid_coords.unwrap())
} else {
(world_mouse_x, world_mouse_y, false)
};
let card_matrix = get_card_matrix(&view, card_spec);
let button_outcome = if in_place {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: mouse_button_state,
},
)
} else {
Default::default()
};
draw_card(p, card_matrix, card.texture_spec());
for (i, piece) in pieces.into_iter().enumerate() {
if i < space_offset as _ || i > (space_offset + PIECES_PER_PAGE) as _ {
continue;
}
let (x, y) = card_relative_piece_coords(i);
draw_piece(p, card_matrix, piece, x, y, piece_texture_spec(piece));
}
let target_space_coords = if button_outcome.clicked {
close_enough_grid_coords
} else {
None
};
if let Some(key) = target_space_coords {
if fly_from_targets.contains(&key) {
state.board.insert(key, space);
state.pile.push(ace);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.board.insert(old_coords, space);
state.player_hand.insert(old_index, ace);
state.turn = SelectTurnOption;
}
}
Hatch => {
if let SelectCardFromHand(index) = action {
//this assumes no pyramids have been duplicated
let no_pieces_on_board = state.stashes.player_stash.is_full();
if no_pieces_on_board {
let valid_target = if let Some(card) = state.player_hand.get(index) {
card.is_number()
} else {
false
};
if valid_target {
state.turn = HatchSelect(state.player_hand.remove(index), index);
}
}
} else if right_mouse_pressed || escape_pressed {
state.turn = SelectTurnOption;
}
}
HatchSelect(held_card, old_index) => {
let hatch_targets = get_all_hatch_targets_set(&state.board);
let target_space_coords = place_card(
p,
state,
&view,
&hatch_targets,
held_card,
(world_mouse_x, world_mouse_y),
mouse_button_state,
);
debug_assert!(state.stashes.player_stash.is_full());
if let Some(key) = target_space_coords {
if hatch_targets.contains(&key) {
let mut pieces: SpacePieces = Default::default();
if let Some(piece) = state.stashes.player_stash.remove(Pips::One) {
pieces.push(piece);
}
state.board.insert(
key,
Space {
card: held_card,
pieces,
..Default::default()
},
);
state.turn = Discard;
}
} else if right_mouse_pressed || escape_pressed {
state.player_hand.insert(old_index, held_card);
state.turn = SelectTurnOption;
}
}
Discard => {
state.highlighted = NoHighlighting;
if state.player_hand.len() > 6 {
if let SelectCardFromHand(index) = action {
state.pile.push(state.player_hand.remove(index));
} else {
state.message = Message {
text: "Discard down to six cards".to_owned(),
timeout: 1000,
};
}
} else {
state.turn = CpuTurn(None);
};
}
CpuTurn(set_participant) => {
let cpu_player_count = cpu_player_count(state);
let mut current_participant =
set_participant.unwrap_or(next_participant(cpu_player_count, Player));
while current_participant != Player {
println!("current_participant: {:?}", current_participant);
let (hand, colour, stashes) = match current_participant {
Player => {
debug_assert!(false, "Attempting to take player's turn");
(
&mut state.player_hand,
state.stashes.player_stash.colour,
&mut state.stashes,
)
}
Cpu(i) => (
&mut state.cpu_hands[i],
state.stashes.cpu_stashes[i].colour,
&mut state.stashes,
),
};
let rng = &mut state.rng;
//DrawInitialCard
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
let mut possible_plan: Option<Plan> =
get_plan(&state.board, stashes, &hand, rng, colour);
'turn: loop {
//TODO better "AI". Evaluate every use of rng in this match statement
let turn_option = if let Some(plan) = possible_plan {
if cfg!(debug_assertions) {
println!("plan is {:?}", plan);
}
match plan {
Plan::Fly(_) | Plan::FlySpecific(_, _) => 6,
Plan::ConvertSlashDemolish(_, _) => 5,
Plan::Move(_) => 4,
Plan::Hatch(_) => 7,
}
} else {
if cfg!(debug_assertions) {
let x = *rng.choose(&vec![0, 1, 2, 3, 4, 5, 7]).unwrap_or(&0);
println!("randomly chose {:?}", x);
x
} else {
*rng.choose(&vec![0, 1, 2, 3, 4, 5, 7]).unwrap_or(&0)
}
};
match turn_option {
1 => {
//Grow
let chosen_piece = {
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i)
{
let possible_piece_index =
state.board.get(&space_coords).and_then(|space| {
let own_pieces = space
.pieces
.filtered_indicies(|p| p.colour == colour);
rng.choose(&own_pieces).map(|&i| i)
});
possible_piece_index
.map(|piece_index| (space_coords, piece_index))
} else {
None
}
};
if let Some((space_coords, piece_index)) = chosen_piece {
match grow_if_available(
space_coords,
piece_index,
&mut state.board,
&mut stashes[colour],
) {
Ok(true) => {
break 'turn;
}
_ => {}
}
}
}
2 => {
//Spawn
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i) {
match spawn_if_possible(
&mut state.board,
&space_coords,
&mut stashes[colour],
) {
Ok(true) => {
break 'turn;
}
_ => {}
}
}
}
3 => {
//Build
let mut number_cards: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.is_number())
.map(|(i, _)| i)
.collect();
//the cpu's choices should be a function of the rng
number_cards.sort();
if let Some(&card_index) = rng.choose(&number_cards) {
let build_targets = get_all_build_targets(&state.board, colour);
if let Some(&key) = rng.choose(&build_targets) {
state.board.insert(
key,
Space {
card: hand.remove(card_index),
..Default::default()
},
);
break 'turn;
}
}
}
4 => {
//Move
let chosen_piece = if let Some(Plan::Move(target)) = possible_plan {
let adjacent_keys: Vec<_> = {
let mut adjacent_keys : Vec<_> = FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + target.0, y + target.1))
.collect();
rng.shuffle(&mut adjacent_keys);
adjacent_keys
};
let mut result = None;
for key in adjacent_keys.iter() {
if let Some(space) = state.board.get(key) {
let own_pieces =
space.pieces.filtered_indicies(|p| p.colour == colour);
if let Some(piece_index) = own_pieces.last() {
result = Some((*key, *piece_index));
break;
}
}
}
if result.is_some() {
result
} else {
possible_plan = None;
None
}
} else {
let occupied_spaces: Vec<_> =
get_all_spaces_occupied_by(&state.board, colour);
if let Some(space_coords) = rng.choose(&occupied_spaces).map(|&i| i)
{
let possible_piece_index =
state.board.get(&space_coords).and_then(|space| {
let own_pieces = space
.pieces
.filtered_indicies(|p| p.colour == colour);
rng.choose(&own_pieces).map(|&i| i)
});
possible_piece_index
.map(|piece_index| (space_coords, piece_index))
} else {
None
}
};
if let Some((space_coords, piece_index)) = chosen_piece {
let possible_target_space_coords =
if let Some(Plan::Move(target)) = possible_plan {
Some(target)
} else {
let valid_targets = set_to_vec(
get_valid_move_targets(&state.board, space_coords),
);
rng.choose(&valid_targets).map(|&i| i)
};
if let Some(target_space_coords) = possible_target_space_coords {
let possible_piece = if let Occupied(mut source_entry) =
state.board.entry(space_coords)
{
let mut source_space = source_entry.get_mut();
source_space.pieces.remove(piece_index)
} else {
None
};
if let Some(piece) = possible_piece {
if let Occupied(mut target_entry) =
state.board.entry(target_space_coords)
{
let mut target_space = target_entry.get_mut();
//shpuld this be an insert at 0
//so the new piece is clearly visible?
target_space.pieces.push(piece);
break 'turn;
}
}
}
}
}
5 => {
//Convert/Demolish
let chosen_enemy_pieces = {
let spaces: Vec<(i8, i8)> =
occupied_by_or_adjacent_spaces(&state.board, colour);
let mut result: Vec<
((i8, i8), usize),
> = vec![];
if let Some(Plan::ConvertSlashDemolish(space_coords, piece_index))
= possible_plan {
if let Some(space) = state.board.get(&space_coords) {
if space.pieces.get(piece_index).is_some() {
result = vec![(space_coords, piece_index)];
}
}
}
if result.len() == 0 {
let mut pieces = Vec::new();
let mut colours = active_colours(stashes);
colours.sort_by_key(|c| stashes[*c].used_count());
colours.retain(|c| *c != colour);
for &target_colour in colours.pop().iter() {
for key in spaces.iter() {
if let Some(space) = state.board.get(key) {
pieces.extend(
space
.pieces
.filtered_indicies(
|piece| piece.colour == target_colour,
)
.iter()
.filter_map(|&i| {
space
.pieces
.get(i)
.map(|p| ((*key, i), p.pips))
}),
);
}
}
}
let stash = &stashes[colour];
let mut available_sizes = Pips::all_values();
available_sizes.retain(|&pips| stash[pips] != NoneLeft);
type Pair = (((i8, i8), usize), Pips);
let (convertable, not_convertable): (Vec<Pair>, Vec<Pair>) =
pieces.iter().partition(|&&(_, pips)|
available_sizes.contains(&pips)
);
result = convertable
.iter()
.chain(not_convertable.iter())
.map(|pair| pair.0)
.collect();
}
result
};
for (space_coords, piece_index) in chosen_enemy_pieces {
if let Some(space) = state.board.get_mut(&space_coords) {
if let Some(piece) = space.pieces.get(piece_index).clone() {
let pips_needed = u8::from(piece.pips);
let selections = {
//TODO we might want to save particular cards to make a
// power block etc.
let mut card_choices :Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| !c.is_number())
.collect();
card_choices.sort_by(|&(_, a), &(_, b)| {
pip_value(&a).cmp(&pip_value(&b))
});
let mut selected_indicies = Vec::new();
let mut pips_selected = 0;
let mut smallest_card_value = 255;
while let Some((index, card)) = card_choices.pop() {
selected_indicies.push(index);
pips_selected += pip_value(card);
smallest_card_value = std::cmp::min(
smallest_card_value,
pip_value(card),
);
if pips_selected >= pips_needed {
break;
}
}
if pips_selected >= pips_needed &&
smallest_card_value > pips_selected - pips_needed
{
let can_convert = match piece.pips {
Pips::One => {
stashes[colour][Pips::One] != NoneLeft
}
Pips::Two => {
stashes[colour][Pips::One] != NoneLeft ||
stashes[colour][Pips::Two] != NoneLeft
}
Pips::Three => {
stashes[colour][Pips::One] != NoneLeft ||
stashes[colour][Pips::Two] !=
NoneLeft ||
stashes[colour][Pips::Three] != NoneLeft
}
};
Some((
selected_indicies,
can_convert,
pips_selected - pips_needed,
))
} else {
possible_plan = None;
None
}
};
//TODO You very rarely might want to demolish instead of
//convert to save a piece in your stash for a future turn
match selections {
Some((selected_indicies, true, cards_owed)) => {
//Convert
for &pips in
vec![Pips::Three, Pips::Two, Pips::One].iter()
{
if pips <= piece.pips {
if let Some(stash_piece) =
stashes[colour].remove(pips)
{
if let Some(old_piece) =
space.pieces.get_mut(piece_index)
{
stashes[old_piece.colour]
.add(*old_piece);
*old_piece = stash_piece;
for i in selected_indicies {
state.pile.push(hand.remove(i));
}
for _ in 0..cards_owed {
if let Some(card) = deal_parts(
&mut state.deck,
&mut state.pile,
rng,
) {
hand.push(card);
}
}
break 'turn;
}
}
}
}
}
Some((selected_indicies, false, cards_owed)) => {
//Demolish
if let Some(piece) =
space.pieces.remove(piece_index)
{
stashes[piece.colour].add(piece);
}
for i in selected_indicies {
state.pile.push(hand.remove(i));
}
for _ in 0..cards_owed {
if let Some(card) = deal_parts(
&mut state.deck,
&mut state.pile,
rng,
) {
hand.push(card);
}
}
break 'turn;
}
_ => {}
};
}
};
}
}
6 => {
//Fly
let ace_indicies: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.value == Ace)
.map(|(i, _)| i)
.collect();
if ace_indicies.len() == 0 {
possible_plan = None;
continue 'turn;
}
let board = &mut state.board;
let chosen_space = {
match possible_plan {
Some(Plan::Fly(target)) |
Some(Plan::FlySpecific(_, target)) => {
if board.contains_key(&target) {
board.remove(&target).map(|space| (target, space))
} else {
possible_plan = None;
None
}
}
_ => {
let spaces = get_all_spaces_occupied_by(board, colour);
rng.choose(&spaces).and_then(
|key| if is_space_movable(board, key) {
board.remove(key).map(|space| (*key, space))
} else {
None
},
)
}
}
};
if let Some((old_coords, space)) = chosen_space {
let target_space_coords: Option<
(i8, i8),
> = if let Some(Plan::FlySpecific(source, _)) = possible_plan {
if let None = board.get(&source) {
Some(source)
} else {
debug_assert!(false, "Bad Plan::FlySpecific!");
None
}
} else {
let fly_from_targets = fly_from_targets(&board, &old_coords);
//TODO if there is a Fly Plan then place
//it as far away as possible
//or in a place that helps the cpu player
rng.choose(&fly_from_targets).cloned()
};
if let Some(key) = target_space_coords {
if let Some(ace_index) = rng.choose(&ace_indicies) {
state.pile.push(hand.remove(*ace_index));
board.insert(key, space);
break 'turn;
}
}
}
}
7 => {
//Hatch
let stash = &mut stashes[colour];
let no_pieces_on_board = stash.is_full();
if no_pieces_on_board {
let mut number_cards: Vec<_> = hand.iter()
.enumerate()
.filter(|&(_, c)| c.is_number())
.map(|(i, _)| i)
.collect();
number_cards.sort();
if let Some(&card_index) = rng.choose(&number_cards) {
let target_space_coords =
if let Some(Plan::Hatch(target)) = possible_plan {
Some(target)
} else {
let mut hatch_targets: Vec<
(i8, i8),
> = get_all_hatch_targets(&state.board)
.iter()
.cloned()
.collect();
hatch_targets.sort();
rng.choose(&hatch_targets).cloned()
};
if let Some(key) = target_space_coords {
let mut pieces: SpacePieces = Default::default();
if let Some(piece) = stash.remove(Pips::One) {
pieces.push(piece);
}
state.board.insert(
key,
Space {
card: hand.remove(card_index),
pieces,
..Default::default()
},
);
break 'turn;
}
}
}
}
_ => {
//DrawThree
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
if let Some(card) = deal_parts(&mut state.deck, &mut state.pile, rng) {
hand.push(card);
}
break 'turn;
}
}
}
current_participant = next_participant(cpu_player_count, current_participant);
}
state.turn = DrawInitialCard;
}
Over(winner, possible_second_winner) => {
fn win_message(participant: Participant) -> String {
match participant {
Player => "You win".to_owned(),
Cpu(i) => format!("Cpu {} wins", i),
}
}
let text = format!("{}!", win_message(winner));
draw_outlined_text(
p,
&text,
(0.0, 0.875),
1.0,
36.0,
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
);
if let Some(second_winner) = possible_second_winner {
draw_outlined_text(
p,
&format!("{} as well!", win_message(second_winner)),
(0.0, 0.75),
1.0,
36.0,
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
);
}
}
};
//draw the hud here so the layering is correct
(p.draw_layer)(1, state.hud_alpha);
//draw the message over top of everything
if state.message.timeout > 0 {
let message_location = (0.0, -((HUD_LINE * 2.0) - 1.0) + 0.125);
let alpha = if state.message.timeout > 512 {
1.0
} else {
state.message.timeout as f32 / 512.0
};
let outline_colour = [0.0, 0.0, 0.0, alpha];
let boosted_alpha = if alpha * 2.0 >= 1.0 { 1.0 } else { alpha * 2.0 };
let middle_alpha = if boosted_alpha >= alpha {
boosted_alpha
} else {
alpha
};
let middle_colour = [1.0, 1.0, 1.0, middle_alpha];
draw_outlined_text(
p,
&state.message.text,
message_location,
1.0,
24.0,
middle_colour,
outline_colour,
);
state.message.timeout = state.message.timeout.saturating_sub(16);
}
if cfg!(debug_assertions) {
if t != state.turn {
println!("{:?}", state.turn);
}
}
match state.turn {
DrawUntilNumberCard |
FirstRound(_, _) |
DrawInitialCard |
SelectTurnOption |
Discard |
CpuTurn(_) |
Over(_, _) => if escape_pressed {
return true;
},
_ => {}
};
if cfg!(debug_assertions) {
fn diff<T: Copy + PartialEq>(a: &Vec<T>, b: &Vec<T>) -> Vec<T> {
let mut diff = Vec::new();
let (shorter, longer) = if a.len() > b.len() {
(&b, &a)
} else {
(&a, &b)
};
for i in 0..longer.len() {
match (shorter.get(i), longer.get(i)) {
(Some(c1), Some(c2)) if c1 == c2 => {}
(Some(_), Some(c2)) => {
diff.push(*c2);
}
(Some(c), None) | (None, Some(c)) => {
diff.push(*c);
}
(None, None) => {}
}
}
diff
}
////////////////////
// card check //
////////////////////
let mut all_cards = Vec::new();
all_cards.extend(state.player_hand.iter().cloned());
for hand in state.cpu_hands.iter() {
all_cards.extend(hand.iter().cloned());
}
all_cards.extend(state.deck.iter().cloned());
all_cards.extend(state.pile.iter().cloned());
let mut over_okay = false;
match state.turn {
FirstRound(starter_cards, _) | FirstRoundPlayer(starter_cards) => {
all_cards.push(starter_cards.player_card.clone());
for possible_card in starter_cards.cpu_cards.iter() {
if let Some(card) = *possible_card {
all_cards.push(card);
}
}
over_okay = true;
}
BuildSelect(card, _) | FlySelectCarpet(card, _) | HatchSelect(card, _) => {
all_cards.push(card);
}
FlySelect(_, space, card, _) => {
all_cards.push(space.card);
all_cards.push(card);
}
_ => {}
}
for space in state.board.values() {
all_cards.push(space.card.clone());
}
all_cards.sort();
let fresh_deck = Card::all_values();
if over_okay {
assert!(all_cards.len() >= fresh_deck.len());
} else {
assert_eq!(
all_cards,
fresh_deck,
"
all_cards.len():{:?}
fresh_deck.len():{:?}
diff :{:?}",
all_cards.len(),
fresh_deck.len(),
diff(&all_cards, &fresh_deck)
);
}
////////////////////
// piece check //
////////////////////
let colours = active_colours(&state.stashes);
let mut all_pieces = Vec::new();
for &colour in colours.iter() {
let stash = &state.stashes[colour];
for pips in Pips::all_values() {
match stash[pips] {
NoneLeft => {}
OneLeft => {
all_pieces.push(Piece { colour, pips });
}
TwoLeft => {
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
}
ThreeLeft => {
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
all_pieces.push(Piece { colour, pips });
}
}
}
}
for space in state.board.values() {
for piece in space.pieces.clone().into_iter() {
all_pieces.push(piece);
}
}
match state.turn {
MoveSelect(_, _, piece) => {
all_pieces.push(piece);
}
FlySelect(_, space, _, _) => for piece in space.pieces.clone().into_iter() {
all_pieces.push(piece);
},
_ => {}
}
all_pieces.sort();
let mut one_of_each = Piece::all_values();
one_of_each.retain(|p| colours.contains(&p.colour));
let mut expected = Vec::new();
for piece in one_of_each {
expected.push(piece);
expected.push(piece);
expected.push(piece);
}
assert_eq!(
all_pieces,
expected,
"
all_pieces.len():{:?}
expected.len():{:?}
diff :{:?}",
all_pieces.len(),
expected.len(),
diff(&all_pieces, &expected)
);
}
false
}
fn occupied_by_or_adjacent_spaces(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
let mut set = get_all_spaces_occupied_by_set(board, colour);
let initial_keys: Vec<(i8, i8)> = set.iter().cloned().collect();
for key in initial_keys {
set.extend(
FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + key.0, y + key.1)),
);
}
set_to_vec(set)
}
//a cheesy way to do an outline
fn draw_outlined_text(
p: &Platform,
text: &str,
location: (f32, f32),
screen_width_percentage: f32,
scale: f32,
middle_colour: [f32; 4],
outline_colour: [f32; 4],
) {
//let's just lineraly extrapolate from what worked before!
let outline_scale = scale * 24.5 / 24.0;
let outline_offset = 1.0 / (512.0 * 24.0);
(p.draw_text)(
text,
(location.0 + outline_offset, location.1 - outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 - outline_offset, location.1 + outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 - outline_offset, location.1 - outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
(location.0 + outline_offset, location.1 + outline_offset),
screen_width_percentage,
outline_scale,
outline_colour,
0,
);
(p.draw_text)(
text,
location,
screen_width_percentage,
scale,
middle_colour,
0,
);
}
const HUD_LINE: f32 = 0.675;
const WARNING_TIMEOUT: u32 = 2500;
fn place_card(
p: &Platform,
state: &mut State,
view: &[f32; 16],
targets: &HashSet<(i8, i8)>,
card: Card,
(world_mouse_x, world_mouse_y): (f32, f32),
button_state: ButtonState,
) -> Option<(i8, i8)> {
for grid_coords in targets.iter() {
let card_matrix = get_card_matrix(&view, get_card_spec(grid_coords));
draw_empty_space(p, card_matrix);
}
let close_enough_grid_coords = get_close_enough_grid_coords(world_mouse_x, world_mouse_y);
let in_place = close_enough_grid_coords.is_some();
let card_spec = if in_place && targets.contains(&close_enough_grid_coords.unwrap()) {
get_card_spec(&close_enough_grid_coords.unwrap())
} else {
(world_mouse_x, world_mouse_y, false)
};
let card_matrix = get_card_matrix(&view, card_spec);
let button_outcome = if in_place {
button_logic(
&mut state.ui_context,
Button {
id: 500,
pointer_inside: true,
state: button_state,
},
)
} else {
Default::default()
};
draw_card(p, card_matrix, card.texture_spec());
if button_outcome.clicked {
close_enough_grid_coords
} else {
None
}
}
fn cpu_player_count(state: &State) -> usize {
state.cpu_hands.len()
}
fn next_participant(cpu_player_count: usize, participant: Participant) -> Participant {
match participant {
Player => Cpu(0),
Cpu(i) => if i >= cpu_player_count - 1 {
Player
} else {
Cpu(i + 1)
},
}
}
fn pip_value(card: &Card) -> u8 {
match card.value {
Ace | Jack /* | Joker*/ => 1,
Queen => 2,
King => 3,
//this value ensures the set of cards will be rejected
_ => 0,
}
}
fn turn_options_button(
p: &Platform,
context: &mut UIContext,
label: &str,
(x, y): (f32, f32),
id: UiId,
(mouse_x, mouse_y): (f32, f32),
state: ButtonState,
) -> bool {
let mut texture_spec = (
3.0 * CARD_TEXTURE_WIDTH,
4.0 * CARD_TEXTURE_HEIGHT + (4.0 * TOOLTIP_TEXTURE_HEIGHT_OFFSET),
TOOLTIP_TEXTURE_WIDTH,
TOOLTIP_TEXTURE_HEIGHT,
0,
0.0,
0.0,
0.0,
0.0,
);
let camera = scale_translation(0.0625, x, y);
let inverse_camera = inverse_scale_translation(0.0625, x, y);
let (box_mouse_x, box_mouse_y, _, _) =
mat4x4_vector_mul(&inverse_camera, mouse_x, mouse_y, 0.0, 1.0);
let pointer_inside = box_mouse_x.abs() <= TOOLTIP_RATIO && box_mouse_y.abs() <= 1.0;
let button_outcome = button_logic(
context,
Button {
id,
pointer_inside,
state,
},
);
match button_outcome.draw_state {
Pressed => {
texture_spec.5 = -0.5;
texture_spec.6 = -0.5;
}
Hover => {
texture_spec.5 = -0.5;
texture_spec.7 = -0.5;
}
Inactive => {}
}
(p.draw_textured_poly_with_matrix)(camera, 2, texture_spec, 0);
let font_scale = if label.len() > 8 { 18.0 } else { 24.0 };
(p.draw_text)(label, (x, y), 1.0, font_scale, [1.0; 4], 0);
button_outcome.clicked
}
fn get_only_ace_index(hand: &Vec<Card>) -> Option<usize> {
let mut result = None;
for (i, card) in hand.iter().enumerate() {
if card.value == Ace {
if result.is_none() {
result = Some(i);
} else {
return None;
}
}
}
result
}
fn spawn_if_possible(
board: &mut Board,
key: &(i8, i8),
stash: &mut Stash,
) -> Result<bool, Message> {
if stash[Pips::One] == NoneLeft {
return Err(Message {
text: "You are out of small pyramids!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
if is_occupied_by(board, key, stash.colour) {
if let Some(mut space) = board.get_mut(key) {
if let Some(piece) = stash.remove(Pips::One) {
space.pieces.push(piece);
return Ok(true);
}
}
}
Ok(false)
}
fn is_occupied_by(board: &Board, grid_coords: &(i8, i8), colour: PieceColour) -> bool {
if let Some(space) = board.get(grid_coords) {
space_occupied_by(space, colour)
} else {
false
}
}
fn space_occupied_by(space: &Space, colour: PieceColour) -> bool {
space.pieces.any(|piece| piece.colour == colour)
}
fn grow_if_available(
space_coords: (i8, i8),
piece_index: usize,
board: &mut Board,
stash: &mut Stash,
) -> Result<bool, Message> {
if let Occupied(mut entry) = board.entry(space_coords) {
let mut space = entry.get_mut();
if let Some(piece) = space.pieces.get_mut(piece_index) {
if piece.colour == stash.colour {
match piece.pips {
Pips::One | Pips::Two => {
if let Some(larger_piece) = stash.remove(piece.pips.higher()) {
let temp = piece.clone();
*piece = larger_piece;
stash.add(temp);
return Ok(true);
}
}
Pips::Three => {
return Err(Message {
text: "That pyramid is already maximum size!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
}
} else {
return Err(Message {
text: "You cannot grow another player's piece!".to_owned(),
timeout: WARNING_TIMEOUT,
});
}
}
}
Ok(false)
}
const PIECES_PER_PAGE: u8 = 4;
fn point_in_square_on_card(
(point_x, point_y): (f32, f32),
(box_center_x, box_center_y): (f32, f32),
square_size: f32,
rotated: bool,
) -> bool {
if rotated {
//swapping x and y and inverting y is equivalent to rotation by 90 degrees
//This trick appears to only works with a square
(-point_y - box_center_x).abs() <= square_size &&
(point_x - box_center_y).abs() <= square_size
} else {
(point_x - box_center_x).abs() <= square_size &&
(point_y - box_center_y).abs() <= square_size
}
}
const ARROW_SIZE: f32 = 15.0;
fn scale_translation(scale: f32, x_offest: f32, y_offset: f32) -> [f32; 16] {
[
scale,
0.0,
0.0,
0.0,
0.0,
scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
x_offest,
y_offset,
0.0,
1.0,
]
}
fn inverse_scale_translation(scale: f32, x_offest: f32, y_offset: f32) -> [f32; 16] {
scale_translation(1.0 / scale, -x_offest / scale, -y_offset / scale)
}
fn get_close_enough_grid_coords(world_mouse_x: f32, world_mouse_y: f32) -> Option<(i8, i8)> {
let closest_grid_coords = from_world_coords((world_mouse_x, world_mouse_y));
let rotated = card_is_rotated(&closest_grid_coords);
let (center_x, center_y) = to_world_coords(closest_grid_coords);
let (x_distance, y_distance) = (
f32::abs(center_x - world_mouse_x),
f32::abs(center_y - world_mouse_y),
);
let in_bounds = if rotated {
x_distance < CARD_LONG_RADIUS && y_distance < CARD_SHORT_RADIUS
} else {
x_distance < CARD_SHORT_RADIUS && y_distance < CARD_LONG_RADIUS
};
if in_bounds {
Some(closest_grid_coords)
} else {
None
}
}
const CARD_LONG_RADIUS: f32 = 1.0;
const CARD_SHORT_RADIUS: f32 = CARD_RATIO;
type CardSpec = (f32, f32, bool);
fn get_card_spec(grid_coords: &(i8, i8)) -> CardSpec {
let (card_x, card_y) = to_world_coords(*grid_coords);
let rotated = card_is_rotated(grid_coords);
(card_x, card_y, rotated)
}
use std::collections::HashSet;
fn get_valid_move_targets(board: &Board, (x, y): (i8, i8)) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
result
}
fn get_all_build_targets(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
set_to_vec(get_all_build_targets_set(board, colour))
}
fn get_all_build_targets_set(board: &Board, colour: PieceColour) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
let occupied_spaces = get_all_spaces_occupied_by_set(board, colour);
for &(x, y) in occupied_spaces.iter() {
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
result
}
fn get_all_hatch_targets(board: &Board) -> Vec<(i8, i8)> {
set_to_vec(get_all_hatch_targets_set(board))
}
fn get_all_hatch_targets_set(board: &Board) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
for &(x, y) in board.keys() {
for &(dx, dy) in EIGHT_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
result
}
fn get_all_spaces_occupied_by(board: &Board, colour: PieceColour) -> Vec<(i8, i8)> {
set_to_vec(get_all_spaces_occupied_by_set(board, colour))
}
fn set_to_vec(set: HashSet<(i8, i8)>) -> Vec<(i8, i8)> {
let mut result: Vec<_> = set.iter().cloned().collect();
//we want the chosen results to be a function only our rng, not the HashSet's internal one
result.sort();
result
}
fn get_all_spaces_occupied_by_set(board: &Board, colour: PieceColour) -> HashSet<(i8, i8)> {
board
.iter()
.filter_map(|(key, space)| if space_occupied_by(space, colour) {
Some(*key)
} else {
None
})
.collect()
}
fn card_is_rotated(grid_coords: &(i8, i8)) -> bool {
(grid_coords.0 + grid_coords.1) % 2 == 0
}
fn card_relative_piece_coords(index: usize) -> (f32, f32) {
match index % 4 {
0 => (0.35, 0.5),
1 => (-0.35, 0.5),
2 => (-0.35, -0.5),
3 => (0.35, -0.5),
_ => (0.0, 0.0),
}
}
fn draw_piece(
p: &Platform,
card_matrix: [f32; 16],
piece: Piece,
x: f32,
y: f32,
piece_texture_spec: TextureSpec,
) {
let scale = piece_scale(piece);
let piece_matrix = scale_translation(scale, x, y);
(p.draw_textured_poly_with_matrix)(
mat4x4_mul(&piece_matrix, &card_matrix),
SQUARE_POLY_INDEX,
piece_texture_spec,
0,
);
}
fn single_controller(stashes: &Stashes, board: &Board, block: Block) -> Option<Participant> {
if let Some(pieces_array) = block_to_pieces(board, block) {
let mut participant_iter = pieces_array
.iter()
.map(|pieces| controller(stashes, pieces));
let possible_particpants: [Option<Participant>; 3] = [
participant_iter.next().and_then(id),
participant_iter.next().and_then(id),
participant_iter.next().and_then(id),
];
match (
possible_particpants[0],
possible_particpants[1],
possible_particpants[2],
) {
(Some(p1), Some(p2), Some(p3)) if p1 == p2 && p2 == p3 => Some(p1),
_ => None,
}
} else {
None
}
}
fn controller(stashes: &Stashes, pieces: &SpacePieces) -> Option<Participant> {
let mut possible_colour = None;
for piece in pieces.into_iter() {
if let Some(colour) = possible_colour {
if colour != piece.colour {
return None;
}
} else {
possible_colour = Some(piece.colour);
}
}
possible_colour.and_then(|colour| if stashes.player_stash.colour == colour {
Some(Player)
} else {
for i in 0..stashes.cpu_stashes.len() {
if stashes.cpu_stashes[i].colour == colour {
return Some(Cpu(i));
}
}
None
})
}
#[derive(Clone, Copy, Debug)]
enum Block {
Horizontal(i8, (i8, i8, i8)),
Vertical(i8, (i8, i8, i8)),
UpRight(i8, i8),
UpLeft(i8, i8),
DownLeft(i8, i8),
DownRight(i8, i8),
}
use Block::*;
fn power_blocks(board: &Board) -> Vec<Block> {
let mut result = Vec::new();
for &(x, y) in board.keys() {
let horizontal = Horizontal(y, (x - 1, x, x + 1));
if is_power_block(board, horizontal) {
result.push(horizontal);
}
let vertical = Vertical(x, (y - 1, y, y + 1));
if is_power_block(board, vertical) {
result.push(vertical);
}
let up_right = UpRight(x, y);
if is_power_block(board, up_right) {
result.push(up_right);
}
let up_left = UpLeft(x, y);
if is_power_block(board, up_left) {
result.push(up_left);
}
let down_right = DownRight(x, y);
if is_power_block(board, down_right) {
result.push(down_right);
}
let down_left = DownLeft(x, y);
if is_power_block(board, down_left) {
result.push(down_left);
}
}
result
}
#[derive(Clone, Copy, Debug)]
struct CompletableBlock {
keys: [(i8, i8); 2],
completion: Completion,
}
#[derive(Clone, Copy, Debug)]
enum Completion {
Unique(Suit, Value),
ValueMatch(Value),
SuitedEnds(Suit, (Value, Value)),
}
use Completion::*;
fn completable_power_block(board: &Board, block: Block) -> Option<CompletableBlock> {
if let Some((keys, mut cards)) = block_to_two_cards_and_a_blank(board, block) {
cards.sort();
match (cards[0], cards[1]) {
(Card { value: v1, .. }, Card { value: v2, .. })
if v1.is_number() && v2.is_number() && v1 == v2 =>
{
Some(CompletableBlock {
keys,
completion: ValueMatch(v1),
})
}
(
Card {
value: v1,
suit: s1,
},
Card {
value: v2,
suit: s2,
},
) if v1.is_number() && v2.is_number() && s1 == s2 =>
{
let v1_f32 = f32::from(v1);
let v2_f32 = f32::from(v2);
if v1_f32 + 1.0 == v2_f32 {
match (v1.lower_number(), v2.higher_number()) {
(Some(low), Some(high)) => Some(CompletableBlock {
keys,
completion: SuitedEnds(s1, (low, high)),
}),
(Some(v), _) | (_, Some(v)) => Some(CompletableBlock {
keys,
completion: Unique(s1, v),
}),
(None, None) => None,
}
} else if v1_f32 + 2.0 == v2_f32 {
v1.higher_number().map(|v| {
CompletableBlock {
keys,
completion: Unique(s1, v),
}
})
} else {
None
}
}
_ => None,
}
} else {
None
}
}
fn block_to_two_cards_and_a_blank(
board: &Board,
block: Block,
) -> Option<([(i8, i8); 2], [Card; 2])> {
let coords = block_to_coords(block);
let mut pairs_iter = coords
.iter()
.map(|key| board.get(key).map(|s| (*key, s.card)));
let possible_pairs: [Option<((i8, i8), Card)>; 3] = [
pairs_iter.next().and_then(id),
pairs_iter.next().and_then(id),
pairs_iter.next().and_then(id),
];
match (possible_pairs[0], possible_pairs[1], possible_pairs[2]) {
(Some(p1), Some(p2), _) | (Some(p1), _, Some(p2)) | (_, Some(p1), Some(p2)) => {
Some(([p1.0, p2.0], [p1.1, p2.1]))
}
_ => None,
}
}
fn completable_power_blocks(board: &Board) -> Vec<CompletableBlock> {
let mut result = Vec::new();
for &(x, y) in board.keys() {
let horizontal = Horizontal(y, (x - 1, x, x + 1));
if let Some(completable) = completable_power_block(board, horizontal) {
result.push(completable);
}
let vertical = Vertical(x, (y - 1, y, y + 1));
if let Some(completable) = completable_power_block(board, vertical) {
result.push(completable);
}
let up_right = UpRight(x, y);
if let Some(completable) = completable_power_block(board, up_right) {
result.push(completable);
}
let up_left = UpLeft(x, y);
if let Some(completable) = completable_power_block(board, up_left) {
result.push(completable);
}
let down_right = DownRight(x, y);
if let Some(completable) = completable_power_block(board, down_right) {
result.push(completable);
}
let down_left = DownLeft(x, y);
if let Some(completable) = completable_power_block(board, down_left) {
result.push(completable);
}
}
result
}
fn block_to_coords(block: Block) -> [(i8, i8); 3] {
match block {
Horizontal(y, (x_minus_1, x, x_plus_1)) => [(x_minus_1, y), (x, y), (x_plus_1, y)],
Vertical(x, (y_minus_1, y, y_plus_1)) => [(x, y_minus_1), (x, y), (x, y_plus_1)],
UpRight(x, y) => [(x, y + 1), (x, y), (x + 1, y)],
UpLeft(x, y) => [(x, y + 1), (x, y), (x - 1, y)],
DownLeft(x, y) => [(x, y - 1), (x, y), (x - 1, y)],
DownRight(x, y) => [(x, y - 1), (x, y), (x + 1, y)],
}
}
/// The identity function.
fn id<T>(x: T) -> T {
x
}
fn block_to_cards(board: &Board, block: Block) -> Option<[Card; 3]> {
let coords = block_to_coords(block);
let mut cards_iter = coords.iter().map(|key| board.get(key).map(|s| s.card));
let possible_cards: [Option<Card>; 3] = [
cards_iter.next().and_then(id),
cards_iter.next().and_then(id),
cards_iter.next().and_then(id),
];
match (possible_cards[0], possible_cards[1], possible_cards[2]) {
(Some(c1), Some(c2), Some(c3)) => Some([c1, c2, c3]),
_ => None,
}
}
fn block_to_pieces(board: &Board, block: Block) -> Option<[SpacePieces; 3]> {
let coords = block_to_coords(block);
let mut coords_iter = coords
.iter()
.map(|key| board.get(key).map(|s| (*s).pieces.clone()));
let possible_pieces: [Option<SpacePieces>; 3] = [
coords_iter.next().and_then(id),
coords_iter.next().and_then(id),
coords_iter.next().and_then(id),
];
match (possible_pieces[0], possible_pieces[1], possible_pieces[2]) {
(Some(p1), Some(p2), Some(p3)) => Some([p1, p2, p3]),
_ => None,
}
}
fn is_power_block(board: &Board, block: Block) -> bool {
if let Some(mut cards) = block_to_cards(board, block) {
cards.sort();
match (cards[0], cards[1], cards[2]) {
(Card { value: v1, .. }, Card { value: v2, .. }, Card { value: v3, .. })
if v1.is_number() && v2.is_number() && v3.is_number() && v1 == v2 && v2 == v3 =>
{
true
}
(
Card {
value: v1,
suit: s1,
},
Card {
value: v2,
suit: s2,
},
Card {
value: v3,
suit: s3,
},
) if v1.is_number() && v2.is_number() && v3.is_number() && s1 == s2 && s2 == s3 =>
{
f32::from(v1) + 1.0 == f32::from(v2) && f32::from(v2) + 1.0 == f32::from(v3)
}
_ => false,
}
} else {
false
}
}
fn draw_card(p: &Platform, card_matrix: [f32; 16], texture_spec: TextureSpec) {
(p.draw_textured_poly_with_matrix)(card_matrix, CARD_POLY_INDEX, texture_spec, 0);
}
fn draw_empty_space(p: &Platform, card_matrix: [f32; 16]) {
(p.draw_textured_poly_with_matrix)(
card_matrix,
CARD_POLY_INDEX,
(
4.0 * CARD_TEXTURE_WIDTH,
4.0 * CARD_TEXTURE_HEIGHT,
CARD_TEXTURE_WIDTH,
CARD_TEXTURE_HEIGHT,
0,
0.0,
0.0,
0.0,
0.0,
),
0,
);
}
fn get_card_matrix(view: &[f32; 16], (card_x, card_y, rotated): CardSpec) -> [f32; 16] {
let angle = if rotated {
std::f32::consts::FRAC_PI_2
} else {
0.0
};
let world_matrix = [
f32::cos(angle),
-f32::sin(angle),
0.0,
0.0,
f32::sin(angle),
f32::cos(angle),
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
mat4x4_mul(&world_matrix, view)
}
fn draw_hud(
p: &Platform,
state: &mut State,
aspect_ratio: f32,
(mouse_x, mouse_y): (f32, f32),
mouse_button_state: ButtonState,
) -> Action {
let mut result = NoAction;
let layer = 1;
let near = 0.5;
let far = 1024.0;
let scale = 8.0;
let top = scale;
let bottom = -top;
let right = aspect_ratio * scale;
let left = -right;
let half_height = scale * 2.0;
let half_width = half_height * aspect_ratio;
let projection_spec = ProjectionSpec {
top,
bottom,
left,
right,
near,
far,
projection: Perspective,
// projection: Orthographic,
};
let hud_view = get_projection(&projection_spec);
let inverse_hud_view = get_projection(&projection_spec.inverse());
let (hud_mouse_x, hud_mouse_y, _, _) =
mat4x4_vector_mul_divide(&inverse_hud_view, mouse_x, mouse_y, 0.0, 1.0);
let card_scale = 3.0;
let hand_length = state.player_hand.len();
let mut card_coords = vec![(0.0, 0.0); hand_length];
let mut selected_index = None;
for i in (0..hand_length).rev() {
let (card_x, card_y) = (-half_width * (13.0 - i as f32) / 16.0, -half_height * 0.75);
card_coords[i] = (card_x, card_y);
if selected_index.is_none() {
let (card_mouse_x, card_mouse_y) = (hud_mouse_x - card_x, hud_mouse_y - card_y);
let on_card = (card_mouse_x).abs() <= CARD_RATIO * card_scale &&
(card_mouse_y).abs() <= card_scale;
if on_card {
selected_index = Some(i);
}
}
}
for (i, card) in state.player_hand.iter().enumerate() {
let (card_x, card_y) = card_coords[i];
let hand_camera_matrix = [
card_scale,
0.0,
0.0,
0.0,
0.0,
card_scale,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
card_x,
card_y,
0.0,
1.0,
];
let card_matrix = mat4x4_mul(&hand_camera_matrix, &hud_view);
let pointer_inside = match state.turn {
Build | Hatch | WhoStarts => card.is_number() && selected_index == Some(i),
ConvertSlashDemolishDiscard(_, _, _, _, _) => {
!card.is_number() && selected_index == Some(i)
}
Fly => card.value == Ace && selected_index == Some(i),
Discard => selected_index == Some(i),
_ => false,
};
let button_outcome = button_logic(
&mut state.ui_context,
Button {
id: (250 + i) as _,
pointer_inside,
state: mouse_button_state,
},
);
let mut texture_spec = card.texture_spec();
if button_outcome.clicked {
result = SelectCardFromHand(i);
} else {
match button_outcome.draw_state {
Pressed => {
texture_spec.5 = -0.5;
texture_spec.6 = -0.5;
}
Hover => {
texture_spec.5 = -0.5;
texture_spec.7 = -0.5;
}
Inactive => {}
}
}
(p.draw_textured_poly_with_matrix)(card_matrix, CARD_POLY_INDEX, texture_spec, layer);
}
let (stash_x, stash_y) = (half_width * 0.75, -half_height * 25.0 / 32.0);
let stash_camera_matrix = [
3.0,
0.0,
0.0,
0.0,
0.0,
3.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
stash_x,
stash_y,
0.0,
1.0,
];
let stash_matrix = mat4x4_mul(&stash_camera_matrix, &hud_view);
draw_stash(p, stash_matrix, &state.stashes.player_stash, layer);
result
}
fn draw_stash(p: &Platform, matrix: [f32; 16], stash: &Stash, layer: usize) {
let pips_vec = vec![Pips::Three, Pips::Two, Pips::One];
for (pile_index, &pips) in pips_vec.iter().enumerate() {
let poly_index = match pips {
Pips::One => 3,
Pips::Two => 4,
Pips::Three => 5,
};
let piece = Piece {
colour: stash.colour,
pips,
};
let scale = piece_scale(piece) * 2.0;
for i in 0..u8::from(stash[pips]) {
//this includes a 90 degree rotation
let camera_matrix = [
0.0,
scale,
0.0,
0.0,
-scale,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
(pile_index as f32 * 1.5) - (0.625 / scale),
(i as f32 * scale) + (pile_index as f32 * -15.0 / 64.0),
0.0,
1.0,
];
let texture_spec = stash_piece_texture_spec(&piece);
(p.draw_textured_poly_with_matrix)(
mat4x4_mul(&camera_matrix, &matrix),
poly_index,
texture_spec,
layer,
);
}
}
}
#[derive(Copy, Clone, Debug)]
struct Button {
id: UiId,
pointer_inside: bool,
state: ButtonState,
}
#[derive(Copy, Clone, Debug)]
struct ButtonState {
pressed: bool,
released: bool,
held: bool,
}
#[derive(Copy, Clone, Debug)]
struct ButtonOutcome {
clicked: bool,
draw_state: DrawState,
}
impl Default for ButtonOutcome {
fn default() -> Self {
ButtonOutcome {
clicked: false,
draw_state: Inactive,
}
}
}
#[derive(Copy, Clone, Debug)]
enum DrawState {
Pressed,
Hover,
Inactive,
}
use DrawState::*;
///This function handles the logic for a given button and returns wheter it was clicked
///and the state of the button so it can be drawn properly elsestate of the button so
///it can be drawn properly elsewhere
fn button_logic(context: &mut UIContext, button: Button) -> ButtonOutcome {
/// In order for this to work properly `context.frame_init();`
/// must be called at the start of each frame, before this function is called
let mut clicked = false;
let inside = button.pointer_inside;
let id = button.id;
if context.active == id {
if button.state.released {
clicked = context.hot == id && inside;
context.set_not_active();
}
} else if context.hot == id {
if button.state.pressed {
context.set_active(id);
}
}
if inside {
context.set_next_hot(id);
}
let draw_state = if context.active == id && (button.state.held || button.state.pressed) {
Pressed
} else if context.hot == id {
Hover
} else {
Inactive
};
ButtonOutcome {
clicked,
draw_state,
}
}
//map [0,1] to [-1,1]
fn center(x: f32) -> f32 {
x * 2.0 - 1.0
}
const LARGEST_PIECE_TEXTURE_SIZE: f32 = 65.0 / T_S;
fn piece_scale(piece: Piece) -> f32 {
piece_size(piece) * 5.0
}
fn piece_size(piece: Piece) -> f32 {
match piece.pips {
Pips::One => 33.0 / T_S,
Pips::Two => 49.0 / T_S,
Pips::Three => LARGEST_PIECE_TEXTURE_SIZE,
}
}
fn piece_texture_spec(piece: Piece) -> TextureSpec {
let size = piece_size(piece);
let (x, y) = match piece.pips {
Pips::One => (114.0 / T_S, 792.0 / T_S),
Pips::Two => (65.0 / T_S, 776.0 / T_S),
Pips::Three => (0.0, 760.0 / T_S),
};
let colour_offset = LARGEST_PIECE_TEXTURE_SIZE * f32::from(piece.colour);
(
x,
y + colour_offset,
size,
size,
i32::from(piece.colour),
0.0,
0.0,
0.0,
0.0,
)
}
fn stash_piece_texture_spec(piece: &Piece) -> TextureSpec {
let (x, y) = match piece.pips {
Pips::One => (320.0 / T_S, 792.0 / T_S),
Pips::Two => (246.0 / T_S, 776.0 / T_S),
Pips::Three => (148.0 / T_S, 760.0 / T_S),
};
let (w, h) = match piece.pips {
Pips::One => (STASH_ONE_PIP_WIDTH / T_S, STASH_ONE_PIP_HEIGHT / T_S),
Pips::Two => (STASH_TWO_PIP_WIDTH / T_S, STASH_TWO_PIP_HEIGHT / T_S),
Pips::Three => (STASH_THREE_PIP_WIDTH / T_S, STASH_THREE_PIP_HEIGHT / T_S),
};
let colour_offset = LARGEST_PIECE_TEXTURE_SIZE * f32::from(piece.colour);
(
x,
y + colour_offset,
w,
h,
i32::from(piece.colour),
0.0,
0.0,
0.0,
0.0,
)
}
fn to_world_coords((grid_x, grid_y): (i8, i8)) -> (f32, f32) {
(grid_x as f32 * 2.0, grid_y as f32 * 2.0)
}
fn from_world_coords((world_x, world_y): (f32, f32)) -> (i8, i8) {
((world_x / 2.0).round() as i8, (world_y / 2.0).round() as i8)
}
fn add_random_board_card(state: &mut State) {
state.board.insert(
(state.rng.gen_range(-10, 10), state.rng.gen_range(-10, 10)),
state.rng.gen(),
);
}
const CARD_POLY_INDEX: usize = 0;
const SQUARE_POLY_INDEX: usize = 1;
const CARD_RATIO: f32 = CARD_TEXTURE_PIXEL_WIDTH / CARD_TEXTURE_PIXEL_HEIGHT;
const TOOLTIP_RATIO: f32 = TOOLTIP_TEXTURE_PIXEL_WIDTH / TOOLTIP_TEXTURE_PIXEL_HEIGHT;
const STASH_ONE_PIP_WIDTH: f32 = 49.0;
const STASH_ONE_PIP_HEIGHT: f32 = 33.0;
const STASH_TWO_PIP_WIDTH: f32 = 73.0;
const STASH_TWO_PIP_HEIGHT: f32 = 49.0;
const STASH_THREE_PIP_WIDTH: f32 = 97.0;
const STASH_THREE_PIP_HEIGHT: f32 = 65.0;
const STASH_ONE_PIP_RATIO: f32 = STASH_ONE_PIP_WIDTH / STASH_ONE_PIP_HEIGHT;
const STASH_TWO_PIP_RATIO: f32 = STASH_TWO_PIP_WIDTH / STASH_TWO_PIP_HEIGHT;
const STASH_THREE_PIP_RATIO: f32 = STASH_THREE_PIP_WIDTH / STASH_THREE_PIP_HEIGHT;
//These are the verticies of the polygons which can be drawn.
//The index refers to the index of the inner vector within the outer vecton.
#[cfg_attr(rustfmt, rustfmt_skip)]
#[no_mangle]
pub fn get_vert_vecs() -> Vec<Vec<f32>> {
vec![
//Card
vec![
-CARD_RATIO, 1.0,
-CARD_RATIO, -1.0,
CARD_RATIO, -1.0,
CARD_RATIO, 1.0,
],
//Square
vec![
-1.0, 1.0,
-1.0, -1.0,
1.0, -1.0,
1.0, 1.0,
],
//Tooltip
vec![
-TOOLTIP_RATIO, 1.0,
-TOOLTIP_RATIO, -1.0,
TOOLTIP_RATIO, -1.0,
TOOLTIP_RATIO, 1.0,
],
//one pip stash
vec![
-STASH_ONE_PIP_RATIO, 1.0,
-STASH_ONE_PIP_RATIO, -1.0,
STASH_ONE_PIP_RATIO, -1.0,
STASH_ONE_PIP_RATIO, 1.0,
],
//two pip stash
vec![
-STASH_TWO_PIP_RATIO, 1.0,
-STASH_TWO_PIP_RATIO, -1.0,
STASH_TWO_PIP_RATIO, -1.0,
STASH_TWO_PIP_RATIO, 1.0,
],
//three pip stash
vec![
-STASH_THREE_PIP_RATIO, 1.0,
-STASH_THREE_PIP_RATIO, -1.0,
STASH_THREE_PIP_RATIO, -1.0,
STASH_THREE_PIP_RATIO, 1.0,
],
]
}
fn clamp(current: f32, min: f32, max: f32) -> f32 {
if current > max {
max
} else if current < min {
min
} else {
current
}
}
fn first_round_targets(board: &Board) -> HashSet<(i8, i8)> {
let mut result = HashSet::new();
if board.len() == 0 {
result.insert((0, 0));
} else {
let full_spaces = board.keys();
for &(x, y) in full_spaces {
for &(dx, dy) in FOUR_WAY_OFFSETS.iter() {
let new_coords = (x.saturating_add(dx), y.saturating_add(dy));
if !board.contains_key(&new_coords) {
result.insert(new_coords);
}
}
}
}
result
}
fn active_colours(stashes: &Stashes) -> Vec<PieceColour> {
let mut colours = Vec::new();
colours.push(stashes.player_stash.colour);
for stash in stashes.cpu_stashes.iter() {
colours.push(stash.colour);
}
colours
}
#[derive(Copy, Clone, Debug)]
enum Plan {
Fly((i8, i8)),
FlySpecific((i8, i8), (i8, i8)),
ConvertSlashDemolish((i8, i8), usize),
Move((i8, i8)),
Hatch((i8, i8)),
}
fn get_plan(
board: &Board,
stashes: &Stashes,
hand: &Vec<Card>,
rng: &mut StdRng,
colour: PieceColour,
) -> Option<Plan> {
let power_blocks = power_blocks(board);
let disruption_targets = {
let mut completable_power_blocks = completable_power_blocks(board);
completable_power_blocks.retain(|completable| {
let has_card_to_complete: bool = match completable.completion {
Unique(suit, value) => hand.contains(&Card { suit, value }),
ValueMatch(v) => hand.iter().any(|c| v == c.value),
SuitedEnds(suit, (v1, v2)) => {
hand.contains(&Card { suit, value: v1 }) ||
hand.contains(&Card { suit, value: v2 })
}
};
!has_card_to_complete
});
let mut power_block_targets: Vec<(i8, i8)> = power_blocks
.iter()
.cloned()
.flat_map(|block| block_to_coords(block).to_vec().into_iter())
.collect();
power_block_targets.sort();
power_block_targets.dedup();
rng.shuffle(&mut power_block_targets);
let mut completable_power_block_targets: Vec<(i8, i8)> = completable_power_blocks
.iter()
.flat_map(|completable| completable.keys.iter().cloned())
.collect();
completable_power_block_targets.sort();
completable_power_block_targets.dedup();
rng.shuffle(&mut completable_power_block_targets);
let disruption_targets: Vec<(i8, i8)> = power_block_targets
.into_iter()
.chain(completable_power_block_targets)
.collect();
disruption_targets
};
let has_ace = hand.iter().filter(|c| c.value == Ace).count() > 0;
for target in disruption_targets {
if let Some(space) = board.get(&target) {
//It's contested enough if it won't be taken for at least one round.
let contested_enough = {
let counts = PieceColour::all_values()
.into_iter()
.map(|c| space.pieces.filtered_indicies(|p| p.colour == c).len());
counts.filter(|&n| n >= 2).count() >= 2
};
if contested_enough {
continue;
}
} else {
continue;
}
let occupys_target = is_occupied_by(&board, &target, colour);
if occupys_target && has_ace {
return Some(Plan::Fly(target));
} else {
let adjacent_keys: Vec<_> = {
let mut adjacent_keys: Vec<_> = FOUR_WAY_OFFSETS
.iter()
.map(|&(x, y)| (x + target.0, y + target.1))
.collect();
rng.shuffle(&mut adjacent_keys);
adjacent_keys
};
let adjacent_to_target = adjacent_keys
.iter()
.any(|key| is_occupied_by(&board, key, colour));
if adjacent_to_target || occupys_target {
let highest_pip_target: Option<u8> =
hand.iter()
.fold(None, |acc, card| match (acc, pip_value(&card)) {
(Some(prev), pip_value) => Some(prev.saturating_add(pip_value)),
(None, pip_value) if pip_value == 0 => None,
(None, pip_value) => Some(pip_value),
});
if let Some(pip_max) = highest_pip_target {
let possible_target_piece = board.get(&target).and_then(|space| {
let other_player_pieces = space.pieces.filtered_indicies(
|p| p.colour != colour && u8::from(p.pips) <= pip_max,
);
//TODO how should we pick which colour to target?
rng.choose(&other_player_pieces).cloned()
});
if let Some(target_piece) = possible_target_piece {
return Some(Plan::ConvertSlashDemolish(target, target_piece));
}
}
};
if adjacent_to_target {
return Some(Plan::Move(target));
} else if stashes[colour].is_full() {
let possible_plan = adjacent_keys
.iter()
.find(|key| !board.contains_key(key))
.map(|target_blank| Plan::Hatch(*target_blank));
if possible_plan.is_some() {
return possible_plan;
}
}
//Try to fly next to the target
if has_ace {
let mut occupied_spaces = get_all_spaces_occupied_by(board, colour);
//We filter out these spaces so the cpu player doesn't
//waste an Ace flying somehere that doesn't change the situation
//TODO check this works on overlapping power blocks
let undesired_coords: HashSet<(i8, i8)> = power_blocks
.iter()
.map(|block| block_to_coords(*block))
.filter(|coords| coords.iter().any(|key| *key == target))
.flat_map(|coords| coords.to_vec().into_iter())
.collect();
if undesired_coords.len() > 0 {
occupied_spaces.retain(|coord| !undesired_coords.contains(coord))
}
let adjacent_empty_spaces: Vec<_> = adjacent_keys
.iter()
.filter(|key| board.get(key).is_none())
.collect();
//Find suggested place to fly from
for source_coord in occupied_spaces.iter() {
let possible_targets = fly_from_targets(board, source_coord);
for target_coord in adjacent_empty_spaces.iter() {
if possible_targets.contains(target_coord) {
return Some(Plan::FlySpecific(*source_coord, **target_coord));
}
}
}
}
};
}
None
}
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
#[cfg(test)]
mod plan_tests {
use ::*;
use common::PieceColour::*;
use common::Suit::*;
fn green_vertical_power_block_board() -> Board {
let mut board = HashMap::new();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(
0,
Piece {
colour: Green,
pips: Pips::One,
},
);
pieces.insert(
1,
Piece {
colour: Green,
pips: Pips::One,
},
);
board.insert(
(0, 0),
Space {
card: Card {
suit: Clubs,
value: Two,
},
pieces,
offset: 0,
},
);
}
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(
0,
Piece {
colour: Green,
pips: Pips::One,
},
);
board.insert(
(0, 1),
Space {
card: Card {
suit: Spades,
value: Two,
},
pieces,
offset: 0,
},
);
}
{
let pieces: SpacePieces = Default::default();
board.insert(
(0, -1),
Space {
card: Card {
suit: Diamonds,
value: Two,
},
pieces,
offset: 0,
},
);
}
board
}
#[cfg_attr(rustfmt, rustfmt_skip)]
quickcheck! {
fn move_in_and_hope(seed: usize) -> bool {
let seed_slice: &[_] = &[seed];
let mut rng: StdRng = SeedableRng::from_seed(seed_slice);
let mut board = green_vertical_power_block_board();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(0, Piece {
colour: Red,
pips: Pips::One,
});
board.insert((-1,0), Space {
card: Card {
suit: Hearts,
value: Ten,
},
pieces,
offset: 0,
});
}
let player_stash = Stash {
colour: Green,
one_pip: NoneLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let red_stash = Stash {
colour: Red,
one_pip: TwoLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let stashes = Stashes {
player_stash,
cpu_stashes: vec![red_stash],
};
let hand = vec![];
let plan = get_plan(&board, &stashes, &hand, &mut rng, Red);
if let Some(Plan::Move((0,0))) = plan {
true
} else {
false
}
}
fn fly_towards(seed: usize) -> bool {
let seed_slice: &[_] = &[seed];
let mut rng: StdRng = SeedableRng::from_seed(seed_slice);
let mut board = green_vertical_power_block_board();
{
let mut pieces: SpacePieces = Default::default();
pieces.insert(0, Piece {
colour: Red,
pips: Pips::One,
});
board.insert((-1,2), Space {
card: Card {
suit: Hearts,
value: Ten,
},
pieces,
offset: 0,
});
}
let player_stash = Stash {
colour: Green,
one_pip: NoneLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let red_stash = Stash {
colour: Red,
one_pip: TwoLeft,
two_pip: ThreeLeft,
three_pip: ThreeLeft,
};
let stashes = Stashes {
player_stash,
cpu_stashes: vec![red_stash],
};
let hand = vec![Card {value: Ace, suit:Spades}];
let plan = get_plan(&board, &stashes, &hand, &mut rng, Red);
if let Some(Plan::FlySpecific((-1,2),_)) = plan {
true
} else {
false
}
}
}
}
|
//! Access Control List (ACL) for shadowsocks
//!
//! This is for advance controlling server behaviors in both local and proxy servers.
use std::{
fmt,
fs::File,
io::{self, BufRead, BufReader, Error, ErrorKind},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
path::Path,
};
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use iprange::IpRange;
use regex::{RegexSet, RegexSetBuilder};
use trust_dns_proto::{
op::Query,
rr::{DNSClass, Name, RecordType},
};
use crate::{context::Context, relay::socks5::Address};
/// Strategy mode that ACL is running
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Mode {
/// BlackList mode, rejects or bypasses all requests by default
BlackList,
/// WhiteList mode, accepts or proxies all requests by default
WhiteList,
}
#[derive(Clone)]
struct Rules {
ipv4: IpRange<Ipv4Net>,
ipv6: IpRange<Ipv6Net>,
rule: RegexSet,
}
impl fmt::Debug for Rules {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Rules {{ ipv4: {:?}, ipv6: {:?}, rule: [", self.ipv4, self.ipv6)?;
let max_len = 2;
let has_more = self.rule.len() > max_len;
for (idx, r) in self.rule.patterns().iter().take(max_len).enumerate() {
if idx > 0 {
f.write_str(", ")?;
}
f.write_str(r)?;
}
if has_more {
f.write_str(", ...")?;
}
f.write_str("] }")
}
}
impl Rules {
/// Create a new rule
fn new(mut ipv4: IpRange<Ipv4Net>, mut ipv6: IpRange<Ipv6Net>, rule: RegexSet) -> Rules {
// Optimization, merging networks
ipv4.simplify();
ipv6.simplify();
Rules { ipv4, ipv6, rule }
}
/// Check if the specified address matches these rules
fn check_address_matched(&self, addr: &Address) -> bool {
match *addr {
Address::SocketAddress(ref saddr) => self.check_ip_matched(&saddr.ip()),
Address::DomainNameAddress(ref domain, ..) => self.check_host_matched(domain),
}
}
/// Check if the specified address matches any rules
fn check_ip_matched(&self, addr: &IpAddr) -> bool {
match addr {
IpAddr::V4(v4) => self.ipv4.contains(v4),
IpAddr::V6(v6) => self.ipv6.contains(v6),
}
}
/// Check if the specified host matches any rules
fn check_host_matched(&self, host: &str) -> bool {
self.rule.is_match(host)
}
/// Check if there are no rules for the corresponding DNS query type
fn is_rule_empty_for_qtype(&self, qtype: RecordType) -> bool {
match qtype {
RecordType::A => self.ipv4.iter().next().is_none(),
RecordType::AAAA => self.ipv6.iter().next().is_none(),
RecordType::PTR => panic!("PTR records should not reach here"),
_ => true
}
}
}
/// ACL rules
///
/// ## Sections
///
/// ACL File is formatted in sections, each section has a name with surrounded by brackets `[` and `]`
/// followed by Rules line by line.
///
/// ```plain
/// [SECTION-1]
/// RULE-1
/// RULE-2
/// RULE-3
///
/// [SECTION-2]
/// RULE-1
/// RULE-2
/// RULE-3
/// ```
///
/// Available sections are
///
/// - For local servers (`sslocal`, `ssredir`, ...)
/// * `[bypass_all]` - ACL runs in `BlackList` mode.
/// * `[proxy_all]` - ACL runs in `WhiteList` mode.
/// * `[bypass_list]` - Rules for connecting directly
/// * `[proxy_list]` - Rules for connecting through proxies
/// - For remote servers (`ssserver`)
/// * `[reject_all]` - ACL runs in `BlackList` mode.
/// * `[accept_all]` - ACL runs in `WhiteList` mode.
/// * `[black_list]` - Rules for rejecting
/// * `[white_list]` - Rules for allowing
/// * `[outbound_block_list]` - Rules for blocking outbound addresses.
///
/// ## Mode
///
/// Mode is the default ACL strategy for those addresses that are not in configuration file.
///
/// - `BlackList` - Bypasses / Rejects all addresses except those in `[proxy_list]` or `[white_list]`
/// - `WhiltList` - Proxies / Accepts all addresses except those in `[bypass_list]` or `[black_list]`
///
/// ## Rules
///
/// Rules can be either
///
/// - CIDR form network addresses, like `10.9.0.32/16`
/// - IP addresses, like `127.0.0.1` or `::1`
/// - Regular Expression for matching hosts, like `(^|\.)gmail\.com$`
#[derive(Debug, Clone)]
pub struct AccessControl {
outbound_block: Rules,
black_list: Rules,
white_list: Rules,
mode: Mode,
}
impl AccessControl {
/// Load ACL rules from a file
pub fn load_from_file<P: AsRef<Path>>(p: P) -> io::Result<AccessControl> {
let fp = File::open(p)?;
let r = BufReader::new(fp);
let mut mode = Mode::BlackList;
let mut outbound_block_ipv4 = IpRange::new();
let mut outbound_block_ipv6 = IpRange::new();
let mut outbound_block_rules = Vec::new();
let mut bypass_ipv4 = IpRange::new();
let mut bypass_ipv6 = IpRange::new();
let mut bypass_rules = Vec::new();
let mut proxy_ipv4 = IpRange::new();
let mut proxy_ipv6 = IpRange::new();
let mut proxy_rules = Vec::new();
let mut curr_ipv4 = &mut bypass_ipv4;
let mut curr_ipv6 = &mut bypass_ipv6;
let mut curr_rules = &mut bypass_rules;
for line in r.lines() {
let line = line?;
if line.is_empty() {
continue;
}
// Comments
if line.starts_with('#') {
continue;
}
match line.as_str() {
"[reject_all]" | "[bypass_all]" => {
mode = Mode::WhiteList;
}
"[accept_all]" | "[proxy_all]" => {
mode = Mode::BlackList;
}
"[outbound_block_list]" => {
curr_ipv4 = &mut outbound_block_ipv4;
curr_ipv6 = &mut outbound_block_ipv6;
curr_rules = &mut outbound_block_rules;
}
"[black_list]" | "[bypass_list]" => {
curr_ipv4 = &mut bypass_ipv4;
curr_ipv6 = &mut bypass_ipv6;
curr_rules = &mut bypass_rules;
}
"[white_list]" | "[proxy_list]" => {
curr_ipv4 = &mut proxy_ipv4;
curr_ipv6 = &mut proxy_ipv6;
curr_rules = &mut proxy_rules;
}
_ => {
match line.parse::<IpNet>() {
Ok(IpNet::V4(v4)) => {
curr_ipv4.add(v4);
}
Ok(IpNet::V6(v6)) => {
curr_ipv6.add(v6);
}
Err(..) => {
// Maybe it is a pure IpAddr
match line.parse::<IpAddr>() {
Ok(IpAddr::V4(v4)) => {
curr_ipv4.add(Ipv4Net::from(v4));
}
Ok(IpAddr::V6(v6)) => {
curr_ipv6.add(Ipv6Net::from(v6));
}
Err(..) => {
// FIXME: If this line is not a valid regex, how can we know without actually compile it?
curr_rules.push(line);
}
}
}
}
}
}
}
const REGEX_SIZE_LIMIT: usize = usize::max_value();
let outbound_block_regex = match RegexSetBuilder::new(outbound_block_rules)
.size_limit(REGEX_SIZE_LIMIT)
.build()
{
Ok(r) => r,
Err(err) => {
let err = Error::new(ErrorKind::Other, format!("[outbound_block_list] regex error: {}", err));
return Err(err);
}
};
let bypass_regex = match RegexSetBuilder::new(bypass_rules).size_limit(REGEX_SIZE_LIMIT).build() {
Ok(r) => r,
Err(err) => {
let err = Error::new(
ErrorKind::Other,
format!("[black_list] or [bypass_list] regex error: {}", err),
);
return Err(err);
}
};
let proxy_regex = match RegexSetBuilder::new(proxy_rules).size_limit(REGEX_SIZE_LIMIT).build() {
Ok(r) => r,
Err(err) => {
let err = Error::new(
ErrorKind::Other,
format!("[white_list] or [proxy_list] regex error: {}", err),
);
return Err(err);
}
};
Ok(AccessControl {
outbound_block: Rules::new(outbound_block_ipv4, outbound_block_ipv6, outbound_block_regex),
black_list: Rules::new(bypass_ipv4, bypass_ipv6, bypass_regex),
white_list: Rules::new(proxy_ipv4, proxy_ipv6, proxy_regex),
mode,
})
}
/// Check if domain name is in proxy_list.
/// If so, it should be resolved from remote (for Android's DNS relay)
pub fn check_query_in_proxy_list(&self, query: &Query) -> Option<bool> {
if query.query_class() != DNSClass::IN || !query.name().is_fqdn() {
// unconditionally use default for all non-IN queries and PQDNs
return Some(self.is_default_in_proxy_list());
}
if query.query_type() == RecordType::PTR {
return Some(self.check_ptr_qname_in_proxy_list(query.name()));
}
// remove the last dot from fqdn name
let mut name = query.name().to_ascii();
name.pop();
let addr = Address::DomainNameAddress(name, 0);
// Addresses in proxy_list will be proxied
if self.white_list.check_address_matched(&addr) {
return Some(true);
}
if self.black_list.check_address_matched(&addr) {
return Some(false);
}
match self.mode {
Mode::BlackList => if self.black_list.is_rule_empty_for_qtype(query.query_type()) {
return Some(true);
},
Mode::WhiteList => if self.white_list.is_rule_empty_for_qtype(query.query_type()) {
return Some(false);
},
}
None
}
fn check_ptr_qname_in_proxy_list(&self, name: &Name) -> bool {
let mut iter = name.iter().rev();
let mut next = || std::str::from_utf8(iter.next().unwrap_or(&[])).unwrap_or("0");
if !"arpa".eq_ignore_ascii_case(next()) {
return self.is_default_in_proxy_list();
}
match &next().to_ascii_lowercase()[..] {
"in-addr" => {
let mut octets: [u8; 4] = [0; 4];
for octet in octets.iter_mut() {
match next().parse() {
Ok(result) => *octet = result,
Err(_) => return self.is_default_in_proxy_list(),
}
}
self.check_ip_in_proxy_list(&IpAddr::V4(Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])))
}
"ip6" => {
let mut segments: [u16; 8] = [0; 8];
for segment in segments.iter_mut() {
match u16::from_str_radix(&[next(), next(), next(), next()].concat(), 16) {
Ok(result) => *segment = result,
Err(_) => return self.is_default_in_proxy_list(),
}
}
self.check_ip_in_proxy_list(&IpAddr::V6(Ipv6Addr::new(
segments[0], segments[1], segments[2], segments[3],
segments[4], segments[5], segments[6], segments[7]
)))
}
_ => self.is_default_in_proxy_list(),
}
}
pub fn check_ip_in_proxy_list(&self, ip: &IpAddr) -> bool {
match self.mode {
Mode::BlackList => !self.black_list.check_ip_matched(ip),
Mode::WhiteList => self.white_list.check_ip_matched(ip),
}
}
pub fn is_default_in_proxy_list(&self) -> bool {
match self.mode {
Mode::BlackList => true,
Mode::WhiteList => false,
}
}
/// Check if target address should be bypassed (for client)
///
/// FIXME: This function may perform a DNS resolution
pub async fn check_target_bypassed(&self, context: &Context, addr: &Address) -> bool {
// Addresses in bypass_list will be bypassed
if self.black_list.check_address_matched(addr) {
return true;
}
// Addresses in proxy_list will be proxied
if self.white_list.check_address_matched(addr) {
return false;
}
// Resolve hostname and check the list
if cfg!(not(target_os = "android")) {
if let Address::DomainNameAddress(ref host, port) = *addr {
if let Ok(vaddr) = context.dns_resolve(host, port).await {
for addr in vaddr {
if self.black_list.check_ip_matched(&addr.ip()) {
return true;
}
if self.white_list.check_ip_matched(&addr.ip()) {
return false;
}
}
}
}
}
!self.is_default_in_proxy_list()
}
/// Check if client address should be blocked (for server)
pub fn check_client_blocked(&self, addr: &SocketAddr) -> bool {
match self.mode {
Mode::BlackList => {
// Only clients in black_list will be blocked
self.black_list.check_ip_matched(&addr.ip())
}
Mode::WhiteList => {
// Only clients in white_list will be proxied
!self.white_list.check_ip_matched(&addr.ip())
}
}
}
/// Check if outbound address is blocked (for server)
///
/// NOTE: `Address::DomainName` is only validated by regex rules,
/// resolved addresses are checked in the `lookup_outbound_then!` macro
pub fn check_outbound_blocked(&self, outbound: &Address) -> bool {
self.outbound_block.check_address_matched(outbound)
}
/// Check resolved outbound address is blocked (for server)
pub fn check_resolved_outbound_blocked(&self, outbound: &SocketAddr) -> bool {
self.outbound_block.check_ip_matched(&outbound.ip())
}
}
Only return 0 when sequence is exhausted
//! Access Control List (ACL) for shadowsocks
//!
//! This is for advance controlling server behaviors in both local and proxy servers.
use std::{
fmt,
fs::File,
io::{self, BufRead, BufReader, Error, ErrorKind},
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
path::Path,
};
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use iprange::IpRange;
use regex::{RegexSet, RegexSetBuilder};
use trust_dns_proto::{
op::Query,
rr::{DNSClass, Name, RecordType},
};
use crate::{context::Context, relay::socks5::Address};
/// Strategy mode that ACL is running
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Mode {
/// BlackList mode, rejects or bypasses all requests by default
BlackList,
/// WhiteList mode, accepts or proxies all requests by default
WhiteList,
}
#[derive(Clone)]
struct Rules {
ipv4: IpRange<Ipv4Net>,
ipv6: IpRange<Ipv6Net>,
rule: RegexSet,
}
impl fmt::Debug for Rules {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Rules {{ ipv4: {:?}, ipv6: {:?}, rule: [", self.ipv4, self.ipv6)?;
let max_len = 2;
let has_more = self.rule.len() > max_len;
for (idx, r) in self.rule.patterns().iter().take(max_len).enumerate() {
if idx > 0 {
f.write_str(", ")?;
}
f.write_str(r)?;
}
if has_more {
f.write_str(", ...")?;
}
f.write_str("] }")
}
}
impl Rules {
/// Create a new rule
fn new(mut ipv4: IpRange<Ipv4Net>, mut ipv6: IpRange<Ipv6Net>, rule: RegexSet) -> Rules {
// Optimization, merging networks
ipv4.simplify();
ipv6.simplify();
Rules { ipv4, ipv6, rule }
}
/// Check if the specified address matches these rules
fn check_address_matched(&self, addr: &Address) -> bool {
match *addr {
Address::SocketAddress(ref saddr) => self.check_ip_matched(&saddr.ip()),
Address::DomainNameAddress(ref domain, ..) => self.check_host_matched(domain),
}
}
/// Check if the specified address matches any rules
fn check_ip_matched(&self, addr: &IpAddr) -> bool {
match addr {
IpAddr::V4(v4) => self.ipv4.contains(v4),
IpAddr::V6(v6) => self.ipv6.contains(v6),
}
}
/// Check if the specified host matches any rules
fn check_host_matched(&self, host: &str) -> bool {
self.rule.is_match(host)
}
/// Check if there are no rules for the corresponding DNS query type
fn is_rule_empty_for_qtype(&self, qtype: RecordType) -> bool {
match qtype {
RecordType::A => self.ipv4.iter().next().is_none(),
RecordType::AAAA => self.ipv6.iter().next().is_none(),
RecordType::PTR => panic!("PTR records should not reach here"),
_ => true
}
}
}
/// ACL rules
///
/// ## Sections
///
/// ACL File is formatted in sections, each section has a name with surrounded by brackets `[` and `]`
/// followed by Rules line by line.
///
/// ```plain
/// [SECTION-1]
/// RULE-1
/// RULE-2
/// RULE-3
///
/// [SECTION-2]
/// RULE-1
/// RULE-2
/// RULE-3
/// ```
///
/// Available sections are
///
/// - For local servers (`sslocal`, `ssredir`, ...)
/// * `[bypass_all]` - ACL runs in `BlackList` mode.
/// * `[proxy_all]` - ACL runs in `WhiteList` mode.
/// * `[bypass_list]` - Rules for connecting directly
/// * `[proxy_list]` - Rules for connecting through proxies
/// - For remote servers (`ssserver`)
/// * `[reject_all]` - ACL runs in `BlackList` mode.
/// * `[accept_all]` - ACL runs in `WhiteList` mode.
/// * `[black_list]` - Rules for rejecting
/// * `[white_list]` - Rules for allowing
/// * `[outbound_block_list]` - Rules for blocking outbound addresses.
///
/// ## Mode
///
/// Mode is the default ACL strategy for those addresses that are not in configuration file.
///
/// - `BlackList` - Bypasses / Rejects all addresses except those in `[proxy_list]` or `[white_list]`
/// - `WhiltList` - Proxies / Accepts all addresses except those in `[bypass_list]` or `[black_list]`
///
/// ## Rules
///
/// Rules can be either
///
/// - CIDR form network addresses, like `10.9.0.32/16`
/// - IP addresses, like `127.0.0.1` or `::1`
/// - Regular Expression for matching hosts, like `(^|\.)gmail\.com$`
#[derive(Debug, Clone)]
pub struct AccessControl {
outbound_block: Rules,
black_list: Rules,
white_list: Rules,
mode: Mode,
}
impl AccessControl {
/// Load ACL rules from a file
pub fn load_from_file<P: AsRef<Path>>(p: P) -> io::Result<AccessControl> {
let fp = File::open(p)?;
let r = BufReader::new(fp);
let mut mode = Mode::BlackList;
let mut outbound_block_ipv4 = IpRange::new();
let mut outbound_block_ipv6 = IpRange::new();
let mut outbound_block_rules = Vec::new();
let mut bypass_ipv4 = IpRange::new();
let mut bypass_ipv6 = IpRange::new();
let mut bypass_rules = Vec::new();
let mut proxy_ipv4 = IpRange::new();
let mut proxy_ipv6 = IpRange::new();
let mut proxy_rules = Vec::new();
let mut curr_ipv4 = &mut bypass_ipv4;
let mut curr_ipv6 = &mut bypass_ipv6;
let mut curr_rules = &mut bypass_rules;
for line in r.lines() {
let line = line?;
if line.is_empty() {
continue;
}
// Comments
if line.starts_with('#') {
continue;
}
match line.as_str() {
"[reject_all]" | "[bypass_all]" => {
mode = Mode::WhiteList;
}
"[accept_all]" | "[proxy_all]" => {
mode = Mode::BlackList;
}
"[outbound_block_list]" => {
curr_ipv4 = &mut outbound_block_ipv4;
curr_ipv6 = &mut outbound_block_ipv6;
curr_rules = &mut outbound_block_rules;
}
"[black_list]" | "[bypass_list]" => {
curr_ipv4 = &mut bypass_ipv4;
curr_ipv6 = &mut bypass_ipv6;
curr_rules = &mut bypass_rules;
}
"[white_list]" | "[proxy_list]" => {
curr_ipv4 = &mut proxy_ipv4;
curr_ipv6 = &mut proxy_ipv6;
curr_rules = &mut proxy_rules;
}
_ => {
match line.parse::<IpNet>() {
Ok(IpNet::V4(v4)) => {
curr_ipv4.add(v4);
}
Ok(IpNet::V6(v6)) => {
curr_ipv6.add(v6);
}
Err(..) => {
// Maybe it is a pure IpAddr
match line.parse::<IpAddr>() {
Ok(IpAddr::V4(v4)) => {
curr_ipv4.add(Ipv4Net::from(v4));
}
Ok(IpAddr::V6(v6)) => {
curr_ipv6.add(Ipv6Net::from(v6));
}
Err(..) => {
// FIXME: If this line is not a valid regex, how can we know without actually compile it?
curr_rules.push(line);
}
}
}
}
}
}
}
const REGEX_SIZE_LIMIT: usize = usize::max_value();
let outbound_block_regex = match RegexSetBuilder::new(outbound_block_rules)
.size_limit(REGEX_SIZE_LIMIT)
.build()
{
Ok(r) => r,
Err(err) => {
let err = Error::new(ErrorKind::Other, format!("[outbound_block_list] regex error: {}", err));
return Err(err);
}
};
let bypass_regex = match RegexSetBuilder::new(bypass_rules).size_limit(REGEX_SIZE_LIMIT).build() {
Ok(r) => r,
Err(err) => {
let err = Error::new(
ErrorKind::Other,
format!("[black_list] or [bypass_list] regex error: {}", err),
);
return Err(err);
}
};
let proxy_regex = match RegexSetBuilder::new(proxy_rules).size_limit(REGEX_SIZE_LIMIT).build() {
Ok(r) => r,
Err(err) => {
let err = Error::new(
ErrorKind::Other,
format!("[white_list] or [proxy_list] regex error: {}", err),
);
return Err(err);
}
};
Ok(AccessControl {
outbound_block: Rules::new(outbound_block_ipv4, outbound_block_ipv6, outbound_block_regex),
black_list: Rules::new(bypass_ipv4, bypass_ipv6, bypass_regex),
white_list: Rules::new(proxy_ipv4, proxy_ipv6, proxy_regex),
mode,
})
}
/// Check if domain name is in proxy_list.
/// If so, it should be resolved from remote (for Android's DNS relay)
pub fn check_query_in_proxy_list(&self, query: &Query) -> Option<bool> {
if query.query_class() != DNSClass::IN || !query.name().is_fqdn() {
// unconditionally use default for all non-IN queries and PQDNs
return Some(self.is_default_in_proxy_list());
}
if query.query_type() == RecordType::PTR {
return Some(self.check_ptr_qname_in_proxy_list(query.name()));
}
// remove the last dot from fqdn name
let mut name = query.name().to_ascii();
name.pop();
let addr = Address::DomainNameAddress(name, 0);
// Addresses in proxy_list will be proxied
if self.white_list.check_address_matched(&addr) {
return Some(true);
}
if self.black_list.check_address_matched(&addr) {
return Some(false);
}
match self.mode {
Mode::BlackList => if self.black_list.is_rule_empty_for_qtype(query.query_type()) {
return Some(true);
},
Mode::WhiteList => if self.white_list.is_rule_empty_for_qtype(query.query_type()) {
return Some(false);
},
}
None
}
fn check_ptr_qname_in_proxy_list(&self, name: &Name) -> bool {
let mut iter = name.iter().rev();
let mut next = || std::str::from_utf8(iter.next().unwrap_or(&[48])).unwrap_or("*");
if !"arpa".eq_ignore_ascii_case(next()) {
return self.is_default_in_proxy_list();
}
match &next().to_ascii_lowercase()[..] {
"in-addr" => {
let mut octets: [u8; 4] = [0; 4];
for octet in octets.iter_mut() {
match next().parse() {
Ok(result) => *octet = result,
Err(_) => return self.is_default_in_proxy_list(),
}
}
self.check_ip_in_proxy_list(&IpAddr::V4(Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])))
}
"ip6" => {
let mut segments: [u16; 8] = [0; 8];
for segment in segments.iter_mut() {
match u16::from_str_radix(&[next(), next(), next(), next()].concat(), 16) {
Ok(result) => *segment = result,
Err(_) => return self.is_default_in_proxy_list(),
}
}
self.check_ip_in_proxy_list(&IpAddr::V6(Ipv6Addr::new(
segments[0], segments[1], segments[2], segments[3],
segments[4], segments[5], segments[6], segments[7]
)))
}
_ => self.is_default_in_proxy_list(),
}
}
pub fn check_ip_in_proxy_list(&self, ip: &IpAddr) -> bool {
match self.mode {
Mode::BlackList => !self.black_list.check_ip_matched(ip),
Mode::WhiteList => self.white_list.check_ip_matched(ip),
}
}
pub fn is_default_in_proxy_list(&self) -> bool {
match self.mode {
Mode::BlackList => true,
Mode::WhiteList => false,
}
}
/// Check if target address should be bypassed (for client)
///
/// FIXME: This function may perform a DNS resolution
pub async fn check_target_bypassed(&self, context: &Context, addr: &Address) -> bool {
// Addresses in bypass_list will be bypassed
if self.black_list.check_address_matched(addr) {
return true;
}
// Addresses in proxy_list will be proxied
if self.white_list.check_address_matched(addr) {
return false;
}
// Resolve hostname and check the list
if cfg!(not(target_os = "android")) {
if let Address::DomainNameAddress(ref host, port) = *addr {
if let Ok(vaddr) = context.dns_resolve(host, port).await {
for addr in vaddr {
if self.black_list.check_ip_matched(&addr.ip()) {
return true;
}
if self.white_list.check_ip_matched(&addr.ip()) {
return false;
}
}
}
}
}
!self.is_default_in_proxy_list()
}
/// Check if client address should be blocked (for server)
pub fn check_client_blocked(&self, addr: &SocketAddr) -> bool {
match self.mode {
Mode::BlackList => {
// Only clients in black_list will be blocked
self.black_list.check_ip_matched(&addr.ip())
}
Mode::WhiteList => {
// Only clients in white_list will be proxied
!self.white_list.check_ip_matched(&addr.ip())
}
}
}
/// Check if outbound address is blocked (for server)
///
/// NOTE: `Address::DomainName` is only validated by regex rules,
/// resolved addresses are checked in the `lookup_outbound_then!` macro
pub fn check_outbound_blocked(&self, outbound: &Address) -> bool {
self.outbound_block.check_address_matched(outbound)
}
/// Check resolved outbound address is blocked (for server)
pub fn check_resolved_outbound_blocked(&self, outbound: &SocketAddr) -> bool {
self.outbound_block.check_ip_matched(&outbound.ip())
}
}
|
use aes::block_cipher::generic_array::GenericArray;
use aes::{BlockCipher, NewBlockCipher};
use arrayvec::{Array, ArrayVec};
use std::io::Read;
use std::{any, fmt, io};
/// Internal block size of an AES cipher.
const AES_BLOCK_SIZE: usize = 16;
/// AES-128.
#[derive(Debug)]
pub struct Aes128;
/// AES-192
#[derive(Debug)]
pub struct Aes192;
/// AES-256.
#[derive(Debug)]
pub struct Aes256;
/// An AES cipher kind.
pub trait AesKind {
/// Key type.
type Key: Array<Item = u8>;
/// Cipher used to decrypt.
type Cipher;
}
impl AesKind for Aes256 {
type Key = [u8; 32];
type Cipher = aes::Aes256;
}
/// An AES-CTR key stream generator.
///
/// Implements the slightly non-standard AES-CTR variant used by WinZip AES encryption.
///
/// Typical AES-CTR implementations combine a nonce with a 64 bit counter. WinZIP AES instead uses
/// no nonce and also uses a different byte order (little endian) than NIST (big endian).
///
/// The stream implements the `Read` trait; encryption or decryption is performed by XOR-ing the
/// bytes from the key stream with the ciphertext/plaintext.
struct AesCtrZipKeyStream<C: AesKind> {
counter: u128,
cipher: C::Cipher,
buffer: ArrayVec<C::Key>,
}
impl<C> fmt::Debug for AesCtrZipKeyStream<C>
where
C: AesKind,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"AesCtrZipKeyStream<{}>(counter: {})",
any::type_name::<C>(),
self.counter
)
}
}
impl<C> AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: NewBlockCipher,
{
#[allow(dead_code)]
/// Creates a new zip variant AES-CTR key stream.
pub fn new(key: &C::Key) -> AesCtrZipKeyStream<C> {
AesCtrZipKeyStream {
counter: 1,
cipher: C::Cipher::new_varkey(key.as_slice()).expect("key should have correct size"),
buffer: ArrayVec::new(),
}
}
}
impl<C> AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: BlockCipher,
{
/// Decrypt or encrypt given data.
pub fn crypt(&mut self, mut data: &mut [u8]) {
while data.len() > 0 {
let mut buffer: [u8; AES_BLOCK_SIZE] = [0u8; AES_BLOCK_SIZE];
let target_len = data.len().min(AES_BLOCK_SIZE);
// Fill buffer with enough data to decrypt the next block.
debug_assert_eq!(
self.read(&mut buffer[0..target_len])
.expect("reading key stream should never fail"),
target_len
);
xor(&mut data[0..target_len], &buffer.as_slice()[0..target_len]);
data = &mut data[target_len..];
}
}
}
impl<C> io::Read for AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: BlockCipher,
{
#[inline]
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.buffer.len() == 0 {
// Note: AES block size is always 16 bytes, same as u128.
let mut block = GenericArray::clone_from_slice(&self.counter.to_le_bytes());
self.cipher.encrypt_block(&mut block);
self.counter += 1;
self.buffer = block.into_iter().collect();
}
let target_len = buf.len().min(self.buffer.len());
buf.copy_from_slice(&self.buffer[0..target_len]);
self.buffer.drain(0..target_len);
Ok(target_len)
}
}
/// XORs a slice in place with another slice.
#[inline]
pub fn xor(dest: &mut [u8], src: &[u8]) {
debug_assert_eq!(dest.len(), src.len());
for (lhs, rhs) in dest.iter_mut().zip(src.iter()) {
*lhs ^= *rhs;
}
}
#[cfg(test)]
mod tests {
use super::{xor, Aes256, AesCtrZipKeyStream};
use std::io::Read;
#[test]
fn simple_example() {
let ciphertext: [u8; 5] = [0xdc, 0x99, 0x93, 0x5e, 0xbf];
let expected_plaintext = &[b'a', b's', b'd', b'f', b'\n'];
let key = [
0xd1, 0x51, 0xa6, 0xab, 0x53, 0x68, 0xd7, 0xb7, 0xbf, 0x49, 0xf7, 0xf5, 0x8a, 0x4e,
0x10, 0x36, 0x25, 0x1c, 0x13, 0xba, 0x12, 0x45, 0x37, 0x65, 0xa9, 0xe4, 0xed, 0x9f,
0x4a, 0xa8, 0xda, 0x3b,
];
let mut key_stream = AesCtrZipKeyStream::<Aes256>::new(&key);
let mut key_buf = [0u8; 5];
key_stream.read(&mut key_buf).unwrap();
let mut plaintext = ciphertext;
xor(&mut plaintext, &key_buf);
assert_eq!(&plaintext, expected_plaintext);
}
#[test]
fn crypt_simple_example() {
let ciphertext: [u8; 5] = [0xdc, 0x99, 0x93, 0x5e, 0xbf];
let expected_plaintext = &[b'a', b's', b'd', b'f', b'\n'];
let key = [
0xd1, 0x51, 0xa6, 0xab, 0x53, 0x68, 0xd7, 0xb7, 0xbf, 0x49, 0xf7, 0xf5, 0x8a, 0x4e,
0x10, 0x36, 0x25, 0x1c, 0x13, 0xba, 0x12, 0x45, 0x37, 0x65, 0xa9, 0xe4, 0xed, 0x9f,
0x4a, 0xa8, 0xda, 0x3b,
];
let mut key_stream = AesCtrZipKeyStream::<Aes256>::new(&key);
let mut plaintext = ciphertext;
key_stream.crypt(&mut plaintext);
assert_eq!(&plaintext, expected_plaintext);
}
}
Simpify `aes_ctr` API to just `crypt`
use aes::block_cipher::generic_array::GenericArray;
use aes::{BlockCipher, NewBlockCipher};
use arrayvec::{Array, ArrayVec};
use std::io::Read;
use std::{any, fmt, io};
/// Internal block size of an AES cipher.
const AES_BLOCK_SIZE: usize = 16;
/// AES-128.
#[derive(Debug)]
pub struct Aes128;
/// AES-192
#[derive(Debug)]
pub struct Aes192;
/// AES-256.
#[derive(Debug)]
pub struct Aes256;
/// An AES cipher kind.
pub trait AesKind {
/// Key type.
type Key: Array<Item = u8>;
/// Cipher used to decrypt.
type Cipher;
}
impl AesKind for Aes256 {
type Key = [u8; 32];
type Cipher = aes::Aes256;
}
/// An AES-CTR key stream generator.
///
/// Implements the slightly non-standard AES-CTR variant used by WinZip AES encryption.
///
/// Typical AES-CTR implementations combine a nonce with a 64 bit counter. WinZIP AES instead uses
/// no nonce and also uses a different byte order (little endian) than NIST (big endian).
///
/// The stream implements the `Read` trait; encryption or decryption is performed by XOR-ing the
/// bytes from the key stream with the ciphertext/plaintext.
struct AesCtrZipKeyStream<C: AesKind> {
counter: u128,
cipher: C::Cipher,
buffer: ArrayVec<C::Key>,
}
impl<C> fmt::Debug for AesCtrZipKeyStream<C>
where
C: AesKind,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"AesCtrZipKeyStream<{}>(counter: {})",
any::type_name::<C>(),
self.counter
)
}
}
impl<C> AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: NewBlockCipher,
{
#[allow(dead_code)]
/// Creates a new zip variant AES-CTR key stream.
pub fn new(key: &C::Key) -> AesCtrZipKeyStream<C> {
AesCtrZipKeyStream {
counter: 1,
cipher: C::Cipher::new_varkey(key.as_slice()).expect("key should have correct size"),
buffer: ArrayVec::new(),
}
}
}
impl<C> AesCtrZipKeyStream<C>
where
C: AesKind,
C::Cipher: BlockCipher,
{
/// Decrypt or encrypt given data.
#[inline]
fn crypt(&mut self, mut target: &mut [u8]) {
while target.len() > 0 {
if self.buffer.len() == 0 {
// Note: AES block size is always 16 bytes, same as u128.
let mut block = GenericArray::clone_from_slice(&self.counter.to_le_bytes());
// TODO: Use trait.
self.cipher.encrypt_block(&mut block);
self.counter += 1;
self.buffer = block.into_iter().collect();
}
let target_len = target.len().min(self.buffer.len());
xor(&mut target[0..target_len], &self.buffer[0..target_len]);
self.buffer.drain(0..target_len);
target = &mut target[target_len..];
}
}
}
/// XORs a slice in place with another slice.
#[inline]
pub fn xor(dest: &mut [u8], src: &[u8]) {
debug_assert_eq!(dest.len(), src.len());
for (lhs, rhs) in dest.iter_mut().zip(src.iter()) {
*lhs ^= *rhs;
}
}
#[cfg(test)]
mod tests {
use super::{xor, Aes256, AesCtrZipKeyStream};
use std::io::Read;
#[test]
fn crypt_simple_example() {
let ciphertext: [u8; 5] = [0xdc, 0x99, 0x93, 0x5e, 0xbf];
let expected_plaintext = &[b'a', b's', b'd', b'f', b'\n'];
let key = [
0xd1, 0x51, 0xa6, 0xab, 0x53, 0x68, 0xd7, 0xb7, 0xbf, 0x49, 0xf7, 0xf5, 0x8a, 0x4e,
0x10, 0x36, 0x25, 0x1c, 0x13, 0xba, 0x12, 0x45, 0x37, 0x65, 0xa9, 0xe4, 0xed, 0x9f,
0x4a, 0xa8, 0xda, 0x3b,
];
let mut key_stream = AesCtrZipKeyStream::<Aes256>::new(&key);
let mut plaintext = ciphertext;
key_stream.crypt(&mut plaintext);
assert_eq!(&plaintext, expected_plaintext);
}
}
|
use gfx;
use image;
use image::{
GenericImage,
ImageBuf,
Rgba,
};
use texture_lib::ImageSize;
/// Represents a texture.
pub struct Texture {
/// A handle to the Gfx texture.
pub handle: gfx::TextureHandle,
}
impl Texture {
/// Creates a texture from path.
pub fn from_path<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(device: &mut D, path: &Path) -> Result<Texture, String> {
let img = match image::open(path) {
Ok(img) => img,
Err(e) => return Err(format!("Could not load '{}': {}",
path.filename_str().unwrap(), e)),
};
match img.color() {
image::RGBA(8) => {},
c => return Err(format!("Unsupported color type {}", c)),
};
let (width, height) = img.dimensions();
let texture_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Texture2D,
format: gfx::tex::RGBA8,
};
let image_info = texture_info.to_image_info();
let texture = device.create_texture(texture_info).unwrap();
device.update_texture(&texture, &image_info,
img.raw_pixels().as_slice())
.unwrap();
Ok(Texture {
handle: texture
})
}
/// Creates a texture from image.
pub fn from_image<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(device: &mut D, image: &ImageBuf<Rgba<u8>>) -> Texture {
let (width, height) = image.dimensions();
let texture_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Texture2D,
format: gfx::tex::RGBA8,
};
let image_info = texture_info.to_image_info();
let texture = device.create_texture(texture_info).unwrap();
device.update_texture(&texture, &image_info,
image.pixelbuf().as_slice())
.unwrap();
Texture {
handle: texture
}
}
/// Updates the texture with an image.
pub fn update<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(&mut self, device: &mut D, image: &ImageBuf<Rgba<u8>>) {
device.update_texture(&self.handle,
&self.handle.get_info().to_image_info(),
image.pixelbuf().as_slice()
).unwrap();
}
}
impl ImageSize for Texture {
fn get_size(&self) -> (u32, u32) {
let info = self.handle.get_info();
(info.width as u32, info.height as u32)
}
}
Added `Texture::from_rgba8`
Closes https://github.com/PistonDevelopers/gfx_texture/issues/5
use gfx;
use image;
use image::{
GenericImage,
ImageBuf,
Rgba,
};
use texture_lib::ImageSize;
/// Represents a texture.
pub struct Texture {
/// A handle to the Gfx texture.
pub handle: gfx::TextureHandle,
}
impl Texture {
/// Creates a texture from path.
pub fn from_path<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(device: &mut D, path: &Path) -> Result<Texture, String> {
let img = match image::open(path) {
Ok(img) => img,
Err(e) => return Err(format!("Could not load '{}': {}",
path.filename_str().unwrap(), e)),
};
match img.color() {
image::RGBA(8) => {},
c => return Err(format!("Unsupported color type {}", c)),
};
let (width, height) = img.dimensions();
let texture_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Texture2D,
format: gfx::tex::RGBA8,
};
let image_info = texture_info.to_image_info();
let texture = device.create_texture(texture_info).unwrap();
device.update_texture(&texture, &image_info,
img.raw_pixels().as_slice())
.unwrap();
Ok(Texture {
handle: texture
})
}
/// Creates a texture from image.
pub fn from_image<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(device: &mut D, image: &ImageBuf<Rgba<u8>>) -> Texture {
let (width, height) = image.dimensions();
let texture_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Texture2D,
format: gfx::tex::RGBA8,
};
let image_info = texture_info.to_image_info();
let texture = device.create_texture(texture_info).unwrap();
device.update_texture(&texture, &image_info,
image.pixelbuf().as_slice())
.unwrap();
Texture {
handle: texture
}
}
/// Creates a texture from RGBA image.
pub fn from_rgba8<D: gfx::Device<C>, C: gfx::CommandBuffer>(
img: ImageBuf<Rgba<u8>>,
d: &mut D
) -> Texture {
let (width, height) = img.dimensions();
let mut ti = gfx::tex::TextureInfo::new();
ti.width = width as u16;
ti.height = height as u16;
ti.kind = gfx::tex::Texture2D;
ti.format = gfx::tex::RGBA8;
let tex = d.create_texture(ti).unwrap();
d.update_texture(&tex, &ti.to_image_info(),
img.into_vec().as_slice()).unwrap();
d.generate_mipmap(&tex);
Texture {
handle: tex,
}
}
/// Updates the texture with an image.
pub fn update<
C: gfx::CommandBuffer,
D: gfx::Device<C>
>(&mut self, device: &mut D, image: &ImageBuf<Rgba<u8>>) {
device.update_texture(&self.handle,
&self.handle.get_info().to_image_info(),
image.pixelbuf().as_slice()
).unwrap();
}
}
impl ImageSize for Texture {
fn get_size(&self) -> (u32, u32) {
let info = self.handle.get_info();
(info.width as u32, info.height as u32)
}
}
|
use super::{ParallelIterator, ExactParallelIterator};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::{BuildHasher, Hash};
use std::collections::LinkedList;
use std::collections::{BinaryHeap, VecDeque};
pub trait FromParallelIterator<PAR_ITER> {
fn from_par_iter(par_iter: PAR_ITER) -> Self;
}
fn combine<PAR_ITER, START, COLL>(par_iter: PAR_ITER, make_start: START) -> COLL
where PAR_ITER: ParallelIterator,
START: FnOnce(&LinkedList<Vec<PAR_ITER::Item>>) -> COLL,
COLL: Extend<PAR_ITER::Item>
{
let list = par_iter
.fold(Vec::new, |mut vec, elem| { vec.push(elem); vec })
.collect();
let start = make_start(&list);
list.into_iter()
.fold(start, |mut coll, vec| { coll.extend(vec); coll })
}
fn combined_len<T>(list: &LinkedList<Vec<T>>) -> usize {
list.iter().map(Vec::len).sum()
}
/// Collect items from a parallel iterator into a freshly allocated
/// vector. This is very efficient, but requires precise knowledge of
/// the number of items being iterated.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for Vec<T>
where PAR_ITER: ExactParallelIterator<Item=T>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
let mut vec = vec![];
par_iter.collect_into(&mut vec);
vec
}
}
/// Collect items from a parallel iterator into a vecdeque.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for VecDeque<T>
where Vec<T>: FromParallelIterator<PAR_ITER>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
Vec::from_par_iter(par_iter).into()
}
}
/// Collect items from a parallel iterator into a binaryheap.
/// The heap-ordering is calculated serially after all items are collected.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for BinaryHeap<T>
where Vec<T>: FromParallelIterator<PAR_ITER>,
T: Ord + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
Vec::from_par_iter(par_iter).into()
}
}
/// Collect items from a parallel iterator into a freshly allocated
/// linked list.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for LinkedList<T>
where PAR_ITER: ParallelIterator<Item=T>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
par_iter.map(|elem| { let mut list = LinkedList::new(); list.push_back(elem); list })
.reduce_with(|mut list1, mut list2| { list1.append(&mut list2); list1 })
.unwrap_or_else(|| LinkedList::new())
}
}
/// Collect (key, value) pairs from a parallel iterator into a
/// hashmap. If multiple pairs correspond to the same key, then the
/// ones produced earlier in the parallel iterator will be
/// overwritten, just as with a sequential iterator.
impl<PAR_ITER, K, V, S> FromParallelIterator<PAR_ITER> for HashMap<K, V, S>
where PAR_ITER: ParallelIterator<Item=(K, V)>,
K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |list| {
let len = combined_len(list);
HashMap::with_capacity_and_hasher(len, Default::default())
})
}
}
/// Collect (key, value) pairs from a parallel iterator into a
/// btreemap. If multiple pairs correspond to the same key, then the
/// ones produced earlier in the parallel iterator will be
/// overwritten, just as with a sequential iterator.
impl<PAR_ITER, K, V> FromParallelIterator<PAR_ITER> for BTreeMap<K, V>
where PAR_ITER: ParallelIterator<Item=(K, V)>,
K: Ord + Send,
V: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |_| BTreeMap::new())
}
}
/// Collect values from a parallel iterator into a hashset.
impl<PAR_ITER, V, S> FromParallelIterator<PAR_ITER> for HashSet<V, S>
where PAR_ITER: ParallelIterator<Item=V>,
V: Eq + Hash + Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |list| {
let len = combined_len(list);
HashSet::with_capacity_and_hasher(len, Default::default())
})
}
}
/// Collect values from a parallel iterator into a btreeset.
impl<PAR_ITER, V> FromParallelIterator<PAR_ITER> for BTreeSet<V>
where PAR_ITER: ParallelIterator<Item=V>,
V: Send + Ord,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |_| BTreeSet::new())
}
}
Reference the map_collect benchmarks
use super::{ParallelIterator, ExactParallelIterator};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::{BuildHasher, Hash};
use std::collections::LinkedList;
use std::collections::{BinaryHeap, VecDeque};
pub trait FromParallelIterator<PAR_ITER> {
fn from_par_iter(par_iter: PAR_ITER) -> Self;
}
fn combine<PAR_ITER, START, COLL>(par_iter: PAR_ITER, make_start: START) -> COLL
where PAR_ITER: ParallelIterator,
START: FnOnce(&LinkedList<Vec<PAR_ITER::Item>>) -> COLL,
COLL: Extend<PAR_ITER::Item>
{
let list = par_iter
.fold(Vec::new, |mut vec, elem| { vec.push(elem); vec })
.collect();
let start = make_start(&list);
list.into_iter()
.fold(start, |mut coll, vec| { coll.extend(vec); coll })
}
fn combined_len<T>(list: &LinkedList<Vec<T>>) -> usize {
list.iter().map(Vec::len).sum()
}
/// Collect items from a parallel iterator into a freshly allocated
/// vector. This is very efficient, but requires precise knowledge of
/// the number of items being iterated.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for Vec<T>
where PAR_ITER: ExactParallelIterator<Item=T>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
let mut vec = vec![];
par_iter.collect_into(&mut vec);
vec
}
}
/// Collect items from a parallel iterator into a vecdeque.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for VecDeque<T>
where Vec<T>: FromParallelIterator<PAR_ITER>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
Vec::from_par_iter(par_iter).into()
}
}
/// Collect items from a parallel iterator into a binaryheap.
/// The heap-ordering is calculated serially after all items are collected.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for BinaryHeap<T>
where Vec<T>: FromParallelIterator<PAR_ITER>,
T: Ord + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
Vec::from_par_iter(par_iter).into()
}
}
/// Collect items from a parallel iterator into a freshly allocated
/// linked list.
impl<PAR_ITER, T> FromParallelIterator<PAR_ITER> for LinkedList<T>
where PAR_ITER: ParallelIterator<Item=T>,
T: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
par_iter.map(|elem| { let mut list = LinkedList::new(); list.push_back(elem); list })
.reduce_with(|mut list1, mut list2| { list1.append(&mut list2); list1 })
.unwrap_or_else(|| LinkedList::new())
}
}
/// Collect (key, value) pairs from a parallel iterator into a
/// hashmap. If multiple pairs correspond to the same key, then the
/// ones produced earlier in the parallel iterator will be
/// overwritten, just as with a sequential iterator.
impl<PAR_ITER, K, V, S> FromParallelIterator<PAR_ITER> for HashMap<K, V, S>
where PAR_ITER: ParallelIterator<Item=(K, V)>,
K: Eq + Hash + Send,
V: Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
// See the map_collect benchmarks in rayon-demo for different strategies.
combine(par_iter, |list| {
let len = combined_len(list);
HashMap::with_capacity_and_hasher(len, Default::default())
})
}
}
/// Collect (key, value) pairs from a parallel iterator into a
/// btreemap. If multiple pairs correspond to the same key, then the
/// ones produced earlier in the parallel iterator will be
/// overwritten, just as with a sequential iterator.
impl<PAR_ITER, K, V> FromParallelIterator<PAR_ITER> for BTreeMap<K, V>
where PAR_ITER: ParallelIterator<Item=(K, V)>,
K: Ord + Send,
V: Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |_| BTreeMap::new())
}
}
/// Collect values from a parallel iterator into a hashset.
impl<PAR_ITER, V, S> FromParallelIterator<PAR_ITER> for HashSet<V, S>
where PAR_ITER: ParallelIterator<Item=V>,
V: Eq + Hash + Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |list| {
let len = combined_len(list);
HashSet::with_capacity_and_hasher(len, Default::default())
})
}
}
/// Collect values from a parallel iterator into a btreeset.
impl<PAR_ITER, V> FromParallelIterator<PAR_ITER> for BTreeSet<V>
where PAR_ITER: ParallelIterator<Item=V>,
V: Send + Ord,
{
fn from_par_iter(par_iter: PAR_ITER) -> Self {
combine(par_iter, |_| BTreeSet::new())
}
}
|
// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Module for working with VCF and BCF files.
//!
//! # Performance Remarks
//!
//! Note that BCF corresponds to the in-memory representation of BCF/VCF records in Htslib
//! itself. Thus, it comes without a runtime penalty for parsing, in contrast to reading VCF
//! files.
use std::ffi;
use std::path::Path;
use std::rc::Rc;
use std::str;
use url::Url;
pub mod buffer;
pub mod errors;
pub mod header;
pub mod record;
use crate::bcf::header::{HeaderView, SampleSubset};
use crate::htslib;
pub use crate::bcf::errors::Error;
pub use crate::bcf::errors::Result;
pub use crate::bcf::header::{Header, HeaderRecord};
pub use crate::bcf::record::Record;
/// A trait for a BCF reader with a read method.
pub trait Read: Sized {
/// Read the next record.
///
/// # Arguments
/// * record - an empty record, that can be created with `bcf::Reader::empty_record`.
///
/// # Returns
/// A result with an error in case of failure. Otherwise, true if a record was read,
/// false if no record was read because the end of the file was reached.
fn read(&mut self, record: &mut record::Record) -> Result<bool>;
/// Return an iterator over all records of the VCF/BCF file.
fn records(&mut self) -> Records<'_, Self>;
/// Return the header.
fn header(&self) -> &HeaderView;
/// Return empty record. Can be reused multiple times.
fn empty_record(&self) -> Record;
/// Activate multi-threaded BCF/VCF read support in htslib. This should permit faster
/// reading of large VCF files.
///
/// Setting `nthreads` to `0` does not change the current state. Note that it is not
/// possible to set the number of background threads below `1` once it has been set.
///
/// # Arguments
///
/// * `n_threads` - number of extra background writer threads to use, must be `> 0`.
fn set_threads(&mut self, n_threads: usize) -> Result<()>;
}
/// A VCF/BCF reader.
#[derive(Debug)]
pub struct Reader {
inner: *mut htslib::htsFile,
header: Rc<HeaderView>,
}
unsafe impl Send for Reader {}
/// # Safety
///
/// Implementation for `Reader::set_threads()` and `Writer::set_threads`.
pub unsafe fn set_threads(hts_file: *mut htslib::htsFile, n_threads: usize) -> Result<()> {
assert!(n_threads > 0, "n_threads must be > 0");
let r = htslib::hts_set_threads(hts_file, n_threads as i32);
if r != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
impl Reader {
/// Create a new reader from a given path.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => Ok(Self::new(p.as_bytes())?),
_ => Err(errors::Error::NonUnicodePath),
}
}
/// Create a new reader from a given URL.
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(url.as_str().as_bytes())
}
/// Create a new reader from standard input.
pub fn from_stdin() -> Result<Self> {
Self::new(b"-")
}
fn new(path: &[u8]) -> Result<Self> {
let htsfile = bcf_open(path, b"r")?;
let header = unsafe { htslib::bcf_hdr_read(htsfile) };
Ok(Reader {
inner: htsfile,
header: Rc::new(HeaderView::new(header)),
})
}
}
impl Read for Reader {
fn read(&mut self, record: &mut record::Record) -> Result<bool> {
match unsafe { htslib::bcf_read(self.inner, self.header.inner, record.inner) } {
0 => {
unsafe {
// Always unpack record.
htslib::bcf_unpack(record.inner_mut(), htslib::BCF_UN_ALL as i32);
}
record.set_header(Rc::clone(&self.header));
Ok(true)
}
-1 => Ok(false),
_ => Err(Error::InvalidRecord),
}
}
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn set_threads(&mut self, n_threads: usize) -> Result<()> {
unsafe { set_threads(self.inner, n_threads) }
}
fn header(&self) -> &HeaderView {
&self.header
}
/// Return empty record. Can be reused multiple times.
fn empty_record(&self) -> Record {
Record::new(Rc::clone(&self.header))
}
}
impl Drop for Reader {
fn drop(&mut self) {
unsafe {
htslib::hts_close(self.inner);
}
}
}
/// An indexed VCF/BCF reader.
#[derive(Debug)]
pub struct IndexedReader {
/// The synced VCF/BCF reader to use internally.
inner: *mut htslib::bcf_srs_t,
/// The header.
header: Rc<HeaderView>,
/// The position of the previous fetch, if any.
current_region: Option<(u32, u64, u64)>,
}
unsafe impl Send for IndexedReader {}
impl IndexedReader {
/// Create a new `IndexedReader` from path.
///
/// # Arguments
///
/// * `path` - the path to open.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => Ok(Self::new(&ffi::CString::new(p).unwrap())?),
_ => Err(Error::NonUnicodePath),
}
}
/// Create a new `IndexedReader` from an URL.
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(&ffi::CString::new(url.as_str()).unwrap())
}
/// Create a new `IndexedReader`.
///
/// # Arguments
///
/// * `path` - the path. Use "-" for stdin.
fn new(path: &ffi::CStr) -> Result<Self> {
// Create reader and require existence of index file.
let ser_reader = unsafe { htslib::bcf_sr_init() };
unsafe {
htslib::bcf_sr_set_opt(ser_reader, 0);
} // 0: BCF_SR_REQUIRE_IDX
// Attach a file with the path from the arguments.
if unsafe { htslib::bcf_sr_add_reader(ser_reader, path.as_ptr()) } >= 0 {
let header = Rc::new(HeaderView::new(unsafe {
htslib::bcf_hdr_dup((*(*ser_reader).readers.offset(0)).header)
}));
Ok(IndexedReader {
inner: ser_reader,
header,
current_region: None,
})
} else {
Err(Error::Open {
target: path.to_str().unwrap().to_owned(),
})
}
}
/// Jump to the given region.
///
/// # Arguments
///
/// * `rid` - numeric ID of the reference to jump to; use `HeaderView::name2rid` for resolving
/// contig name to ID.
/// * `start` - `0`-based start coordinate of region on reference.
/// * `end` - `0`-based end coordinate of region on reference.
pub fn fetch(&mut self, rid: u32, start: u64, end: u64) -> Result<()> {
let contig = self.header.rid2name(rid).unwrap();
let contig = ffi::CString::new(contig).unwrap();
if unsafe { htslib::bcf_sr_seek(self.inner, contig.as_ptr(), start as i64) } != 0 {
Err(Error::Seek {
contig: contig.to_str().unwrap().to_owned(),
start,
})
} else {
self.current_region = Some((rid, start, end));
Ok(())
}
}
}
impl Read for IndexedReader {
fn read(&mut self, record: &mut record::Record) -> Result<bool> {
match unsafe { htslib::bcf_sr_next_line(self.inner) } {
0 => {
if unsafe { (*self.inner).errnum } != 0 {
Err(Error::InvalidRecord)
} else {
Ok(false)
}
}
i => {
assert!(i > 0, "Must not be negative");
// Note that the sync BCF reader has a different interface than the others
// as it keeps its own buffer already for each record. An alternative here
// would be to replace the `inner` value by an enum that can be a pointer
// into a synced reader or an owning popinter to an allocated record.
unsafe {
htslib::bcf_copy(
record.inner,
*(*(*self.inner).readers.offset(0)).buffer.offset(0),
);
}
record.set_header(Rc::clone(&self.header));
match self.current_region {
Some((rid, _start, end)) => {
if record.rid().is_some()
&& rid == record.rid().unwrap()
&& record.pos() as u64 <= end
{
Ok(true)
} else {
Ok(false)
}
}
None => Ok(true),
}
}
}
}
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn set_threads(&mut self, n_threads: usize) -> Result<()> {
assert!(n_threads > 0, "n_threads must be > 0");
let r = unsafe { htslib::bcf_sr_set_threads(self.inner, n_threads as i32) };
if r != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
fn header(&self) -> &HeaderView {
&self.header
}
fn empty_record(&self) -> Record {
Record::new(Rc::clone(&self.header))
}
}
impl Drop for IndexedReader {
fn drop(&mut self) {
unsafe { htslib::bcf_sr_destroy(self.inner) };
}
}
/// This module contains the `SyncedReader` class and related code.
pub mod synced {
use super::*;
/// This module contains bitmask constants for `SyncedReader`.
pub mod pairing {
/// Allow different alleles, as long as they all are SNPs.
pub const SNPS: u32 = crate::htslib::BCF_SR_PAIR_SNPS;
/// The same as above, but with indels.
pub const INDELS: u32 = crate::htslib::BCF_SR_PAIR_INDELS;
/// Any combination of alleles can be returned by `bcf_sr_next_line()`.
pub const ANY: u32 = crate::htslib::BCF_SR_PAIR_ANY;
/// At least some of multiallelic ALTs must match. Implied by all the others with the exception of `EXACT`.
pub const SOME: u32 = crate::htslib::BCF_SR_PAIR_SOME;
/// Allow REF-only records with SNPs.
pub const SNP_REF: u32 = crate::htslib::BCF_SR_PAIR_SNP_REF;
/// Allow REF-only records with indels.
pub const INDEL_REF: u32 = crate::htslib::BCF_SR_PAIR_INDEL_REF;
/// Require the exact same set of alleles in all files.
pub const EXACT: u32 = crate::htslib::BCF_SR_PAIR_EXACT;
/// `SNPS | INDELS`.
pub const BOTH: u32 = crate::htslib::BCF_SR_PAIR_BOTH;
/// `SNPS | INDELS | SNP_REF | INDEL_REF`.
pub const BOTH_REF: u32 = crate::htslib::BCF_SR_PAIR_BOTH_REF;
}
/// A wrapper for `bcf_srs_t`; allows joint traversal of multiple VCF and/or BCF files.
#[derive(Debug)]
pub struct SyncedReader {
/// Internal handle for the synced reader.
inner: *mut crate::htslib::bcf_srs_t,
/// RC's of `HeaderView`s of the readers.
headers: Vec<Rc<HeaderView>>,
/// The position of the previous fetch, if any.
current_region: Option<(u32, u64, u64)>,
}
// TODO: add interface for setting threads, ensure that the pool is freed properly
impl SyncedReader {
pub fn new() -> Result<Self> {
let inner = unsafe { crate::htslib::bcf_sr_init() };
if inner.is_null() {
return Err(errors::Error::AllocationError);
}
Ok(SyncedReader {
inner,
headers: Vec::new(),
current_region: None,
})
}
/// Enable or disable requiring of index
pub fn set_require_index(&mut self, do_require: bool) {
unsafe {
(*self.inner).require_index = if do_require { 1 } else { 0 };
}
}
/// Set the given bitmask of values from `sr_pairing` module.
pub fn set_pairing(&mut self, bitmask: u32) {
unsafe {
// TODO: 1 actually is BCF_SR_PAIR_LOGIC but is not available here?
crate::htslib::bcf_sr_set_opt(self.inner, 1, bitmask);
}
}
/// Add new reader with the path to the file.
pub fn add_reader<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => {
let p_cstring = ffi::CString::new(p).unwrap();
let res =
unsafe { crate::htslib::bcf_sr_add_reader(self.inner, p_cstring.as_ptr()) };
if res == 0 {
return Err(errors::Error::Open {
target: p.to_owned(),
});
}
let i = (self.reader_count() - 1) as isize;
let header = Rc::new(HeaderView::new(unsafe {
crate::htslib::bcf_hdr_dup((*(*self.inner).readers.offset(i)).header)
}));
self.headers.push(header);
Ok(())
}
_ => Err(errors::Error::NonUnicodePath),
}
}
/// Remove reader with the given index.
pub fn remove_reader(&mut self, idx: u32) {
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
unsafe {
crate::htslib::bcf_sr_remove_reader(self.inner, idx as i32);
}
self.headers.remove(idx as usize);
}
}
/// Return number of open files/readers.
pub fn reader_count(&self) -> u32 {
unsafe { (*self.inner).nreaders as u32 }
}
/// Read next line and return number of readers that have the given line (0 if end of all files is reached).
pub fn read_next(&mut self) -> Result<u32> {
let num = unsafe { crate::htslib::bcf_sr_next_line(self.inner) as u32 };
if num == 0 {
if unsafe { (*self.inner).errnum } != 0 {
return Err(errors::Error::InvalidRecord);
}
Ok(0)
} else {
assert!(num > 0, "num returned by htslib must not be negative");
match self.current_region {
Some((rid, _start, end)) => {
for idx in 0..self.reader_count() {
if !self.has_line(idx) {
continue;
}
unsafe {
let record = *(*(*self.inner).readers.offset(idx as isize))
.buffer
.offset(0);
if (*record).rid != (rid as i32) || (*record).pos >= (end as i64) {
return Ok(0);
}
}
}
Ok(num)
}
None => Ok(num),
}
}
}
/// Return whether the given reader has the line.
pub fn has_line(&self, idx: u32) -> bool {
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
unsafe { (*(*self.inner).has_line.offset(idx as isize)) != 0 }
}
}
/// Return record from the given reader, if any.
pub fn record(&self, idx: u32) -> Option<Record> {
if self.has_line(idx) {
let record = Record::new(self.headers[idx as usize].clone());
unsafe {
crate::htslib::bcf_copy(
record.inner,
*(*(*self.inner).readers.offset(idx as isize))
.buffer
.offset(0),
);
}
Some(record)
} else {
None
}
}
/// Return header from the given reader.
pub fn header(&self, idx: u32) -> &HeaderView {
// TODO: is the mutability here correct?
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
&self.headers[idx as usize]
}
}
/// Jump to the given region.
///
/// # Arguments
///
/// * `rid` - numeric ID of the reference to jump to; use `HeaderView::name2rid` for resolving
/// contig name to ID.
/// * `start` - `0`-based start coordinate of region on reference.
/// * `end` - `0`-based end coordinate of region on reference.
pub fn fetch(&mut self, rid: u32, start: u64, end: u64) -> Result<()> {
let contig = {
let contig = self.header(0).rid2name(rid).unwrap(); //.clone();
ffi::CString::new(contig).unwrap()
};
if unsafe { htslib::bcf_sr_seek(self.inner, contig.as_ptr(), start as i64) } != 0 {
Err(Error::Seek {
contig: contig.to_str().unwrap().to_owned(),
start,
})
} else {
self.current_region = Some((rid, start, end));
Ok(())
}
}
}
impl Drop for SyncedReader {
fn drop(&mut self) {
unsafe { crate::htslib::bcf_sr_destroy(self.inner) };
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum Format {
VCF,
BCF,
}
/// A VCF/BCF writer.
#[derive(Debug)]
pub struct Writer {
inner: *mut htslib::htsFile,
header: Rc<HeaderView>,
subset: Option<SampleSubset>,
}
unsafe impl Send for Writer {}
impl Writer {
/// Create a new writer that writes to the given path.
///
/// # Arguments
///
/// * `path` - the path
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_path<P: AsRef<Path>>(
path: P,
header: &Header,
uncompressed: bool,
format: Format,
) -> Result<Self> {
if let Some(p) = path.as_ref().to_str() {
Ok(Self::new(p.as_bytes(), header, uncompressed, format)?)
} else {
Err(errors::Error::NonUnicodePath)
}
}
/// Create a new writer from a URL.
///
/// # Arguments
///
/// * `url` - the URL
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_url(
url: &Url,
header: &Header,
uncompressed: bool,
format: Format,
) -> Result<Self> {
Self::new(url.as_str().as_bytes(), header, uncompressed, format)
}
/// Create a new writer to stdout.
///
/// # Arguments
///
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_stdout(header: &Header, uncompressed: bool, format: Format) -> Result<Self> {
Self::new(b"-", header, uncompressed, format)
}
fn new(path: &[u8], header: &Header, uncompressed: bool, format: Format) -> Result<Self> {
let mode: &[u8] = match (uncompressed, format) {
(true, Format::VCF) => b"w",
(false, Format::VCF) => b"wz",
(true, Format::BCF) => b"wbu",
(false, Format::BCF) => b"wb",
};
let htsfile = bcf_open(path, mode)?;
unsafe { htslib::bcf_hdr_write(htsfile, header.inner) };
Ok(Writer {
inner: htsfile,
header: Rc::new(HeaderView::new(unsafe {
htslib::bcf_hdr_dup(header.inner)
})),
subset: header.subset.clone(),
})
}
/// Obtain reference to the lightweight `HeaderView` of the BCF header.
pub fn header(&self) -> &HeaderView {
&self.header
}
/// Create empty record for writing to this writer.
///
/// This record can then be reused multiple times.
pub fn empty_record(&self) -> Record {
record::Record::new(Rc::clone(&self.header))
}
/// Translate record to header of this writer.
///
/// # Arguments
///
/// - `record` - The `Record` to translate.
pub fn translate(&mut self, record: &mut record::Record) {
unsafe {
htslib::bcf_translate(self.header.inner, record.header().inner, record.inner);
}
record.set_header(Rc::clone(&self.header));
}
/// Subset samples of record to match header of this writer.
///
/// # Arguments
///
/// - `record` - The `Record` to modify.
pub fn subset(&mut self, record: &mut record::Record) {
if let Some(ref mut subset) = self.subset {
unsafe {
htslib::bcf_subset(
self.header.inner,
record.inner,
subset.len() as i32,
subset.as_mut_ptr(),
);
}
}
}
/// Write `record` to the Writer.
///
/// # Arguments
///
/// - `record` - The `Record` to write.
pub fn write(&mut self, record: &record::Record) -> Result<()> {
if unsafe { htslib::bcf_write(self.inner, self.header.inner, record.inner) } == -1 {
Err(Error::Write)
} else {
Ok(())
}
}
/// Activate multi-threaded BCF write support in htslib. This should permit faster
/// writing of large BCF files.
///
/// # Arguments
///
/// * `n_threads` - number of extra background writer threads to use, must be `> 0`.
pub fn set_threads(&mut self, n_threads: usize) -> Result<()> {
unsafe { set_threads(self.inner, n_threads) }
}
}
impl Drop for Writer {
fn drop(&mut self) {
unsafe {
htslib::hts_close(self.inner);
}
}
}
#[derive(Debug)]
pub struct Records<'a, R: Read> {
reader: &'a mut R,
}
impl<'a, R: Read> Iterator for Records<'a, R> {
type Item = Result<record::Record>;
fn next(&mut self) -> Option<Result<record::Record>> {
let mut record = self.reader.empty_record();
match self.reader.read(&mut record) {
Err(e) => Some(Err(e)),
Ok(true) => Some(Ok(record)),
Ok(false) => None,
}
}
}
/// Wrapper for opening a BCF file.
fn bcf_open(target: &[u8], mode: &[u8]) -> Result<*mut htslib::htsFile> {
let p = ffi::CString::new(target).unwrap();
let c_str = ffi::CString::new(mode).unwrap();
let ret = unsafe { htslib::hts_open(p.as_ptr(), c_str.as_ptr()) };
if ret.is_null() {
return Err(errors::Error::Open {
target: str::from_utf8(target).unwrap().to_owned(),
});
}
unsafe {
if !(mode.contains(&b'w')
|| (*ret).format.category == htslib::htsFormatCategory_variant_data)
{
return Err(errors::Error::Open {
target: str::from_utf8(target).unwrap().to_owned(),
});
}
}
Ok(ret)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bcf::header::Id;
use crate::bcf::record::Numeric;
use std::fs::File;
use std::io::prelude::Read as IoRead;
use std::path::Path;
use std::str;
fn _test_read<P: AsRef<Path>>(path: &P) {
let mut bcf = Reader::from_path(path).expect("Error opening file.");
assert_eq!(bcf.header.samples(), [b"NA12878.subsample-0.25-0"]);
for (i, rec) in bcf.records().enumerate() {
let mut record = rec.expect("Error reading record.");
assert_eq!(record.sample_count(), 1);
assert_eq!(record.rid().expect("Error reading rid."), 0);
assert_eq!(record.pos(), 10021 + i as i64);
assert!((record.qual() - 0f32).abs() < f32::EPSILON);
assert!(
(record
.info(b"MQ0F")
.float()
.expect("Error reading info.")
.expect("Missing tag")[0]
- 1.0)
.abs()
< f32::EPSILON
);
if i == 59 {
assert!(
(record
.info(b"SGB")
.float()
.expect("Error reading info.")
.expect("Missing tag")[0]
- -0.379885)
.abs()
< f32::EPSILON
);
}
// the artificial "not observed" allele is present in each record.
assert_eq!(record.alleles().iter().last().unwrap(), b"<X>");
let mut fmt = record.format(b"PL");
let pl = fmt.integer().expect("Error reading format.");
assert_eq!(pl.len(), 1);
if i == 59 {
assert_eq!(pl[0].len(), 6);
} else {
assert_eq!(pl[0].len(), 3);
}
}
}
#[test]
fn test_read() {
_test_read(&"test/test.bcf");
}
#[test]
fn test_reader_set_threads() {
let path = &"test/test.bcf";
let mut bcf = Reader::from_path(path).expect("Error opening file.");
bcf.set_threads(2).unwrap();
}
#[test]
fn test_writer_set_threads() {
let path = &"test/test.bcf";
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let bcfpath = tmp.path().join("test.bcf");
let bcf = Reader::from_path(path).expect("Error opening file.");
let header = Header::from_template_subset(&bcf.header, &[b"NA12878.subsample-0.25-0"])
.expect("Error subsetting samples.");
let mut writer =
Writer::from_path(&bcfpath, &header, false, Format::BCF).expect("Error opening file.");
writer.set_threads(2).unwrap();
}
#[test]
fn test_fetch() {
let mut bcf = IndexedReader::from_path(&"test/test.bcf").expect("Error opening file.");
bcf.set_threads(2).unwrap();
let rid = bcf
.header()
.name2rid(b"1")
.expect("Translating from contig '1' to ID failed.");
bcf.fetch(rid, 10_033, 10_060).expect("Fetching failed");
assert_eq!(bcf.records().count(), 28);
}
#[test]
fn test_write() {
let mut bcf = Reader::from_path(&"test/test_multi.bcf").expect("Error opening file.");
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let bcfpath = tmp.path().join("test.bcf");
println!("{:?}", bcfpath);
{
let header = Header::from_template_subset(&bcf.header, &[b"NA12878.subsample-0.25-0"])
.expect("Error subsetting samples.");
let mut writer = Writer::from_path(&bcfpath, &header, false, Format::BCF)
.expect("Error opening file.");
for rec in bcf.records() {
let mut record = rec.expect("Error reading record.");
writer.translate(&mut record);
writer.subset(&mut record);
record.trim_alleles().expect("Error trimming alleles.");
writer.write(&record).expect("Error writing record");
}
}
{
_test_read(&bcfpath);
}
tmp.close().expect("Failed to delete temp dir");
}
#[test]
fn test_strings() {
let mut vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let fs1 = [
&b"LongString1"[..],
&b"LongString2"[..],
&b"."[..],
&b"LongString4"[..],
&b"evenlength"[..],
&b"ss6"[..],
];
for (i, rec) in vcf.records().enumerate() {
println!("record {}", i);
let mut record = rec.expect("Error reading record.");
assert_eq!(
record
.info(b"S1")
.string()
.expect("Error reading string.")
.expect("Missing tag")[0],
format!("string{}", i + 1).as_bytes()
);
println!(
"{}",
String::from_utf8_lossy(
record
.format(b"FS1")
.string()
.expect("Error reading string.")[0]
)
);
assert_eq!(
record
.format(b"FS1")
.string()
.expect("Error reading string.")[0],
fs1[i]
);
}
}
#[test]
fn test_missing() {
let mut vcf = Reader::from_path(&"test/test_missing.vcf").expect("Error opening file.");
let fn4 = [
&[
i32::missing(),
i32::missing(),
i32::missing(),
i32::missing(),
][..],
&[i32::missing()][..],
];
let f1 = [false, true];
for (i, rec) in vcf.records().enumerate() {
let mut record = rec.expect("Error reading record.");
assert_eq!(
record
.info(b"F1")
.float()
.expect("Error reading float.")
.expect("Missing tag")[0]
.is_nan(),
f1[i]
);
assert_eq!(
record
.format(b"FN4")
.integer()
.expect("Error reading integer.")[1],
fn4[i]
);
assert!(
record.format(b"FF4").float().expect("Error reading float.")[1]
.iter()
.all(|&v| v.is_missing())
);
}
}
#[test]
fn test_genotypes() {
let mut vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let expected = ["./1", "1|1", "0/1", "0|1", "1|.", "1/1"];
for (rec, exp_gt) in vcf.records().zip(expected.iter()) {
let mut rec = rec.expect("Error reading record.");
let genotypes = rec.genotypes().expect("Error reading genotypes");
assert_eq!(&format!("{}", genotypes.get(0)), exp_gt);
}
}
#[test]
fn test_header_ids() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let header = &vcf.header();
use crate::bcf::header::Id;
assert_eq!(header.id_to_name(Id(4)), b"GT");
assert_eq!(header.name_to_id(b"GT").unwrap(), Id(4));
assert!(header.name_to_id(b"XX").is_err());
}
#[test]
fn test_header_samples() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let header = &vcf.header();
assert_eq!(header.id_to_sample(Id(0)), b"one");
assert_eq!(header.id_to_sample(Id(1)), b"two");
assert_eq!(header.sample_to_id(b"one").unwrap(), Id(0));
assert_eq!(header.sample_to_id(b"two").unwrap(), Id(1));
assert!(header.sample_to_id(b"three").is_err());
}
#[test]
fn test_header_contigs() {
let vcf = Reader::from_path(&"test/test_multi.bcf").expect("Error opening file.");
let header = &vcf.header();
assert_eq!(header.contig_count(), 86);
// test existing contig names and IDs
assert_eq!(header.rid2name(0).unwrap(), b"1");
assert_eq!(header.name2rid(b"1").unwrap(), 0);
assert_eq!(header.rid2name(85).unwrap(), b"hs37d5");
assert_eq!(header.name2rid(b"hs37d5").unwrap(), 85);
// test nonexistent contig names and IDs
assert!(header.name2rid(b"nonexistent_contig").is_err());
assert!(header.rid2name(100).is_err());
}
#[test]
fn test_header_records() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let records = vcf.header().header_records();
assert_eq!(records.len(), 10);
match records[1] {
HeaderRecord::Filter {
ref key,
ref values,
} => {
assert_eq!(key, "FILTER");
assert_eq!(values["ID"], "PASS");
}
_ => {
panic!("Invalid HeaderRecord");
}
}
}
#[test]
fn test_header_info_types() {
let vcf = Reader::from_path(&"test/test.bcf").unwrap();
let header = vcf.header();
let truth = vec![
(
// INFO=<ID=INDEL,Number=0,Type=Flag>
"INDEL",
header::TagType::Flag,
header::TagLength::Fixed(0),
),
(
// INFO=<ID=DP,Number=1,Type=Integer>
"DP",
header::TagType::Integer,
header::TagLength::Fixed(1),
),
(
// INFO=<ID=QS,Number=R,Type=Float>
"QS",
header::TagType::Float,
header::TagLength::Alleles,
),
(
// INFO=<ID=I16,Number=16,Type=Float>
"I16",
header::TagType::Float,
header::TagLength::Fixed(16),
),
];
for (ref_name, ref_type, ref_length) in truth {
let (tag_type, tag_length) = header.info_type(ref_name.as_bytes()).unwrap();
assert_eq!(tag_type, ref_type);
assert_eq!(tag_length, ref_length);
}
let vcf = Reader::from_path(&"test/test_svlen.vcf").unwrap();
let header = vcf.header();
let truth = vec![
(
// INFO=<ID=IMPRECISE,Number=0,Type=Flag>
"IMPRECISE",
header::TagType::Flag,
header::TagLength::Fixed(0),
),
(
// INFO=<ID=SVTYPE,Number=1,Type=String>
"SVTYPE",
header::TagType::String,
header::TagLength::Fixed(1),
),
(
// INFO=<ID=SVLEN,Number=.,Type=Integer>
"SVLEN",
header::TagType::Integer,
header::TagLength::Variable,
),
(
// INFO<ID=CIGAR,Number=A,Type=String>
"CIGAR",
header::TagType::String,
header::TagLength::AltAlleles,
),
];
for (ref_name, ref_type, ref_length) in truth {
let (tag_type, tag_length) = header.info_type(ref_name.as_bytes()).unwrap();
assert_eq!(tag_type, ref_type);
assert_eq!(tag_length, ref_length);
}
assert!(header.info_type(b"NOT_THERE").is_err());
}
#[test]
fn test_remove_alleles() {
let mut bcf = Reader::from_path(&"test/test_multi.bcf").unwrap();
for res in bcf.records() {
let mut record = res.unwrap();
if record.pos() == 10080 {
record.remove_alleles(&[false, false, true]).unwrap();
assert_eq!(record.alleles(), [b"A", b"C"]);
}
}
}
// Helper function reading full file into string.
fn read_all<P: AsRef<Path>>(path: P) -> String {
let mut file = File::open(path.as_ref())
.unwrap_or_else(|_| panic!("Unable to open the file: {:?}", path.as_ref()));
let mut contents = String::new();
file.read_to_string(&mut contents)
.unwrap_or_else(|_| panic!("Unable to read the file: {:?}", path.as_ref()));
contents
}
// Open `test_various.vcf`, add a record from scratch to it and write it out again.
//
// This exercises the full functionality of updating information in a `record::Record`.
#[test]
fn test_write_various() {
// Open reader, then create writer.
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let out_path = tmp.path().join("test_various.out.vcf");
let vcf = Reader::from_path(&"test/test_various.vcf").expect("Error opening file.");
// The writer goes into its own block so we can ensure that the file is closed and
// all data is written below.
{
let mut writer = Writer::from_path(
&out_path,
&Header::from_template(&vcf.header()),
true,
Format::VCF,
)
.expect("Error opening file.");
let header = writer.header().clone();
// Setup empty record, filled below.
let mut record = writer.empty_record();
record.set_rid(Some(0));
assert_eq!(record.rid().unwrap(), 0);
record.set_pos(12);
assert_eq!(record.pos(), 12);
assert_eq!(str::from_utf8(record.id().as_ref()).unwrap(), ".");
record.set_id(b"to_be_cleared").unwrap();
assert_eq!(
str::from_utf8(record.id().as_ref()).unwrap(),
"to_be_cleared"
);
record.clear_id().unwrap();
assert_eq!(str::from_utf8(record.id().as_ref()).unwrap(), ".");
record.set_id(b"first_id").unwrap();
record.push_id(b"second_id").unwrap();
record.push_id(b"first_id").unwrap();
assert!(record.filters().next().is_none());
record.set_filters(&[header.name_to_id(b"q10").unwrap()]);
record.push_filter(header.name_to_id(b"s50").unwrap());
record.remove_filter(header.name_to_id(b"q10").unwrap(), true);
record.push_filter(header.name_to_id(b"q10").unwrap());
record.set_alleles(&[b"C", b"T", b"G"]).unwrap();
record.set_qual(10.0);
record.push_info_integer(b"N1", &[32]).unwrap();
record.push_info_float(b"F1", &[33.0]).unwrap();
record.push_info_string(b"S1", &[b"fourtytwo"]).unwrap();
record.push_info_flag(b"X1").unwrap();
record
.push_format_string(b"FS1", &[&b"yes"[..], &b"no"[..]])
.unwrap();
record.push_format_integer(b"FF1", &[43, 11]).unwrap();
record.push_format_float(b"FN1", &[42.0, 10.0]).unwrap();
record
.push_format_char(b"CH1", &[b"A"[0], b"B"[0]])
.unwrap();
// Finally, write out the record.
writer.write(&record).unwrap();
}
// Now, compare expected and real output.
let expected = read_all("test/test_various.out.vcf");
let actual = read_all(&out_path);
assert_eq!(expected, actual);
}
#[test]
fn test_remove_headers() {
let vcf = Reader::from_path(&"test/test_headers.vcf").expect("Error opening file.");
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let vcfpath = tmp.path().join("test.vcf");
let mut header = Header::from_template(&vcf.header);
header
.remove_contig(b"contig2")
.remove_info(b"INFO2")
.remove_format(b"FORMAT2")
.remove_filter(b"FILTER2")
.remove_structured(b"Foo2")
.remove_generic(b"Bar2");
{
let mut _writer = Writer::from_path(&vcfpath, &header, true, Format::VCF)
.expect("Error opening output file.");
// Note that we don't need to write anything, we are just looking at the header.
}
let expected = read_all("test/test_headers.out.vcf");
let actual = read_all(&vcfpath);
assert_eq!(expected, actual);
}
#[test]
fn test_synced_reader() {
let mut reader = synced::SyncedReader::new().unwrap();
reader.set_require_index(true);
reader.set_pairing(synced::pairing::SNPS);
assert_eq!(reader.reader_count(), 0);
reader.add_reader(&"test/test_left.vcf.gz").unwrap();
reader.add_reader(&"test/test_right.vcf.gz").unwrap();
assert_eq!(reader.reader_count(), 2);
let res1 = reader.read_next();
assert_eq!(res1.unwrap(), 2);
assert!(reader.has_line(0));
assert!(reader.has_line(1));
let res2 = reader.read_next();
assert_eq!(res2.unwrap(), 1);
assert!(reader.has_line(0));
assert!(!reader.has_line(1));
let res3 = reader.read_next();
assert_eq!(res3.unwrap(), 1);
assert!(!reader.has_line(0));
assert!(reader.has_line(1));
let res4 = reader.read_next();
assert_eq!(res4.unwrap(), 0);
}
#[test]
fn test_synced_reader_fetch() {
let mut reader = synced::SyncedReader::new().unwrap();
reader.set_require_index(true);
reader.set_pairing(synced::pairing::SNPS);
assert_eq!(reader.reader_count(), 0);
reader.add_reader(&"test/test_left.vcf.gz").unwrap();
reader.add_reader(&"test/test_right.vcf.gz").unwrap();
assert_eq!(reader.reader_count(), 2);
reader.fetch(0, 0, 1000).unwrap();
let res1 = reader.read_next();
assert_eq!(res1.unwrap(), 2);
assert!(reader.has_line(0));
assert!(reader.has_line(1));
let res2 = reader.read_next();
assert_eq!(res2.unwrap(), 1);
assert!(reader.has_line(0));
assert!(!reader.has_line(1));
let res3 = reader.read_next();
assert_eq!(res3.unwrap(), 1);
assert!(!reader.has_line(0));
assert!(reader.has_line(1));
let res4 = reader.read_next();
assert_eq!(res4.unwrap(), 0);
}
#[test]
fn test_svlen() {
let mut reader = Reader::from_path("test/test_svlen.vcf").unwrap();
let mut record = reader.empty_record();
reader.read(&mut record).unwrap();
assert_eq!(record.info(b"SVLEN").integer().unwrap(), Some(&[-127][..]));
}
#[test]
fn test_fails_on_bam() {
let reader = Reader::from_path("test/test.bam");
assert!(reader.is_err());
}
#[test]
fn test_fails_on_non_existiant() {
let reader = Reader::from_path("test/no_such_file");
assert!(reader.is_err());
}
#[test]
fn test_multi_string_info_tag() {
let mut reader = Reader::from_path("test/test-info-multi-string.vcf").unwrap();
let mut rec = reader.empty_record();
let _ = reader.read(&mut rec);
assert_eq!(rec.info(b"ANN").string().unwrap().unwrap().len(), 14);
}
#[test]
fn test_multi_string_info_tag_number_a() {
let mut reader = Reader::from_path("test/test-info-multi-string-number=A.vcf").unwrap();
let mut rec = reader.empty_record();
let _ = reader.read(&mut rec);
assert_eq!(rec.info(b"X").string().unwrap().unwrap().len(), 2);
}
}
keep compat w/ older rust (#220)
Co-authored-by: Roman Valls Guimera <4e95058a32f7f441e0c9ae52530d203ad26c7079@users.noreply.github.com>
// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Module for working with VCF and BCF files.
//!
//! # Performance Remarks
//!
//! Note that BCF corresponds to the in-memory representation of BCF/VCF records in Htslib
//! itself. Thus, it comes without a runtime penalty for parsing, in contrast to reading VCF
//! files.
use std::ffi;
use std::path::Path;
use std::rc::Rc;
use std::str;
use url::Url;
pub mod buffer;
pub mod errors;
pub mod header;
pub mod record;
use crate::bcf::header::{HeaderView, SampleSubset};
use crate::htslib;
pub use crate::bcf::errors::Error;
pub use crate::bcf::errors::Result;
pub use crate::bcf::header::{Header, HeaderRecord};
pub use crate::bcf::record::Record;
/// A trait for a BCF reader with a read method.
pub trait Read: Sized {
/// Read the next record.
///
/// # Arguments
/// * record - an empty record, that can be created with `bcf::Reader::empty_record`.
///
/// # Returns
/// A result with an error in case of failure. Otherwise, true if a record was read,
/// false if no record was read because the end of the file was reached.
fn read(&mut self, record: &mut record::Record) -> Result<bool>;
/// Return an iterator over all records of the VCF/BCF file.
fn records(&mut self) -> Records<'_, Self>;
/// Return the header.
fn header(&self) -> &HeaderView;
/// Return empty record. Can be reused multiple times.
fn empty_record(&self) -> Record;
/// Activate multi-threaded BCF/VCF read support in htslib. This should permit faster
/// reading of large VCF files.
///
/// Setting `nthreads` to `0` does not change the current state. Note that it is not
/// possible to set the number of background threads below `1` once it has been set.
///
/// # Arguments
///
/// * `n_threads` - number of extra background writer threads to use, must be `> 0`.
fn set_threads(&mut self, n_threads: usize) -> Result<()>;
}
/// A VCF/BCF reader.
#[derive(Debug)]
pub struct Reader {
inner: *mut htslib::htsFile,
header: Rc<HeaderView>,
}
unsafe impl Send for Reader {}
/// # Safety
///
/// Implementation for `Reader::set_threads()` and `Writer::set_threads`.
pub unsafe fn set_threads(hts_file: *mut htslib::htsFile, n_threads: usize) -> Result<()> {
assert!(n_threads > 0, "n_threads must be > 0");
let r = htslib::hts_set_threads(hts_file, n_threads as i32);
if r != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
impl Reader {
/// Create a new reader from a given path.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => Ok(Self::new(p.as_bytes())?),
_ => Err(errors::Error::NonUnicodePath),
}
}
/// Create a new reader from a given URL.
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(url.as_str().as_bytes())
}
/// Create a new reader from standard input.
pub fn from_stdin() -> Result<Self> {
Self::new(b"-")
}
fn new(path: &[u8]) -> Result<Self> {
let htsfile = bcf_open(path, b"r")?;
let header = unsafe { htslib::bcf_hdr_read(htsfile) };
Ok(Reader {
inner: htsfile,
header: Rc::new(HeaderView::new(header)),
})
}
}
impl Read for Reader {
fn read(&mut self, record: &mut record::Record) -> Result<bool> {
match unsafe { htslib::bcf_read(self.inner, self.header.inner, record.inner) } {
0 => {
unsafe {
// Always unpack record.
htslib::bcf_unpack(record.inner_mut(), htslib::BCF_UN_ALL as i32);
}
record.set_header(Rc::clone(&self.header));
Ok(true)
}
-1 => Ok(false),
_ => Err(Error::InvalidRecord),
}
}
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn set_threads(&mut self, n_threads: usize) -> Result<()> {
unsafe { set_threads(self.inner, n_threads) }
}
fn header(&self) -> &HeaderView {
&self.header
}
/// Return empty record. Can be reused multiple times.
fn empty_record(&self) -> Record {
Record::new(Rc::clone(&self.header))
}
}
impl Drop for Reader {
fn drop(&mut self) {
unsafe {
htslib::hts_close(self.inner);
}
}
}
/// An indexed VCF/BCF reader.
#[derive(Debug)]
pub struct IndexedReader {
/// The synced VCF/BCF reader to use internally.
inner: *mut htslib::bcf_srs_t,
/// The header.
header: Rc<HeaderView>,
/// The position of the previous fetch, if any.
current_region: Option<(u32, u64, u64)>,
}
unsafe impl Send for IndexedReader {}
impl IndexedReader {
/// Create a new `IndexedReader` from path.
///
/// # Arguments
///
/// * `path` - the path to open.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => Ok(Self::new(&ffi::CString::new(p).unwrap())?),
_ => Err(Error::NonUnicodePath),
}
}
/// Create a new `IndexedReader` from an URL.
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(&ffi::CString::new(url.as_str()).unwrap())
}
/// Create a new `IndexedReader`.
///
/// # Arguments
///
/// * `path` - the path. Use "-" for stdin.
fn new(path: &ffi::CStr) -> Result<Self> {
// Create reader and require existence of index file.
let ser_reader = unsafe { htslib::bcf_sr_init() };
unsafe {
htslib::bcf_sr_set_opt(ser_reader, 0);
} // 0: BCF_SR_REQUIRE_IDX
// Attach a file with the path from the arguments.
if unsafe { htslib::bcf_sr_add_reader(ser_reader, path.as_ptr()) } >= 0 {
let header = Rc::new(HeaderView::new(unsafe {
htslib::bcf_hdr_dup((*(*ser_reader).readers.offset(0)).header)
}));
Ok(IndexedReader {
inner: ser_reader,
header,
current_region: None,
})
} else {
Err(Error::Open {
target: path.to_str().unwrap().to_owned(),
})
}
}
/// Jump to the given region.
///
/// # Arguments
///
/// * `rid` - numeric ID of the reference to jump to; use `HeaderView::name2rid` for resolving
/// contig name to ID.
/// * `start` - `0`-based start coordinate of region on reference.
/// * `end` - `0`-based end coordinate of region on reference.
pub fn fetch(&mut self, rid: u32, start: u64, end: u64) -> Result<()> {
let contig = self.header.rid2name(rid).unwrap();
let contig = ffi::CString::new(contig).unwrap();
if unsafe { htslib::bcf_sr_seek(self.inner, contig.as_ptr(), start as i64) } != 0 {
Err(Error::Seek {
contig: contig.to_str().unwrap().to_owned(),
start,
})
} else {
self.current_region = Some((rid, start, end));
Ok(())
}
}
}
impl Read for IndexedReader {
fn read(&mut self, record: &mut record::Record) -> Result<bool> {
match unsafe { htslib::bcf_sr_next_line(self.inner) } {
0 => {
if unsafe { (*self.inner).errnum } != 0 {
Err(Error::InvalidRecord)
} else {
Ok(false)
}
}
i => {
assert!(i > 0, "Must not be negative");
// Note that the sync BCF reader has a different interface than the others
// as it keeps its own buffer already for each record. An alternative here
// would be to replace the `inner` value by an enum that can be a pointer
// into a synced reader or an owning popinter to an allocated record.
unsafe {
htslib::bcf_copy(
record.inner,
*(*(*self.inner).readers.offset(0)).buffer.offset(0),
);
}
record.set_header(Rc::clone(&self.header));
match self.current_region {
Some((rid, _start, end)) => {
if record.rid().is_some()
&& rid == record.rid().unwrap()
&& record.pos() as u64 <= end
{
Ok(true)
} else {
Ok(false)
}
}
None => Ok(true),
}
}
}
}
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn set_threads(&mut self, n_threads: usize) -> Result<()> {
assert!(n_threads > 0, "n_threads must be > 0");
let r = unsafe { htslib::bcf_sr_set_threads(self.inner, n_threads as i32) };
if r != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
fn header(&self) -> &HeaderView {
&self.header
}
fn empty_record(&self) -> Record {
Record::new(Rc::clone(&self.header))
}
}
impl Drop for IndexedReader {
fn drop(&mut self) {
unsafe { htslib::bcf_sr_destroy(self.inner) };
}
}
/// This module contains the `SyncedReader` class and related code.
pub mod synced {
use super::*;
/// This module contains bitmask constants for `SyncedReader`.
pub mod pairing {
/// Allow different alleles, as long as they all are SNPs.
pub const SNPS: u32 = crate::htslib::BCF_SR_PAIR_SNPS;
/// The same as above, but with indels.
pub const INDELS: u32 = crate::htslib::BCF_SR_PAIR_INDELS;
/// Any combination of alleles can be returned by `bcf_sr_next_line()`.
pub const ANY: u32 = crate::htslib::BCF_SR_PAIR_ANY;
/// At least some of multiallelic ALTs must match. Implied by all the others with the exception of `EXACT`.
pub const SOME: u32 = crate::htslib::BCF_SR_PAIR_SOME;
/// Allow REF-only records with SNPs.
pub const SNP_REF: u32 = crate::htslib::BCF_SR_PAIR_SNP_REF;
/// Allow REF-only records with indels.
pub const INDEL_REF: u32 = crate::htslib::BCF_SR_PAIR_INDEL_REF;
/// Require the exact same set of alleles in all files.
pub const EXACT: u32 = crate::htslib::BCF_SR_PAIR_EXACT;
/// `SNPS | INDELS`.
pub const BOTH: u32 = crate::htslib::BCF_SR_PAIR_BOTH;
/// `SNPS | INDELS | SNP_REF | INDEL_REF`.
pub const BOTH_REF: u32 = crate::htslib::BCF_SR_PAIR_BOTH_REF;
}
/// A wrapper for `bcf_srs_t`; allows joint traversal of multiple VCF and/or BCF files.
#[derive(Debug)]
pub struct SyncedReader {
/// Internal handle for the synced reader.
inner: *mut crate::htslib::bcf_srs_t,
/// RC's of `HeaderView`s of the readers.
headers: Vec<Rc<HeaderView>>,
/// The position of the previous fetch, if any.
current_region: Option<(u32, u64, u64)>,
}
// TODO: add interface for setting threads, ensure that the pool is freed properly
impl SyncedReader {
pub fn new() -> Result<Self> {
let inner = unsafe { crate::htslib::bcf_sr_init() };
if inner.is_null() {
return Err(errors::Error::AllocationError);
}
Ok(SyncedReader {
inner,
headers: Vec::new(),
current_region: None,
})
}
/// Enable or disable requiring of index
pub fn set_require_index(&mut self, do_require: bool) {
unsafe {
(*self.inner).require_index = if do_require { 1 } else { 0 };
}
}
/// Set the given bitmask of values from `sr_pairing` module.
pub fn set_pairing(&mut self, bitmask: u32) {
unsafe {
// TODO: 1 actually is BCF_SR_PAIR_LOGIC but is not available here?
crate::htslib::bcf_sr_set_opt(self.inner, 1, bitmask);
}
}
/// Add new reader with the path to the file.
pub fn add_reader<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
match path.as_ref().to_str() {
Some(p) if path.as_ref().exists() => {
let p_cstring = ffi::CString::new(p).unwrap();
let res =
unsafe { crate::htslib::bcf_sr_add_reader(self.inner, p_cstring.as_ptr()) };
if res == 0 {
return Err(errors::Error::Open {
target: p.to_owned(),
});
}
let i = (self.reader_count() - 1) as isize;
let header = Rc::new(HeaderView::new(unsafe {
crate::htslib::bcf_hdr_dup((*(*self.inner).readers.offset(i)).header)
}));
self.headers.push(header);
Ok(())
}
_ => Err(errors::Error::NonUnicodePath),
}
}
/// Remove reader with the given index.
pub fn remove_reader(&mut self, idx: u32) {
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
unsafe {
crate::htslib::bcf_sr_remove_reader(self.inner, idx as i32);
}
self.headers.remove(idx as usize);
}
}
/// Return number of open files/readers.
pub fn reader_count(&self) -> u32 {
unsafe { (*self.inner).nreaders as u32 }
}
/// Read next line and return number of readers that have the given line (0 if end of all files is reached).
pub fn read_next(&mut self) -> Result<u32> {
let num = unsafe { crate::htslib::bcf_sr_next_line(self.inner) as u32 };
if num == 0 {
if unsafe { (*self.inner).errnum } != 0 {
return Err(errors::Error::InvalidRecord);
}
Ok(0)
} else {
assert!(num > 0, "num returned by htslib must not be negative");
match self.current_region {
Some((rid, _start, end)) => {
for idx in 0..self.reader_count() {
if !self.has_line(idx) {
continue;
}
unsafe {
let record = *(*(*self.inner).readers.offset(idx as isize))
.buffer
.offset(0);
if (*record).rid != (rid as i32) || (*record).pos >= (end as i64) {
return Ok(0);
}
}
}
Ok(num)
}
None => Ok(num),
}
}
}
/// Return whether the given reader has the line.
pub fn has_line(&self, idx: u32) -> bool {
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
unsafe { (*(*self.inner).has_line.offset(idx as isize)) != 0 }
}
}
/// Return record from the given reader, if any.
pub fn record(&self, idx: u32) -> Option<Record> {
if self.has_line(idx) {
let record = Record::new(self.headers[idx as usize].clone());
unsafe {
crate::htslib::bcf_copy(
record.inner,
*(*(*self.inner).readers.offset(idx as isize))
.buffer
.offset(0),
);
}
Some(record)
} else {
None
}
}
/// Return header from the given reader.
pub fn header(&self, idx: u32) -> &HeaderView {
// TODO: is the mutability here correct?
if idx >= self.reader_count() {
panic!("Invalid reader!");
} else {
&self.headers[idx as usize]
}
}
/// Jump to the given region.
///
/// # Arguments
///
/// * `rid` - numeric ID of the reference to jump to; use `HeaderView::name2rid` for resolving
/// contig name to ID.
/// * `start` - `0`-based start coordinate of region on reference.
/// * `end` - `0`-based end coordinate of region on reference.
pub fn fetch(&mut self, rid: u32, start: u64, end: u64) -> Result<()> {
let contig = {
let contig = self.header(0).rid2name(rid).unwrap(); //.clone();
ffi::CString::new(contig).unwrap()
};
if unsafe { htslib::bcf_sr_seek(self.inner, contig.as_ptr(), start as i64) } != 0 {
Err(Error::Seek {
contig: contig.to_str().unwrap().to_owned(),
start,
})
} else {
self.current_region = Some((rid, start, end));
Ok(())
}
}
}
impl Drop for SyncedReader {
fn drop(&mut self) {
unsafe { crate::htslib::bcf_sr_destroy(self.inner) };
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum Format {
VCF,
BCF,
}
/// A VCF/BCF writer.
#[derive(Debug)]
pub struct Writer {
inner: *mut htslib::htsFile,
header: Rc<HeaderView>,
subset: Option<SampleSubset>,
}
unsafe impl Send for Writer {}
impl Writer {
/// Create a new writer that writes to the given path.
///
/// # Arguments
///
/// * `path` - the path
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_path<P: AsRef<Path>>(
path: P,
header: &Header,
uncompressed: bool,
format: Format,
) -> Result<Self> {
if let Some(p) = path.as_ref().to_str() {
Ok(Self::new(p.as_bytes(), header, uncompressed, format)?)
} else {
Err(errors::Error::NonUnicodePath)
}
}
/// Create a new writer from a URL.
///
/// # Arguments
///
/// * `url` - the URL
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_url(
url: &Url,
header: &Header,
uncompressed: bool,
format: Format,
) -> Result<Self> {
Self::new(url.as_str().as_bytes(), header, uncompressed, format)
}
/// Create a new writer to stdout.
///
/// # Arguments
///
/// * `header` - header definition to use
/// * `uncompressed` - disable compression
/// * `vcf` - write VCF instead of BCF
pub fn from_stdout(header: &Header, uncompressed: bool, format: Format) -> Result<Self> {
Self::new(b"-", header, uncompressed, format)
}
fn new(path: &[u8], header: &Header, uncompressed: bool, format: Format) -> Result<Self> {
let mode: &[u8] = match (uncompressed, format) {
(true, Format::VCF) => b"w",
(false, Format::VCF) => b"wz",
(true, Format::BCF) => b"wbu",
(false, Format::BCF) => b"wb",
};
let htsfile = bcf_open(path, mode)?;
unsafe { htslib::bcf_hdr_write(htsfile, header.inner) };
Ok(Writer {
inner: htsfile,
header: Rc::new(HeaderView::new(unsafe {
htslib::bcf_hdr_dup(header.inner)
})),
subset: header.subset.clone(),
})
}
/// Obtain reference to the lightweight `HeaderView` of the BCF header.
pub fn header(&self) -> &HeaderView {
&self.header
}
/// Create empty record for writing to this writer.
///
/// This record can then be reused multiple times.
pub fn empty_record(&self) -> Record {
record::Record::new(Rc::clone(&self.header))
}
/// Translate record to header of this writer.
///
/// # Arguments
///
/// - `record` - The `Record` to translate.
pub fn translate(&mut self, record: &mut record::Record) {
unsafe {
htslib::bcf_translate(self.header.inner, record.header().inner, record.inner);
}
record.set_header(Rc::clone(&self.header));
}
/// Subset samples of record to match header of this writer.
///
/// # Arguments
///
/// - `record` - The `Record` to modify.
pub fn subset(&mut self, record: &mut record::Record) {
if let Some(ref mut subset) = self.subset {
unsafe {
htslib::bcf_subset(
self.header.inner,
record.inner,
subset.len() as i32,
subset.as_mut_ptr(),
);
}
}
}
/// Write `record` to the Writer.
///
/// # Arguments
///
/// - `record` - The `Record` to write.
pub fn write(&mut self, record: &record::Record) -> Result<()> {
if unsafe { htslib::bcf_write(self.inner, self.header.inner, record.inner) } == -1 {
Err(Error::Write)
} else {
Ok(())
}
}
/// Activate multi-threaded BCF write support in htslib. This should permit faster
/// writing of large BCF files.
///
/// # Arguments
///
/// * `n_threads` - number of extra background writer threads to use, must be `> 0`.
pub fn set_threads(&mut self, n_threads: usize) -> Result<()> {
unsafe { set_threads(self.inner, n_threads) }
}
}
impl Drop for Writer {
fn drop(&mut self) {
unsafe {
htslib::hts_close(self.inner);
}
}
}
#[derive(Debug)]
pub struct Records<'a, R: Read> {
reader: &'a mut R,
}
impl<'a, R: Read> Iterator for Records<'a, R> {
type Item = Result<record::Record>;
fn next(&mut self) -> Option<Result<record::Record>> {
let mut record = self.reader.empty_record();
match self.reader.read(&mut record) {
Err(e) => Some(Err(e)),
Ok(true) => Some(Ok(record)),
Ok(false) => None,
}
}
}
/// Wrapper for opening a BCF file.
fn bcf_open(target: &[u8], mode: &[u8]) -> Result<*mut htslib::htsFile> {
let p = ffi::CString::new(target).unwrap();
let c_str = ffi::CString::new(mode).unwrap();
let ret = unsafe { htslib::hts_open(p.as_ptr(), c_str.as_ptr()) };
if ret.is_null() {
return Err(errors::Error::Open {
target: str::from_utf8(target).unwrap().to_owned(),
});
}
unsafe {
if !(mode.contains(&b'w')
|| (*ret).format.category == htslib::htsFormatCategory_variant_data)
{
return Err(errors::Error::Open {
target: str::from_utf8(target).unwrap().to_owned(),
});
}
}
Ok(ret)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bcf::header::Id;
use crate::bcf::record::Numeric;
use std::fs::File;
use std::io::prelude::Read as IoRead;
use std::path::Path;
use std::str;
fn _test_read<P: AsRef<Path>>(path: &P) {
let mut bcf = Reader::from_path(path).expect("Error opening file.");
assert_eq!(bcf.header.samples(), [b"NA12878.subsample-0.25-0"]);
for (i, rec) in bcf.records().enumerate() {
let mut record = rec.expect("Error reading record.");
assert_eq!(record.sample_count(), 1);
assert_eq!(record.rid().expect("Error reading rid."), 0);
assert_eq!(record.pos(), 10021 + i as i64);
assert!((record.qual() - 0f32).abs() < std::f32::EPSILON);
assert!(
(record
.info(b"MQ0F")
.float()
.expect("Error reading info.")
.expect("Missing tag")[0]
- 1.0)
.abs()
< std::f32::EPSILON
);
if i == 59 {
assert!(
(record
.info(b"SGB")
.float()
.expect("Error reading info.")
.expect("Missing tag")[0]
- -0.379885)
.abs()
< std::f32::EPSILON
);
}
// the artificial "not observed" allele is present in each record.
assert_eq!(record.alleles().iter().last().unwrap(), b"<X>");
let mut fmt = record.format(b"PL");
let pl = fmt.integer().expect("Error reading format.");
assert_eq!(pl.len(), 1);
if i == 59 {
assert_eq!(pl[0].len(), 6);
} else {
assert_eq!(pl[0].len(), 3);
}
}
}
#[test]
fn test_read() {
_test_read(&"test/test.bcf");
}
#[test]
fn test_reader_set_threads() {
let path = &"test/test.bcf";
let mut bcf = Reader::from_path(path).expect("Error opening file.");
bcf.set_threads(2).unwrap();
}
#[test]
fn test_writer_set_threads() {
let path = &"test/test.bcf";
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let bcfpath = tmp.path().join("test.bcf");
let bcf = Reader::from_path(path).expect("Error opening file.");
let header = Header::from_template_subset(&bcf.header, &[b"NA12878.subsample-0.25-0"])
.expect("Error subsetting samples.");
let mut writer =
Writer::from_path(&bcfpath, &header, false, Format::BCF).expect("Error opening file.");
writer.set_threads(2).unwrap();
}
#[test]
fn test_fetch() {
let mut bcf = IndexedReader::from_path(&"test/test.bcf").expect("Error opening file.");
bcf.set_threads(2).unwrap();
let rid = bcf
.header()
.name2rid(b"1")
.expect("Translating from contig '1' to ID failed.");
bcf.fetch(rid, 10_033, 10_060).expect("Fetching failed");
assert_eq!(bcf.records().count(), 28);
}
#[test]
fn test_write() {
let mut bcf = Reader::from_path(&"test/test_multi.bcf").expect("Error opening file.");
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let bcfpath = tmp.path().join("test.bcf");
println!("{:?}", bcfpath);
{
let header = Header::from_template_subset(&bcf.header, &[b"NA12878.subsample-0.25-0"])
.expect("Error subsetting samples.");
let mut writer = Writer::from_path(&bcfpath, &header, false, Format::BCF)
.expect("Error opening file.");
for rec in bcf.records() {
let mut record = rec.expect("Error reading record.");
writer.translate(&mut record);
writer.subset(&mut record);
record.trim_alleles().expect("Error trimming alleles.");
writer.write(&record).expect("Error writing record");
}
}
{
_test_read(&bcfpath);
}
tmp.close().expect("Failed to delete temp dir");
}
#[test]
fn test_strings() {
let mut vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let fs1 = [
&b"LongString1"[..],
&b"LongString2"[..],
&b"."[..],
&b"LongString4"[..],
&b"evenlength"[..],
&b"ss6"[..],
];
for (i, rec) in vcf.records().enumerate() {
println!("record {}", i);
let mut record = rec.expect("Error reading record.");
assert_eq!(
record
.info(b"S1")
.string()
.expect("Error reading string.")
.expect("Missing tag")[0],
format!("string{}", i + 1).as_bytes()
);
println!(
"{}",
String::from_utf8_lossy(
record
.format(b"FS1")
.string()
.expect("Error reading string.")[0]
)
);
assert_eq!(
record
.format(b"FS1")
.string()
.expect("Error reading string.")[0],
fs1[i]
);
}
}
#[test]
fn test_missing() {
let mut vcf = Reader::from_path(&"test/test_missing.vcf").expect("Error opening file.");
let fn4 = [
&[
i32::missing(),
i32::missing(),
i32::missing(),
i32::missing(),
][..],
&[i32::missing()][..],
];
let f1 = [false, true];
for (i, rec) in vcf.records().enumerate() {
let mut record = rec.expect("Error reading record.");
assert_eq!(
record
.info(b"F1")
.float()
.expect("Error reading float.")
.expect("Missing tag")[0]
.is_nan(),
f1[i]
);
assert_eq!(
record
.format(b"FN4")
.integer()
.expect("Error reading integer.")[1],
fn4[i]
);
assert!(
record.format(b"FF4").float().expect("Error reading float.")[1]
.iter()
.all(|&v| v.is_missing())
);
}
}
#[test]
fn test_genotypes() {
let mut vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let expected = ["./1", "1|1", "0/1", "0|1", "1|.", "1/1"];
for (rec, exp_gt) in vcf.records().zip(expected.iter()) {
let mut rec = rec.expect("Error reading record.");
let genotypes = rec.genotypes().expect("Error reading genotypes");
assert_eq!(&format!("{}", genotypes.get(0)), exp_gt);
}
}
#[test]
fn test_header_ids() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let header = &vcf.header();
use crate::bcf::header::Id;
assert_eq!(header.id_to_name(Id(4)), b"GT");
assert_eq!(header.name_to_id(b"GT").unwrap(), Id(4));
assert!(header.name_to_id(b"XX").is_err());
}
#[test]
fn test_header_samples() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let header = &vcf.header();
assert_eq!(header.id_to_sample(Id(0)), b"one");
assert_eq!(header.id_to_sample(Id(1)), b"two");
assert_eq!(header.sample_to_id(b"one").unwrap(), Id(0));
assert_eq!(header.sample_to_id(b"two").unwrap(), Id(1));
assert!(header.sample_to_id(b"three").is_err());
}
#[test]
fn test_header_contigs() {
let vcf = Reader::from_path(&"test/test_multi.bcf").expect("Error opening file.");
let header = &vcf.header();
assert_eq!(header.contig_count(), 86);
// test existing contig names and IDs
assert_eq!(header.rid2name(0).unwrap(), b"1");
assert_eq!(header.name2rid(b"1").unwrap(), 0);
assert_eq!(header.rid2name(85).unwrap(), b"hs37d5");
assert_eq!(header.name2rid(b"hs37d5").unwrap(), 85);
// test nonexistent contig names and IDs
assert!(header.name2rid(b"nonexistent_contig").is_err());
assert!(header.rid2name(100).is_err());
}
#[test]
fn test_header_records() {
let vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
let records = vcf.header().header_records();
assert_eq!(records.len(), 10);
match records[1] {
HeaderRecord::Filter {
ref key,
ref values,
} => {
assert_eq!(key, "FILTER");
assert_eq!(values["ID"], "PASS");
}
_ => {
panic!("Invalid HeaderRecord");
}
}
}
#[test]
fn test_header_info_types() {
let vcf = Reader::from_path(&"test/test.bcf").unwrap();
let header = vcf.header();
let truth = vec![
(
// INFO=<ID=INDEL,Number=0,Type=Flag>
"INDEL",
header::TagType::Flag,
header::TagLength::Fixed(0),
),
(
// INFO=<ID=DP,Number=1,Type=Integer>
"DP",
header::TagType::Integer,
header::TagLength::Fixed(1),
),
(
// INFO=<ID=QS,Number=R,Type=Float>
"QS",
header::TagType::Float,
header::TagLength::Alleles,
),
(
// INFO=<ID=I16,Number=16,Type=Float>
"I16",
header::TagType::Float,
header::TagLength::Fixed(16),
),
];
for (ref_name, ref_type, ref_length) in truth {
let (tag_type, tag_length) = header.info_type(ref_name.as_bytes()).unwrap();
assert_eq!(tag_type, ref_type);
assert_eq!(tag_length, ref_length);
}
let vcf = Reader::from_path(&"test/test_svlen.vcf").unwrap();
let header = vcf.header();
let truth = vec![
(
// INFO=<ID=IMPRECISE,Number=0,Type=Flag>
"IMPRECISE",
header::TagType::Flag,
header::TagLength::Fixed(0),
),
(
// INFO=<ID=SVTYPE,Number=1,Type=String>
"SVTYPE",
header::TagType::String,
header::TagLength::Fixed(1),
),
(
// INFO=<ID=SVLEN,Number=.,Type=Integer>
"SVLEN",
header::TagType::Integer,
header::TagLength::Variable,
),
(
// INFO<ID=CIGAR,Number=A,Type=String>
"CIGAR",
header::TagType::String,
header::TagLength::AltAlleles,
),
];
for (ref_name, ref_type, ref_length) in truth {
let (tag_type, tag_length) = header.info_type(ref_name.as_bytes()).unwrap();
assert_eq!(tag_type, ref_type);
assert_eq!(tag_length, ref_length);
}
assert!(header.info_type(b"NOT_THERE").is_err());
}
#[test]
fn test_remove_alleles() {
let mut bcf = Reader::from_path(&"test/test_multi.bcf").unwrap();
for res in bcf.records() {
let mut record = res.unwrap();
if record.pos() == 10080 {
record.remove_alleles(&[false, false, true]).unwrap();
assert_eq!(record.alleles(), [b"A", b"C"]);
}
}
}
// Helper function reading full file into string.
fn read_all<P: AsRef<Path>>(path: P) -> String {
let mut file = File::open(path.as_ref())
.unwrap_or_else(|_| panic!("Unable to open the file: {:?}", path.as_ref()));
let mut contents = String::new();
file.read_to_string(&mut contents)
.unwrap_or_else(|_| panic!("Unable to read the file: {:?}", path.as_ref()));
contents
}
// Open `test_various.vcf`, add a record from scratch to it and write it out again.
//
// This exercises the full functionality of updating information in a `record::Record`.
#[test]
fn test_write_various() {
// Open reader, then create writer.
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let out_path = tmp.path().join("test_various.out.vcf");
let vcf = Reader::from_path(&"test/test_various.vcf").expect("Error opening file.");
// The writer goes into its own block so we can ensure that the file is closed and
// all data is written below.
{
let mut writer = Writer::from_path(
&out_path,
&Header::from_template(&vcf.header()),
true,
Format::VCF,
)
.expect("Error opening file.");
let header = writer.header().clone();
// Setup empty record, filled below.
let mut record = writer.empty_record();
record.set_rid(Some(0));
assert_eq!(record.rid().unwrap(), 0);
record.set_pos(12);
assert_eq!(record.pos(), 12);
assert_eq!(str::from_utf8(record.id().as_ref()).unwrap(), ".");
record.set_id(b"to_be_cleared").unwrap();
assert_eq!(
str::from_utf8(record.id().as_ref()).unwrap(),
"to_be_cleared"
);
record.clear_id().unwrap();
assert_eq!(str::from_utf8(record.id().as_ref()).unwrap(), ".");
record.set_id(b"first_id").unwrap();
record.push_id(b"second_id").unwrap();
record.push_id(b"first_id").unwrap();
assert!(record.filters().next().is_none());
record.set_filters(&[header.name_to_id(b"q10").unwrap()]);
record.push_filter(header.name_to_id(b"s50").unwrap());
record.remove_filter(header.name_to_id(b"q10").unwrap(), true);
record.push_filter(header.name_to_id(b"q10").unwrap());
record.set_alleles(&[b"C", b"T", b"G"]).unwrap();
record.set_qual(10.0);
record.push_info_integer(b"N1", &[32]).unwrap();
record.push_info_float(b"F1", &[33.0]).unwrap();
record.push_info_string(b"S1", &[b"fourtytwo"]).unwrap();
record.push_info_flag(b"X1").unwrap();
record
.push_format_string(b"FS1", &[&b"yes"[..], &b"no"[..]])
.unwrap();
record.push_format_integer(b"FF1", &[43, 11]).unwrap();
record.push_format_float(b"FN1", &[42.0, 10.0]).unwrap();
record
.push_format_char(b"CH1", &[b"A"[0], b"B"[0]])
.unwrap();
// Finally, write out the record.
writer.write(&record).unwrap();
}
// Now, compare expected and real output.
let expected = read_all("test/test_various.out.vcf");
let actual = read_all(&out_path);
assert_eq!(expected, actual);
}
#[test]
fn test_remove_headers() {
let vcf = Reader::from_path(&"test/test_headers.vcf").expect("Error opening file.");
let tmp = tempdir::TempDir::new("rust-htslib").expect("Cannot create temp dir");
let vcfpath = tmp.path().join("test.vcf");
let mut header = Header::from_template(&vcf.header);
header
.remove_contig(b"contig2")
.remove_info(b"INFO2")
.remove_format(b"FORMAT2")
.remove_filter(b"FILTER2")
.remove_structured(b"Foo2")
.remove_generic(b"Bar2");
{
let mut _writer = Writer::from_path(&vcfpath, &header, true, Format::VCF)
.expect("Error opening output file.");
// Note that we don't need to write anything, we are just looking at the header.
}
let expected = read_all("test/test_headers.out.vcf");
let actual = read_all(&vcfpath);
assert_eq!(expected, actual);
}
#[test]
fn test_synced_reader() {
let mut reader = synced::SyncedReader::new().unwrap();
reader.set_require_index(true);
reader.set_pairing(synced::pairing::SNPS);
assert_eq!(reader.reader_count(), 0);
reader.add_reader(&"test/test_left.vcf.gz").unwrap();
reader.add_reader(&"test/test_right.vcf.gz").unwrap();
assert_eq!(reader.reader_count(), 2);
let res1 = reader.read_next();
assert_eq!(res1.unwrap(), 2);
assert!(reader.has_line(0));
assert!(reader.has_line(1));
let res2 = reader.read_next();
assert_eq!(res2.unwrap(), 1);
assert!(reader.has_line(0));
assert!(!reader.has_line(1));
let res3 = reader.read_next();
assert_eq!(res3.unwrap(), 1);
assert!(!reader.has_line(0));
assert!(reader.has_line(1));
let res4 = reader.read_next();
assert_eq!(res4.unwrap(), 0);
}
#[test]
fn test_synced_reader_fetch() {
let mut reader = synced::SyncedReader::new().unwrap();
reader.set_require_index(true);
reader.set_pairing(synced::pairing::SNPS);
assert_eq!(reader.reader_count(), 0);
reader.add_reader(&"test/test_left.vcf.gz").unwrap();
reader.add_reader(&"test/test_right.vcf.gz").unwrap();
assert_eq!(reader.reader_count(), 2);
reader.fetch(0, 0, 1000).unwrap();
let res1 = reader.read_next();
assert_eq!(res1.unwrap(), 2);
assert!(reader.has_line(0));
assert!(reader.has_line(1));
let res2 = reader.read_next();
assert_eq!(res2.unwrap(), 1);
assert!(reader.has_line(0));
assert!(!reader.has_line(1));
let res3 = reader.read_next();
assert_eq!(res3.unwrap(), 1);
assert!(!reader.has_line(0));
assert!(reader.has_line(1));
let res4 = reader.read_next();
assert_eq!(res4.unwrap(), 0);
}
#[test]
fn test_svlen() {
let mut reader = Reader::from_path("test/test_svlen.vcf").unwrap();
let mut record = reader.empty_record();
reader.read(&mut record).unwrap();
assert_eq!(record.info(b"SVLEN").integer().unwrap(), Some(&[-127][..]));
}
#[test]
fn test_fails_on_bam() {
let reader = Reader::from_path("test/test.bam");
assert!(reader.is_err());
}
#[test]
fn test_fails_on_non_existiant() {
let reader = Reader::from_path("test/no_such_file");
assert!(reader.is_err());
}
#[test]
fn test_multi_string_info_tag() {
let mut reader = Reader::from_path("test/test-info-multi-string.vcf").unwrap();
let mut rec = reader.empty_record();
let _ = reader.read(&mut rec);
assert_eq!(rec.info(b"ANN").string().unwrap().unwrap().len(), 14);
}
#[test]
fn test_multi_string_info_tag_number_a() {
let mut reader = Reader::from_path("test/test-info-multi-string-number=A.vcf").unwrap();
let mut rec = reader.empty_record();
let _ = reader.read(&mut rec);
assert_eq!(rec.info(b"X").string().unwrap().unwrap().len(), 2);
}
}
|
use std::ffi::OsStr;
use std::fmt::Display;
use std::io::BufRead;
use clap::{self, Arg, SubCommand};
use shlex;
use config::{self, Config};
use errors::Result;
use repository::{self, Repository};
use vcs;
pub struct App {
config: Config,
}
impl App {
/// Creates a new instance of rhq application.
pub fn new() -> Result<App> {
let config = config::read_all_config()?;
Ok(App { config: config })
}
pub fn clone_from_queries<Q, R, S>(&self, queries: R, args: Vec<S>, dry_run: bool) -> Result<()>
where Q: AsRef<str>,
R: Iterator<Item = Q>,
S: AsRef<OsStr> + Display
{
for query in queries {
let query = query.as_ref().parse()?;
vcs::clone_from_query(query, &self.config.root, &args, dry_run)?;
}
Ok(())
}
pub fn iter_repos<F>(&self, func: F) -> Result<()>
where F: Fn(&Repository) -> Result<()>
{
for root in self.config.roots() {
for ref repo in repository::collect_from(root) {
func(repo)?;
}
}
Ok(())
}
/// Returns the reference of configuration.
pub fn command_config(&self) -> Result<()> {
println!("{}", self.config);
Ok(())
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn build_cli() -> clap::App<'static, 'static> {
cli_template()
.subcommand(SubCommand::with_name("clone")
.about("Clone remote repositories into the root directory")
.arg(Arg::from_usage("[query] 'URL or query of remote repository'"))
.arg(Arg::from_usage("--arg=[arg] 'Supplemental arguments for Git command'"))
.arg(Arg::from_usage("-n, --dry-run 'Do not actually execute Git command'")))
.subcommand(SubCommand::with_name("list")
.about("List local repositories managed by rhq"))
.subcommand(SubCommand::with_name("foreach")
.about("Execute command into each repositories")
.arg(Arg::from_usage("<command> 'Command name'"))
.arg(Arg::from_usage("[args]... 'Arguments of command'"))
.arg(Arg::from_usage("-n, --dry-run 'Do not actually execute command'")))
.subcommand(SubCommand::with_name("config")
.about("Show current configuration"))
}
pub fn run() -> Result<()> {
let matches = get_matches(build_cli())?;
let app = App::new()?;
match matches.subcommand() {
("clone", Some(m)) => {
let args = m.value_of("arg").and_then(|s| shlex::split(s)).unwrap_or_default();
let dry_run = m.is_present("dry-run");
if let Some(query) = m.value_of("query") {
app.clone_from_queries(vec![query].into_iter(), args, dry_run)?;
} else {
let stdin = ::std::io::stdin();
app.clone_from_queries(stdin.lock().lines().filter_map(|l| l.ok()), args, dry_run)?;
}
Ok(())
}
("list", _) => {
app.iter_repos(|ref repo| {
println!("{}", repo.path_string());
Ok(())
})
}
("foreach", Some(m)) => {
let command = m.value_of("command").unwrap();
let args: Vec<_> = m.values_of("args").map(|s| s.collect()).unwrap_or_default();
let dry_run = m.is_present("dry-run");
app.iter_repos(|repo| if repo.run_command(command, &args, dry_run)? {
Ok(())
} else {
Err("failed to execute command".to_owned().into())
})
}
("config", _) => app.command_config(),
_ => unreachable!(),
}
}
fn cli_template<'a, 'b>() -> clap::App<'a, 'b> {
app_from_crate!()
.setting(clap::AppSettings::VersionlessSubcommands)
.setting(clap::AppSettings::SubcommandRequiredElseHelp)
.subcommand(clap::SubCommand::with_name("completion")
.about("Generate completion scripts for your shell")
.setting(clap::AppSettings::ArgRequiredElseHelp)
.arg(clap::Arg::with_name("shell")
.help("target shell")
.possible_values(&["bash", "zsh", "fish", "powershell"])
.required(true))
.arg(Arg::from_usage("[out-file] 'path to output script'")))
}
fn get_matches<'a, 'b>(mut cli: clap::App<'a, 'b>) -> ::std::io::Result<clap::ArgMatches<'a>> {
let matches = cli.clone().get_matches();
if let ("completion", Some(m)) = matches.subcommand() {
let shell = m.value_of("shell")
.and_then(|s| s.parse().ok())
.expect("failed to parse target shell");
if let Some(path) = m.value_of("out-file") {
let mut file =
::std::fs::OpenOptions::new().write(true).create(true).append(false).open(path)?;
cli.gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut file);
} else {
cli.gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut ::std::io::stdout());
}
::std::process::exit(0);
}
Ok(matches)
}
clone: add option "--root", for setting root directory explicitly
use std::ffi::OsStr;
use std::fmt::Display;
use std::io::BufRead;
use std::path::PathBuf;
use clap::{self, Arg, SubCommand};
use shlex;
use config::{self, Config};
use errors::Result;
use repository::{self, Repository};
use vcs;
pub struct App {
config: Config,
}
impl App {
/// Creates a new instance of rhq application.
pub fn new() -> Result<App> {
let config = config::read_all_config()?;
Ok(App { config: config })
}
pub fn clone_from_queries<Q, R, S>(&self,
queries: R,
args: Vec<S>,
dry_run: bool,
root: Option<&str>)
-> Result<()>
where Q: AsRef<str>,
R: Iterator<Item = Q>,
S: AsRef<OsStr> + Display
{
let root = root.map(|s| PathBuf::from(s));
let root = root.as_ref().unwrap_or(&self.config.root);
for query in queries {
let query = query.as_ref().parse()?;
vcs::clone_from_query(query, root, &args, dry_run)?;
}
Ok(())
}
pub fn iter_repos<F>(&self, func: F) -> Result<()>
where F: Fn(&Repository) -> Result<()>
{
for root in self.config.roots() {
for ref repo in repository::collect_from(root) {
func(repo)?;
}
}
Ok(())
}
/// Returns the reference of configuration.
pub fn command_config(&self) -> Result<()> {
println!("{}", self.config);
Ok(())
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn build_cli() -> clap::App<'static, 'static> {
cli_template()
.subcommand(SubCommand::with_name("clone")
.about("Clone remote repositories into the root directory")
.arg(Arg::from_usage("[query] 'URL or query of remote repository'"))
.arg(Arg::from_usage("--root=[root] 'Root directory of cloned repository'"))
.arg(Arg::from_usage("--arg=[arg] 'Supplemental arguments for Git command'"))
.arg(Arg::from_usage("-n, --dry-run 'Do not actually execute Git command'")))
.subcommand(SubCommand::with_name("list")
.about("List local repositories managed by rhq"))
.subcommand(SubCommand::with_name("foreach")
.about("Execute command into each repositories")
.arg(Arg::from_usage("<command> 'Command name'"))
.arg(Arg::from_usage("[args]... 'Arguments of command'"))
.arg(Arg::from_usage("-n, --dry-run 'Do not actually execute command'")))
.subcommand(SubCommand::with_name("config")
.about("Show current configuration"))
}
pub fn run() -> Result<()> {
let matches = get_matches(build_cli())?;
let app = App::new()?;
match matches.subcommand() {
("clone", Some(m)) => {
let args = m.value_of("arg").and_then(|s| shlex::split(s)).unwrap_or_default();
let root = m.value_of("root");
let dry_run = m.is_present("dry-run");
if let Some(query) = m.value_of("query") {
app.clone_from_queries(vec![query].into_iter(), args, dry_run, root)?;
} else {
let stdin = ::std::io::stdin();
app.clone_from_queries(stdin.lock().lines().filter_map(|l| l.ok()),
args,
dry_run,
root)?;
}
Ok(())
}
("list", _) => {
app.iter_repos(|ref repo| {
println!("{}", repo.path_string());
Ok(())
})
}
("foreach", Some(m)) => {
let command = m.value_of("command").unwrap();
let args: Vec<_> = m.values_of("args").map(|s| s.collect()).unwrap_or_default();
let dry_run = m.is_present("dry-run");
app.iter_repos(|repo| if repo.run_command(command, &args, dry_run)? {
Ok(())
} else {
Err("failed to execute command".to_owned().into())
})
}
("config", _) => app.command_config(),
_ => unreachable!(),
}
}
fn cli_template<'a, 'b>() -> clap::App<'a, 'b> {
app_from_crate!()
.setting(clap::AppSettings::VersionlessSubcommands)
.setting(clap::AppSettings::SubcommandRequiredElseHelp)
.subcommand(clap::SubCommand::with_name("completion")
.about("Generate completion scripts for your shell")
.setting(clap::AppSettings::ArgRequiredElseHelp)
.arg(clap::Arg::with_name("shell")
.help("target shell")
.possible_values(&["bash", "zsh", "fish", "powershell"])
.required(true))
.arg(Arg::from_usage("[out-file] 'path to output script'")))
}
fn get_matches<'a, 'b>(mut cli: clap::App<'a, 'b>) -> ::std::io::Result<clap::ArgMatches<'a>> {
let matches = cli.clone().get_matches();
if let ("completion", Some(m)) = matches.subcommand() {
let shell = m.value_of("shell")
.and_then(|s| s.parse().ok())
.expect("failed to parse target shell");
if let Some(path) = m.value_of("out-file") {
let mut file =
::std::fs::OpenOptions::new().write(true).create(true).append(false).open(path)?;
cli.gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut file);
} else {
cli.gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut ::std::io::stdout());
}
::std::process::exit(0);
}
Ok(matches)
}
|
use quickcheck::{Arbitrary, Gen};
use rand::{
distributions::{weighted::WeightedIndex, Distribution},
Rng,
};
use crate::MultihashGeneric;
/// Generates a random valid multihash.
impl Arbitrary for MultihashGeneric<64> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
// In real world lower multihash codes are more likely to happen, hence distribute them
// with bias towards smaller values.
let weights = [128, 64, 32, 16, 8, 4, 2, 1];
let dist = WeightedIndex::new(weights.iter()).unwrap();
let code = match dist.sample(g) {
0 => g.gen_range(0, u64::pow(2, 7)),
1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)),
2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)),
3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)),
4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)),
5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)),
6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)),
7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)),
_ => unreachable!(),
};
// Maximum size is 64 byte due to the `U64` generic
let size = g.gen_range(0, 64);
let mut data = [0; 64];
g.fill_bytes(&mut data);
MultihashGeneric::wrap(code, &data[..size]).unwrap()
}
}
make arbitrary generic over size
use quickcheck::{Arbitrary, Gen};
use rand::{
distributions::{weighted::WeightedIndex, Distribution},
Rng,
};
use crate::MultihashGeneric;
/// Generates a random valid multihash.
impl<const S: usize> Arbitrary for MultihashGeneric<S> {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
// In real world lower multihash codes are more likely to happen, hence distribute them
// with bias towards smaller values.
let weights = [128, 64, 32, 16, 8, 4, 2, 1];
let dist = WeightedIndex::new(weights.iter()).unwrap();
let code = match dist.sample(g) {
0 => g.gen_range(0, u64::pow(2, 7)),
1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)),
2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)),
3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)),
4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)),
5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)),
6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)),
7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)),
_ => unreachable!(),
};
// Maximum size is S byte due to the generic.
let size = g.gen_range(0, S);
let mut data = [0; S];
g.fill_bytes(&mut data);
MultihashGeneric::wrap(code, &data[..size]).unwrap()
}
}
|
use core::intrinsics;
#[cfg(feature = "mem")]
use mem::{memcpy, memmove, memset};
// NOTE This function and the ones below are implemented using assembly because they using a custom
// calling convention which can't be implemented using a normal Rust function
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_uidivmod() {
asm!("push {lr}
sub sp, sp, #4
mov r2, sp
bl __udivmodsi4
ldr r1, [sp]
add sp, sp, #4
pop {pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_uldivmod() {
asm!("push {r4, lr}
sub sp, sp, #16
add r4, sp, #8
str r4, [sp]
bl __udivmoddi4
ldr r2, [sp, #8]
ldr r3, [sp, #12]
add sp, sp, #16
pop {r4, pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_idivmod() {
asm!("push {r0, r1, r4, lr}
bl __divsi3
pop {r1, r2}
muls r2, r2, r0
subs r1, r1, r2
pop {r4, pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_ldivmod() {
asm!("push {r4, lr}
sub sp, sp, #16
add r4, sp, #8
str r4, [sp]
bl __divmoddi4
ldr r2, [sp, #8]
ldr r3, [sp, #12]
add sp, sp, #16
pop {r4, pc}");
intrinsics::unreachable();
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_dadd(a: f64, b: f64) -> f64 {
::float::add::__adddf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_fadd(a: f32, b: f32) -> f32 {
::float::add::__addsf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_dsub(a: f64, b: f64) -> f64 {
::float::sub::__subdf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_fsub(a: f32, b: f32) -> f32 {
::float::sub::__subsf3(a, b)
}
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_idiv(a: i32, b: i32) -> i32 {
::int::sdiv::__divsi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_lasr(a: i64, b: u32) -> i64 {
::int::shift::__ashrdi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_llsl(a: u64, b: u32) -> u64 {
::int::shift::__ashldi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_llsr(a: u64, b: u32) -> u64 {
::int::shift::__lshrdi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_lmul(a: u64, b: u64) -> u64 {
::int::mul::__muldi3(a, b)
}
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_uidiv(a: u32, b: u32) -> u32 {
::int::udiv::__udivsi3(a, b)
}
#[cfg(not(feature = "c"))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __aeabi_ui2d(a: u32) -> f64 {
::float::conv::__floatunsidf(a)
}
// TODO: These aeabi_* functions should be defined as aliases
#[cfg(not(feature = "mem"))]
extern "C" {
fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
fn memmove(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
fn memset(dest: *mut u8, c: i32, n: usize) -> *mut u8;
}
// FIXME: The `*4` and `*8` variants should be defined as aliases.
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy4(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy8(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove4(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove8(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
// Note the different argument order
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset4(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset8(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr4(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr8(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
#[cfg(test)]
mod tests {
use quickcheck::TestResult;
use qc::{U32, U64};
quickcheck!{
fn uldivmod(n: U64, d: U64) -> TestResult {
let (n, d) = (n.0, d.0);
if d == 0 {
TestResult::discard()
} else {
let q: u64;
let r: u64;
unsafe {
// The inline asm is a bit tricky here, LLVM will allocate
// both r0 and r1 when we specify a 64-bit value for {r0}.
asm!("bl __aeabi_uldivmod"
: "={r0}" (q), "={r2}" (r)
: "{r0}" (n), "{r2}" (d)
: "r12", "lr", "flags");
}
TestResult::from_bool(q == n / d && r == n % d)
}
}
fn uidivmod(n: U32, d: U32) -> TestResult {
let (n, d) = (n.0, d.0);
if d == 0 {
TestResult::discard()
} else {
let q: u32;
let r: u32;
unsafe {
asm!("bl __aeabi_uidivmod"
: "={r0}" (q), "={r1}" (r)
: "{r0}" (n), "{r1}" (d)
: "r2", "r3", "r12", "lr", "flags");
}
TestResult::from_bool(q == n / d && r == n % d)
}
}
fn ldivmod(n: U64, d: U64) -> TestResult {
let (n, d) = (n.0 as i64, d.0 as i64);
if d == 0 {
TestResult::discard()
} else {
let q: i64;
let r: i64;
unsafe {
// The inline asm is a bit tricky here, LLVM will allocate
// both r0 and r1 when we specify a 64-bit value for {r0}.
asm!("bl __aeabi_ldivmod"
: "={r0}" (q), "={r2}" (r)
: "{r0}" (n), "{r2}" (d)
: "r12", "lr", "flags");
}
TestResult::from_bool(q == n / d && r == n % d)
}
}
fn idivmod(n: U32, d: U32) -> TestResult {
let (n, d) = (n.0 as i32, d.0 as i32);
if d == 0 || (n == i32::min_value() && d == -1) {
TestResult::discard()
} else {
let q: i32;
let r: i32;
unsafe {
asm!("bl __aeabi_idivmod"
: "={r0}" (q), "={r1}" (r)
: "{r0}" (n), "{r1}" (d)
: "r2", "r3", "r12", "lr", "flags");
}
TestResult::from_bool(q == n / d && r == n % d)
}
}
}
}
remove arm tests from the old test suite
use core::intrinsics;
#[cfg(feature = "mem")]
use mem::{memcpy, memmove, memset};
// NOTE This function and the ones below are implemented using assembly because they using a custom
// calling convention which can't be implemented using a normal Rust function
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_uidivmod() {
asm!("push {lr}
sub sp, sp, #4
mov r2, sp
bl __udivmodsi4
ldr r1, [sp]
add sp, sp, #4
pop {pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_uldivmod() {
asm!("push {r4, lr}
sub sp, sp, #16
add r4, sp, #8
str r4, [sp]
bl __udivmoddi4
ldr r2, [sp, #8]
ldr r3, [sp, #12]
add sp, sp, #16
pop {r4, pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_idivmod() {
asm!("push {r0, r1, r4, lr}
bl __divsi3
pop {r1, r2}
muls r2, r2, r0
subs r1, r1, r2
pop {r4, pc}");
intrinsics::unreachable();
}
#[naked]
#[cfg_attr(not(test), no_mangle)]
pub unsafe fn __aeabi_ldivmod() {
asm!("push {r4, lr}
sub sp, sp, #16
add r4, sp, #8
str r4, [sp]
bl __divmoddi4
ldr r2, [sp, #8]
ldr r3, [sp, #12]
add sp, sp, #16
pop {r4, pc}");
intrinsics::unreachable();
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_dadd(a: f64, b: f64) -> f64 {
::float::add::__adddf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_fadd(a: f32, b: f32) -> f32 {
::float::add::__addsf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_dsub(a: f64, b: f64) -> f64 {
::float::sub::__subdf3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_fsub(a: f32, b: f32) -> f32 {
::float::sub::__subsf3(a, b)
}
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_idiv(a: i32, b: i32) -> i32 {
::int::sdiv::__divsi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_lasr(a: i64, b: u32) -> i64 {
::int::shift::__ashrdi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_llsl(a: u64, b: u32) -> u64 {
::int::shift::__ashldi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_llsr(a: u64, b: u32) -> u64 {
::int::shift::__lshrdi3(a, b)
}
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_lmul(a: u64, b: u64) -> u64 {
::int::mul::__muldi3(a, b)
}
#[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))]
#[cfg_attr(not(test), no_mangle)]
pub extern "aapcs" fn __aeabi_uidiv(a: u32, b: u32) -> u32 {
::int::udiv::__udivsi3(a, b)
}
#[cfg(not(feature = "c"))]
#[cfg_attr(not(test), no_mangle)]
pub extern "C" fn __aeabi_ui2d(a: u32) -> f64 {
::float::conv::__floatunsidf(a)
}
// TODO: These aeabi_* functions should be defined as aliases
#[cfg(not(feature = "mem"))]
extern "C" {
fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
fn memmove(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
fn memset(dest: *mut u8, c: i32, n: usize) -> *mut u8;
}
// FIXME: The `*4` and `*8` variants should be defined as aliases.
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy4(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memcpy8(dest: *mut u8, src: *const u8, n: usize) {
memcpy(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove4(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memmove8(dest: *mut u8, src: *const u8, n: usize) {
memmove(dest, src, n);
}
// Note the different argument order
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset4(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memset8(dest: *mut u8, n: usize, c: i32) {
memset(dest, c, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr4(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
#[cfg_attr(not(test), no_mangle)]
pub unsafe extern "aapcs" fn __aeabi_memclr8(dest: *mut u8, n: usize) {
memset(dest, 0, n);
}
|
//! Methods for reading tile and static data out of art.mul
//!
//! Tiles and Statics are both traditionally stored in art.mul/artidx.mul
use std::fs::{File};
use mul_reader::MulReader;
use std::io::{Result, Error, ErrorKind, Cursor, SeekFrom, Seek, Write, Read};
use color::{Color, Color16, Color32};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use utils::{MEMWRITER_ERROR, SURFACE_ERROR};
use std::path::Path;
#[cfg(feature = "use-sdl2")]
use sdl2::surface::Surface;
#[cfg(feature = "use-sdl2")]
use sdl2::pixels::PixelFormatEnum;
use image::{Rgba, RgbaImage};
pub trait Art {
/**
* Convert to a 32bit array
*
* Returns (width, height, colors)
*/
fn to_32bit(&self) -> (u32, u32, Vec<Color32>);
fn serialize(&self) -> Vec<u8>;
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface;
fn to_image(&self) -> RgbaImage;
}
pub const TILE_SIZE: u32 = 2048;
pub const STATIC_OFFSET: u32 = 0x4000;
pub struct RunPair {
pub offset: u16,
pub run: Vec<Color16>
}
impl RunPair {
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u16::<LittleEndian>(self.offset).expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.run.len() as u16).expect(MEMWRITER_ERROR);
for &color in self.run.iter() {
writer.write_u16::<LittleEndian>(color).expect(MEMWRITER_ERROR);
}
writer
}
}
pub type StaticRow = Vec<RunPair>;
/// A Map Tile, 44px by 44px
///
/// Map tiles are stored as
/// |Header:u32|Pixels:u16|
/// Where pixels represents a list of rows, length 2, 4, 6, 8 .. 42, 44, 44, 42 .. 8, 6, 4, 2 and are drawn
/// centred
pub struct Tile {
/// Header information for a tile. Unused
pub header: u32,
/// Individual pixels. These work as rows, of length 2, 4, 6, 8 .. 42, 44, 44, 42 .. 8, 6, 4, 2
pub image_data: [Color16; 1022]
}
impl Art for Tile {
fn to_32bit(&self) -> (u32, u32, Vec<Color32>) {
let mut image: Vec<Color32> = vec![];
let mut read_idx = 0;
for i in 0..44 {
let slice_size = if i >= 22 {
(44 - i) * 2
} else {
(i + 1) * 2
};
image.extend_from_slice(vec![0; (22 - (slice_size / 2))].as_slice());
for _pixel_idx in 0..slice_size {
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
image.push(Color::from_rgba(r, g, b, a));
read_idx += 1;
}
image.extend_from_slice(vec![0; (22 - (slice_size / 2))].as_slice());
};
(44, 44, image)
}
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u32::<LittleEndian>(self.header).ok().expect(MEMWRITER_ERROR);
for &pixel in self.image_data.iter() {
writer.write_u16::<LittleEndian>(pixel).ok().expect(MEMWRITER_ERROR);
}
writer
}
fn to_image(&self) -> RgbaImage {
let mut buffer = RgbaImage::new(44, 44);
let mut read_idx = 0;
for y in 0..44 {
let slice_size = if y >= 22 {
(44 - y) * 2
} else {
(y + 1) * 2
};
let indent = 22 - (slice_size / 2);
for x in 0..slice_size {
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
buffer.put_pixel(indent + x, y, Rgba([r, g, b, a]));
read_idx += 1;
}
};
buffer
}
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface {
let mut surface = Surface::new(44, 44, PixelFormatEnum::RGBA8888).expect(SURFACE_ERROR);
surface.with_lock_mut(|bitmap| {
let mut read_idx = 0;
for y in 0..44 {
let slice_width = if y >= 22 {
(44 - y) * 2
} else {
(y + 1) * 2
};
let offset_left = 22 - (slice_width / 2);
for pixel_idx in 0..slice_width {
let x = offset_left + pixel_idx;
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
let target = ((y * 44) + x) * 4;
bitmap[target] = a;
bitmap[target + 1] = b;
bitmap[target + 2] = g;
bitmap[target + 3] = r;
read_idx += 1;
}
};
});
surface
}
}
impl Art for Static {
fn to_32bit(&self) -> (u32, u32, Vec<Color32>) {
let mut image: Vec<Color32> = vec![];
for row in self.rows.iter() {
let mut current_width = 0;
for run_pair in row.iter() {
image.extend_from_slice(vec![0; run_pair.offset as usize].as_slice());
for pixel in run_pair.run.iter() {
let (r, g, b, a) = pixel.to_rgba();
image.push(Color::from_rgba(r, g, b, a));
}
current_width += run_pair.offset + run_pair.run.len() as u16;
assert!(current_width <= self.width)
}
if current_width < self.width {
image.extend_from_slice(vec![0; (self.width - current_width) as usize].as_slice());
}
};
(self.width as u32, self.height as u32, image)
}
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u16::<LittleEndian>(self.size).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.trigger).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.width).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.height).ok().expect(MEMWRITER_ERROR);
let mut rows = vec![];
//Write our rows
for row in self.rows.iter() {
let mut out = vec![];
for pair in row.iter() {
out.write(pair.serialize().as_slice()).ok().expect(MEMWRITER_ERROR);
}
//We write a "newline" after each out
out.write_u16::<LittleEndian>(0).ok().expect(MEMWRITER_ERROR);
out.write_u16::<LittleEndian>(0).ok().expect(MEMWRITER_ERROR);
rows.push(out);
}
let mut lookup_table = vec![];
let mut last_position = 0;
//Generate a lookup table
for row in rows.iter() {
lookup_table.write_u16::<LittleEndian>(last_position).ok().expect(MEMWRITER_ERROR);
last_position += (row.len() / 2) as u16;
}
writer.write(lookup_table.as_slice()).ok().expect(MEMWRITER_ERROR);
for row in rows.iter() {
writer.write(row.as_slice()).ok().expect(MEMWRITER_ERROR);
}
writer
}
fn to_image(&self) -> RgbaImage {
panic!("Not implemented");
}
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface {
let mut surface = Surface::new(self.width as u32, self.height as u32, PixelFormatEnum::RGBA8888).expect(SURFACE_ERROR);
let mut surface_target: usize = 0;
surface.with_lock_mut(|bitmap| {
for row in self.rows.iter() {
let mut current_width = 0;
for run_pair in row.iter() {
surface_target += run_pair.offset as usize * 4;
for pixel in run_pair.run.iter() {
let (r, g, b, a) = pixel.to_rgba();
bitmap[surface_target] = a;
bitmap[surface_target + 1] = b;
bitmap[surface_target + 2] = g;
bitmap[surface_target + 3] = r;
surface_target += 4;
}
current_width += run_pair.offset + run_pair.run.len() as u16;
assert!(current_width <= self.width)
}
if current_width < self.width {
surface_target += (self.width - current_width) as usize * 4;
}
};
});
surface
}
}
pub struct Static {
pub size: u16,
pub trigger: u16,
pub width: u16,
pub height: u16,
pub rows: Vec<StaticRow>
}
pub enum TileOrStatic {
Tile(Tile),
Static(Static)
}
pub struct ArtReader<T: Read + Seek> {
mul_reader: MulReader<T>
}
impl ArtReader<File> {
pub fn new(index_path: &Path, mul_path: &Path) -> Result<ArtReader<File>> {
let mul_reader = try!(MulReader::new(index_path, mul_path));
Ok(ArtReader {
mul_reader: mul_reader
})
}
}
impl <T: Read + Seek> ArtReader<T> {
pub fn from_mul(reader: MulReader<T>) -> ArtReader<T> {
ArtReader {
mul_reader: reader
}
}
pub fn read(&mut self, id: u32) -> Result<TileOrStatic> {
let raw = try!(self.mul_reader.read(id));
let mut reader = Cursor::new(raw.data);
if id >= STATIC_OFFSET {
//It's a static, so deal with accordingly
let size = try!(reader.read_u16::<LittleEndian>());
let trigger = try!(reader.read_u16::<LittleEndian>());
let width = try!(reader.read_u16::<LittleEndian>());
let height = try!(reader.read_u16::<LittleEndian>());
if width == 0 || height >= 1024 || height == 0 || height >= 1024 {
Err(Error::new(ErrorKind::Other, format!("Got invalid width and height of {}, {}", width, height)))
} else {
//Load our offset table
let mut offset_table = vec![];
for _index in 0..height {
offset_table.push(try!(reader.read_u16::<LittleEndian>()));
}
let data_start_pos = reader.position();
let mut rows = vec![];
for &offset in offset_table.iter() {
try!(reader.seek(SeekFrom::Start((data_start_pos + offset as u64 * 2))));
let mut row = vec![];
loop {
let x_offset = try!(reader.read_u16::<LittleEndian>());
let run_length = try!(reader.read_u16::<LittleEndian>());
if x_offset + run_length == 0 {
break
} else {
let mut run = vec![];
for _index in 0..run_length {
run.push(try!(reader.read_u16::<LittleEndian>()));
}
row.push(RunPair {
offset: x_offset,
run: run
});
}
}
rows.push(row);
}
Ok(TileOrStatic::Static(Static {
size: size,
trigger: trigger,
width: width,
height: height,
rows: rows
}))
}
} else {
//It's a map tile
if raw.length != TILE_SIZE {
Err(Error::new(ErrorKind::Other, format!("Got tile size of {}, expected {}", raw.length, TILE_SIZE)))
} else {
let header = try!(reader.read_u32::<LittleEndian>());
let mut body = [0; 1022];
for idx in 0..1022 {
body[idx] = try!(reader.read_u16::<LittleEndian>());
}
Ok(TileOrStatic::Tile(Tile {
header: header, image_data: body
}))
}
}
}
pub fn read_tile(&mut self, id: u32) -> Result<Tile> {
match self.read(id) {
Ok(TileOrStatic::Tile(tile)) => Ok(tile),
Ok(_) => Err(Error::new(
ErrorKind::Other,
"Index out of bounds"
)),
Err(e) => Err(e)
}
}
pub fn read_static(&mut self, id: u32)-> Result<Static> {
match self.read(id + STATIC_OFFSET) {
Ok(TileOrStatic::Static(stat)) => Ok(stat),
Ok(_) => Err(Error::new(
ErrorKind::Other,
"Index out of bounds"
)),
Err(e) => Err(e)
}
}
}
Static to Image
//! Methods for reading tile and static data out of art.mul
//!
//! Tiles and Statics are both traditionally stored in art.mul/artidx.mul
use std::fs::{File};
use mul_reader::MulReader;
use std::io::{Result, Error, ErrorKind, Cursor, SeekFrom, Seek, Write, Read};
use color::{Color, Color16, Color32};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use utils::{MEMWRITER_ERROR, SURFACE_ERROR};
use std::path::Path;
#[cfg(feature = "use-sdl2")]
use sdl2::surface::Surface;
#[cfg(feature = "use-sdl2")]
use sdl2::pixels::PixelFormatEnum;
use image::{Rgba, RgbaImage};
pub trait Art {
/**
* Convert to a 32bit array
*
* Returns (width, height, colors)
*/
fn to_32bit(&self) -> (u32, u32, Vec<Color32>);
fn serialize(&self) -> Vec<u8>;
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface;
fn to_image(&self) -> RgbaImage;
}
pub const TILE_SIZE: u32 = 2048;
pub const STATIC_OFFSET: u32 = 0x4000;
pub struct RunPair {
pub offset: u16,
pub run: Vec<Color16>
}
impl RunPair {
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u16::<LittleEndian>(self.offset).expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.run.len() as u16).expect(MEMWRITER_ERROR);
for &color in self.run.iter() {
writer.write_u16::<LittleEndian>(color).expect(MEMWRITER_ERROR);
}
writer
}
}
pub type StaticRow = Vec<RunPair>;
/// A Map Tile, 44px by 44px
///
/// Map tiles are stored as
/// |Header:u32|Pixels:u16|
/// Where pixels represents a list of rows, length 2, 4, 6, 8 .. 42, 44, 44, 42 .. 8, 6, 4, 2 and are drawn
/// centred
pub struct Tile {
/// Header information for a tile. Unused
pub header: u32,
/// Individual pixels. These work as rows, of length 2, 4, 6, 8 .. 42, 44, 44, 42 .. 8, 6, 4, 2
pub image_data: [Color16; 1022]
}
impl Art for Tile {
fn to_32bit(&self) -> (u32, u32, Vec<Color32>) {
let mut image: Vec<Color32> = vec![];
let mut read_idx = 0;
for i in 0..44 {
let slice_size = if i >= 22 {
(44 - i) * 2
} else {
(i + 1) * 2
};
image.extend_from_slice(vec![0; (22 - (slice_size / 2))].as_slice());
for _pixel_idx in 0..slice_size {
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
image.push(Color::from_rgba(r, g, b, a));
read_idx += 1;
}
image.extend_from_slice(vec![0; (22 - (slice_size / 2))].as_slice());
};
(44, 44, image)
}
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u32::<LittleEndian>(self.header).ok().expect(MEMWRITER_ERROR);
for &pixel in self.image_data.iter() {
writer.write_u16::<LittleEndian>(pixel).ok().expect(MEMWRITER_ERROR);
}
writer
}
fn to_image(&self) -> RgbaImage {
let mut buffer = RgbaImage::new(44, 44);
let mut read_idx = 0;
for y in 0..44 {
let slice_size = if y >= 22 {
(44 - y) * 2
} else {
(y + 1) * 2
};
let indent = 22 - (slice_size / 2);
for x in 0..slice_size {
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
buffer.put_pixel(indent + x, y, Rgba([r, g, b, a]));
read_idx += 1;
}
};
buffer
}
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface {
let mut surface = Surface::new(44, 44, PixelFormatEnum::RGBA8888).expect(SURFACE_ERROR);
surface.with_lock_mut(|bitmap| {
let mut read_idx = 0;
for y in 0..44 {
let slice_width = if y >= 22 {
(44 - y) * 2
} else {
(y + 1) * 2
};
let offset_left = 22 - (slice_width / 2);
for pixel_idx in 0..slice_width {
let x = offset_left + pixel_idx;
let (r, g, b, a) = self.image_data[read_idx].to_rgba();
let target = ((y * 44) + x) * 4;
bitmap[target] = a;
bitmap[target + 1] = b;
bitmap[target + 2] = g;
bitmap[target + 3] = r;
read_idx += 1;
}
};
});
surface
}
}
impl Art for Static {
fn to_32bit(&self) -> (u32, u32, Vec<Color32>) {
let mut image: Vec<Color32> = vec![];
for row in self.rows.iter() {
let mut current_width = 0;
for run_pair in row.iter() {
image.extend_from_slice(vec![0; run_pair.offset as usize].as_slice());
for pixel in run_pair.run.iter() {
let (r, g, b, a) = pixel.to_rgba();
image.push(Color::from_rgba(r, g, b, a));
}
current_width += run_pair.offset + run_pair.run.len() as u16;
assert!(current_width <= self.width)
}
if current_width < self.width {
image.extend_from_slice(vec![0; (self.width - current_width) as usize].as_slice());
}
};
(self.width as u32, self.height as u32, image)
}
fn serialize(&self) -> Vec<u8> {
let mut writer = vec![];
writer.write_u16::<LittleEndian>(self.size).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.trigger).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.width).ok().expect(MEMWRITER_ERROR);
writer.write_u16::<LittleEndian>(self.height).ok().expect(MEMWRITER_ERROR);
let mut rows = vec![];
//Write our rows
for row in self.rows.iter() {
let mut out = vec![];
for pair in row.iter() {
out.write(pair.serialize().as_slice()).ok().expect(MEMWRITER_ERROR);
}
//We write a "newline" after each out
out.write_u16::<LittleEndian>(0).ok().expect(MEMWRITER_ERROR);
out.write_u16::<LittleEndian>(0).ok().expect(MEMWRITER_ERROR);
rows.push(out);
}
let mut lookup_table = vec![];
let mut last_position = 0;
//Generate a lookup table
for row in rows.iter() {
lookup_table.write_u16::<LittleEndian>(last_position).ok().expect(MEMWRITER_ERROR);
last_position += (row.len() / 2) as u16;
}
writer.write(lookup_table.as_slice()).ok().expect(MEMWRITER_ERROR);
for row in rows.iter() {
writer.write(row.as_slice()).ok().expect(MEMWRITER_ERROR);
}
writer
}
fn to_image(&self) -> RgbaImage {
let mut buffer = RgbaImage::new(self.width as u32, self.height as u32);
for (y, row) in self.rows.iter().enumerate() {
let mut x: u32 = 0;
for run_pair in row.iter() {
x += run_pair.offset as u32;
for pixel in run_pair.run.iter() {
let (r, g, b, a) = pixel.to_rgba();
buffer.put_pixel(x, y as u32, Rgba([r, g, b, a]));
x += 1;
}
}
};
buffer
}
#[cfg(feature = "use-sdl2")]
fn to_surface(&self) -> Surface {
let mut surface = Surface::new(self.width as u32, self.height as u32, PixelFormatEnum::RGBA8888).expect(SURFACE_ERROR);
let mut surface_target: usize = 0;
surface.with_lock_mut(|bitmap| {
for row in self.rows.iter() {
let mut current_width = 0;
for run_pair in row.iter() {
surface_target += run_pair.offset as usize * 4;
for pixel in run_pair.run.iter() {
let (r, g, b, a) = pixel.to_rgba();
bitmap[surface_target] = a;
bitmap[surface_target + 1] = b;
bitmap[surface_target + 2] = g;
bitmap[surface_target + 3] = r;
surface_target += 4;
}
current_width += run_pair.offset + run_pair.run.len() as u16;
assert!(current_width <= self.width)
}
if current_width < self.width {
surface_target += (self.width - current_width) as usize * 4;
}
};
});
surface
}
}
pub struct Static {
pub size: u16,
pub trigger: u16,
pub width: u16,
pub height: u16,
pub rows: Vec<StaticRow>
}
pub enum TileOrStatic {
Tile(Tile),
Static(Static)
}
pub struct ArtReader<T: Read + Seek> {
mul_reader: MulReader<T>
}
impl ArtReader<File> {
pub fn new(index_path: &Path, mul_path: &Path) -> Result<ArtReader<File>> {
let mul_reader = try!(MulReader::new(index_path, mul_path));
Ok(ArtReader {
mul_reader: mul_reader
})
}
}
impl <T: Read + Seek> ArtReader<T> {
pub fn from_mul(reader: MulReader<T>) -> ArtReader<T> {
ArtReader {
mul_reader: reader
}
}
pub fn read(&mut self, id: u32) -> Result<TileOrStatic> {
let raw = try!(self.mul_reader.read(id));
let mut reader = Cursor::new(raw.data);
if id >= STATIC_OFFSET {
//It's a static, so deal with accordingly
let size = try!(reader.read_u16::<LittleEndian>());
let trigger = try!(reader.read_u16::<LittleEndian>());
let width = try!(reader.read_u16::<LittleEndian>());
let height = try!(reader.read_u16::<LittleEndian>());
if width == 0 || height >= 1024 || height == 0 || height >= 1024 {
Err(Error::new(ErrorKind::Other, format!("Got invalid width and height of {}, {}", width, height)))
} else {
//Load our offset table
let mut offset_table = vec![];
for _index in 0..height {
offset_table.push(try!(reader.read_u16::<LittleEndian>()));
}
let data_start_pos = reader.position();
let mut rows = vec![];
for &offset in offset_table.iter() {
try!(reader.seek(SeekFrom::Start((data_start_pos + offset as u64 * 2))));
let mut row = vec![];
loop {
let x_offset = try!(reader.read_u16::<LittleEndian>());
let run_length = try!(reader.read_u16::<LittleEndian>());
if x_offset + run_length == 0 {
break
} else {
let mut run = vec![];
for _index in 0..run_length {
run.push(try!(reader.read_u16::<LittleEndian>()));
}
row.push(RunPair {
offset: x_offset,
run: run
});
}
}
rows.push(row);
}
Ok(TileOrStatic::Static(Static {
size: size,
trigger: trigger,
width: width,
height: height,
rows: rows
}))
}
} else {
//It's a map tile
if raw.length != TILE_SIZE {
Err(Error::new(ErrorKind::Other, format!("Got tile size of {}, expected {}", raw.length, TILE_SIZE)))
} else {
let header = try!(reader.read_u32::<LittleEndian>());
let mut body = [0; 1022];
for idx in 0..1022 {
body[idx] = try!(reader.read_u16::<LittleEndian>());
}
Ok(TileOrStatic::Tile(Tile {
header: header, image_data: body
}))
}
}
}
pub fn read_tile(&mut self, id: u32) -> Result<Tile> {
match self.read(id) {
Ok(TileOrStatic::Tile(tile)) => Ok(tile),
Ok(_) => Err(Error::new(
ErrorKind::Other,
"Index out of bounds"
)),
Err(e) => Err(e)
}
}
pub fn read_static(&mut self, id: u32)-> Result<Static> {
match self.read(id + STATIC_OFFSET) {
Ok(TileOrStatic::Static(stat)) => Ok(stat),
Ok(_) => Err(Error::new(
ErrorKind::Other,
"Index out of bounds"
)),
Err(e) => Err(e)
}
}
}
|
use byteorder::{LittleEndian, WriteBytesExt};
use libc::consts::os::posix88::*;
use libc::funcs::posix88::mman::mmap;
use libc::funcs::posix88::mman::munmap;
use libc::funcs::posix88::mman::mprotect;
use libc::types::common::c95::c_void;
use libc::types::os::arch::c95::size_t;
use std::ptr;
use std::mem;
use asm::Reg::*;
#[derive(PartialEq,Eq,Debug,Copy,Clone)]
pub enum Reg {
rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
r8, r9, r10, r11, r12, r13, r14, r15,
}
impl Reg {
// most significant bit
fn msb(&self) -> u8 {
match *self {
rax | rcx | rdx | rbx | rsp | rbp | rsi | rdi => 0,
r8 | r9 | r10 | r11 | r12 | r13 | r14 | r15 => 1,
}
}
// least 3 significant bit
fn lsb3(&self) -> u8 {
match *self {
rax => 0,
rcx => 1,
rdx => 2,
rbx => 3,
rsp => 4,
rbp => 5,
rsi => 6,
rdi => 7,
r8 => 0,
r9 => 1,
r10 => 2,
r11 => 3,
r12 => 4,
r13 => 5,
r14 => 6,
r15 => 7,
}
}
// index of enum
fn idx(&self) -> u8 {
match *self {
rax => 0,
rcx => 1,
rdx => 2,
rbx => 3,
rsp => 4,
rbp => 5,
rsi => 6,
rdi => 7,
r8 => 8,
r9 => 9,
r10 => 10,
r11 => 11,
r12 => 12,
r13 => 13,
r14 => 14,
r15 => 15,
}
}
}
#[test]
fn test_msb() {
assert_eq!(0, rax.msb());
assert_eq!(0, rcx.msb());
assert_eq!(0, rdx.msb());
assert_eq!(0, rbx.msb());
assert_eq!(0, rsp.msb());
assert_eq!(0, rbp.msb());
assert_eq!(0, rsi.msb());
assert_eq!(0, rdi.msb());
assert_eq!(1, r8.msb());
assert_eq!(1, r9.msb());
assert_eq!(1, r10.msb());
assert_eq!(1, r11.msb());
assert_eq!(1, r12.msb());
assert_eq!(1, r13.msb());
assert_eq!(1, r14.msb());
assert_eq!(1, r15.msb());
}
#[test]
fn test_idx() {
assert_eq!(0, rax.idx());
assert_eq!(1, rcx.idx());
assert_eq!(2, rdx.idx());
assert_eq!(3, rbx.idx());
assert_eq!(4, rsp.idx());
assert_eq!(5, rbp.idx());
assert_eq!(6, rsi.idx());
assert_eq!(7, rdi.idx());
assert_eq!(8, r8.idx());
assert_eq!(9, r9.idx());
assert_eq!(10, r10.idx());
assert_eq!(11, r11.idx());
assert_eq!(12, r12.idx());
assert_eq!(13, r13.idx());
assert_eq!(14, r14.idx());
assert_eq!(15, r15.idx());
}
#[test]
fn test_lsb3() {
assert_eq!(0, rax.lsb3());
assert_eq!(1, rcx.lsb3());
assert_eq!(2, rdx.lsb3());
assert_eq!(3, rbx.lsb3());
assert_eq!(4, rsp.lsb3());
assert_eq!(5, rbp.lsb3());
assert_eq!(6, rsi.lsb3());
assert_eq!(7, rdi.lsb3());
assert_eq!(0, r8.lsb3());
assert_eq!(1, r9.lsb3());
assert_eq!(2, r10.lsb3());
assert_eq!(3, r11.lsb3());
assert_eq!(4, r12.lsb3());
assert_eq!(5, r13.lsb3());
assert_eq!(6, r14.lsb3());
assert_eq!(7, r15.lsb3());
}
#[derive(Debug)]
pub struct Addr {
base: Reg,
index: Option<Reg>,
scale: u8,
disp: i32,
direct: bool,
}
impl Addr {
pub fn direct(base: Reg) -> Addr {
Addr { base: base, index: None, scale: 0, disp: 0, direct: true }
}
pub fn indirect(base: Reg) -> Addr {
Addr { base: base, index: None, scale: 0, disp: 0, direct: false }
}
pub fn with_disp(base: Reg, disp: i32) -> Addr {
Addr { base: base, index: None, scale: 0, disp: disp, direct: false }
}
pub fn with_sib(base: Reg, idx: Reg, scale: u8, disp: i32) -> Addr {
assert!(idx != rsp);
assert!(scale <= 3);
Addr { base: base, index: Some(idx), scale: scale, disp: disp, direct: false }
}
fn msb(&self) -> u8 {
self.base.msb()
}
fn base_special(&self) -> bool {
self.base == rsp || self.base == rbp || self.base == r12 || self.base == r13
}
fn emit(&self, asm: &mut Assembler, modrm_reg: u8) {
if self.direct {
asm.modrm(0b11, modrm_reg, self.base.lsb3());
} else if self.index.is_none() {
if !self.base_special() {
self.emit_without_sib(asm, modrm_reg);
} else if self.base == rsp || self.base == r13 {
self.emit_rsp(asm, modrm_reg);
} else {
self.emit_rbp(asm, modrm_reg);
}
} else {
self.emit_sib(asm, modrm_reg);
}
}
fn emit_rsp(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b100);
asm.sib(0, 0b100, self.base.lsb3());
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
fn emit_rbp(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b101);
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
fn emit_sib(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b100);
asm.sib(self.scale, self.index.unwrap().lsb3(), self.base.lsb3());
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
fn emit_without_sib(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if self.disp == 0 { 0b00 }
else if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, self.base.lsb3());
if self.disp != 0 {
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
}
}
fn fits8(v: i64) -> bool {
v == (v as i8) as i64
}
fn fits16(v: i64) -> bool {
v == (v as i16) as i64
}
fn fits32(v: i64) -> bool {
v == (v as i32) as i64
}
#[test]
fn test_fits8() {
assert!(fits8(0));
assert!(fits8(127));
assert!(fits8(-128));
assert!(!fits8(128));
assert!(!fits8(-129));
}
#[test]
fn test_fits16() {
assert!(fits16(8));
assert!(fits16(32767));
assert!(fits16(-32768));
assert!(!fits16(32768));
assert!(!fits16(-32769));
}
// Machine instruction without any operands, just emits the given
// opcode
macro_rules! i0p {
($i:ident, $w:expr) => {pub fn $i(&mut self) { self.opcode($w); }}
}
// Machine Instruction with 1 register operand, register
// index is added to opcode
macro_rules! q1p_r_rpo {
($i:ident, $w:expr) => {pub fn $i(&mut self, dest: Reg) {
if dest.msb() != 0 {
self.rex_prefix(0, 0, 0, 1);
}
self.opcode($w + dest.lsb3());
}}
}
macro_rules! q2p_atr {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: Addr, dest: Reg) {
self.rex_prefix(1, dest.msb(), 0, src.msb());
self.opcode($w);
src.emit(self, dest.lsb3());
}}
}
// machine instruction with 2 operands. register to address
macro_rules! q2p_rta {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: Reg, dest: Addr) {
self.rex_prefix(1, src.msb(), 0, dest.msb());
self.opcode($w);
dest.emit(self, src.lsb3());
}}
}
// machine instruction with 2 operands. u64 to register. register index is
// added to opcode
macro_rules! q2p_i64tr {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: u64, dest: Reg) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w + dest.lsb3());
self.emitq(src);
}}
}
// machine instruction with 2 operands. 32 bit immediate and destination operand
macro_rules! q2p_i32ta {
($i:ident, $w: expr, $modrm_reg: expr) => {pub fn $i(&mut self, src: u32, dest: Addr) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w);
dest.emit(self, $modrm_reg);
self.emitd(src);
}}
}
// machine instruction with 2 operands. 8 bit immediate and destination operand
macro_rules! q2p_i8ta {
($i:ident, $w: expr, $modrm_reg: expr) => {pub fn $i(&mut self, src: u8, dest: Addr) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w);
dest.emit(self, $modrm_reg);
self.emitb(src);
}}
}
pub struct Assembler {
code: Vec<u8>
}
impl Assembler {
pub fn new() -> Assembler {
Assembler { code: Vec::new() }
}
i0p!(nop, 0x90);
i0p!(ret, 0xC3);
q1p_r_rpo!(pushq, 0x50);
q1p_r_rpo!(popq, 0x58);
q2p_rta!(addq_rta, 0x01);
q2p_atr!(addq_atr, 0x03);
q2p_i32ta!(addq_i32ta, 0x81, 0);
q2p_i8ta!(addq_i8ta, 0x83, 0);
q2p_rta!(subq_rta, 0x29);
q2p_atr!(subq_atr, 0x2B);
q2p_i32ta!(subq_i32ta, 0x81, 5);
q2p_i8ta!(subq_i8ta, 0x83, 5);
q2p_rta!(movq_rta, 0x89);
q2p_atr!(movq_atr, 0x8B);
q2p_i64tr!(movq_i64tr, 0xB8);
q2p_i32ta!(movq_i32ta, 0xC7, 0);
fn opcode(&mut self, c: u8) { self.code.push(c); }
fn emitb(&mut self, c: u8) { self.code.push(c); }
fn emitw(&mut self, w: u16) { self.code.write_u16::<LittleEndian>(w).unwrap(); }
fn emitd(&mut self, d: u32) { self.code.write_u32::<LittleEndian>(d).unwrap(); }
fn emitq(&mut self, q: u64) { self.code.write_u64::<LittleEndian>(q).unwrap(); }
fn modrm(&mut self, mode: u8, reg: u8, rm: u8) {
self.emitb(mode << 6 | reg << 3 | rm );
}
fn sib(&mut self, scale: u8, index: u8, base: u8) {
self.emitb(scale << 6 | index << 3 | base);
}
fn rex_prefix(&mut self, w: u8, r: u8, x: u8, b: u8) {
let v = 0x40 | w << 3 | r << 2 | x << 1 | b;
self.code.push(v);
}
}
#[test]
fn test_nop() {
let mut asm = Assembler::new();
asm.nop();
assert_eq!(vec![0x90], asm.code);
}
#[test]
fn test_ret() {
let mut asm = Assembler::new();
asm.ret();
assert_eq!(vec![0xc3], asm.code);
}
#[test]
fn test_push() {
let mut asm = Assembler::new();
asm.pushq(rax);
asm.pushq(r8);
asm.pushq(rcx);
assert_eq!(vec![0x50, 0x41, 0x50, 0x51], asm.code);
}
#[test]
fn test_pop() {
let mut asm = Assembler::new();
asm.popq(rax);
asm.popq(r8);
asm.popq(rcx);
assert_eq!(vec![0x58, 0x41, 0x58, 0x59], asm.code);
}
#[test]
fn test_mov() {
let mut asm = Assembler::new();
asm.movq_rta(r15, Addr::direct(rax));
asm.movq_rta(rsi, Addr::direct(r8));
assert_eq!(vec![0x4c, 0x89, 0xf8, 0x49, 0x89, 0xf0], asm.code);
}
#[test]
fn test_mov_i64_to_reg() {
let mut asm = Assembler::new();
asm.movq_i64tr(1, rax);
asm.movq_i64tr(2, r8);
assert_eq!(vec![0x48, 0xb8, 1, 0, 0, 0, 0, 0, 0, 0,
0x49, 0xb8, 2, 0, 0, 0, 0, 0, 0, 0], asm.code);
}
#[test]
fn test_mov_i32_to_mem() {
let mut asm = Assembler::new();
asm.movq_i32ta(2, Addr::with_disp(rbp, 1));
asm.movq_i32ta(3, Addr::with_disp(r8, -1));
assert_eq!(vec![0x48, 0xC7, 0x45, 0x01, 2, 0, 0, 0,
0x49, 0xC7, 0x40, 0xFF, 3, 0, 0, 0], asm.code);
}
#[test]
fn test_mov_i32_to_reg() {
let mut asm = Assembler::new();
asm.movq_i32ta(1, Addr::direct(rax));
asm.movq_i32ta(2, Addr::direct(r9));
assert_eq!(vec![0x48, 0xC7, 0xC0, 1, 0, 0, 0,
0x49, 0xC7, 0xC1, 2, 0, 0, 0], asm.code);
}
#[test]
fn test_add_reg_to_reg() {
let mut asm = Assembler::new();
asm.addq_rta(r10, Addr::direct(rcx));
asm.addq_rta(rbx, Addr::direct(r10));
assert_eq!(vec![0x4c, 0x01, 0xd1,
0x49, 0x01, 0xda], asm.code);
}
#[test]
fn test_add_reg_to_addr() {
let mut asm = Assembler::new();
asm.addq_rta(r9, Addr::with_disp(rbp, 1));
asm.addq_rta(rcx, Addr::with_disp(rax, -1));
assert_eq!(vec![0x4C, 0x01, 0x4D, 0x01,
0x48, 0x01, 0x48, 0xFF], asm.code);
}
#[test]
fn test_add_addr_to_reg() {
let mut asm = Assembler::new();
asm.addq_atr(Addr::with_disp(rbp, 1), r9);
asm.addq_atr(Addr::with_disp(rax, -1), rcx);
asm.addq_atr(Addr::with_sib(rsp, rbp, 1, 3), r9);
assert_eq!(vec![0x4C, 0x03, 0x4D, 0x01,
0x48, 0x03, 0x48, 0xFF,
0x4C, 0x03, 0x4C, 0x6C, 0x03], asm.code);
}
#[test]
fn test_add_i32_to_reg() {
let mut asm = Assembler::new();
asm.addq_i32ta(1, Addr::direct(rcx));
asm.addq_i32ta(0x100, Addr::direct(r9));
assert_eq!(vec![0x48, 0x81, 0xC1, 1, 0, 0, 0,
0x49, 0x81, 0xC1, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_add_i8_to_reg() {
let mut asm = Assembler::new();
asm.addq_i8ta(1, Addr::direct(r8));
asm.addq_i8ta(1, Addr::direct(rsi));
assert_eq!(vec![0x49, 0x83, 0xC0, 0x01,
0x48, 0x83, 0xC6, 0x01], asm.code);
}
#[test]
fn test_add_i32_to_addr() {
let mut asm = Assembler::new();
asm.addq_i32ta(1, Addr::with_disp(rcx,1));
asm.addq_i32ta(0x100, Addr::with_disp(r10,-1));
assert_eq!(vec![0x48, 0x81, 0x41, 0x01, 1, 0, 0, 0,
0x49, 0x81, 0x42, 0xFF, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_add_i8_to_addr() {
let mut asm = Assembler::new();
asm.addq_i8ta(1, Addr::with_disp(rcx, 1));
asm.addq_i8ta(2, Addr::with_disp(r11, -1));
assert_eq!(vec![0x48, 0x83, 0x41, 0x01, 0x01,
0x49, 0x83, 0x43, 0xFF, 0x02], asm.code);
}
#[test]
fn test_sub_i32_from_addr() {
let mut asm = Assembler::new();
asm.subq_i32ta(1, Addr::with_disp(rcx,1));
asm.subq_i32ta(0x100, Addr::with_disp(r10,-1));
assert_eq!(vec![0x48, 0x81, 0x69, 0x01, 1, 0, 0, 0,
0x49, 0x81, 0x6A, 0xFF, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_sub_i8_from_addr() {
let mut asm = Assembler::new();
asm.subq_i8ta(1, Addr::with_disp(rcx, 1));
asm.subq_i8ta(2, Addr::with_disp(r11, -1));
assert_eq!(vec![0x48, 0x83, 0x69, 0x01, 0x01,
0x49, 0x83, 0x6B, 0xFF, 0x02], asm.code);
}
#[test]
fn test_sub_reg_from_reg() {
let mut asm = Assembler::new();
asm.subq_rta(r10, Addr::direct(rcx));
asm.subq_rta(rbx, Addr::direct(r10));
assert_eq!(vec![0x4C, 0x29, 0xD1,
0x49, 0x29, 0xDA], asm.code);
}
#[test]
fn test_sub_reg_from_addr() {
let mut asm = Assembler::new();
asm.subq_rta(r9, Addr::with_disp(rbp, 1));
asm.subq_rta(rcx, Addr::with_disp(rax, -1));
assert_eq!(vec![0x4C, 0x29, 0x4D, 0x01,
0x48, 0x29, 0x48, 0xFF], asm.code);
}
#[test]
fn test_sub_addr_from_reg() {
let mut asm = Assembler::new();
asm.subq_atr(Addr::with_disp(rbp, 1), r9);
asm.subq_atr(Addr::with_disp(rax, -1), rcx);
assert_eq!(vec![0x4C, 0x2B, 0x4D, 0x01,
0x48, 0x2B, 0x48, 0xFF], asm.code);
}
#[test]
fn test_sub_i32_from_reg() {
let mut asm = Assembler::new();
asm.subq_i32ta(1, Addr::direct(rcx));
asm.subq_i32ta(0x100, Addr::direct(r9));
assert_eq!(vec![0x48, 0x81, 0xE9, 1, 0, 0, 0,
0x49, 0x81, 0xE9, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_sub_i8_from_reg() {
let mut asm = Assembler::new();
asm.subq_i8ta(1, Addr::direct(r8));
asm.subq_i8ta(1, Addr::direct(rsi));
assert_eq!(vec![0x49, 0x83, 0xE8, 0x01,
0x48, 0x83, 0xEE, 0x01], asm.code);
}
static CODE : [u8;8] = [ 0x48, 0x89, 0xf8, 0x48, 0x83, 0xc0, 0x04, 0xc3 ];
pub struct JitFunction {
pub size: size_t,
pub ptr: extern fn (u64) -> u64
}
impl JitFunction {
pub fn new(code: &[u8]) -> JitFunction {
let size = code.len() as u64;
unsafe {
let fct = mmap(0 as *mut c_void, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
if fct == MAP_FAILED {
panic!("mmap failed");
}
ptr::copy_nonoverlapping(code.as_ptr() as *const c_void, fct, code.len());
if mprotect(fct, size, PROT_READ | PROT_EXEC) == -1 {
panic!("mprotect failed");
}
JitFunction {
size: size,
ptr: mem::transmute(fct)
}
}
}
}
impl Drop for JitFunction {
fn drop(&mut self) {
unsafe {
munmap(mem::transmute(self.ptr), self.size);
}
}
}
#[test]
fn test_create_function() {
let fct = JitFunction::new(&CODE);
assert_eq!(5, (fct.ptr)(1));
}
used assembler for test program
use byteorder::{LittleEndian, WriteBytesExt};
use libc::consts::os::posix88::*;
use libc::funcs::posix88::mman::mmap;
use libc::funcs::posix88::mman::munmap;
use libc::funcs::posix88::mman::mprotect;
use libc::types::common::c95::c_void;
use libc::types::os::arch::c95::size_t;
use std::ptr;
use std::mem;
use asm::Reg::*;
#[derive(PartialEq,Eq,Debug,Copy,Clone)]
pub enum Reg {
rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
r8, r9, r10, r11, r12, r13, r14, r15,
}
impl Reg {
// most significant bit
fn msb(&self) -> u8 {
match *self {
rax | rcx | rdx | rbx | rsp | rbp | rsi | rdi => 0,
r8 | r9 | r10 | r11 | r12 | r13 | r14 | r15 => 1,
}
}
// least 3 significant bit
fn lsb3(&self) -> u8 {
match *self {
rax => 0,
rcx => 1,
rdx => 2,
rbx => 3,
rsp => 4,
rbp => 5,
rsi => 6,
rdi => 7,
r8 => 0,
r9 => 1,
r10 => 2,
r11 => 3,
r12 => 4,
r13 => 5,
r14 => 6,
r15 => 7,
}
}
// index of enum
fn idx(&self) -> u8 {
match *self {
rax => 0,
rcx => 1,
rdx => 2,
rbx => 3,
rsp => 4,
rbp => 5,
rsi => 6,
rdi => 7,
r8 => 8,
r9 => 9,
r10 => 10,
r11 => 11,
r12 => 12,
r13 => 13,
r14 => 14,
r15 => 15,
}
}
}
#[test]
fn test_msb() {
assert_eq!(0, rax.msb());
assert_eq!(0, rcx.msb());
assert_eq!(0, rdx.msb());
assert_eq!(0, rbx.msb());
assert_eq!(0, rsp.msb());
assert_eq!(0, rbp.msb());
assert_eq!(0, rsi.msb());
assert_eq!(0, rdi.msb());
assert_eq!(1, r8.msb());
assert_eq!(1, r9.msb());
assert_eq!(1, r10.msb());
assert_eq!(1, r11.msb());
assert_eq!(1, r12.msb());
assert_eq!(1, r13.msb());
assert_eq!(1, r14.msb());
assert_eq!(1, r15.msb());
}
#[test]
fn test_idx() {
assert_eq!(0, rax.idx());
assert_eq!(1, rcx.idx());
assert_eq!(2, rdx.idx());
assert_eq!(3, rbx.idx());
assert_eq!(4, rsp.idx());
assert_eq!(5, rbp.idx());
assert_eq!(6, rsi.idx());
assert_eq!(7, rdi.idx());
assert_eq!(8, r8.idx());
assert_eq!(9, r9.idx());
assert_eq!(10, r10.idx());
assert_eq!(11, r11.idx());
assert_eq!(12, r12.idx());
assert_eq!(13, r13.idx());
assert_eq!(14, r14.idx());
assert_eq!(15, r15.idx());
}
#[test]
fn test_lsb3() {
assert_eq!(0, rax.lsb3());
assert_eq!(1, rcx.lsb3());
assert_eq!(2, rdx.lsb3());
assert_eq!(3, rbx.lsb3());
assert_eq!(4, rsp.lsb3());
assert_eq!(5, rbp.lsb3());
assert_eq!(6, rsi.lsb3());
assert_eq!(7, rdi.lsb3());
assert_eq!(0, r8.lsb3());
assert_eq!(1, r9.lsb3());
assert_eq!(2, r10.lsb3());
assert_eq!(3, r11.lsb3());
assert_eq!(4, r12.lsb3());
assert_eq!(5, r13.lsb3());
assert_eq!(6, r14.lsb3());
assert_eq!(7, r15.lsb3());
}
#[derive(Debug)]
pub struct Addr {
base: Reg,
index: Option<Reg>,
scale: u8,
disp: i32,
direct: bool,
}
impl Addr {
pub fn direct(base: Reg) -> Addr {
Addr { base: base, index: None, scale: 0, disp: 0, direct: true }
}
pub fn indirect(base: Reg) -> Addr {
Addr { base: base, index: None, scale: 0, disp: 0, direct: false }
}
pub fn with_disp(base: Reg, disp: i32) -> Addr {
Addr { base: base, index: None, scale: 0, disp: disp, direct: false }
}
pub fn with_sib(base: Reg, idx: Reg, scale: u8, disp: i32) -> Addr {
assert!(idx != rsp);
assert!(scale <= 3);
Addr { base: base, index: Some(idx), scale: scale, disp: disp, direct: false }
}
fn msb(&self) -> u8 {
self.base.msb()
}
fn base_special(&self) -> bool {
self.base == rsp || self.base == rbp || self.base == r12 || self.base == r13
}
fn emit(&self, asm: &mut Assembler, modrm_reg: u8) {
if self.direct {
asm.modrm(0b11, modrm_reg, self.base.lsb3());
} else if self.index.is_none() {
if !self.base_special() {
self.emit_without_sib(asm, modrm_reg);
} else if self.base == rsp || self.base == r13 {
self.emit_rsp(asm, modrm_reg);
} else {
self.emit_rbp(asm, modrm_reg);
}
} else {
self.emit_sib(asm, modrm_reg);
}
}
fn emit_rsp(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b100);
asm.sib(0, 0b100, self.base.lsb3());
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
fn emit_rbp(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b101);
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
fn emit_sib(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if self.disp == 0 { 0b00 }
else if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, 0b100);
asm.sib(self.scale, self.index.unwrap().lsb3(), self.base.lsb3());
if self.disp != 0 {
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
}
fn emit_without_sib(&self, asm: &mut Assembler, modrm_reg: u8) {
let fits_into_byte = fits8(self.disp as i64);
let mode =
if self.disp == 0 { 0b00 }
else if fits_into_byte { 0b01 }
else { 0b10 };
asm.modrm(mode, modrm_reg, self.base.lsb3());
if self.disp != 0 {
if fits_into_byte {
asm.emitb(self.disp as u8);
} else {
asm.emitd(self.disp as u32);
}
}
}
}
fn fits8(v: i64) -> bool {
v == (v as i8) as i64
}
fn fits16(v: i64) -> bool {
v == (v as i16) as i64
}
fn fits32(v: i64) -> bool {
v == (v as i32) as i64
}
#[test]
fn test_fits8() {
assert!(fits8(0));
assert!(fits8(127));
assert!(fits8(-128));
assert!(!fits8(128));
assert!(!fits8(-129));
}
#[test]
fn test_fits16() {
assert!(fits16(8));
assert!(fits16(32767));
assert!(fits16(-32768));
assert!(!fits16(32768));
assert!(!fits16(-32769));
}
// Machine instruction without any operands, just emits the given
// opcode
macro_rules! i0p {
($i:ident, $w:expr) => {pub fn $i(&mut self) { self.opcode($w); }}
}
// Machine Instruction with 1 register operand, register
// index is added to opcode
macro_rules! q1p_r_rpo {
($i:ident, $w:expr) => {pub fn $i(&mut self, dest: Reg) {
if dest.msb() != 0 {
self.rex_prefix(0, 0, 0, 1);
}
self.opcode($w + dest.lsb3());
}}
}
macro_rules! q2p_atr {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: Addr, dest: Reg) {
self.rex_prefix(1, dest.msb(), 0, src.msb());
self.opcode($w);
src.emit(self, dest.lsb3());
}}
}
// machine instruction with 2 operands. register to address
macro_rules! q2p_rta {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: Reg, dest: Addr) {
self.rex_prefix(1, src.msb(), 0, dest.msb());
self.opcode($w);
dest.emit(self, src.lsb3());
}}
}
// machine instruction with 2 operands. u64 to register. register index is
// added to opcode
macro_rules! q2p_i64tr {
($i:ident, $w: expr) => {pub fn $i(&mut self, src: u64, dest: Reg) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w + dest.lsb3());
self.emitq(src);
}}
}
// machine instruction with 2 operands. 32 bit immediate and destination operand
macro_rules! q2p_i32ta {
($i:ident, $w: expr, $modrm_reg: expr) => {pub fn $i(&mut self, src: u32, dest: Addr) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w);
dest.emit(self, $modrm_reg);
self.emitd(src);
}}
}
// machine instruction with 2 operands. 8 bit immediate and destination operand
macro_rules! q2p_i8ta {
($i:ident, $w: expr, $modrm_reg: expr) => {pub fn $i(&mut self, src: u8, dest: Addr) {
self.rex_prefix(1, 0, 0, dest.msb());
self.opcode($w);
dest.emit(self, $modrm_reg);
self.emitb(src);
}}
}
pub struct Assembler {
code: Vec<u8>
}
impl Assembler {
pub fn new() -> Assembler {
Assembler { code: Vec::new() }
}
i0p!(nop, 0x90);
i0p!(ret, 0xC3);
q1p_r_rpo!(pushq, 0x50);
q1p_r_rpo!(popq, 0x58);
q2p_rta!(addq_rta, 0x01);
q2p_atr!(addq_atr, 0x03);
q2p_i32ta!(addq_i32ta, 0x81, 0);
q2p_i8ta!(addq_i8ta, 0x83, 0);
q2p_rta!(subq_rta, 0x29);
q2p_atr!(subq_atr, 0x2B);
q2p_i32ta!(subq_i32ta, 0x81, 5);
q2p_i8ta!(subq_i8ta, 0x83, 5);
q2p_rta!(movq_rta, 0x89);
q2p_atr!(movq_atr, 0x8B);
q2p_i64tr!(movq_i64tr, 0xB8);
q2p_i32ta!(movq_i32ta, 0xC7, 0);
fn opcode(&mut self, c: u8) { self.code.push(c); }
fn emitb(&mut self, c: u8) { self.code.push(c); }
fn emitw(&mut self, w: u16) { self.code.write_u16::<LittleEndian>(w).unwrap(); }
fn emitd(&mut self, d: u32) { self.code.write_u32::<LittleEndian>(d).unwrap(); }
fn emitq(&mut self, q: u64) { self.code.write_u64::<LittleEndian>(q).unwrap(); }
fn modrm(&mut self, mode: u8, reg: u8, rm: u8) {
self.emitb(mode << 6 | reg << 3 | rm );
}
fn sib(&mut self, scale: u8, index: u8, base: u8) {
self.emitb(scale << 6 | index << 3 | base);
}
fn rex_prefix(&mut self, w: u8, r: u8, x: u8, b: u8) {
let v = 0x40 | w << 3 | r << 2 | x << 1 | b;
self.code.push(v);
}
}
#[test]
fn test_nop() {
let mut asm = Assembler::new();
asm.nop();
assert_eq!(vec![0x90], asm.code);
}
#[test]
fn test_ret() {
let mut asm = Assembler::new();
asm.ret();
assert_eq!(vec![0xc3], asm.code);
}
#[test]
fn test_push() {
let mut asm = Assembler::new();
asm.pushq(rax);
asm.pushq(r8);
asm.pushq(rcx);
assert_eq!(vec![0x50, 0x41, 0x50, 0x51], asm.code);
}
#[test]
fn test_pop() {
let mut asm = Assembler::new();
asm.popq(rax);
asm.popq(r8);
asm.popq(rcx);
assert_eq!(vec![0x58, 0x41, 0x58, 0x59], asm.code);
}
#[test]
fn test_mov() {
let mut asm = Assembler::new();
asm.movq_rta(r15, Addr::direct(rax));
asm.movq_rta(rsi, Addr::direct(r8));
assert_eq!(vec![0x4c, 0x89, 0xf8, 0x49, 0x89, 0xf0], asm.code);
}
#[test]
fn test_mov_i64_to_reg() {
let mut asm = Assembler::new();
asm.movq_i64tr(1, rax);
asm.movq_i64tr(2, r8);
assert_eq!(vec![0x48, 0xb8, 1, 0, 0, 0, 0, 0, 0, 0,
0x49, 0xb8, 2, 0, 0, 0, 0, 0, 0, 0], asm.code);
}
#[test]
fn test_mov_i32_to_mem() {
let mut asm = Assembler::new();
asm.movq_i32ta(2, Addr::with_disp(rbp, 1));
asm.movq_i32ta(3, Addr::with_disp(r8, -1));
assert_eq!(vec![0x48, 0xC7, 0x45, 0x01, 2, 0, 0, 0,
0x49, 0xC7, 0x40, 0xFF, 3, 0, 0, 0], asm.code);
}
#[test]
fn test_mov_i32_to_reg() {
let mut asm = Assembler::new();
asm.movq_i32ta(1, Addr::direct(rax));
asm.movq_i32ta(2, Addr::direct(r9));
assert_eq!(vec![0x48, 0xC7, 0xC0, 1, 0, 0, 0,
0x49, 0xC7, 0xC1, 2, 0, 0, 0], asm.code);
}
#[test]
fn test_add_reg_to_reg() {
let mut asm = Assembler::new();
asm.addq_rta(r10, Addr::direct(rcx));
asm.addq_rta(rbx, Addr::direct(r10));
assert_eq!(vec![0x4c, 0x01, 0xd1,
0x49, 0x01, 0xda], asm.code);
}
#[test]
fn test_add_reg_to_addr() {
let mut asm = Assembler::new();
asm.addq_rta(r9, Addr::with_disp(rbp, 1));
asm.addq_rta(rcx, Addr::with_disp(rax, -1));
assert_eq!(vec![0x4C, 0x01, 0x4D, 0x01,
0x48, 0x01, 0x48, 0xFF], asm.code);
}
#[test]
fn test_add_addr_to_reg() {
let mut asm = Assembler::new();
asm.addq_atr(Addr::with_disp(rbp, 1), r9);
asm.addq_atr(Addr::with_disp(rax, -1), rcx);
asm.addq_atr(Addr::with_sib(rsp, rbp, 1, 3), r9);
asm.addq_atr(Addr::with_sib(rsp, rbp, 2, 0), r9);
assert_eq!(vec![0x4C, 0x03, 0x4D, 0x01,
0x48, 0x03, 0x48, 0xFF,
0x4C, 0x03, 0x4C, 0x6C, 0x03,
0x4C, 0x03, 0x0C, 0xAC], asm.code);
}
#[test]
fn test_add_i32_to_reg() {
let mut asm = Assembler::new();
asm.addq_i32ta(1, Addr::direct(rcx));
asm.addq_i32ta(0x100, Addr::direct(r9));
assert_eq!(vec![0x48, 0x81, 0xC1, 1, 0, 0, 0,
0x49, 0x81, 0xC1, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_add_i8_to_reg() {
let mut asm = Assembler::new();
asm.addq_i8ta(1, Addr::direct(r8));
asm.addq_i8ta(1, Addr::direct(rsi));
assert_eq!(vec![0x49, 0x83, 0xC0, 0x01,
0x48, 0x83, 0xC6, 0x01], asm.code);
}
#[test]
fn test_add_i32_to_addr() {
let mut asm = Assembler::new();
asm.addq_i32ta(1, Addr::with_disp(rcx,1));
asm.addq_i32ta(0x100, Addr::with_disp(r10,-1));
assert_eq!(vec![0x48, 0x81, 0x41, 0x01, 1, 0, 0, 0,
0x49, 0x81, 0x42, 0xFF, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_add_i8_to_addr() {
let mut asm = Assembler::new();
asm.addq_i8ta(1, Addr::with_disp(rcx, 1));
asm.addq_i8ta(2, Addr::with_disp(r11, -1));
assert_eq!(vec![0x48, 0x83, 0x41, 0x01, 0x01,
0x49, 0x83, 0x43, 0xFF, 0x02], asm.code);
}
#[test]
fn test_sub_i32_from_addr() {
let mut asm = Assembler::new();
asm.subq_i32ta(1, Addr::with_disp(rcx,1));
asm.subq_i32ta(0x100, Addr::with_disp(r10,-1));
assert_eq!(vec![0x48, 0x81, 0x69, 0x01, 1, 0, 0, 0,
0x49, 0x81, 0x6A, 0xFF, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_sub_i8_from_addr() {
let mut asm = Assembler::new();
asm.subq_i8ta(1, Addr::with_disp(rcx, 1));
asm.subq_i8ta(2, Addr::with_disp(r11, -1));
assert_eq!(vec![0x48, 0x83, 0x69, 0x01, 0x01,
0x49, 0x83, 0x6B, 0xFF, 0x02], asm.code);
}
#[test]
fn test_sub_reg_from_reg() {
let mut asm = Assembler::new();
asm.subq_rta(r10, Addr::direct(rcx));
asm.subq_rta(rbx, Addr::direct(r10));
assert_eq!(vec![0x4C, 0x29, 0xD1,
0x49, 0x29, 0xDA], asm.code);
}
#[test]
fn test_sub_reg_from_addr() {
let mut asm = Assembler::new();
asm.subq_rta(r9, Addr::with_disp(rbp, 1));
asm.subq_rta(rcx, Addr::with_disp(rax, -1));
assert_eq!(vec![0x4C, 0x29, 0x4D, 0x01,
0x48, 0x29, 0x48, 0xFF], asm.code);
}
#[test]
fn test_sub_addr_from_reg() {
let mut asm = Assembler::new();
asm.subq_atr(Addr::with_disp(rbp, 1), r9);
asm.subq_atr(Addr::with_disp(rax, -1), rcx);
assert_eq!(vec![0x4C, 0x2B, 0x4D, 0x01,
0x48, 0x2B, 0x48, 0xFF], asm.code);
}
#[test]
fn test_sub_i32_from_reg() {
let mut asm = Assembler::new();
asm.subq_i32ta(1, Addr::direct(rcx));
asm.subq_i32ta(0x100, Addr::direct(r9));
assert_eq!(vec![0x48, 0x81, 0xE9, 1, 0, 0, 0,
0x49, 0x81, 0xE9, 0, 1, 0, 0], asm.code);
}
#[test]
fn test_sub_i8_from_reg() {
let mut asm = Assembler::new();
asm.subq_i8ta(1, Addr::direct(r8));
asm.subq_i8ta(1, Addr::direct(rsi));
assert_eq!(vec![0x49, 0x83, 0xE8, 0x01,
0x48, 0x83, 0xEE, 0x01], asm.code);
}
pub struct JitFunction {
pub size: size_t,
pub ptr: extern fn (u64) -> u64
}
impl JitFunction {
pub fn new(code: &[u8]) -> JitFunction {
let size = code.len() as u64;
unsafe {
let fct = mmap(0 as *mut c_void, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
if fct == MAP_FAILED {
panic!("mmap failed");
}
ptr::copy_nonoverlapping(code.as_ptr() as *const c_void, fct, code.len());
if mprotect(fct, size, PROT_READ | PROT_EXEC) == -1 {
panic!("mprotect failed");
}
JitFunction {
size: size,
ptr: mem::transmute(fct)
}
}
}
}
impl Drop for JitFunction {
fn drop(&mut self) {
unsafe {
munmap(mem::transmute(self.ptr), self.size);
}
}
}
#[test]
fn test_create_function() {
let mut asm = Assembler::new();
asm.movq_rta(rdi, Addr::direct(rax));
asm.addq_i8ta(4, Addr::direct(rax));
asm.ret();
let fct = JitFunction::new(&asm.code);
assert_eq!(5, (fct.ptr)(1));
}
|
use std::fmt::{Display, Error, Formatter};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinOp {
And,
Ge,
Gt,
Eql,
Le,
Lt,
Minus,
Neq,
Or,
Plus,
Slash,
Star,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Precedence {
Const = 110,
Sign = 100,
Inc = 90,
Mult = 70,
Add = 60,
Equality = 50,
And = 40,
Or = 30,
}
impl BinOp {
pub fn precedence(&self) -> Precedence {
match *self {
BinOp::And => Precedence::And,
BinOp::Ge | BinOp::Gt | BinOp::Eql | BinOp::Le | BinOp::Lt |
BinOp::Neq => Precedence::Equality,
BinOp::Or => Precedence::Or,
BinOp::Minus | BinOp::Plus => Precedence::Add,
BinOp::Slash | BinOp::Star => Precedence::Mult,
}
}
pub fn is_commutative(&self) -> bool {
match *self {
BinOp::Minus | BinOp::Slash => false,
_ => true
}
}
}
impl Display for BinOp {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
match *self {
BinOp::And => write!(fmt, "&&"),
BinOp::Ge => write!(fmt, ">="),
BinOp::Gt => write!(fmt, ">"),
BinOp::Eql => write!(fmt, "=="),
BinOp::Le => write!(fmt, "<="),
BinOp::Lt => write!(fmt, "<"),
BinOp::Minus => write!(fmt, "-"),
BinOp::Neq => write!(fmt, "!="),
BinOp::Or => write!(fmt, "||"),
BinOp::Plus => write!(fmt, "+"),
BinOp::Slash => write!(fmt, "/"),
BinOp::Star => write!(fmt, "*"),
}
}
}
#[derive(Clone, Debug)]
pub enum Exp {
BinExp(Box<Exp>, BinOp, Box<Exp>),
Bool(bool),
Call(Box<Exp>, Vec<Box<Exp>>),
Defun(Option<String>, Vec<String>, Box<Stmt>),
Float(f64),
InstanceVar(Box<Exp>, String),
Neg(Box<Exp>),
Null,
NewObject(Box<Exp>, Vec<Box<Exp>>),
Object(Vec<(String, Box<Exp>)>),
Pos(Box<Exp>),
PostDec(Box<Exp>),
PostInc(Box<Exp>),
PreDec(Box<Exp>),
PreInc(Box<Exp>),
Undefined,
Var(String),
}
impl Exp {
pub fn precedence(&self) -> Precedence {
match *self {
Exp::BinExp(_, ref o, _) => o.precedence(),
Exp::Bool(_) | Exp::Call(..) | Exp::Defun(..) | Exp::Float(_) | Exp::InstanceVar(..) |
Exp::NewObject(..) | Exp::Null | Exp::Object(_) | Exp::Undefined |
Exp::Var(_) => Precedence::Const,
Exp::Neg(_) | Exp::Pos(_) => Precedence::Sign,
Exp::PostDec(_) | Exp::PostInc(_) | Exp::PreDec(_) | Exp::PreInc(_) => Precedence::Inc,
}
}
}
macro_rules! group {
($e:expr, $p:expr) => {
if $e.precedence() < $p {
format!("({})", $e)
} else {
format!("{}", $e)
}
}
}
impl Exp {
fn fmt_helper(&self, mut fmt: &mut Formatter, indent_level: i32) -> Result<(), Error> {
match *self {
Exp::BinExp(ref e1, ref o, ref e2) => {
let prec = self.precedence();
// Put grouping parentheses if the left subexpression has a lower-precedence
// operator, e.g. (1 + 2) * 3
let left = if prec > e1.precedence() {
format!("({})", e1)
} else {
format!("{}", e1)
};
let right_prec = e2.precedence();
// Put grouping parentheses around the right subexpression if it has a
// lower-precedence operator, __OR__ if `o` is not commutative and the precedence
// is the same, e.g. (1 + 2) * 3 __OR__ 1 - (2 + 3)
let right = if prec > right_prec || (!o.is_commutative() && prec == right_prec) {
format!("({})", e2)
} else {
format!("{}", e2)
};
write!(fmt, "{} {} {}", left, o, right)
}
Exp::Bool(b) => write!(fmt, "{}", b),
Exp::Call(ref func, ref args) => {
try!(write!(fmt, "{}(", func));
for (i, arg) in args.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", arg));
}
write!(fmt, ")")
}
Exp::Defun(ref opt, ref params, ref body) => {
try!(write!(fmt, "function"));
if let &Some(ref func) = opt {
try!(write!(fmt, " {}", func));
}
try!(write!(fmt, "("));
for (i, param) in params.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", param));
}
try!(write!(fmt, ") {{\n"));
try!(body.fmt_helper(&mut fmt, indent_level + 2));
let indent : String = (0..indent_level).map(|_| " ").collect();
write!(fmt, "{}}}", indent)
}
Exp::Float(f) => write!(fmt, "{}", f),
Exp::InstanceVar(ref obj, ref name) => write!(fmt, "{}.{}", obj, name),
Exp::Neg(ref e) => write!(fmt, "-{}", group!(e, Precedence::Sign)),
Exp::NewObject(ref name, ref args) => {
try!(write!(fmt, "new {}(", name));
for (i, arg) in args.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", arg))
}
write!(fmt, ")")
}
Exp::Null => write!(fmt, "null"),
Exp::Object(ref properties) => {
if properties.is_empty() {
return write!(fmt, "{{}}");
}
try!(writeln!(fmt, "{{"));
let indent : String = (0..indent_level + 2).map(|_| " ").collect();
for (i, &(ref name, ref prop)) in properties.iter().enumerate() {
if i != 0 {
try!(writeln!(fmt, ","));
}
try!(write!(fmt, "{}{}: ", indent, name));
try!(prop.fmt_helper(&mut fmt, indent_level + 2));
}
write!(fmt, "\n}}")
}
Exp::Pos(ref e) => write!(fmt, "+{}", group!(e, Precedence::Sign)),
Exp::PostDec(ref e) => write!(fmt, "{}--", group!(e, Precedence::Inc)),
Exp::PostInc(ref e) => write!(fmt, "{}++", group!(e, Precedence::Inc)),
Exp::PreDec(ref e) => write!(fmt, "--{}", group!(e, Precedence::Inc)),
Exp::PreInc(ref e) => write!(fmt, "++{}", group!(e, Precedence::Inc)),
Exp::Undefined => write!(fmt, "undefined"),
Exp::Var(ref v) => write!(fmt, "{}", v),
}
}
}
impl Display for Exp {
fn fmt(&self, mut fmt: &mut Formatter) -> Result<(), Error> {
self.fmt_helper(&mut fmt, 0)
}
}
#[derive(Clone, Debug)]
pub enum Stmt {
Assign(String, Exp),
BareExp(Exp),
Decl(String, Exp),
If(Exp, Box<Stmt>, Option<Box<Stmt>>),
Ret(Exp),
Seq(Box<Stmt>, Box<Stmt>),
While(Exp, Box<Stmt>),
}
impl Stmt {
fn fmt_helper(&self, mut fmt: &mut Formatter, indent_level: i32) -> Result<(), Error> {
macro_rules! indented_stmt {
($stmt:expr) => {
try!($stmt.fmt_helper(&mut fmt, indent_level + 2))
}
}
macro_rules! exp_semi {
($exp:expr) => {{
try!($exp.fmt_helper(&mut fmt, indent_level));
writeln!(fmt, ";")
}}
}
let indent : String = (0..indent_level).map(|_| " ").collect();
match *self {
Stmt::Assign(ref v, ref exp) => {
try!(write!(fmt, "{}{} = ", indent, v));
exp_semi!(exp)
}
Stmt::BareExp(ref exp) => {
try!(write!(fmt, "{}", indent));
exp_semi!(exp)
}
Stmt::Decl(ref v, ref exp) => {
try!(write!(fmt, "{}var {} = ", indent, v));
exp_semi!(exp)
}
Stmt::If(ref e, ref s, ref els) => {
try!(write!(fmt, "{}if (", indent));
try!(e.fmt_helper(&mut fmt, indent_level + 2));
try!(writeln!(fmt, ") {{\n"));
indented_stmt!(s);
if let &Some(ref stmt) = els {
try!(write!(fmt, "{}else {{\n", indent));
indented_stmt!(stmt);
try!(write!(fmt, "{}}}\n", indent));
}
Ok(())
}
Stmt::Ret(ref e) => {
try!(write!(fmt, "{}return ", indent));
exp_semi!(e)
}
Stmt::Seq(ref s1, ref s2) => {
try!(s1.fmt_helper(&mut fmt, indent_level));
s2.fmt_helper(&mut fmt, indent_level)
}
Stmt::While(ref exp, ref stmt) => {
try!(write!(fmt, "{}while ({}) {{\n", indent, exp));
try!(stmt.fmt_helper(&mut fmt, indent_level + 2));
write!(fmt, "{}}}\n", indent)
}
}
}
}
impl Display for Stmt {
fn fmt(&self, mut fmt: &mut Formatter) -> Result<(), Error> {
self.fmt_helper(&mut fmt, 0)
}
}
add AST nodes for `throw` and `typeof`
use std::fmt::{Display, Error, Formatter};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinOp {
And,
Ge,
Gt,
Eql,
Le,
Lt,
Minus,
Neq,
Or,
Plus,
Slash,
Star,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Precedence {
Const = 110,
Sign = 100,
Inc = 90,
Mult = 70,
Add = 60,
Equality = 50,
And = 40,
Or = 30,
}
impl BinOp {
pub fn precedence(&self) -> Precedence {
match *self {
BinOp::And => Precedence::And,
BinOp::Ge | BinOp::Gt | BinOp::Eql | BinOp::Le | BinOp::Lt |
BinOp::Neq => Precedence::Equality,
BinOp::Or => Precedence::Or,
BinOp::Minus | BinOp::Plus => Precedence::Add,
BinOp::Slash | BinOp::Star => Precedence::Mult,
}
}
pub fn is_commutative(&self) -> bool {
match *self {
BinOp::Minus | BinOp::Slash => false,
_ => true
}
}
}
impl Display for BinOp {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
match *self {
BinOp::And => write!(fmt, "&&"),
BinOp::Ge => write!(fmt, ">="),
BinOp::Gt => write!(fmt, ">"),
BinOp::Eql => write!(fmt, "=="),
BinOp::Le => write!(fmt, "<="),
BinOp::Lt => write!(fmt, "<"),
BinOp::Minus => write!(fmt, "-"),
BinOp::Neq => write!(fmt, "!="),
BinOp::Or => write!(fmt, "||"),
BinOp::Plus => write!(fmt, "+"),
BinOp::Slash => write!(fmt, "/"),
BinOp::Star => write!(fmt, "*"),
}
}
}
#[derive(Clone, Debug)]
pub enum Exp {
BinExp(Box<Exp>, BinOp, Box<Exp>),
Bool(bool),
Call(Box<Exp>, Vec<Box<Exp>>),
Defun(Option<String>, Vec<String>, Box<Stmt>),
Float(f64),
InstanceVar(Box<Exp>, String),
Neg(Box<Exp>),
Null,
NewObject(Box<Exp>, Vec<Box<Exp>>),
Object(Vec<(String, Box<Exp>)>),
Pos(Box<Exp>),
PostDec(Box<Exp>),
PostInc(Box<Exp>),
PreDec(Box<Exp>),
PreInc(Box<Exp>),
TypeOf(Box<Exp>),
Undefined,
Var(String),
}
impl Exp {
pub fn precedence(&self) -> Precedence {
match *self {
Exp::BinExp(_, ref o, _) => o.precedence(),
Exp::Bool(_) | Exp::Call(..) | Exp::Defun(..) | Exp::Float(_) | Exp::InstanceVar(..) |
Exp::NewObject(..) | Exp::Null | Exp::Object(_) | Exp::TypeOf(_) | Exp::Undefined |
Exp::Var(_) => Precedence::Const,
Exp::Neg(_) | Exp::Pos(_) => Precedence::Sign,
Exp::PostDec(_) | Exp::PostInc(_) | Exp::PreDec(_) | Exp::PreInc(_) => Precedence::Inc,
}
}
}
macro_rules! group {
($e:expr, $p:expr) => {
if $e.precedence() < $p {
format!("({})", $e)
} else {
format!("{}", $e)
}
}
}
impl Exp {
fn fmt_helper(&self, mut fmt: &mut Formatter, indent_level: i32) -> Result<(), Error> {
match *self {
Exp::BinExp(ref e1, ref o, ref e2) => {
let prec = self.precedence();
// Put grouping parentheses if the left subexpression has a lower-precedence
// operator, e.g. (1 + 2) * 3
let left = if prec > e1.precedence() {
format!("({})", e1)
} else {
format!("{}", e1)
};
let right_prec = e2.precedence();
// Put grouping parentheses around the right subexpression if it has a
// lower-precedence operator, __OR__ if `o` is not commutative and the precedence
// is the same, e.g. (1 + 2) * 3 __OR__ 1 - (2 + 3)
let right = if prec > right_prec || (!o.is_commutative() && prec == right_prec) {
format!("({})", e2)
} else {
format!("{}", e2)
};
write!(fmt, "{} {} {}", left, o, right)
}
Exp::Bool(b) => write!(fmt, "{}", b),
Exp::Call(ref func, ref args) => {
try!(write!(fmt, "{}(", func));
for (i, arg) in args.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", arg));
}
write!(fmt, ")")
}
Exp::Defun(ref opt, ref params, ref body) => {
try!(write!(fmt, "function"));
if let &Some(ref func) = opt {
try!(write!(fmt, " {}", func));
}
try!(write!(fmt, "("));
for (i, param) in params.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", param));
}
try!(write!(fmt, ") {{\n"));
try!(body.fmt_helper(&mut fmt, indent_level + 2));
let indent : String = (0..indent_level).map(|_| " ").collect();
write!(fmt, "{}}}", indent)
}
Exp::Float(f) => write!(fmt, "{}", f),
Exp::InstanceVar(ref obj, ref name) => write!(fmt, "{}.{}", obj, name),
Exp::Neg(ref e) => write!(fmt, "-{}", group!(e, Precedence::Sign)),
Exp::NewObject(ref name, ref args) => {
try!(write!(fmt, "new {}(", name));
for (i, arg) in args.iter().enumerate() {
if i != 0 {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", arg))
}
write!(fmt, ")")
}
Exp::Null => write!(fmt, "null"),
Exp::Object(ref properties) => {
if properties.is_empty() {
return write!(fmt, "{{}}");
}
try!(writeln!(fmt, "{{"));
let indent : String = (0..indent_level + 2).map(|_| " ").collect();
for (i, &(ref name, ref prop)) in properties.iter().enumerate() {
if i != 0 {
try!(writeln!(fmt, ","));
}
try!(write!(fmt, "{}{}: ", indent, name));
try!(prop.fmt_helper(&mut fmt, indent_level + 2));
}
write!(fmt, "\n}}")
}
Exp::Pos(ref e) => write!(fmt, "+{}", group!(e, Precedence::Sign)),
Exp::PostDec(ref e) => write!(fmt, "{}--", group!(e, Precedence::Inc)),
Exp::PostInc(ref e) => write!(fmt, "{}++", group!(e, Precedence::Inc)),
Exp::PreDec(ref e) => write!(fmt, "--{}", group!(e, Precedence::Inc)),
Exp::PreInc(ref e) => write!(fmt, "++{}", group!(e, Precedence::Inc)),
Exp::TypeOf(ref e) => write!(fmt, "typeof {}", e),
Exp::Undefined => write!(fmt, "undefined"),
Exp::Var(ref v) => write!(fmt, "{}", v),
}
}
}
impl Display for Exp {
fn fmt(&self, mut fmt: &mut Formatter) -> Result<(), Error> {
self.fmt_helper(&mut fmt, 0)
}
}
#[derive(Clone, Debug)]
pub enum Stmt {
Assign(String, Exp),
BareExp(Exp),
Decl(String, Exp),
If(Exp, Box<Stmt>, Option<Box<Stmt>>),
Ret(Exp),
Seq(Box<Stmt>, Box<Stmt>),
Throw(Box<Exp>),
While(Exp, Box<Stmt>),
}
impl Stmt {
fn fmt_helper(&self, mut fmt: &mut Formatter, indent_level: i32) -> Result<(), Error> {
macro_rules! indented_stmt {
($stmt:expr) => {
try!($stmt.fmt_helper(&mut fmt, indent_level + 2))
}
}
macro_rules! exp_semi {
($exp:expr) => {{
try!($exp.fmt_helper(&mut fmt, indent_level));
writeln!(fmt, ";")
}}
}
let indent : String = (0..indent_level).map(|_| " ").collect();
match *self {
Stmt::Assign(ref v, ref exp) => {
try!(write!(fmt, "{}{} = ", indent, v));
exp_semi!(exp)
}
Stmt::BareExp(ref exp) => {
try!(write!(fmt, "{}", indent));
exp_semi!(exp)
}
Stmt::Decl(ref v, ref exp) => {
try!(write!(fmt, "{}var {} = ", indent, v));
exp_semi!(exp)
}
Stmt::If(ref e, ref s, ref els) => {
try!(write!(fmt, "{}if (", indent));
try!(e.fmt_helper(&mut fmt, indent_level + 2));
try!(writeln!(fmt, ") {{\n"));
indented_stmt!(s);
if let &Some(ref stmt) = els {
try!(write!(fmt, "{}else {{\n", indent));
indented_stmt!(stmt);
try!(write!(fmt, "{}}}\n", indent));
}
Ok(())
}
Stmt::Ret(ref e) => {
try!(write!(fmt, "{}return ", indent));
exp_semi!(e)
}
Stmt::Seq(ref s1, ref s2) => {
try!(s1.fmt_helper(&mut fmt, indent_level));
s2.fmt_helper(&mut fmt, indent_level)
}
Stmt::Throw(ref e) => {
write!(fmt, "{}throw {}", indent, e)
}
Stmt::While(ref exp, ref stmt) => {
try!(write!(fmt, "{}while ({}) {{\n", indent, exp));
try!(stmt.fmt_helper(&mut fmt, indent_level + 2));
write!(fmt, "{}}}\n", indent)
}
}
}
}
impl Display for Stmt {
fn fmt(&self, mut fmt: &mut Formatter) -> Result<(), Error> {
self.fmt_helper(&mut fmt, 0)
}
}
|
use std::path::Path;
use std::io;
use std::fs::File;
use std::convert;
use std::time::Duration;
use lru_time_cache::LruCache;
use serde_json;
use gerrit;
use spark;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
spark_person_id: spark::PersonId,
/// email of the user; assumed to be the same in Spark and Gerrit
email: spark::Email,
enabled: bool,
}
impl User {
fn new(person_id: spark::PersonId, email: spark::Email) -> User {
User {
spark_person_id: person_id,
email: email,
enabled: true,
}
}
}
/// Cache line in LRU Cache containing last approval messages
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MsgCacheLine {
/// position of the user in bots.user vector
user_ref: usize,
subject: String,
approver: String,
approval_type: String,
approval_value: String,
}
impl MsgCacheLine {
fn new(
user_ref: usize,
subject: String,
approver: String,
approval_type: String,
approval_value: String,
) -> MsgCacheLine {
MsgCacheLine {
user_ref: user_ref,
subject: subject,
approver: approver,
approval_type: approval_type,
approval_value: approval_value,
}
}
}
/// Describes a state of the bot
#[derive(Clone, Serialize, Deserialize)]
pub struct Bot {
users: Vec<User>,
/// We use Option<Cache> here, to be able to create an empty bot without initializing the
/// cache.
#[serde(skip_serializing, skip_deserializing)]
msg_cache: Option<LruCache<MsgCacheLine, ()>>,
}
#[derive(Debug)]
pub enum BotError {
Io(io::Error),
Serialization(serde_json::Error),
}
impl convert::From<io::Error> for BotError {
fn from(err: io::Error) -> BotError {
BotError::Io(err)
}
}
impl convert::From<serde_json::Error> for BotError {
fn from(err: serde_json::Error) -> BotError {
BotError::Serialization(err)
}
}
fn format_approval_value(value: &str, approval_type: &str) -> String {
let value: i8 = value.parse().unwrap_or(0);
let sign = if value > 0 { "+" } else { "" };
let icon = if approval_type.contains("WaitForVerification") {
"⌛"
} else if value > 0 {
"👍"
} else if value == 0 {
"👉"
} else {
"👎"
};
// TODO: when Spark will allow to format text with different colors, set
// green resp. red color here.
format!("{} {}{}", icon, sign, value)
}
impl Bot {
pub fn new() -> Bot {
Bot {
users: Vec::new(),
msg_cache: None,
}
}
#[allow(dead_code)]
pub fn with_msg_cache(capacity: usize, expiration: Duration) -> Bot {
Bot {
users: Vec::new(),
msg_cache: Some(
LruCache::<MsgCacheLine, ()>::with_expiry_duration_and_capacity(
expiration,
capacity,
),
),
}
}
pub fn init_msg_cache(&mut self, capacity: usize, expiration: Duration) {
self.msg_cache =
Some(
LruCache::<MsgCacheLine, ()>::with_expiry_duration_and_capacity(expiration, capacity),
);
}
fn add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
self.users.push(User::new(
String::from(person_id),
String::from(email),
));
self.users.last_mut().unwrap()
}
fn find_or_add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
let pos = self.users.iter().position(
|u| u.spark_person_id == person_id,
);
let user: &'a mut User = match pos {
Some(pos) => &mut self.users[pos],
None => self.add_user(person_id, email),
};
user
}
fn enable<'a>(&'a mut self, person_id: &str, email: &str, enabled: bool) -> &'a User {
let user: &'a mut User = self.find_or_add_user(person_id, email);
user.enabled = enabled;
user
}
fn get_approvals_msg(&mut self, event: gerrit::Event) -> Option<(&User, String)> {
debug!("Incoming approvals: {:?}", event);
let approvals = tryopt![event.approvals];
let change = event.change;
let approver = &event.author.as_ref().unwrap().username;
if approver == &change.owner.username {
// No need to notify about user's own approvals.
return None;
}
let owner_email = tryopt![change.owner.email.as_ref()];
// TODO: Fix linear search
let user_pos = tryopt![
self.users.iter().position(
|u| u.enabled && &u.email == owner_email
)// bug in rustfmt: it adds ',' automatically
];
let msgs: Vec<String> = approvals
.iter()
.filter_map(|approval| {
// filter if there was no previous value, or value did not change, or it is 0
let filtered = !approval
.old_value
.as_ref()
.map(|old_value| {
old_value != &approval.value && approval.value != "0"
})
.unwrap_or(false);
debug!("Filtered approval: {:?}", filtered);
if filtered {
return None;
}
// filter all messages that were already sent to the user recently
if let Some(cache) = self.msg_cache.as_mut() {
let key = MsgCacheLine::new(
user_pos,
if change.topic.is_some() {
change.topic.as_ref().unwrap().clone()
} else {
change.subject.clone()
},
approver.clone(),
approval.approval_type.clone(),
approval.value.clone(),
);
let hit = cache.get(&key).is_some();
if hit {
debug!("Filtered approval due to cache hit.");
return None;
} else {
cache.insert(key, ());
}
};
Some(format!(
"[{}]({}) {} ({}) from {}",
change.subject,
change.url,
format_approval_value(
&approval.value,
&approval.approval_type,
),
approval.approval_type,
approver
))
})
.collect();
if !msgs.is_empty() {
Some((&self.users[user_pos], msgs.join("\n\n"))) // two newlines since it is markdown
} else {
None
}
}
pub fn save<P>(self, filename: P) -> Result<(), BotError>
where
P: AsRef<Path>,
{
let f = File::create(filename)?;
serde_json::to_writer(f, &self)?;
Ok(())
}
pub fn load<P>(filename: P) -> Result<Self, BotError>
where
P: AsRef<Path>,
{
let f = File::open(filename)?;
let bot: Bot = serde_json::from_reader(f)?;
Ok(bot)
}
pub fn num_users(&self) -> usize {
self.users.len()
}
pub fn status_for(&self, person_id: &str) -> String {
let user = self.users.iter().find(|u| u.spark_person_id == person_id);
let enabled = user.map_or(false, |u| u.enabled);
format!(
"Notifications for you are **{}**. Besides you, I am notifying another {} user(s).",
if enabled { "enabled" } else { "disabled" },
self.num_users() - 1
)
}
}
#[derive(Debug)]
pub enum Action {
Enable(spark::PersonId, spark::Email),
Disable(spark::PersonId, spark::Email),
UpdateApprovals(gerrit::Event),
Help(spark::PersonId),
Unknown(spark::PersonId),
Status(spark::PersonId),
NoOp,
}
#[derive(Debug)]
pub struct Response {
pub person_id: spark::PersonId,
pub message: String,
}
impl Response {
pub fn new(person_id: spark::PersonId, message: String) -> Response {
Response {
person_id: person_id,
message: message,
}
}
}
#[derive(Debug)]
pub enum Task {
Reply(Response),
ReplyAndSave(Response),
}
const GREETINGS_MSG: &'static str =
r#"Hi. I am GerritBot (**in a very early alpha**). I can watch Gerrit reviews for you, and notify you about new +1/-1's.
To enable notifications, just type in 'enable'. A small note: your email in Spark and in Gerrit has to be the same. Otherwise, I can't match your accounts.
For more information, type in **help**.
By the way, my icon is made by
[ Madebyoliver ](http://www.flaticon.com/authors/madebyoliver)
from
[ www.flaticon.com ](http://www.flaticon.com)
and is licensed by
[ CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
"#;
const HELP_MSG: &'static str = r#"Commands:
`enable` I will start notifying you.
`disable` I will stop notifying you.
`status` Show if I am notifying you, and a little bit more information. 😉
`help` This message
"#;
/// Action controller
/// Return new bot state and an optional message to send to the user
pub fn update(action: Action, bot: Bot) -> (Bot, Option<Task>) {
let mut bot = bot;
let task = match action {
Action::Enable(person_id, email) => {
bot.enable(&person_id, &email, true);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! Happy reviewing!"),
));
Some(task)
}
Action::Disable(person_id, email) => {
bot.enable(&person_id, &email, false);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! I will stay silent."),
));
Some(task)
}
Action::UpdateApprovals(event) => {
bot.get_approvals_msg(event).map(|(user, message)| {
Task::Reply(Response::new(user.spark_person_id.clone(), message))
})
}
Action::Help(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(HELP_MSG)),
))
}
Action::Unknown(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(GREETINGS_MSG)),
))
}
Action::Status(person_id) => {
let status = bot.status_for(&person_id);
Some(Task::Reply(Response::new(person_id, status)))
}
_ => None,
};
(bot, task)
}
#[cfg(test)]
mod test {
use std::time::Duration;
use std::thread;
use serde_json;
use gerrit;
use super::{Bot, User};
#[test]
fn add_user() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
assert_eq!(bot.users.len(), 1);
assert_eq!(bot.users[0].spark_person_id, "some_person_id");
assert_eq!(bot.users[0].email, "some@example.com");
assert!(bot.users[0].enabled);
}
#[test]
fn status_for() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
let resp = bot.status_for("some_person_id");
assert!(resp.contains("enabled"));
bot.users[0].enabled = false;
let resp = bot.status_for("some_person_id");
assert!(resp.contains("disabled"));
let resp = bot.status_for("some_non_existent_id");
assert!(resp.contains("disabled"));
}
#[test]
fn enable_non_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users + 1);
};
test(true);
test(false);
}
#[test]
fn enable_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
bot.users.push(User::new(
String::from("some_person_id"),
String::from("some@example.com"),
));
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users);
};
test(true);
test(false);
}
const EVENT_JSON : &'static str = r#"
{"author":{"name":"Approver","username":"approver"},"approvals":[{"type":"Code-Review","description":"Code-Review","value":"2","oldValue":"-1"}],"comment":"Patch Set 1: Code-Review+2","patchSet":{"number":"1","revision":"49a65998c02eda928559f2d0b586c20bc8e37b10","parents":["fb1909b4eda306985d2bbce769310e5a50a98cf5"],"ref":"refs/changes/42/42/1","uploader":{"name":"Author","email":"author@example.com","username":"Author"},"createdOn":1494165142,"author":{"name":"Author","email":"author@example.com","username":"Author"},"isDraft":false,"kind":"REWORK","sizeInsertions":0,"sizeDeletions":0},"change":{"project":"demo-project","branch":"master","id":"Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14","number":"49","subject":"Some review.","owner":{"name":"Author","email":"author@example.com","username":"author"},"url":"http://localhost/42","commitMessage":"Some review.\n\nChange-Id: Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14\n","status":"NEW"},"project":"demo-project","refName":"refs/heads/master","changeKey":{"id":"Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14"},"type":"comment-added","eventCreatedOn":1499190282}"#;
fn get_event() -> gerrit::Event {
let event: Result<gerrit::Event, _> = serde_json::from_str(EVENT_JSON);
assert!(event.is_ok());
event.unwrap()
}
#[test]
fn get_approvals_msg_for_empty_bot() {
// bot does not have the user => no message
let mut bot = Bot::new();
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_same_author_and_approver() {
// the approval is from the author => no message
let mut bot = Bot::new();
bot.add_user("approver_spark_id", "approver@example.com");
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_user_with_disabled_notifications() {
// the approval is for the user with disabled notifications
// => no message
let mut bot = Bot::new();
bot.add_user("author_spark_id", "author@example.com");
bot.users[0].enabled = false;
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_user_with_enabled_notifications() {
// the approval is for the user with enabled notifications
// => message
let mut bot = Bot::new();
bot.add_user("author_spark_id", "author@example.com");
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
#[test]
fn get_approvals_msg_for_quickly_repeated_event() {
// same approval for the user with enabled notifications 2 times in less than 1 sec
// => first time get message, second time nothing
let mut bot = Bot::with_msg_cache(10, Duration::from_secs(1));
bot.add_user("author_spark_id", "author@example.com");
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
}
#[test]
fn get_approvals_msg_for_slowly_repeated_event() {
// same approval for the user with enabled notifications 2 times in more than 100 msec
// => get message 2 times
let mut bot = Bot::with_msg_cache(10, Duration::from_millis(50));
bot.add_user("author_spark_id", "author@example.com");
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
thread::sleep(Duration::from_millis(200));
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
}
#[test]
fn get_approvals_msg_for_bot_with_low_msgs_capacity() {
// same approval for the user with enabled notifications 2 times in more less 100 msec
// but there is also another approval and bot's msg capacity is 1
// => get message 3 times
let mut bot = Bot::with_msg_cache(1, Duration::from_secs(1));
bot.add_user("author_spark_id", "author@example.com");
{
let mut event = get_event();
event.change.subject = String::from("A");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
{
let mut event = get_event();
event.change.subject = String::from("B");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
{
let mut event = get_event();
event.change.subject = String::from("A");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
}
}
Replace alpha by beta in welcome message.
use std::path::Path;
use std::io;
use std::fs::File;
use std::convert;
use std::time::Duration;
use lru_time_cache::LruCache;
use serde_json;
use gerrit;
use spark;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
spark_person_id: spark::PersonId,
/// email of the user; assumed to be the same in Spark and Gerrit
email: spark::Email,
enabled: bool,
}
impl User {
fn new(person_id: spark::PersonId, email: spark::Email) -> User {
User {
spark_person_id: person_id,
email: email,
enabled: true,
}
}
}
/// Cache line in LRU Cache containing last approval messages
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MsgCacheLine {
/// position of the user in bots.user vector
user_ref: usize,
subject: String,
approver: String,
approval_type: String,
approval_value: String,
}
impl MsgCacheLine {
fn new(
user_ref: usize,
subject: String,
approver: String,
approval_type: String,
approval_value: String,
) -> MsgCacheLine {
MsgCacheLine {
user_ref: user_ref,
subject: subject,
approver: approver,
approval_type: approval_type,
approval_value: approval_value,
}
}
}
/// Describes a state of the bot
#[derive(Clone, Serialize, Deserialize)]
pub struct Bot {
users: Vec<User>,
/// We use Option<Cache> here, to be able to create an empty bot without initializing the
/// cache.
#[serde(skip_serializing, skip_deserializing)]
msg_cache: Option<LruCache<MsgCacheLine, ()>>,
}
#[derive(Debug)]
pub enum BotError {
Io(io::Error),
Serialization(serde_json::Error),
}
impl convert::From<io::Error> for BotError {
fn from(err: io::Error) -> BotError {
BotError::Io(err)
}
}
impl convert::From<serde_json::Error> for BotError {
fn from(err: serde_json::Error) -> BotError {
BotError::Serialization(err)
}
}
fn format_approval_value(value: &str, approval_type: &str) -> String {
let value: i8 = value.parse().unwrap_or(0);
let sign = if value > 0 { "+" } else { "" };
let icon = if approval_type.contains("WaitForVerification") {
"⌛"
} else if value > 0 {
"👍"
} else if value == 0 {
"👉"
} else {
"👎"
};
// TODO: when Spark will allow to format text with different colors, set
// green resp. red color here.
format!("{} {}{}", icon, sign, value)
}
impl Bot {
pub fn new() -> Bot {
Bot {
users: Vec::new(),
msg_cache: None,
}
}
#[allow(dead_code)]
pub fn with_msg_cache(capacity: usize, expiration: Duration) -> Bot {
Bot {
users: Vec::new(),
msg_cache: Some(
LruCache::<MsgCacheLine, ()>::with_expiry_duration_and_capacity(
expiration,
capacity,
),
),
}
}
pub fn init_msg_cache(&mut self, capacity: usize, expiration: Duration) {
self.msg_cache =
Some(
LruCache::<MsgCacheLine, ()>::with_expiry_duration_and_capacity(expiration, capacity),
);
}
fn add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
self.users.push(User::new(
String::from(person_id),
String::from(email),
));
self.users.last_mut().unwrap()
}
fn find_or_add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
let pos = self.users.iter().position(
|u| u.spark_person_id == person_id,
);
let user: &'a mut User = match pos {
Some(pos) => &mut self.users[pos],
None => self.add_user(person_id, email),
};
user
}
fn enable<'a>(&'a mut self, person_id: &str, email: &str, enabled: bool) -> &'a User {
let user: &'a mut User = self.find_or_add_user(person_id, email);
user.enabled = enabled;
user
}
fn get_approvals_msg(&mut self, event: gerrit::Event) -> Option<(&User, String)> {
debug!("Incoming approvals: {:?}", event);
let approvals = tryopt![event.approvals];
let change = event.change;
let approver = &event.author.as_ref().unwrap().username;
if approver == &change.owner.username {
// No need to notify about user's own approvals.
return None;
}
let owner_email = tryopt![change.owner.email.as_ref()];
// TODO: Fix linear search
let user_pos = tryopt![
self.users.iter().position(
|u| u.enabled && &u.email == owner_email
)// bug in rustfmt: it adds ',' automatically
];
let msgs: Vec<String> = approvals
.iter()
.filter_map(|approval| {
// filter if there was no previous value, or value did not change, or it is 0
let filtered = !approval
.old_value
.as_ref()
.map(|old_value| {
old_value != &approval.value && approval.value != "0"
})
.unwrap_or(false);
debug!("Filtered approval: {:?}", filtered);
if filtered {
return None;
}
// filter all messages that were already sent to the user recently
if let Some(cache) = self.msg_cache.as_mut() {
let key = MsgCacheLine::new(
user_pos,
if change.topic.is_some() {
change.topic.as_ref().unwrap().clone()
} else {
change.subject.clone()
},
approver.clone(),
approval.approval_type.clone(),
approval.value.clone(),
);
let hit = cache.get(&key).is_some();
if hit {
debug!("Filtered approval due to cache hit.");
return None;
} else {
cache.insert(key, ());
}
};
Some(format!(
"[{}]({}) {} ({}) from {}",
change.subject,
change.url,
format_approval_value(
&approval.value,
&approval.approval_type,
),
approval.approval_type,
approver
))
})
.collect();
if !msgs.is_empty() {
Some((&self.users[user_pos], msgs.join("\n\n"))) // two newlines since it is markdown
} else {
None
}
}
pub fn save<P>(self, filename: P) -> Result<(), BotError>
where
P: AsRef<Path>,
{
let f = File::create(filename)?;
serde_json::to_writer(f, &self)?;
Ok(())
}
pub fn load<P>(filename: P) -> Result<Self, BotError>
where
P: AsRef<Path>,
{
let f = File::open(filename)?;
let bot: Bot = serde_json::from_reader(f)?;
Ok(bot)
}
pub fn num_users(&self) -> usize {
self.users.len()
}
pub fn status_for(&self, person_id: &str) -> String {
let user = self.users.iter().find(|u| u.spark_person_id == person_id);
let enabled = user.map_or(false, |u| u.enabled);
format!(
"Notifications for you are **{}**. Besides you, I am notifying another {} user(s).",
if enabled { "enabled" } else { "disabled" },
self.num_users() - 1
)
}
}
#[derive(Debug)]
pub enum Action {
Enable(spark::PersonId, spark::Email),
Disable(spark::PersonId, spark::Email),
UpdateApprovals(gerrit::Event),
Help(spark::PersonId),
Unknown(spark::PersonId),
Status(spark::PersonId),
NoOp,
}
#[derive(Debug)]
pub struct Response {
pub person_id: spark::PersonId,
pub message: String,
}
impl Response {
pub fn new(person_id: spark::PersonId, message: String) -> Response {
Response {
person_id: person_id,
message: message,
}
}
}
#[derive(Debug)]
pub enum Task {
Reply(Response),
ReplyAndSave(Response),
}
const GREETINGS_MSG: &'static str =
r#"Hi. I am GerritBot (**in a beta phase**). I can watch Gerrit reviews for you, and notify you about new +1/-1's.
To enable notifications, just type in 'enable'. A small note: your email in Spark and in Gerrit has to be the same. Otherwise, I can't match your accounts.
For more information, type in **help**.
By the way, my icon is made by
[ Madebyoliver ](http://www.flaticon.com/authors/madebyoliver)
from
[ www.flaticon.com ](http://www.flaticon.com)
and is licensed by
[ CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
"#;
const HELP_MSG: &'static str = r#"Commands:
`enable` I will start notifying you.
`disable` I will stop notifying you.
`status` Show if I am notifying you, and a little bit more information. 😉
`help` This message
"#;
/// Action controller
/// Return new bot state and an optional message to send to the user
pub fn update(action: Action, bot: Bot) -> (Bot, Option<Task>) {
let mut bot = bot;
let task = match action {
Action::Enable(person_id, email) => {
bot.enable(&person_id, &email, true);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! Happy reviewing!"),
));
Some(task)
}
Action::Disable(person_id, email) => {
bot.enable(&person_id, &email, false);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! I will stay silent."),
));
Some(task)
}
Action::UpdateApprovals(event) => {
bot.get_approvals_msg(event).map(|(user, message)| {
Task::Reply(Response::new(user.spark_person_id.clone(), message))
})
}
Action::Help(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(HELP_MSG)),
))
}
Action::Unknown(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(GREETINGS_MSG)),
))
}
Action::Status(person_id) => {
let status = bot.status_for(&person_id);
Some(Task::Reply(Response::new(person_id, status)))
}
_ => None,
};
(bot, task)
}
#[cfg(test)]
mod test {
use std::time::Duration;
use std::thread;
use serde_json;
use gerrit;
use super::{Bot, User};
#[test]
fn add_user() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
assert_eq!(bot.users.len(), 1);
assert_eq!(bot.users[0].spark_person_id, "some_person_id");
assert_eq!(bot.users[0].email, "some@example.com");
assert!(bot.users[0].enabled);
}
#[test]
fn status_for() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
let resp = bot.status_for("some_person_id");
assert!(resp.contains("enabled"));
bot.users[0].enabled = false;
let resp = bot.status_for("some_person_id");
assert!(resp.contains("disabled"));
let resp = bot.status_for("some_non_existent_id");
assert!(resp.contains("disabled"));
}
#[test]
fn enable_non_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users + 1);
};
test(true);
test(false);
}
#[test]
fn enable_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
bot.users.push(User::new(
String::from("some_person_id"),
String::from("some@example.com"),
));
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users);
};
test(true);
test(false);
}
const EVENT_JSON : &'static str = r#"
{"author":{"name":"Approver","username":"approver"},"approvals":[{"type":"Code-Review","description":"Code-Review","value":"2","oldValue":"-1"}],"comment":"Patch Set 1: Code-Review+2","patchSet":{"number":"1","revision":"49a65998c02eda928559f2d0b586c20bc8e37b10","parents":["fb1909b4eda306985d2bbce769310e5a50a98cf5"],"ref":"refs/changes/42/42/1","uploader":{"name":"Author","email":"author@example.com","username":"Author"},"createdOn":1494165142,"author":{"name":"Author","email":"author@example.com","username":"Author"},"isDraft":false,"kind":"REWORK","sizeInsertions":0,"sizeDeletions":0},"change":{"project":"demo-project","branch":"master","id":"Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14","number":"49","subject":"Some review.","owner":{"name":"Author","email":"author@example.com","username":"author"},"url":"http://localhost/42","commitMessage":"Some review.\n\nChange-Id: Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14\n","status":"NEW"},"project":"demo-project","refName":"refs/heads/master","changeKey":{"id":"Ic160fa37fca005fec17a2434aadf0d9dcfbb7b14"},"type":"comment-added","eventCreatedOn":1499190282}"#;
fn get_event() -> gerrit::Event {
let event: Result<gerrit::Event, _> = serde_json::from_str(EVENT_JSON);
assert!(event.is_ok());
event.unwrap()
}
#[test]
fn get_approvals_msg_for_empty_bot() {
// bot does not have the user => no message
let mut bot = Bot::new();
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_same_author_and_approver() {
// the approval is from the author => no message
let mut bot = Bot::new();
bot.add_user("approver_spark_id", "approver@example.com");
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_user_with_disabled_notifications() {
// the approval is for the user with disabled notifications
// => no message
let mut bot = Bot::new();
bot.add_user("author_spark_id", "author@example.com");
bot.users[0].enabled = false;
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
#[test]
fn get_approvals_msg_for_user_with_enabled_notifications() {
// the approval is for the user with enabled notifications
// => message
let mut bot = Bot::new();
bot.add_user("author_spark_id", "author@example.com");
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
#[test]
fn get_approvals_msg_for_quickly_repeated_event() {
// same approval for the user with enabled notifications 2 times in less than 1 sec
// => first time get message, second time nothing
let mut bot = Bot::with_msg_cache(10, Duration::from_secs(1));
bot.add_user("author_spark_id", "author@example.com");
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_none());
}
}
#[test]
fn get_approvals_msg_for_slowly_repeated_event() {
// same approval for the user with enabled notifications 2 times in more than 100 msec
// => get message 2 times
let mut bot = Bot::with_msg_cache(10, Duration::from_millis(50));
bot.add_user("author_spark_id", "author@example.com");
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
thread::sleep(Duration::from_millis(200));
{
let res = bot.get_approvals_msg(get_event());
assert!(res.is_some());
let (user, msg) = res.unwrap();
assert_eq!(user.spark_person_id, "author_spark_id");
assert_eq!(user.email, "author@example.com");
assert!(msg.contains("Some review."));
}
}
#[test]
fn get_approvals_msg_for_bot_with_low_msgs_capacity() {
// same approval for the user with enabled notifications 2 times in more less 100 msec
// but there is also another approval and bot's msg capacity is 1
// => get message 3 times
let mut bot = Bot::with_msg_cache(1, Duration::from_secs(1));
bot.add_user("author_spark_id", "author@example.com");
{
let mut event = get_event();
event.change.subject = String::from("A");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
{
let mut event = get_event();
event.change.subject = String::from("B");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
{
let mut event = get_event();
event.change.subject = String::from("A");
let res = bot.get_approvals_msg(event);
assert!(res.is_some());
}
}
}
|
use std::path::Path;
use std::io;
use std::fs::File;
use std::convert;
use serde_json;
use gerrit;
use spark;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
spark_person_id: spark::PersonId,
/// email of the user; assumed to be the same in Spark and Gerrit
email: spark::Email,
enabled: bool,
}
impl User {
fn new(person_id: spark::PersonId, email: spark::Email) -> User {
User {
spark_person_id: person_id,
email: email,
enabled: true,
}
}
}
/// Describes a state of the bot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bot {
users: Vec<User>,
}
#[derive(Debug)]
pub enum BotError {
Io(io::Error),
Serialization(serde_json::Error),
}
impl convert::From<io::Error> for BotError {
fn from(err: io::Error) -> BotError {
BotError::Io(err)
}
}
impl convert::From<serde_json::Error> for BotError {
fn from(err: serde_json::Error) -> BotError {
BotError::Serialization(err)
}
}
fn format_approval_value(value: &str, comment: &str) -> String {
let value: i8 = value.parse().unwrap_or(0);
let sign = if value > 0 { "+" } else { "" };
let icon = if comment.contains("WaitForVerification-1") {
"⌛"
} else if value > 0 {
"👍"
} else if value == 0 {
"👉"
} else {
"👎"
};
// TODO: when Spark will allow to format text with different colors, set
// green resp. red color here.
format!("{} {}{}", icon, sign, value)
}
impl Bot {
pub fn new() -> Bot {
Bot { users: Vec::new() }
}
fn add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
self.users.push(User::new(
String::from(person_id),
String::from(email),
));
self.users.last_mut().unwrap()
}
fn find_or_add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
let pos = self.users.iter().position(
|u| u.spark_person_id == person_id,
);
let user: &'a mut User = match pos {
Some(pos) => &mut self.users[pos],
None => self.add_user(person_id, email),
};
user
}
fn enable<'a>(&'a mut self, person_id: &str, email: &str, enabled: bool) -> &'a User {
let user: &'a mut User = self.find_or_add_user(person_id, email);
user.enabled = enabled;
user
}
fn get_approvals_msg(&self, event: gerrit::Event) -> Option<(&User, String)> {
debug!("Incoming approvals: {:?}", event);
let author = event.author;
let change = event.change;
let approvals = event.approvals;
let comment = event.comment.unwrap_or_default();
let approver = author.unwrap().username.clone();
if approver == change.owner.username {
// No need to notify about user's own approvals.
return None;
}
if let Some(ref owner_email) = change.owner.email {
// TODO: Fix linear search
let users = &self.users;
for user in users.iter() {
if &user.email == owner_email {
if !user.enabled {
break;
}
if let Some(approvals) = approvals {
let msgs: Vec<String> = approvals
.iter()
.filter(|approval| {
let filtered = if let Some(ref old_value) = approval.old_value {
old_value != &approval.value && approval.value != "0"
} else {
approval.value != "0"
};
debug!("Filtered approval: {:?}", !filtered);
filtered
})
.map(|approval| {
format!(
"[{}]({}) {} ({}) from {}",
change.subject,
change.url,
format_approval_value(&approval.value, &comment),
approval.approval_type,
approver
)
})
.collect();
return if !msgs.is_empty() {
Some((user, msgs.join("\n\n"))) // two newlines since it is markdown
} else {
None
};
}
}
}
}
None
}
pub fn save<P>(self, filename: P) -> Result<(), BotError>
where
P: AsRef<Path>,
{
let f = File::create(filename)?;
serde_json::to_writer(f, &self)?;
Ok(())
}
pub fn load<P>(filename: P) -> Result<Self, BotError>
where
P: AsRef<Path>,
{
let f = File::open(filename)?;
let bot: Bot = serde_json::from_reader(f)?;
Ok(bot)
}
pub fn num_users(&self) -> usize {
self.users.len()
}
pub fn status_for(&self, person_id: &str) -> String {
let user = self.users.iter().find(|u| u.spark_person_id == person_id);
let enabled = user.map_or(false, |u| u.enabled);
format!(
"Notification for you are **{}**. I am notifying {} user(s).",
if enabled { "enabled" } else { "disabled" },
self.num_users()
)
}
}
#[derive(Debug)]
pub enum Action {
Enable(spark::PersonId, spark::Email),
Disable(spark::PersonId, spark::Email),
UpdateApprovals(gerrit::Event),
Help(spark::PersonId),
Unknown(spark::PersonId),
Status(spark::PersonId),
NoOp,
}
#[derive(Debug)]
pub struct Response {
pub person_id: spark::PersonId,
pub message: String,
}
impl Response {
pub fn new(person_id: spark::PersonId, message: String) -> Response {
Response {
person_id: person_id,
message: message,
}
}
}
#[derive(Debug)]
pub enum Task {
Reply(Response),
ReplyAndSave(Response),
}
const GREETINGS_MSG: &'static str =
r#"Hi. I am GerritBot (**in a very early alpha**). I can watch Gerrit reviews for you, and notify you about new +1/-1's.
To enable notifications, just type in 'enable'. A small note: your email in Spark and in Gerrit has to be the same. Otherwise, I can't match your accounts.
For more information, type in **help**.
By the way, my icon is made by
[ Madebyoliver ](http://www.flaticon.com/authors/madebyoliver)
from
[ www.flaticon.com ](http://www.flaticon.com)
and is licensed by
[ CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
"#;
const HELP_MSG: &'static str = r#"Commands:
`enable` I will start notifying you.
`disable` I will stop notifying you.
`status` Show if I am notifying you, and a little bit more information. 😉
`help` This message
"#;
/// Action controller
/// Return new bot state and an optional message to send to the user
pub fn update(action: Action, bot: Bot) -> (Bot, Option<Task>) {
let mut bot = bot;
let task = match action {
Action::Enable(person_id, email) => {
bot.enable(&person_id, &email, true);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! Happy reviewing!"),
));
Some(task)
}
Action::Disable(person_id, email) => {
bot.enable(&person_id, &email, false);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! I will stay silent."),
));
Some(task)
}
Action::UpdateApprovals(event) => {
bot.get_approvals_msg(event).map(|(user, message)| {
Task::Reply(Response::new(user.spark_person_id.clone(), message))
})
}
Action::Help(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(HELP_MSG)),
))
}
Action::Unknown(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(GREETINGS_MSG)),
))
}
Action::Status(person_id) => {
let status = bot.status_for(&person_id);
Some(Task::Reply(Response::new(person_id, status)))
}
_ => None,
};
(bot, task)
}
#[cfg(test)]
mod test {
use super::{Bot, User};
#[test]
fn test_add_user() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
assert_eq!(bot.users.len(), 1);
assert_eq!(bot.users[0].spark_person_id, "some_person_id");
assert_eq!(bot.users[0].email, "some@example.com");
assert!(bot.users[0].enabled);
}
#[test]
fn test_status_for() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
let resp = bot.status_for("some_person_id");
assert!(resp.contains("enabled"));
bot.users[0].enabled = false;
let resp = bot.status_for("some_person_id");
assert!(resp.contains("disabled"));
let resp = bot.status_for("some_non_existent_id");
assert!(resp.contains("disabled"));
}
#[test]
fn enable_non_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users + 1);
};
test(true);
test(false);
}
#[test]
fn enable_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
bot.users.push(User::new(
String::from("some_person_id"),
String::from("some@example.com"),
));
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users);
};
test(true);
test(false);
}
}
Show hourglass for approvals with wait for verification.
use std::path::Path;
use std::io;
use std::fs::File;
use std::convert;
use serde_json;
use gerrit;
use spark;
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
spark_person_id: spark::PersonId,
/// email of the user; assumed to be the same in Spark and Gerrit
email: spark::Email,
enabled: bool,
}
impl User {
fn new(person_id: spark::PersonId, email: spark::Email) -> User {
User {
spark_person_id: person_id,
email: email,
enabled: true,
}
}
}
/// Describes a state of the bot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bot {
users: Vec<User>,
}
#[derive(Debug)]
pub enum BotError {
Io(io::Error),
Serialization(serde_json::Error),
}
impl convert::From<io::Error> for BotError {
fn from(err: io::Error) -> BotError {
BotError::Io(err)
}
}
impl convert::From<serde_json::Error> for BotError {
fn from(err: serde_json::Error) -> BotError {
BotError::Serialization(err)
}
}
fn format_approval_value(value: &str, approval_type: &str) -> String {
let value: i8 = value.parse().unwrap_or(0);
let sign = if value > 0 { "+" } else { "" };
let icon = if approval_type.contains("WaitForVerification") {
"⌛"
} else if value > 0 {
"👍"
} else if value == 0 {
"👉"
} else {
"👎"
};
// TODO: when Spark will allow to format text with different colors, set
// green resp. red color here.
format!("{} {}{}", icon, sign, value)
}
impl Bot {
pub fn new() -> Bot {
Bot { users: Vec::new() }
}
fn add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
self.users.push(User::new(
String::from(person_id),
String::from(email),
));
self.users.last_mut().unwrap()
}
fn find_or_add_user<'a>(&'a mut self, person_id: &str, email: &str) -> &'a mut User {
let pos = self.users.iter().position(
|u| u.spark_person_id == person_id,
);
let user: &'a mut User = match pos {
Some(pos) => &mut self.users[pos],
None => self.add_user(person_id, email),
};
user
}
fn enable<'a>(&'a mut self, person_id: &str, email: &str, enabled: bool) -> &'a User {
let user: &'a mut User = self.find_or_add_user(person_id, email);
user.enabled = enabled;
user
}
fn get_approvals_msg(&self, event: gerrit::Event) -> Option<(&User, String)> {
debug!("Incoming approvals: {:?}", event);
let author = event.author;
let change = event.change;
let approvals = event.approvals;
let approver = author.unwrap().username.clone();
if approver == change.owner.username {
// No need to notify about user's own approvals.
return None;
}
if let Some(ref owner_email) = change.owner.email {
// TODO: Fix linear search
let users = &self.users;
for user in users.iter() {
if &user.email == owner_email {
if !user.enabled {
break;
}
if let Some(approvals) = approvals {
let msgs: Vec<String> = approvals
.iter()
.filter(|approval| {
let filtered = if let Some(ref old_value) = approval.old_value {
old_value != &approval.value && approval.value != "0"
} else {
approval.value != "0"
};
debug!("Filtered approval: {:?}", !filtered);
filtered
})
.map(|approval| {
format!(
"[{}]({}) {} ({}) from {}",
change.subject,
change.url,
format_approval_value(&approval.value, &approval.approval_type),
approval.approval_type,
approver
)
})
.collect();
return if !msgs.is_empty() {
Some((user, msgs.join("\n\n"))) // two newlines since it is markdown
} else {
None
};
}
}
}
}
None
}
pub fn save<P>(self, filename: P) -> Result<(), BotError>
where
P: AsRef<Path>,
{
let f = File::create(filename)?;
serde_json::to_writer(f, &self)?;
Ok(())
}
pub fn load<P>(filename: P) -> Result<Self, BotError>
where
P: AsRef<Path>,
{
let f = File::open(filename)?;
let bot: Bot = serde_json::from_reader(f)?;
Ok(bot)
}
pub fn num_users(&self) -> usize {
self.users.len()
}
pub fn status_for(&self, person_id: &str) -> String {
let user = self.users.iter().find(|u| u.spark_person_id == person_id);
let enabled = user.map_or(false, |u| u.enabled);
format!(
"Notification for you are **{}**. I am notifying {} user(s).",
if enabled { "enabled" } else { "disabled" },
self.num_users()
)
}
}
#[derive(Debug)]
pub enum Action {
Enable(spark::PersonId, spark::Email),
Disable(spark::PersonId, spark::Email),
UpdateApprovals(gerrit::Event),
Help(spark::PersonId),
Unknown(spark::PersonId),
Status(spark::PersonId),
NoOp,
}
#[derive(Debug)]
pub struct Response {
pub person_id: spark::PersonId,
pub message: String,
}
impl Response {
pub fn new(person_id: spark::PersonId, message: String) -> Response {
Response {
person_id: person_id,
message: message,
}
}
}
#[derive(Debug)]
pub enum Task {
Reply(Response),
ReplyAndSave(Response),
}
const GREETINGS_MSG: &'static str =
r#"Hi. I am GerritBot (**in a very early alpha**). I can watch Gerrit reviews for you, and notify you about new +1/-1's.
To enable notifications, just type in 'enable'. A small note: your email in Spark and in Gerrit has to be the same. Otherwise, I can't match your accounts.
For more information, type in **help**.
By the way, my icon is made by
[ Madebyoliver ](http://www.flaticon.com/authors/madebyoliver)
from
[ www.flaticon.com ](http://www.flaticon.com)
and is licensed by
[ CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).
"#;
const HELP_MSG: &'static str = r#"Commands:
`enable` I will start notifying you.
`disable` I will stop notifying you.
`status` Show if I am notifying you, and a little bit more information. 😉
`help` This message
"#;
/// Action controller
/// Return new bot state and an optional message to send to the user
pub fn update(action: Action, bot: Bot) -> (Bot, Option<Task>) {
let mut bot = bot;
let task = match action {
Action::Enable(person_id, email) => {
bot.enable(&person_id, &email, true);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! Happy reviewing!"),
));
Some(task)
}
Action::Disable(person_id, email) => {
bot.enable(&person_id, &email, false);
let task = Task::ReplyAndSave(Response::new(
person_id,
String::from("Got it! I will stay silent."),
));
Some(task)
}
Action::UpdateApprovals(event) => {
bot.get_approvals_msg(event).map(|(user, message)| {
Task::Reply(Response::new(user.spark_person_id.clone(), message))
})
}
Action::Help(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(HELP_MSG)),
))
}
Action::Unknown(person_id) => {
Some(Task::Reply(
Response::new(person_id, String::from(GREETINGS_MSG)),
))
}
Action::Status(person_id) => {
let status = bot.status_for(&person_id);
Some(Task::Reply(Response::new(person_id, status)))
}
_ => None,
};
(bot, task)
}
#[cfg(test)]
mod test {
use super::{Bot, User};
#[test]
fn test_add_user() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
assert_eq!(bot.users.len(), 1);
assert_eq!(bot.users[0].spark_person_id, "some_person_id");
assert_eq!(bot.users[0].email, "some@example.com");
assert!(bot.users[0].enabled);
}
#[test]
fn test_status_for() {
let mut bot = Bot::new();
bot.add_user("some_person_id", "some@example.com");
let resp = bot.status_for("some_person_id");
assert!(resp.contains("enabled"));
bot.users[0].enabled = false;
let resp = bot.status_for("some_person_id");
assert!(resp.contains("disabled"));
let resp = bot.status_for("some_non_existent_id");
assert!(resp.contains("disabled"));
}
#[test]
fn enable_non_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users + 1);
};
test(true);
test(false);
}
#[test]
fn enable_existent_user() {
let test = |enable| {
let mut bot = Bot::new();
bot.users.push(User::new(
String::from("some_person_id"),
String::from("some@example.com"),
));
let num_users = bot.num_users();
bot.enable("some_person_id", "some@example.com", enable);
assert!(
bot.users
.iter()
.position(|u| {
u.spark_person_id == "some_person_id" && u.email == "some@example.com" &&
u.enabled == enable
})
.is_some()
);
assert!(bot.num_users() == num_users);
};
test(true);
test(false);
}
}
|
use std::any::{Any, AnyMutRefExt, AnyRefExt};
use std::intrinsics::TypeId;
use std::collections::HashMap;
pub struct TypeMap {
data: HashMap<TypeId, Box<Any>>
}
impl TypeMap {
pub fn find<T: 'static>(&self) -> Option<&T> {
self.data.find(&TypeId::of::<T>()).and_then(|a| a.downcast_ref())
}
pub fn find_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.data.find_mut(&TypeId::of::<T>()).and_then(|a| a.downcast_mut())
}
pub fn insert<T: 'static>(&mut self, val: T) -> bool {
self.data.insert(TypeId::of::<T>(), box val as Box<Any>)
}
pub fn remove<T: 'static>(&mut self) -> bool {
self.data.remove(&TypeId::of::<T>())
}
pub fn contains<T: 'static>(&mut self) -> bool {
self.data.contains_key(&TypeId::of::<T>())
}
}
Add a TypeMap consturctor
use std::any::{Any, AnyMutRefExt, AnyRefExt};
use std::intrinsics::TypeId;
use std::collections::HashMap;
pub struct TypeMap {
data: HashMap<TypeId, Box<Any>>
}
impl TypeMap {
pub fn new() -> TypeMap {
TypeMap { data: HashMap::new() }
}
pub fn find<T: 'static>(&self) -> Option<&T> {
self.data.find(&TypeId::of::<T>()).and_then(|a| a.downcast_ref())
}
pub fn find_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.data.find_mut(&TypeId::of::<T>()).and_then(|a| a.downcast_mut())
}
pub fn insert<T: 'static>(&mut self, val: T) -> bool {
self.data.insert(TypeId::of::<T>(), box val as Box<Any>)
}
pub fn remove<T: 'static>(&mut self) -> bool {
self.data.remove(&TypeId::of::<T>())
}
pub fn contains<T: 'static>(&mut self) -> bool {
self.data.contains_key(&TypeId::of::<T>())
}
}
|
use std::cmp;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::iter;
use std::error::Error;
use std::ascii::AsciiExt;
use itertools::Itertools;
use std::borrow::Cow;
use rustbox::{RustBox};
use rustbox::keyboard::Key;
use rex_utils;
use rex_utils::split_vec::SplitVec;
use rex_utils::rect::Rect;
use super::super::config::Config;
use super::RustBoxEx::{RustBoxEx, Style};
use super::input::Input;
use super::inputline::{InputLine, GotoInputLine, FindInputLine, PathInputLine};
use super::overlay::OverlayText;
#[derive(Debug)]
enum UndoAction {
Delete(isize, isize),
Insert(isize, Vec<u8>),
Write(isize, Vec<u8>),
}
#[derive(Debug)]
enum LineNumberMode {
None,
Short,
Long
}
#[derive(Copy,Clone,Debug)]
pub enum HexEditActions {
Edit(char),
SwitchView,
MoveLeft,
MoveRight,
MoveUp,
MoveDown,
MovePageUp,
MovePageDown,
MoveToFirstColumn,
MoveToLastColumn,
Delete,
DeleteWithMove,
CopySelection,
CutSelection,
PasteSelection,
Undo,
ToggleInsert,
ToggleSelecion,
HelpView,
LogView,
AskGoto,
AskFind,
AskOpen,
AskSave
}
signalreceiver_decl!{HexEditSignalReceiver(HexEdit)}
pub struct HexEdit {
buffer: SplitVec,
config: Config,
rect: Rect<isize>,
cursor_nibble_pos: isize,
status_log: Vec<String>,
show_last_status: bool,
data_offset: isize,
row_offset: isize,
nibble_active: bool,
selection_start: Option<isize>,
insert_mode: bool,
input: Input,
undo_stack: Vec<UndoAction>,
input_entry: Option<Box<InputLine>>,
overlay: Option<OverlayText>,
cur_path: Option<PathBuf>,
clipboard: Option<Vec<u8>>,
signal_receiver: Option<HexEditSignalReceiver>,
}
impl HexEdit {
pub fn new(config: Config) -> HexEdit {
HexEdit {
buffer: SplitVec::new(),
config: config,
rect: Default::default(),
cursor_nibble_pos: 0,
data_offset: 0,
row_offset: 0,
status_log: vec!["Press C-/ for help".to_string()],
show_last_status: true,
nibble_active: true,
selection_start: None,
insert_mode: false,
input_entry: None,
undo_stack: Vec::new(),
overlay: None,
cur_path: None,
clipboard: None,
input: Input::new(),
signal_receiver: Some(HexEditSignalReceiver::new()),
}
}
fn reset(&mut self) {
self.cursor_nibble_pos = 0;
self.data_offset = 0;
self.nibble_active = true;
self.selection_start = None;
self.insert_mode = false;
self.input_entry = None;
self.undo_stack = Vec::new();
}
fn get_linenumber_mode(&self) -> LineNumberMode {
if !self.config.show_linenum {
LineNumberMode::None
} else if self.buffer.len() <= 0xFFFF {
LineNumberMode::Short
} else {
LineNumberMode::Long
}
}
fn get_linenumber_width(&self) -> isize {
match self.get_linenumber_mode() {
LineNumberMode::None => 0,
LineNumberMode::Short => 4 + 1, // 4 for the XXXX + 1 for whitespace
LineNumberMode::Long => 9 + 1, // 7 for XXXX:XXXX + 1 for whitespace
}
}
fn get_line_width(&self) -> isize {
self.config.line_width.unwrap_or(self.get_bytes_per_row() as u32) as isize
}
fn get_bytes_per_row(&self) -> isize {
// This is the number of cells on the screen that are used for each byte.
// For the nibble view, we need 3 (1 for each nibble and 1 for the spacing). For
// the ascii view, if it is shown, we need another one.
let cells_per_byte = if self.config.show_ascii { 4 } else { 3 };
(self.rect.width - self.get_linenumber_width()) / cells_per_byte
}
fn get_bytes_per_screen(&self) -> isize {
self.get_line_width() * self.rect.height
}
fn draw_line_number(&self, rb: &RustBox, row: usize, line_number: usize) {
match self.get_linenumber_mode() {
LineNumberMode::None => (),
LineNumberMode::Short => {
rb.print_style(0, row, Style::Default, &format!("{:04X}", line_number));
}
LineNumberMode::Long => {
rb.print_style(0, row, Style::Default, &format!("{:04X}:{:04X}", line_number >> 16, line_number & 0xFFFF));
}
};
}
fn draw_line(&self, rb: &RustBox, iter: &mut Iterator<Item=(usize, Option<&u8>)>, row: usize) {
let nibble_view_start = self.get_linenumber_width() as usize;
// The value of this is wrong if we are not showing the ascii view
let byte_view_start = nibble_view_start + self.get_bytes_per_row() as usize * 3;
// We want the selection draw to not go out of the editor view
let mut prev_in_selection = false;
for (row_offset, (byte_pos, maybe_byte)) in iter.skip(self.row_offset as usize).enumerate().take(self.get_bytes_per_row() as usize) {
let at_current_byte = byte_pos as isize == (self.cursor_nibble_pos / 2);
let in_selection = if let Some(selection_pos) = self.selection_start {
rex_utils::is_between(byte_pos as isize, selection_pos, self.cursor_nibble_pos / 2)
} else {
false
};
// Now we draw the nibble view
let hex_chars = if let Some(&byte) = maybe_byte {
rex_utils::u8_to_hex(byte)
} else {
(' ', ' ')
};
let nibble_view_column = nibble_view_start + (row_offset * 3);
let nibble_style = if (!self.nibble_active && at_current_byte) || in_selection {
Style::Selection
} else {
Style::Default
};
rb.print_char_style(nibble_view_column, row, nibble_style,
hex_chars.0);
rb.print_char_style(nibble_view_column + 1, row, nibble_style,
hex_chars.1);
if prev_in_selection && in_selection {
rb.print_char_style(nibble_view_column - 1, row, nibble_style,
' ');
}
if self.nibble_active && self.input_entry.is_none() && at_current_byte {
rb.set_cursor(nibble_view_column as isize + (self.cursor_nibble_pos & 1),
row as isize);
};
if self.config.show_ascii {
// Now let's draw the byte window
let byte_char = if let Some(&byte) = maybe_byte {
let bc = byte as char;
if bc.is_ascii() && bc.is_alphanumeric() {
bc
} else {
'.'
}
} else {
' '
};
// If we are at the current byte but the nibble view is active, we want to draw a
// "fake" cursor by dawing a selection square
let byte_style = if (self.nibble_active && at_current_byte) || in_selection {
Style::Selection
} else {
Style::Default
};
rb.print_char_style(byte_view_start + row_offset, row, byte_style,
byte_char);
if !self.nibble_active && self.input_entry.is_none() && at_current_byte {
rb.set_cursor((byte_view_start + row_offset) as isize, row as isize);
}
// Remember if we had a selection, so that we know for next char to "fill in" with
// selection in the nibble view
prev_in_selection = in_selection;
}
}
// We just need to consume the iterator
iter.count();
}
pub fn draw_view(&self, rb: &RustBox) {
let start_iter = self.data_offset as usize;
let stop_iter = cmp::min(start_iter + self.get_bytes_per_screen() as usize, self.buffer.len());
let itit = (start_iter..).zip( // We are zipping the byte position
self.buffer.iter_range(start_iter..stop_iter) // With the data at those bytes
.map(|x| Some(x)) // And wrapping it in an option
.chain(iter::once(None))) // So we can have a "fake" last item that will be None
.chunks_lazy(self.get_line_width() as usize); //And split it into nice row-sized chunks
for (row, row_iter_) in itit.into_iter().take(self.rect.height as usize).enumerate() {
// We need to be able to peek in the iterable so we can get the current position
let mut row_iter = row_iter_.peekable();
let byte_pos = row_iter.peek().unwrap().0;
self.draw_line_number(rb, row, byte_pos);
self.draw_line(rb, &mut row_iter, row);
}
}
fn draw_statusbar(&self, rb: &RustBox) {
rb.print_style(0, rb.height() - 1, Style::StatusBar, &rex_utils::string_with_repeat(' ', rb.width()));
if self.show_last_status {
if let Some(ref status_line) = self.status_log.last() {
rb.print_style(0, rb.height() - 1, Style::StatusBar, &status_line);
}
}
let mode = if let Some(_) = self.selection_start {
"SEL"
} else if self.insert_mode {
"INS"
} else {
"OVR"
};
let right_status;
if let Some(selection_start) = self.selection_start {
let size = (self.cursor_nibble_pos/2 - selection_start).abs();
right_status = format!(
" Start: {} Size: {} Pos: {} {}",
selection_start, size, self.cursor_nibble_pos/2, mode);
} else {
right_status = format!(
" Pos: {} Undo: {} {}",
self.undo_stack.len(), self.cursor_nibble_pos/2, mode);
};
let (x_pos, start_index) = if rb.width() >= right_status.len() {
(rb.width() - right_status.len(), 0)
} else {
(0, right_status.len() - rb.width())
};
rb.print_style(x_pos, rb.height() - 1, Style::StatusBar, &right_status[start_index..]);
}
pub fn draw(&mut self, rb: &RustBox) {
self.draw_view(rb);
if let Some(entry) = self.input_entry.as_mut() {
entry.draw(rb, Rect {
top: (rb.height() - 2) as isize,
left: 0,
height: 1,
width: rb.width() as isize
}, true);
}
if let Some(overlay) = self.overlay.as_mut() {
overlay.draw(rb, Rect {
top: 0,
left: 0,
height: self.rect.height,
width: self.rect.width,
}, true);
}
self.draw_statusbar(rb);
}
fn status<S: Into<Cow<'static, str>> + ?Sized>(&mut self, st: S) {
self.show_last_status = true;
let cow: Cow<'static, str> = st.into();
self.status_log.push(format!("{}", &cow));
}
fn clear_status(&mut self) {
self.show_last_status = false;
}
pub fn open(&mut self, path: &Path) {
let mut v = vec![];
if let Err(e) = File::open(path).and_then(|mut f| f.read_to_end(&mut v)) {
self.status(format!("ERROR: {}", e.description()));
return;
}
self.buffer = SplitVec::from_vec(v);
self.cur_path = Some(PathBuf::from(path));
self.reset();
}
pub fn save(&mut self, path: &Path) {
let result = File::create(path)
.and_then(|mut f| self.buffer.iter_slices()
.fold(Ok(()), |res, val| res
.and_then(|_| f.write_all(val))));
match result {
Ok(_) => {
self.cur_path = Some(PathBuf::from(path));
}
Err(e) => {
self.status(format!("ERROR: {}", e.description()));
}
}
}
fn do_action(&mut self, act: UndoAction, add_to_undo: bool) -> (isize, isize) {
let stat = format!("doing = {:?}", act);
let mut begin_region: isize;
let mut end_region: isize;
match act {
UndoAction::Insert(offset, buf) => {
begin_region = offset;
end_region = offset + buf.len() as isize;
self.buffer.insert(offset as usize, &buf);
if add_to_undo {
self.push_undo(UndoAction::Delete(offset, offset + buf.len() as isize))
}
}
UndoAction::Delete(offset, end) => {
begin_region = offset;
end_region = end;
let res = self.buffer.move_out(offset as usize..end as usize);
if add_to_undo { self.push_undo(UndoAction::Insert(offset, res)) }
}
UndoAction::Write(offset, buf) => {
begin_region = offset;
end_region = offset + buf.len() as isize;
let orig_data = self.buffer.copy_out(offset as usize..(offset as usize + buf.len()));
self.buffer.copy_in(offset as usize, &buf);
if add_to_undo { self.push_undo(UndoAction::Write(offset, orig_data)) }
}
}
self.status(stat);
(begin_region, end_region)
}
fn push_undo(&mut self, act: UndoAction) {
self.undo_stack.push(act);
}
fn undo(&mut self) {
if let Some(act) = self.undo_stack.pop() {
let (begin, _) = self.do_action(act, false);
self.set_cursor(begin * 2);
}
}
fn cursor_at_end(&self) -> bool {
self.cursor_nibble_pos == (self.buffer.len()*2) as isize
}
fn delete_at_cursor(&mut self, with_bksp: bool) {
let mut cursor_nibble_pos = self.cursor_nibble_pos;
let selection_pos = match self.selection_start {
Some(selection_pos_tag) => selection_pos_tag,
None => {
if with_bksp {
if cursor_nibble_pos < 2 {
return;
}
cursor_nibble_pos -= 2;
}
cursor_nibble_pos / 2
}
};
let del_start = cmp::min(selection_pos, cursor_nibble_pos / 2);
let mut del_stop = cmp::max(selection_pos, cursor_nibble_pos / 2) + 1;
if del_stop > self.buffer.len() as isize {
del_stop -= 1;
if del_stop == del_start {
return;
}
}
if self.buffer.len() == 0 {
self.status("Nothing to delete");
return;
}
self.selection_start = None;
self.do_action(UndoAction::Delete(del_start, del_stop), true);
self.set_cursor(del_start * 2);
}
fn write_nibble_at_cursor(&mut self, c: u8) {
// Replace the text at the selection before writing the data
if self.selection_start.is_some() {
self.delete_at_cursor(false);
}
if self.insert_mode || self.cursor_at_end() {
self.insert_nibble_at_cursor(c);
} else {
self.set_nibble_at_cursor(c);
}
}
fn set_nibble_at_cursor(&mut self, c: u8) {
let mut byte = self.buffer[(self.cursor_nibble_pos / 2) as usize];
byte = match self.cursor_nibble_pos & 1 {
0 => (byte & 0x0f) + c * 16,
1 => (byte & 0xf0) + c,
_ => 0xff,
};
let byte_offset = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Write(byte_offset, vec![byte]), true);
}
fn insert_nibble_at_cursor(&mut self, c: u8) {
// If we are at half byte, we still overwrite
if self.cursor_nibble_pos & 1 == 1 {
self.set_nibble_at_cursor(c);
return
}
let pos_div2 = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Insert(pos_div2, vec![c * 16]), true);
}
fn toggle_insert_mode(&mut self) {
self.insert_mode = !self.insert_mode;
self.move_cursor(0);
}
fn write_byte_at_cursor(&mut self, c: u8) {
// Replace the text at the selection before writing the data
if self.selection_start.is_some() {
self.delete_at_cursor(false);
}
let byte_offset = self.cursor_nibble_pos / 2;
if self.insert_mode || self.cursor_at_end() {
self.do_action(UndoAction::Insert(byte_offset, vec![c]), true);
} else {
self.do_action(UndoAction::Write(byte_offset, vec![c]), true);
}
}
fn move_cursor(&mut self, pos: isize) {
self.cursor_nibble_pos += pos;
self.update_cursor()
}
fn set_cursor(&mut self, pos: isize) {
self.cursor_nibble_pos = pos;
self.update_cursor()
}
fn update_cursor(&mut self) {
self.cursor_nibble_pos = cmp::max(self.cursor_nibble_pos, 0);
self.cursor_nibble_pos = cmp::min(self.cursor_nibble_pos, (self.buffer.len()*2) as isize);
let cursor_byte_pos = self.cursor_nibble_pos / 2;
let cursor_row_offset = cursor_byte_pos % self.get_line_width();
// If the cursor moves above or below the view, scroll it
if cursor_byte_pos < self.data_offset {
self.data_offset = (cursor_byte_pos) - cursor_row_offset;
}
if cursor_byte_pos > (self.data_offset + self.get_bytes_per_screen() - 1) {
self.data_offset = cursor_byte_pos - cursor_row_offset -
self.get_bytes_per_screen() + self.get_line_width();
}
// If the cursor moves to the right or left of the view, scroll it
if cursor_row_offset < self.row_offset {
self.row_offset = cursor_row_offset;
}
if cursor_row_offset >= self.row_offset + self.get_bytes_per_row() {
self.row_offset = cursor_row_offset - self.get_bytes_per_row() + 1;
}
}
fn toggle_selection(&mut self) {
match self.selection_start {
Some(_) => self.selection_start = None,
None => self.selection_start = Some(self.cursor_nibble_pos / 2)
}
let selection_start = self.selection_start; // Yay! Lifetimes!
self.status(format!("selection = {:?}", selection_start));
}
fn goto(&mut self, pos: isize) {
self.status(format!("Going to {:?}", pos));
self.set_cursor(pos * 2);
}
fn find_buf(&mut self, needle: &[u8]) {
let found_pos = match self.buffer.find_slice_from((self.cursor_nibble_pos / 2) as usize, needle) {
None => {
self.buffer.find_slice_from(0, needle)
}
a => a
};
if let Some(pos) = found_pos {
self.status(format!("Found at {:?}", pos));
self.set_cursor((pos * 2) as isize);
} else {
self.status("Nothing found!");
}
}
fn read_cursor_to_clipboard(&mut self) -> Option<usize> {
let (start, stop) = match self.selection_start {
None => { return None; },
Some(selection_pos) => {
(cmp::min(selection_pos, self.cursor_nibble_pos / 2),
cmp::max(selection_pos, self.cursor_nibble_pos / 2))
}
};
let data = self.buffer.copy_out(start as usize..stop as usize);
let data_len = data.len();
self.clipboard = Some(data);
Some(data_len)
}
fn edit_copy(&mut self) {
if let Some(data_len) = self.read_cursor_to_clipboard() {
self.status(format!("Copied {}", data_len));
self.selection_start = None;
}
}
fn edit_cut(&mut self) {
if let Some(data_len) = self.read_cursor_to_clipboard() {
self.delete_at_cursor(false);
self.status(format!("Cut {}", data_len));
}
}
fn edit_paste(&mut self) {
let data = if let Some(ref d) = self.clipboard {
d.clone()
} else {
return;
};
let data_len = data.len() as isize;
// This is needed to satisfy the borrow checker
let cur_pos_in_bytes = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Insert(cur_pos_in_bytes, data), true);
self.move_cursor(data_len + 1);
}
fn view_input(&mut self, key: Key) {
let action = self.input.editor_input(key);
if action.is_none() {
return;
}
match action.unwrap() {
// Movement
HexEditActions::MoveLeft if self.nibble_active => self.move_cursor(-1),
HexEditActions::MoveRight if self.nibble_active => self.move_cursor(1),
HexEditActions::MoveLeft if !self.nibble_active => self.move_cursor(-2),
HexEditActions::MoveRight if !self.nibble_active => self.move_cursor(2),
HexEditActions::MoveUp => {
let t = -self.get_line_width() * 2;
self.move_cursor(t)
}
HexEditActions::MoveDown => {
let t = self.get_line_width() * 2;
self.move_cursor(t)
}
HexEditActions::MovePageUp => {
// We want to move the cursor the amount of bytes on screen divided by two, we then
// multiply by two for it to be in nibbles
let t = -(self.get_bytes_per_screen() - self.get_line_width()) / 2 * 2;
self.move_cursor(t)
}
HexEditActions::MovePageDown => {
let t = (self.get_bytes_per_screen() - self.get_line_width()) / 2 * 2;
self.move_cursor(t)
}
HexEditActions::MoveToFirstColumn => {
let pos_in_line = self.cursor_nibble_pos % (self.get_line_width()*2);
self.move_cursor(-pos_in_line)
}
HexEditActions::MoveToLastColumn => {
let pos_in_line = self.cursor_nibble_pos % (self.get_line_width()*2);
let i = self.get_line_width()*2 - 2 - pos_in_line;
self.move_cursor(i);
}
// UndoAction::Delete
HexEditActions::Delete => self.delete_at_cursor(false),
HexEditActions::DeleteWithMove => self.delete_at_cursor(true),
// Ctrl X, C V
HexEditActions::CutSelection => self.edit_cut(),
HexEditActions::CopySelection => self.edit_copy(),
HexEditActions::PasteSelection => self.edit_paste(),
// Hex input for nibble view
HexEditActions::Edit(ch) if self.nibble_active => {
if let Some(val) = ch.to_digit(16) {
self.write_nibble_at_cursor(val as u8);
self.move_cursor(1);
} else {
// TODO: Show error?
}
},
// Ascii edit for byte view
HexEditActions::Edit(ch) if !self.nibble_active => {
if ch.len_utf8() == 1 && ch.is_alphanumeric() {
// TODO: Make it printable rather than alphanumeric
self.write_byte_at_cursor(ch as u8);
self.move_cursor(2);
} else {
// TODO: Show error?
}
}
HexEditActions::SwitchView => {
self.nibble_active = !self.nibble_active;
let t = self.nibble_active;
self.status(format!("nibble_active = {:?}", t));
},
HexEditActions::HelpView => self.start_help(),
HexEditActions::LogView => self.start_logview(),
HexEditActions::ToggleInsert => self.toggle_insert_mode(),
HexEditActions::ToggleSelecion => self.toggle_selection(),
HexEditActions::Undo => self.undo(),
HexEditActions::AskGoto => self.start_goto(),
HexEditActions::AskFind => self.start_find(),
HexEditActions::AskOpen => self.start_open(),
HexEditActions::AskSave => self.start_save(),
_ => self.status(format!("key = {:?}", key)),
}
}
fn start_help(&mut self) {
let help_text = include_str!("Help.txt");
// YAY Lifetimes! (This will hopfully be fixed once rust gains MIR/HIR)
{
let ref sr = self.signal_receiver.as_mut().unwrap();
let mut ot = OverlayText::with_text(help_text.to_string(), false);
ot.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.overlay = None;
}));
self.overlay = Some(ot);
}
{
self.status("Press Esc to return");
}
}
fn start_logview(&mut self) {
let logs = self.status_log.clone();
let ref sr = self.signal_receiver.as_mut().unwrap();
let mut ot = OverlayText::with_logs(logs, true);
ot.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.overlay = None;
}));
self.overlay = Some(ot);
}
fn start_goto(&mut self) {
let mut gt = GotoInputLine::new();
// let mut sender_clone0 = self.sender.clone();
let ref sr = self.signal_receiver.as_mut().unwrap();
gt.on_done.connect(signal!(sr with |obj, pos| {
obj.goto(pos*2);
obj.input_entry = None;
}));
gt.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(gt) as Box<InputLine>)
}
fn start_find(&mut self) {
let mut find_line = FindInputLine::new();
let ref sr = self.signal_receiver.as_mut().unwrap();
find_line.on_find.connect(signal!(sr with |obj, needle| {
obj.find_buf(&needle);
obj.input_entry = None;
}));
find_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(find_line) as Box<InputLine>)
}
fn start_save(&mut self) {
let mut path_line = PathInputLine::new("Save: ".into());
let ref sr = self.signal_receiver.as_mut().unwrap();
path_line.on_done.connect(signal!(sr with |obj, path| {
obj.save(&path);
obj.input_entry = None;
}));
path_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(path_line) as Box<InputLine>)
}
fn start_open(&mut self) {
let mut path_line = PathInputLine::new("Open: ".into());
let ref sr = self.signal_receiver.as_mut().unwrap();
path_line.on_done.connect(signal!(sr with |obj, path| {
obj.open(&path);
obj.input_entry = None;
}));
path_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(path_line) as Box<InputLine>)
}
fn process_msgs(&mut self) {
let mut sr = self.signal_receiver.take().unwrap();
sr.run(self);
self.signal_receiver = Some(sr);
}
pub fn input(&mut self, key: Key) {
self.process_msgs();
if let Some(ref mut overlay) = self.overlay {
overlay.input(&self.input, key);
} else if let Some(ref mut input_entry) = self.input_entry {
input_entry.input(&self.input, key);
} else {
self.view_input(key);
}
self.process_msgs();
}
pub fn resize(&mut self, width: i32, height: i32) {
self.rect.height = height as isize - 1; // Substract 1 for the status line on the bottom
self.rect.width = width as isize;
self.update_cursor();
}
}
Make the PageDown/Up actually do a PageDown/Up.
The previous behavior tried doing a half-page, but it just didn't look
good. So let's skip that for now.
use std::cmp;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::iter;
use std::error::Error;
use std::ascii::AsciiExt;
use itertools::Itertools;
use std::borrow::Cow;
use rustbox::{RustBox};
use rustbox::keyboard::Key;
use rex_utils;
use rex_utils::split_vec::SplitVec;
use rex_utils::rect::Rect;
use super::super::config::Config;
use super::RustBoxEx::{RustBoxEx, Style};
use super::input::Input;
use super::inputline::{InputLine, GotoInputLine, FindInputLine, PathInputLine};
use super::overlay::OverlayText;
#[derive(Debug)]
enum UndoAction {
Delete(isize, isize),
Insert(isize, Vec<u8>),
Write(isize, Vec<u8>),
}
#[derive(Debug)]
enum LineNumberMode {
None,
Short,
Long
}
#[derive(Copy,Clone,Debug)]
pub enum HexEditActions {
Edit(char),
SwitchView,
MoveLeft,
MoveRight,
MoveUp,
MoveDown,
MovePageUp,
MovePageDown,
MoveToFirstColumn,
MoveToLastColumn,
Delete,
DeleteWithMove,
CopySelection,
CutSelection,
PasteSelection,
Undo,
ToggleInsert,
ToggleSelecion,
HelpView,
LogView,
AskGoto,
AskFind,
AskOpen,
AskSave
}
signalreceiver_decl!{HexEditSignalReceiver(HexEdit)}
pub struct HexEdit {
buffer: SplitVec,
config: Config,
rect: Rect<isize>,
cursor_nibble_pos: isize,
status_log: Vec<String>,
show_last_status: bool,
data_offset: isize,
row_offset: isize,
nibble_active: bool,
selection_start: Option<isize>,
insert_mode: bool,
input: Input,
undo_stack: Vec<UndoAction>,
input_entry: Option<Box<InputLine>>,
overlay: Option<OverlayText>,
cur_path: Option<PathBuf>,
clipboard: Option<Vec<u8>>,
signal_receiver: Option<HexEditSignalReceiver>,
}
impl HexEdit {
pub fn new(config: Config) -> HexEdit {
HexEdit {
buffer: SplitVec::new(),
config: config,
rect: Default::default(),
cursor_nibble_pos: 0,
data_offset: 0,
row_offset: 0,
status_log: vec!["Press C-/ for help".to_string()],
show_last_status: true,
nibble_active: true,
selection_start: None,
insert_mode: false,
input_entry: None,
undo_stack: Vec::new(),
overlay: None,
cur_path: None,
clipboard: None,
input: Input::new(),
signal_receiver: Some(HexEditSignalReceiver::new()),
}
}
fn reset(&mut self) {
self.cursor_nibble_pos = 0;
self.data_offset = 0;
self.nibble_active = true;
self.selection_start = None;
self.insert_mode = false;
self.input_entry = None;
self.undo_stack = Vec::new();
}
fn get_linenumber_mode(&self) -> LineNumberMode {
if !self.config.show_linenum {
LineNumberMode::None
} else if self.buffer.len() <= 0xFFFF {
LineNumberMode::Short
} else {
LineNumberMode::Long
}
}
fn get_linenumber_width(&self) -> isize {
match self.get_linenumber_mode() {
LineNumberMode::None => 0,
LineNumberMode::Short => 4 + 1, // 4 for the XXXX + 1 for whitespace
LineNumberMode::Long => 9 + 1, // 7 for XXXX:XXXX + 1 for whitespace
}
}
fn get_line_width(&self) -> isize {
self.config.line_width.unwrap_or(self.get_bytes_per_row() as u32) as isize
}
fn get_bytes_per_row(&self) -> isize {
// This is the number of cells on the screen that are used for each byte.
// For the nibble view, we need 3 (1 for each nibble and 1 for the spacing). For
// the ascii view, if it is shown, we need another one.
let cells_per_byte = if self.config.show_ascii { 4 } else { 3 };
(self.rect.width - self.get_linenumber_width()) / cells_per_byte
}
fn get_bytes_per_screen(&self) -> isize {
self.get_line_width() * self.rect.height
}
fn draw_line_number(&self, rb: &RustBox, row: usize, line_number: usize) {
match self.get_linenumber_mode() {
LineNumberMode::None => (),
LineNumberMode::Short => {
rb.print_style(0, row, Style::Default, &format!("{:04X}", line_number));
}
LineNumberMode::Long => {
rb.print_style(0, row, Style::Default, &format!("{:04X}:{:04X}", line_number >> 16, line_number & 0xFFFF));
}
};
}
fn draw_line(&self, rb: &RustBox, iter: &mut Iterator<Item=(usize, Option<&u8>)>, row: usize) {
let nibble_view_start = self.get_linenumber_width() as usize;
// The value of this is wrong if we are not showing the ascii view
let byte_view_start = nibble_view_start + self.get_bytes_per_row() as usize * 3;
// We want the selection draw to not go out of the editor view
let mut prev_in_selection = false;
for (row_offset, (byte_pos, maybe_byte)) in iter.skip(self.row_offset as usize).enumerate().take(self.get_bytes_per_row() as usize) {
let at_current_byte = byte_pos as isize == (self.cursor_nibble_pos / 2);
let in_selection = if let Some(selection_pos) = self.selection_start {
rex_utils::is_between(byte_pos as isize, selection_pos, self.cursor_nibble_pos / 2)
} else {
false
};
// Now we draw the nibble view
let hex_chars = if let Some(&byte) = maybe_byte {
rex_utils::u8_to_hex(byte)
} else {
(' ', ' ')
};
let nibble_view_column = nibble_view_start + (row_offset * 3);
let nibble_style = if (!self.nibble_active && at_current_byte) || in_selection {
Style::Selection
} else {
Style::Default
};
rb.print_char_style(nibble_view_column, row, nibble_style,
hex_chars.0);
rb.print_char_style(nibble_view_column + 1, row, nibble_style,
hex_chars.1);
if prev_in_selection && in_selection {
rb.print_char_style(nibble_view_column - 1, row, nibble_style,
' ');
}
if self.nibble_active && self.input_entry.is_none() && at_current_byte {
rb.set_cursor(nibble_view_column as isize + (self.cursor_nibble_pos & 1),
row as isize);
};
if self.config.show_ascii {
// Now let's draw the byte window
let byte_char = if let Some(&byte) = maybe_byte {
let bc = byte as char;
if bc.is_ascii() && bc.is_alphanumeric() {
bc
} else {
'.'
}
} else {
' '
};
// If we are at the current byte but the nibble view is active, we want to draw a
// "fake" cursor by dawing a selection square
let byte_style = if (self.nibble_active && at_current_byte) || in_selection {
Style::Selection
} else {
Style::Default
};
rb.print_char_style(byte_view_start + row_offset, row, byte_style,
byte_char);
if !self.nibble_active && self.input_entry.is_none() && at_current_byte {
rb.set_cursor((byte_view_start + row_offset) as isize, row as isize);
}
// Remember if we had a selection, so that we know for next char to "fill in" with
// selection in the nibble view
prev_in_selection = in_selection;
}
}
// We just need to consume the iterator
iter.count();
}
pub fn draw_view(&self, rb: &RustBox) {
let start_iter = self.data_offset as usize;
let stop_iter = cmp::min(start_iter + self.get_bytes_per_screen() as usize, self.buffer.len());
let itit = (start_iter..).zip( // We are zipping the byte position
self.buffer.iter_range(start_iter..stop_iter) // With the data at those bytes
.map(|x| Some(x)) // And wrapping it in an option
.chain(iter::once(None))) // So we can have a "fake" last item that will be None
.chunks_lazy(self.get_line_width() as usize); //And split it into nice row-sized chunks
for (row, row_iter_) in itit.into_iter().take(self.rect.height as usize).enumerate() {
// We need to be able to peek in the iterable so we can get the current position
let mut row_iter = row_iter_.peekable();
let byte_pos = row_iter.peek().unwrap().0;
self.draw_line_number(rb, row, byte_pos);
self.draw_line(rb, &mut row_iter, row);
}
}
fn draw_statusbar(&self, rb: &RustBox) {
rb.print_style(0, rb.height() - 1, Style::StatusBar, &rex_utils::string_with_repeat(' ', rb.width()));
if self.show_last_status {
if let Some(ref status_line) = self.status_log.last() {
rb.print_style(0, rb.height() - 1, Style::StatusBar, &status_line);
}
}
let mode = if let Some(_) = self.selection_start {
"SEL"
} else if self.insert_mode {
"INS"
} else {
"OVR"
};
let right_status;
if let Some(selection_start) = self.selection_start {
let size = (self.cursor_nibble_pos/2 - selection_start).abs();
right_status = format!(
" Start: {} Size: {} Pos: {} {}",
selection_start, size, self.cursor_nibble_pos/2, mode);
} else {
right_status = format!(
" Pos: {} Undo: {} {}",
self.undo_stack.len(), self.cursor_nibble_pos/2, mode);
};
let (x_pos, start_index) = if rb.width() >= right_status.len() {
(rb.width() - right_status.len(), 0)
} else {
(0, right_status.len() - rb.width())
};
rb.print_style(x_pos, rb.height() - 1, Style::StatusBar, &right_status[start_index..]);
}
pub fn draw(&mut self, rb: &RustBox) {
self.draw_view(rb);
if let Some(entry) = self.input_entry.as_mut() {
entry.draw(rb, Rect {
top: (rb.height() - 2) as isize,
left: 0,
height: 1,
width: rb.width() as isize
}, true);
}
if let Some(overlay) = self.overlay.as_mut() {
overlay.draw(rb, Rect {
top: 0,
left: 0,
height: self.rect.height,
width: self.rect.width,
}, true);
}
self.draw_statusbar(rb);
}
fn status<S: Into<Cow<'static, str>> + ?Sized>(&mut self, st: S) {
self.show_last_status = true;
let cow: Cow<'static, str> = st.into();
self.status_log.push(format!("{}", &cow));
}
fn clear_status(&mut self) {
self.show_last_status = false;
}
pub fn open(&mut self, path: &Path) {
let mut v = vec![];
if let Err(e) = File::open(path).and_then(|mut f| f.read_to_end(&mut v)) {
self.status(format!("ERROR: {}", e.description()));
return;
}
self.buffer = SplitVec::from_vec(v);
self.cur_path = Some(PathBuf::from(path));
self.reset();
}
pub fn save(&mut self, path: &Path) {
let result = File::create(path)
.and_then(|mut f| self.buffer.iter_slices()
.fold(Ok(()), |res, val| res
.and_then(|_| f.write_all(val))));
match result {
Ok(_) => {
self.cur_path = Some(PathBuf::from(path));
}
Err(e) => {
self.status(format!("ERROR: {}", e.description()));
}
}
}
fn do_action(&mut self, act: UndoAction, add_to_undo: bool) -> (isize, isize) {
let stat = format!("doing = {:?}", act);
let mut begin_region: isize;
let mut end_region: isize;
match act {
UndoAction::Insert(offset, buf) => {
begin_region = offset;
end_region = offset + buf.len() as isize;
self.buffer.insert(offset as usize, &buf);
if add_to_undo {
self.push_undo(UndoAction::Delete(offset, offset + buf.len() as isize))
}
}
UndoAction::Delete(offset, end) => {
begin_region = offset;
end_region = end;
let res = self.buffer.move_out(offset as usize..end as usize);
if add_to_undo { self.push_undo(UndoAction::Insert(offset, res)) }
}
UndoAction::Write(offset, buf) => {
begin_region = offset;
end_region = offset + buf.len() as isize;
let orig_data = self.buffer.copy_out(offset as usize..(offset as usize + buf.len()));
self.buffer.copy_in(offset as usize, &buf);
if add_to_undo { self.push_undo(UndoAction::Write(offset, orig_data)) }
}
}
self.status(stat);
(begin_region, end_region)
}
fn push_undo(&mut self, act: UndoAction) {
self.undo_stack.push(act);
}
fn undo(&mut self) {
if let Some(act) = self.undo_stack.pop() {
let (begin, _) = self.do_action(act, false);
self.set_cursor(begin * 2);
}
}
fn cursor_at_end(&self) -> bool {
self.cursor_nibble_pos == (self.buffer.len()*2) as isize
}
fn delete_at_cursor(&mut self, with_bksp: bool) {
let mut cursor_nibble_pos = self.cursor_nibble_pos;
let selection_pos = match self.selection_start {
Some(selection_pos_tag) => selection_pos_tag,
None => {
if with_bksp {
if cursor_nibble_pos < 2 {
return;
}
cursor_nibble_pos -= 2;
}
cursor_nibble_pos / 2
}
};
let del_start = cmp::min(selection_pos, cursor_nibble_pos / 2);
let mut del_stop = cmp::max(selection_pos, cursor_nibble_pos / 2) + 1;
if del_stop > self.buffer.len() as isize {
del_stop -= 1;
if del_stop == del_start {
return;
}
}
if self.buffer.len() == 0 {
self.status("Nothing to delete");
return;
}
self.selection_start = None;
self.do_action(UndoAction::Delete(del_start, del_stop), true);
self.set_cursor(del_start * 2);
}
fn write_nibble_at_cursor(&mut self, c: u8) {
// Replace the text at the selection before writing the data
if self.selection_start.is_some() {
self.delete_at_cursor(false);
}
if self.insert_mode || self.cursor_at_end() {
self.insert_nibble_at_cursor(c);
} else {
self.set_nibble_at_cursor(c);
}
}
fn set_nibble_at_cursor(&mut self, c: u8) {
let mut byte = self.buffer[(self.cursor_nibble_pos / 2) as usize];
byte = match self.cursor_nibble_pos & 1 {
0 => (byte & 0x0f) + c * 16,
1 => (byte & 0xf0) + c,
_ => 0xff,
};
let byte_offset = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Write(byte_offset, vec![byte]), true);
}
fn insert_nibble_at_cursor(&mut self, c: u8) {
// If we are at half byte, we still overwrite
if self.cursor_nibble_pos & 1 == 1 {
self.set_nibble_at_cursor(c);
return
}
let pos_div2 = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Insert(pos_div2, vec![c * 16]), true);
}
fn toggle_insert_mode(&mut self) {
self.insert_mode = !self.insert_mode;
self.move_cursor(0);
}
fn write_byte_at_cursor(&mut self, c: u8) {
// Replace the text at the selection before writing the data
if self.selection_start.is_some() {
self.delete_at_cursor(false);
}
let byte_offset = self.cursor_nibble_pos / 2;
if self.insert_mode || self.cursor_at_end() {
self.do_action(UndoAction::Insert(byte_offset, vec![c]), true);
} else {
self.do_action(UndoAction::Write(byte_offset, vec![c]), true);
}
}
fn move_cursor(&mut self, pos: isize) {
self.cursor_nibble_pos += pos;
self.update_cursor()
}
fn set_cursor(&mut self, pos: isize) {
self.cursor_nibble_pos = pos;
self.update_cursor()
}
fn update_cursor(&mut self) {
self.cursor_nibble_pos = cmp::max(self.cursor_nibble_pos, 0);
self.cursor_nibble_pos = cmp::min(self.cursor_nibble_pos, (self.buffer.len()*2) as isize);
let cursor_byte_pos = self.cursor_nibble_pos / 2;
let cursor_row_offset = cursor_byte_pos % self.get_line_width();
// If the cursor moves above or below the view, scroll it
if cursor_byte_pos < self.data_offset {
self.data_offset = (cursor_byte_pos) - cursor_row_offset;
}
if cursor_byte_pos > (self.data_offset + self.get_bytes_per_screen() - 1) {
self.data_offset = cursor_byte_pos - cursor_row_offset -
self.get_bytes_per_screen() + self.get_line_width();
}
// If the cursor moves to the right or left of the view, scroll it
if cursor_row_offset < self.row_offset {
self.row_offset = cursor_row_offset;
}
if cursor_row_offset >= self.row_offset + self.get_bytes_per_row() {
self.row_offset = cursor_row_offset - self.get_bytes_per_row() + 1;
}
}
fn toggle_selection(&mut self) {
match self.selection_start {
Some(_) => self.selection_start = None,
None => self.selection_start = Some(self.cursor_nibble_pos / 2)
}
let selection_start = self.selection_start; // Yay! Lifetimes!
self.status(format!("selection = {:?}", selection_start));
}
fn goto(&mut self, pos: isize) {
self.status(format!("Going to {:?}", pos));
self.set_cursor(pos * 2);
}
fn find_buf(&mut self, needle: &[u8]) {
let found_pos = match self.buffer.find_slice_from((self.cursor_nibble_pos / 2) as usize, needle) {
None => {
self.buffer.find_slice_from(0, needle)
}
a => a
};
if let Some(pos) = found_pos {
self.status(format!("Found at {:?}", pos));
self.set_cursor((pos * 2) as isize);
} else {
self.status("Nothing found!");
}
}
fn read_cursor_to_clipboard(&mut self) -> Option<usize> {
let (start, stop) = match self.selection_start {
None => { return None; },
Some(selection_pos) => {
(cmp::min(selection_pos, self.cursor_nibble_pos / 2),
cmp::max(selection_pos, self.cursor_nibble_pos / 2))
}
};
let data = self.buffer.copy_out(start as usize..stop as usize);
let data_len = data.len();
self.clipboard = Some(data);
Some(data_len)
}
fn edit_copy(&mut self) {
if let Some(data_len) = self.read_cursor_to_clipboard() {
self.status(format!("Copied {}", data_len));
self.selection_start = None;
}
}
fn edit_cut(&mut self) {
if let Some(data_len) = self.read_cursor_to_clipboard() {
self.delete_at_cursor(false);
self.status(format!("Cut {}", data_len));
}
}
fn edit_paste(&mut self) {
let data = if let Some(ref d) = self.clipboard {
d.clone()
} else {
return;
};
let data_len = data.len() as isize;
// This is needed to satisfy the borrow checker
let cur_pos_in_bytes = self.cursor_nibble_pos / 2;
self.do_action(UndoAction::Insert(cur_pos_in_bytes, data), true);
self.move_cursor(data_len + 1);
}
fn view_input(&mut self, key: Key) {
let action = self.input.editor_input(key);
if action.is_none() {
return;
}
match action.unwrap() {
// Movement
HexEditActions::MoveLeft if self.nibble_active => self.move_cursor(-1),
HexEditActions::MoveRight if self.nibble_active => self.move_cursor(1),
HexEditActions::MoveLeft if !self.nibble_active => self.move_cursor(-2),
HexEditActions::MoveRight if !self.nibble_active => self.move_cursor(2),
HexEditActions::MoveUp => {
let t = -self.get_line_width() * 2;
self.move_cursor(t)
}
HexEditActions::MoveDown => {
let t = self.get_line_width() * 2;
self.move_cursor(t)
}
HexEditActions::MovePageUp => {
let t = -(self.get_bytes_per_screen() * 2);
self.move_cursor(t)
}
HexEditActions::MovePageDown => {
let t = self.get_bytes_per_screen() * 2;
self.move_cursor(t)
}
HexEditActions::MoveToFirstColumn => {
let pos_in_line = self.cursor_nibble_pos % (self.get_line_width()*2);
self.move_cursor(-pos_in_line)
}
HexEditActions::MoveToLastColumn => {
let pos_in_line = self.cursor_nibble_pos % (self.get_line_width()*2);
let i = self.get_line_width()*2 - 2 - pos_in_line;
self.move_cursor(i);
}
// UndoAction::Delete
HexEditActions::Delete => self.delete_at_cursor(false),
HexEditActions::DeleteWithMove => self.delete_at_cursor(true),
// Ctrl X, C V
HexEditActions::CutSelection => self.edit_cut(),
HexEditActions::CopySelection => self.edit_copy(),
HexEditActions::PasteSelection => self.edit_paste(),
// Hex input for nibble view
HexEditActions::Edit(ch) if self.nibble_active => {
if let Some(val) = ch.to_digit(16) {
self.write_nibble_at_cursor(val as u8);
self.move_cursor(1);
} else {
// TODO: Show error?
}
},
// Ascii edit for byte view
HexEditActions::Edit(ch) if !self.nibble_active => {
if ch.len_utf8() == 1 && ch.is_alphanumeric() {
// TODO: Make it printable rather than alphanumeric
self.write_byte_at_cursor(ch as u8);
self.move_cursor(2);
} else {
// TODO: Show error?
}
}
HexEditActions::SwitchView => {
self.nibble_active = !self.nibble_active;
let t = self.nibble_active;
self.status(format!("nibble_active = {:?}", t));
},
HexEditActions::HelpView => self.start_help(),
HexEditActions::LogView => self.start_logview(),
HexEditActions::ToggleInsert => self.toggle_insert_mode(),
HexEditActions::ToggleSelecion => self.toggle_selection(),
HexEditActions::Undo => self.undo(),
HexEditActions::AskGoto => self.start_goto(),
HexEditActions::AskFind => self.start_find(),
HexEditActions::AskOpen => self.start_open(),
HexEditActions::AskSave => self.start_save(),
_ => self.status(format!("key = {:?}", key)),
}
}
fn start_help(&mut self) {
let help_text = include_str!("Help.txt");
// YAY Lifetimes! (This will hopfully be fixed once rust gains MIR/HIR)
{
let ref sr = self.signal_receiver.as_mut().unwrap();
let mut ot = OverlayText::with_text(help_text.to_string(), false);
ot.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.overlay = None;
}));
self.overlay = Some(ot);
}
{
self.status("Press Esc to return");
}
}
fn start_logview(&mut self) {
let logs = self.status_log.clone();
let ref sr = self.signal_receiver.as_mut().unwrap();
let mut ot = OverlayText::with_logs(logs, true);
ot.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.overlay = None;
}));
self.overlay = Some(ot);
}
fn start_goto(&mut self) {
let mut gt = GotoInputLine::new();
// let mut sender_clone0 = self.sender.clone();
let ref sr = self.signal_receiver.as_mut().unwrap();
gt.on_done.connect(signal!(sr with |obj, pos| {
obj.goto(pos*2);
obj.input_entry = None;
}));
gt.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(gt) as Box<InputLine>)
}
fn start_find(&mut self) {
let mut find_line = FindInputLine::new();
let ref sr = self.signal_receiver.as_mut().unwrap();
find_line.on_find.connect(signal!(sr with |obj, needle| {
obj.find_buf(&needle);
obj.input_entry = None;
}));
find_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(find_line) as Box<InputLine>)
}
fn start_save(&mut self) {
let mut path_line = PathInputLine::new("Save: ".into());
let ref sr = self.signal_receiver.as_mut().unwrap();
path_line.on_done.connect(signal!(sr with |obj, path| {
obj.save(&path);
obj.input_entry = None;
}));
path_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(path_line) as Box<InputLine>)
}
fn start_open(&mut self) {
let mut path_line = PathInputLine::new("Open: ".into());
let ref sr = self.signal_receiver.as_mut().unwrap();
path_line.on_done.connect(signal!(sr with |obj, path| {
obj.open(&path);
obj.input_entry = None;
}));
path_line.on_cancel.connect(signal!(sr with |obj, opt_msg| {
if let Some(ref msg) = opt_msg {
obj.status(msg.clone());
} else {
obj.clear_status();
}
obj.input_entry = None;
}));
self.input_entry = Some(Box::new(path_line) as Box<InputLine>)
}
fn process_msgs(&mut self) {
let mut sr = self.signal_receiver.take().unwrap();
sr.run(self);
self.signal_receiver = Some(sr);
}
pub fn input(&mut self, key: Key) {
self.process_msgs();
if let Some(ref mut overlay) = self.overlay {
overlay.input(&self.input, key);
} else if let Some(ref mut input_entry) = self.input_entry {
input_entry.input(&self.input, key);
} else {
self.view_input(key);
}
self.process_msgs();
}
pub fn resize(&mut self, width: i32, height: i32) {
self.rect.height = height as isize - 1; // Substract 1 for the status line on the bottom
self.rect.width = width as isize;
self.update_cursor();
}
}
|
//! This module defines a [`BVH`] building procedure as well as a [`BVH`] flattening procedure
//! so that the recursive structure can be easily used in compute shaders.
//!
//! [`BVH`]: struct.BVH.html
//!
use aabb::{AABB, Bounded};
use ray::Ray;
use std::boxed::Box;
use std::f32;
use std::iter::repeat;
/// Enum which describes the union type of a node in a [`BVH`]s.
/// This structure does not allow to store a root node's [`AABB`]. Therefore rays
/// which do not hit the root [`AABB`] perform two [`AABB`] tests (left/right) instead of one.
/// On the other hand this structure decreases the total number of indirections.
///
/// [`AABB`]: ../aabb/struct.AABB.html
/// [`BVH`]: struct.BVH.html
///
enum BVHNode {
/// Leaf node.
Leaf {
/// The shapes contained in this leaf.
shapes: Vec<usize>,
},
/// Inner node.
Node {
/// The union `AABB` of the shapes in child_l.
child_l_aabb: AABB,
child_l: Box<BVHNode>,
/// The union `AABB` of the shapes in child_r.
child_r_aabb: AABB,
child_r: Box<BVHNode>,
},
}
impl BVHNode {
/// Builds a [`BVHNode`] recursively using SAH partitioning.
///
/// [`BVHNode`]: enum.BVHNode.html
///
pub fn build<T: Bounded>(shapes: &[T], indices: Vec<usize>) -> BVHNode {
// Helper function to accumulate the AABB union and the centroids AABB.
fn grow_union_bounds(union_bounds: (AABB, AABB), shape_aabb: &AABB) -> (AABB, AABB) {
let center = &shape_aabb.center();
let union_aabbs = &union_bounds.0;
let union_centroids = &union_bounds.1;
(union_aabbs.union(shape_aabb), union_centroids.grow(center))
}
let mut union_bounds = Default::default();
for index in &indices {
union_bounds = grow_union_bounds(union_bounds, &shapes[*index].aabb());
}
let (aabb_bounds, centroid_bounds) = union_bounds;
// If there are less than five elements, don't split anymore
if indices.len() <= 5 {
return BVHNode::Leaf { shapes: indices };
}
// Find the axis along which the shapes are spread the most
let split_axis = centroid_bounds.largest_axis();
let split_axis_size = centroid_bounds.max[split_axis] - centroid_bounds.min[split_axis];
const EPSILON: f32 = 0.0000001;
if split_axis_size < EPSILON {
return BVHNode::Leaf { shapes: indices };
}
/// Defines a Bucket utility object
#[derive(Copy, Clone)]
struct Bucket {
size: usize,
aabb: AABB,
}
impl Bucket {
/// Returns an empty bucket
fn empty() -> Bucket {
Bucket {
size: 0,
aabb: AABB::empty(),
}
}
/// Extends this `Bucket` by the given `AABB`.
fn add_aabb(&mut self, aabb: &AABB) {
self.size += 1;
self.aabb = self.aabb.union(aabb);
}
}
/// Returns the union of two `Bucket`s.
fn bucket_union(a: Bucket, b: &Bucket) -> Bucket {
Bucket {
size: a.size + b.size,
aabb: a.aabb.union(&b.aabb),
}
}
// Create twelve buckets, and twelve index assignment vectors
const NUM_BUCKETS: usize = 6;
let mut buckets = [Bucket::empty(); NUM_BUCKETS];
let mut bucket_assignments: [Vec<usize>; NUM_BUCKETS] = Default::default();
// Iterate through all shapes
for idx in &indices {
let shape = &shapes[*idx];
let shape_aabb = shape.aabb();
let shape_center = shape_aabb.center();
// Get the relative position of the shape centroid [0.0..1.0]
let bucket_num_relative = (shape_center[split_axis] - centroid_bounds.min[split_axis]) /
split_axis_size;
// Convert that to the actual `Bucket` number
let bucket_num = (bucket_num_relative * (NUM_BUCKETS as f32 - 0.01)) as usize;
// Extend the selected `Bucket` and add the index to the actual bucket
buckets[bucket_num].add_aabb(&shape_aabb);
bucket_assignments[bucket_num].push(*idx);
}
// Compute the costs for each configuration and
// select the configuration with the minimal costs
let mut min_bucket = 0;
let mut min_cost = f32::INFINITY;
let mut child_l_aabb = AABB::empty();
let mut child_r_aabb = AABB::empty();
for i in 0..(NUM_BUCKETS - 1) {
let child_l = buckets.iter().take(i + 1).fold(Bucket::empty(), bucket_union);
let child_r = buckets.iter().skip(i + 1).fold(Bucket::empty(), bucket_union);
let cost = (child_l.size as f32 * child_l.aabb.surface_area() +
child_r.size as f32 * child_r.aabb.surface_area()) /
aabb_bounds.surface_area();
if cost < min_cost {
min_bucket = i;
min_cost = cost;
child_l_aabb = child_l.aabb;
child_r_aabb = child_r.aabb;
}
}
// Join together all index buckets, and proceed recursively
let mut child_l_indices = Vec::new();
for mut indices in bucket_assignments.iter_mut().take(min_bucket + 1) {
child_l_indices.append(&mut indices);
}
let mut child_r_indices = Vec::new();
for mut indices in bucket_assignments.iter_mut().skip(min_bucket + 1) {
child_r_indices.append(&mut indices);
}
// Construct the actual data structure
BVHNode::Node {
child_l_aabb: child_l_aabb,
child_l: Box::new(BVHNode::build(shapes, child_l_indices)),
child_r_aabb: child_r_aabb,
child_r: Box::new(BVHNode::build(shapes, child_r_indices)),
}
}
/// Prints a textual representation of the recursive [`BVH`] structure.
///
/// [`BVH`]: struct.BVH.html
///
fn print(&self, depth: usize) {
let padding: String = repeat(" ").take(depth).collect();
match *self {
BVHNode::Node { ref child_l, ref child_r, .. } => {
println!("{}child_l", padding);
child_l.print(depth + 1);
println!("{}child_r", padding);
child_r.print(depth + 1);
}
BVHNode::Leaf { ref shapes } => {
println!("{}shapes\t{:?}", padding, shapes);
}
}
}
/// Traverses the [`BVH`] recursively and returns a [`Vec`]
/// of all shapes which are hit with a high probability.
///
/// [`BVH`]: struct.BVH.html
/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
///
pub fn traverse_recursive(&self, ray: &Ray, indices: &mut Vec<usize>) {
match *self {
BVHNode::Node { ref child_l_aabb, ref child_l, ref child_r_aabb, ref child_r } => {
if ray.intersects_aabb(child_l_aabb) {
child_l.traverse_recursive(ray, indices);
}
if ray.intersects_aabb(child_r_aabb) {
child_r.traverse_recursive(ray, indices);
}
}
BVHNode::Leaf { ref shapes } => {
for index in shapes {
indices.push(*index);
}
}
}
}
}
/// The [`BVH`] data structure. Only contains the [`BVH`] structure and indices to
/// the slice of shapes given in the [`build`] function.
///
/// [`BVH`]: struct.BVH.html
/// [`build`]: struct.BVH.html#method.build
///
pub struct BVH {
/// The root node of the [`BVH`].
///
/// [`BVH`]: struct.BVH.html
///
root: BVHNode,
}
impl BVH {
/// Creates a new [`BVH`] from the slice of shapes.
///
/// [`BVH`]: struct.BVH.html
///
pub fn build<T: Bounded>(shapes: &[T]) -> BVH {
let indices = (0..shapes.len()).collect::<Vec<usize>>();
let root = BVHNode::build(shapes, indices);
BVH { root: root }
}
/// Prints the [`BVH`] in a tree-like visualization.
///
/// [`BVH`]: struct.BVH.html
///
pub fn print(&self) {
self.root.print(0);
}
/// Traverses the tree recursively. Returns an array of all shapes, the [`AABB`]s of which
/// were hit.
///
/// [`AABB`]: ../aabb/struct.AABB.html
///
pub fn traverse_recursive<'a, T: Bounded>(&'a self, ray: &Ray, shapes: &'a [T]) -> Vec<&T> {
let mut indices = Vec::new();
self.root.traverse_recursive(ray, &mut indices);
let mut hit_shapes = Vec::new();
for index in &indices {
let shape = &shapes[*index];
if ray.intersects_aabb(&shape.aabb()) {
hit_shapes.push(shape);
}
}
hit_shapes
}
}
#[cfg(test)]
mod tests {
use aabb::{AABB, Bounded};
use bvh::BVH;
use nalgebra::{Point3, Vector3};
use std::collections::HashSet;
use ray::Ray;
/// Define some Bounded structure.
struct XBox {
x: i32,
}
/// `XBox`'s `AABB`s are unit `AABB`s centered on the given x-position.
impl Bounded for XBox {
fn aabb(&self) -> AABB {
let min = Point3::new(self.x as f32 - 0.5, -0.5, -0.5);
let max = Point3::new(self.x as f32 + 0.5, 0.5, 0.5);
AABB::with_bounds(min, max)
}
}
/// Creates a `BVH` for a fixed scene structure.
fn build_some_bvh() -> (Vec<XBox>, BVH) {
// Create 21 boxes along the x-axis
let mut shapes = Vec::new();
for x in -10..11 {
shapes.push(XBox { x: x });
}
let bvh = BVH::build(&shapes);
(shapes, bvh)
}
#[test]
/// Tests whether the building procedure succeeds in not failing.
fn test_build_bvh() {
build_some_bvh();
}
#[test]
/// Runs some primitive tests for intersections of a ray with a fixed scene given as a BVH.
fn test_traverse_recursive_bvh() {
let (shapes, bvh) = build_some_bvh();
// Define a ray which traverses the x-axis from afar
let position_1 = Point3::new(-1000.0, 0.0, 0.0);
let direction_1 = Vector3::new(1.0, 0.0, 0.0);
let ray_1 = Ray::new(position_1, direction_1);
// It shuold hit all shapes
let hit_shapes_1 = bvh.traverse_recursive(&ray_1, &shapes);
assert!(hit_shapes_1.len() == 21);
let mut xs_1 = HashSet::new();
for shape in &hit_shapes_1 {
xs_1.insert(shape.x);
}
for x in -10..11 {
assert!(xs_1.contains(&x));
}
// Define a ray which traverses the y-axis from afar
let position_2 = Point3::new(0.0, -1000.0, 0.0);
let direction_2 = Vector3::new(0.0, 1.0, 0.0);
let ray_2 = Ray::new(position_2, direction_2);
// It should hit only one box
let hit_shapes_2 = bvh.traverse_recursive(&ray_2, &shapes);
assert!(hit_shapes_2.len() == 1);
assert!(hit_shapes_2[0].x == 0);
// Define a ray which intersects the x-axis diagonally
let position_3 = Point3::new(6.0, 0.5, 0.0);
let direction_3 = Vector3::new(-2.0, -1.0, 0.0);
let ray_3 = Ray::new(position_3, direction_3);
// It should hit exactly three boxes
let hit_shapes_3 = bvh.traverse_recursive(&ray_3, &shapes);
assert!(hit_shapes_3.len() == 3);
let mut xs_3 = HashSet::new();
for shape in &hit_shapes_3 {
xs_3.insert(shape.x);
}
assert!(xs_3.contains(&6));
assert!(xs_3.contains(&5));
assert!(xs_3.contains(&4));
}
/// A triangle struct. Instance of a more complex `Bounded` primitive.
pub struct Triangle {
a: Point3<f32>,
b: Point3<f32>,
c: Point3<f32>,
aabb: AABB,
}
impl Triangle {
fn new(a: Point3<f32>, b: Point3<f32>, c: Point3<f32>) -> Triangle {
let mut min = a;
let mut max = a;
min.x = min.x.min(b.x).min(c.x);
min.y = min.y.min(b.y).min(c.y);
min.z = min.z.min(b.z).min(c.z);
max.x = max.x.max(b.x).max(c.x);
max.y = max.y.max(b.y).max(c.y);
max.z = max.z.max(b.z).max(c.z);
Triangle {
a: a,
b: b,
c: c,
aabb: AABB::with_bounds(min, max),
}
}
}
impl Bounded for Triangle {
fn aabb(&self) -> AABB {
self.aabb
}
}
/// Creates a unit size cube centered at `pos` and pushes the triangles to `shapes`
fn push_cube(pos: Point3<f32>, shapes: &mut Vec<Triangle>) {
let top_front_right = pos + Vector3::new(0.5, 0.5, -0.5);
let top_back_right = pos + Vector3::new(0.5, 0.5, 0.5);
let top_back_left = pos + Vector3::new(-0.5, 0.5, 0.5);
let top_front_left = pos + Vector3::new(-0.5, 0.5, -0.5);
let bottom_front_right = pos + Vector3::new(0.5, -0.5, -0.5);
let bottom_back_right = pos + Vector3::new(0.5, -0.5, 0.5);
let bottom_back_left = pos + Vector3::new(-0.5, -0.5, 0.5);
let bottom_front_left = pos + Vector3::new(-0.5, -0.5, -0.5);
shapes.push(Triangle::new(top_back_right, top_front_right, top_front_left));
shapes.push(Triangle::new(top_front_left, top_back_left, top_back_right));
shapes.push(Triangle::new(bottom_front_left, bottom_front_right, bottom_back_right));
shapes.push(Triangle::new(bottom_back_right, bottom_back_left, bottom_front_left));
shapes.push(Triangle::new(top_back_left, top_front_left, bottom_front_left));
shapes.push(Triangle::new(bottom_front_left, bottom_back_left, top_back_left));
shapes.push(Triangle::new(bottom_front_right, top_front_right, top_back_right));
shapes.push(Triangle::new(top_back_right, bottom_back_right, bottom_front_right));
shapes.push(Triangle::new(top_front_left, top_front_right, bottom_front_right));
shapes.push(Triangle::new(bottom_front_right, bottom_front_left, top_front_left));
shapes.push(Triangle::new(bottom_back_right, top_back_right, top_back_left));
shapes.push(Triangle::new(top_back_left, bottom_back_left, bottom_back_right));
}
/// Implementation of splitmix64.
/// For reference see: http://xoroshiro.di.unimi.it/splitmix64.c
fn splitmix64(x: &mut u64) -> u64 {
*x = x.wrapping_add(0x9E3779B97F4A7C15u64);
let mut z = *x;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9u64);
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EBu64);
z ^ (z >> 31)
}
fn next_point3(seed: &mut u64) -> Point3<f32> {
let u = splitmix64(seed);
let a = (u >> 48 & 0xFFFFFFFF) as i32 - 0xFFFF;
let b = (u >> 48 & 0xFFFFFFFF) as i32 - 0xFFFF;
let c = a ^ b.rotate_left(6);
Point3::new(a as f32, b as f32, c as f32)
}
pub fn create_n_cubes(n: u64) -> Vec<Triangle> {
let mut vec = Vec::new();
let mut seed = 0;
for _ in 0..n {
push_cube(next_point3(&mut seed), &mut vec);
}
vec
}
pub fn create_ray(seed: &mut u64) -> Ray {
let origin = next_point3(seed);
let direction = next_point3(seed).to_vector();
Ray::new(origin, direction)
}
#[bench]
/// Benchmark the construction of a BVH with 120,000 triangles.
fn bench_build_120k_triangles_bvh(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
b.iter(|| {
BVH::build(&triangles);
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles directly.
fn bench_intersect_120k_triangles_list(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Iterate over the list of triangles
for triangle in &triangles {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles with preceeding `AABB` tests.
fn bench_intersect_120k_triangles_list_aabb(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Iterate over the list of triangles
for triangle in &triangles {
// First test whether the ray intersects the AABB of the triangle
if ray.intersects_aabb(&triangle.aabb()) {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
}
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles using the recursive BVH.
fn bench_intersect_120k_triangles_bvh_recursive(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let bvh = BVH::build(&triangles);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Traverse the BVH recursively
let hits = bvh.traverse_recursive(&ray, &triangles);
// Traverse the resulting list of positive AABB tests
for triangle in &hits {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
});
}
}
Fix comments
//! This module defines a [`BVH`] building procedure as well as a [`BVH`] flattening procedure
//! so that the recursive structure can be easily used in compute shaders.
//!
//! [`BVH`]: struct.BVH.html
//!
use aabb::{AABB, Bounded};
use ray::Ray;
use std::boxed::Box;
use std::f32;
use std::iter::repeat;
/// Enum which describes the union type of a node in a [`BVH`].
/// This structure does not allow to store a root node's [`AABB`]. Therefore rays
/// which do not hit the root [`AABB`] perform two [`AABB`] tests (left/right) instead of one.
/// On the other hand this structure decreases the total number of indirections.
///
/// [`AABB`]: ../aabb/struct.AABB.html
/// [`BVH`]: struct.BVH.html
///
enum BVHNode {
/// Leaf node.
Leaf {
/// The shapes contained in this leaf.
shapes: Vec<usize>,
},
/// Inner node.
Node {
/// The union `AABB` of the shapes in child_l.
child_l_aabb: AABB,
child_l: Box<BVHNode>,
/// The union `AABB` of the shapes in child_r.
child_r_aabb: AABB,
child_r: Box<BVHNode>,
},
}
impl BVHNode {
/// Builds a [`BVHNode`] recursively using SAH partitioning.
///
/// [`BVHNode`]: enum.BVHNode.html
///
pub fn build<T: Bounded>(shapes: &[T], indices: Vec<usize>) -> BVHNode {
// Helper function to accumulate the AABB union and the centroids AABB
fn grow_union_bounds(union_bounds: (AABB, AABB), shape_aabb: &AABB) -> (AABB, AABB) {
let center = &shape_aabb.center();
let union_aabbs = &union_bounds.0;
let union_centroids = &union_bounds.1;
(union_aabbs.union(shape_aabb), union_centroids.grow(center))
}
let mut union_bounds = Default::default();
for index in &indices {
union_bounds = grow_union_bounds(union_bounds, &shapes[*index].aabb());
}
let (aabb_bounds, centroid_bounds) = union_bounds;
// If there are less than five elements, don't split anymore
if indices.len() <= 5 {
return BVHNode::Leaf { shapes: indices };
}
// Find the axis along which the shapes are spread the most
let split_axis = centroid_bounds.largest_axis();
let split_axis_size = centroid_bounds.max[split_axis] - centroid_bounds.min[split_axis];
const EPSILON: f32 = 0.0000001;
if split_axis_size < EPSILON {
return BVHNode::Leaf { shapes: indices };
}
/// Defines a Bucket utility object.
#[derive(Copy, Clone)]
struct Bucket {
size: usize,
aabb: AABB,
}
impl Bucket {
/// Returns an empty bucket.
fn empty() -> Bucket {
Bucket {
size: 0,
aabb: AABB::empty(),
}
}
/// Extends this `Bucket` by the given `AABB`.
fn add_aabb(&mut self, aabb: &AABB) {
self.size += 1;
self.aabb = self.aabb.union(aabb);
}
}
/// Returns the union of two `Bucket`s.
fn bucket_union(a: Bucket, b: &Bucket) -> Bucket {
Bucket {
size: a.size + b.size,
aabb: a.aabb.union(&b.aabb),
}
}
// Create twelve buckets, and twelve index assignment vectors
const NUM_BUCKETS: usize = 6;
let mut buckets = [Bucket::empty(); NUM_BUCKETS];
let mut bucket_assignments: [Vec<usize>; NUM_BUCKETS] = Default::default();
// Iterate through all shapes
for idx in &indices {
let shape = &shapes[*idx];
let shape_aabb = shape.aabb();
let shape_center = shape_aabb.center();
// Get the relative position of the shape centroid [0.0..1.0]
let bucket_num_relative = (shape_center[split_axis] - centroid_bounds.min[split_axis]) /
split_axis_size;
// Convert that to the actual `Bucket` number
let bucket_num = (bucket_num_relative * (NUM_BUCKETS as f32 - 0.01)) as usize;
// Extend the selected `Bucket` and add the index to the actual bucket
buckets[bucket_num].add_aabb(&shape_aabb);
bucket_assignments[bucket_num].push(*idx);
}
// Compute the costs for each configuration and
// select the configuration with the minimal costs
let mut min_bucket = 0;
let mut min_cost = f32::INFINITY;
let mut child_l_aabb = AABB::empty();
let mut child_r_aabb = AABB::empty();
for i in 0..(NUM_BUCKETS - 1) {
let child_l = buckets.iter().take(i + 1).fold(Bucket::empty(), bucket_union);
let child_r = buckets.iter().skip(i + 1).fold(Bucket::empty(), bucket_union);
let cost = (child_l.size as f32 * child_l.aabb.surface_area() +
child_r.size as f32 * child_r.aabb.surface_area()) /
aabb_bounds.surface_area();
if cost < min_cost {
min_bucket = i;
min_cost = cost;
child_l_aabb = child_l.aabb;
child_r_aabb = child_r.aabb;
}
}
// Join together all index buckets, and proceed recursively
let mut child_l_indices = Vec::new();
for mut indices in bucket_assignments.iter_mut().take(min_bucket + 1) {
child_l_indices.append(&mut indices);
}
let mut child_r_indices = Vec::new();
for mut indices in bucket_assignments.iter_mut().skip(min_bucket + 1) {
child_r_indices.append(&mut indices);
}
// Construct the actual data structure
BVHNode::Node {
child_l_aabb: child_l_aabb,
child_l: Box::new(BVHNode::build(shapes, child_l_indices)),
child_r_aabb: child_r_aabb,
child_r: Box::new(BVHNode::build(shapes, child_r_indices)),
}
}
/// Prints a textual representation of the recursive [`BVH`] structure.
///
/// [`BVH`]: struct.BVH.html
///
fn print(&self, depth: usize) {
let padding: String = repeat(" ").take(depth).collect();
match *self {
BVHNode::Node { ref child_l, ref child_r, .. } => {
println!("{}child_l", padding);
child_l.print(depth + 1);
println!("{}child_r", padding);
child_r.print(depth + 1);
}
BVHNode::Leaf { ref shapes } => {
println!("{}shapes\t{:?}", padding, shapes);
}
}
}
/// Traverses the [`BVH`] recursively and returns a [`Vec`]
/// of all shapes which are hit with a high probability.
///
/// [`BVH`]: struct.BVH.html
/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
///
pub fn traverse_recursive(&self, ray: &Ray, indices: &mut Vec<usize>) {
match *self {
BVHNode::Node { ref child_l_aabb, ref child_l, ref child_r_aabb, ref child_r } => {
if ray.intersects_aabb(child_l_aabb) {
child_l.traverse_recursive(ray, indices);
}
if ray.intersects_aabb(child_r_aabb) {
child_r.traverse_recursive(ray, indices);
}
}
BVHNode::Leaf { ref shapes } => {
for index in shapes {
indices.push(*index);
}
}
}
}
}
/// The [`BVH`] data structure. Only contains the [`BVH`] structure and indices to
/// the slice of shapes given in the [`build`] function.
///
/// [`BVH`]: struct.BVH.html
/// [`build`]: struct.BVH.html#method.build
///
pub struct BVH {
/// The root node of the [`BVH`].
///
/// [`BVH`]: struct.BVH.html
///
root: BVHNode,
}
impl BVH {
/// Creates a new [`BVH`] from the slice of shapes.
///
/// [`BVH`]: struct.BVH.html
///
pub fn build<T: Bounded>(shapes: &[T]) -> BVH {
let indices = (0..shapes.len()).collect::<Vec<usize>>();
let root = BVHNode::build(shapes, indices);
BVH { root: root }
}
/// Prints the [`BVH`] in a tree-like visualization.
///
/// [`BVH`]: struct.BVH.html
///
pub fn print(&self) {
self.root.print(0);
}
/// Traverses the tree recursively. Returns an array of all shapes, the [`AABB`]s of which
/// were hit.
///
/// [`AABB`]: ../aabb/struct.AABB.html
///
pub fn traverse_recursive<'a, T: Bounded>(&'a self, ray: &Ray, shapes: &'a [T]) -> Vec<&T> {
let mut indices = Vec::new();
self.root.traverse_recursive(ray, &mut indices);
let mut hit_shapes = Vec::new();
for index in &indices {
let shape = &shapes[*index];
if ray.intersects_aabb(&shape.aabb()) {
hit_shapes.push(shape);
}
}
hit_shapes
}
}
#[cfg(test)]
mod tests {
use aabb::{AABB, Bounded};
use bvh::BVH;
use nalgebra::{Point3, Vector3};
use std::collections::HashSet;
use ray::Ray;
/// Define some Bounded structure.
struct XBox {
x: i32,
}
/// `XBox`'s `AABB`s are unit `AABB`s centered on the given x-position.
impl Bounded for XBox {
fn aabb(&self) -> AABB {
let min = Point3::new(self.x as f32 - 0.5, -0.5, -0.5);
let max = Point3::new(self.x as f32 + 0.5, 0.5, 0.5);
AABB::with_bounds(min, max)
}
}
/// Creates a `BVH` for a fixed scene structure.
fn build_some_bvh() -> (Vec<XBox>, BVH) {
// Create 21 boxes along the x-axis
let mut shapes = Vec::new();
for x in -10..11 {
shapes.push(XBox { x: x });
}
let bvh = BVH::build(&shapes);
(shapes, bvh)
}
#[test]
/// Tests whether the building procedure succeeds in not failing.
fn test_build_bvh() {
build_some_bvh();
}
#[test]
/// Runs some primitive tests for intersections of a ray with a fixed scene given as a BVH.
fn test_traverse_recursive_bvh() {
let (shapes, bvh) = build_some_bvh();
// Define a ray which traverses the x-axis from afar
let position_1 = Point3::new(-1000.0, 0.0, 0.0);
let direction_1 = Vector3::new(1.0, 0.0, 0.0);
let ray_1 = Ray::new(position_1, direction_1);
// It shuold hit all shapes
let hit_shapes_1 = bvh.traverse_recursive(&ray_1, &shapes);
assert!(hit_shapes_1.len() == 21);
let mut xs_1 = HashSet::new();
for shape in &hit_shapes_1 {
xs_1.insert(shape.x);
}
for x in -10..11 {
assert!(xs_1.contains(&x));
}
// Define a ray which traverses the y-axis from afar
let position_2 = Point3::new(0.0, -1000.0, 0.0);
let direction_2 = Vector3::new(0.0, 1.0, 0.0);
let ray_2 = Ray::new(position_2, direction_2);
// It should hit only one box
let hit_shapes_2 = bvh.traverse_recursive(&ray_2, &shapes);
assert!(hit_shapes_2.len() == 1);
assert!(hit_shapes_2[0].x == 0);
// Define a ray which intersects the x-axis diagonally
let position_3 = Point3::new(6.0, 0.5, 0.0);
let direction_3 = Vector3::new(-2.0, -1.0, 0.0);
let ray_3 = Ray::new(position_3, direction_3);
// It should hit exactly three boxes
let hit_shapes_3 = bvh.traverse_recursive(&ray_3, &shapes);
assert!(hit_shapes_3.len() == 3);
let mut xs_3 = HashSet::new();
for shape in &hit_shapes_3 {
xs_3.insert(shape.x);
}
assert!(xs_3.contains(&6));
assert!(xs_3.contains(&5));
assert!(xs_3.contains(&4));
}
/// A triangle struct. Instance of a more complex `Bounded` primitive.
pub struct Triangle {
a: Point3<f32>,
b: Point3<f32>,
c: Point3<f32>,
aabb: AABB,
}
impl Triangle {
fn new(a: Point3<f32>, b: Point3<f32>, c: Point3<f32>) -> Triangle {
let mut min = a;
let mut max = a;
min.x = min.x.min(b.x).min(c.x);
min.y = min.y.min(b.y).min(c.y);
min.z = min.z.min(b.z).min(c.z);
max.x = max.x.max(b.x).max(c.x);
max.y = max.y.max(b.y).max(c.y);
max.z = max.z.max(b.z).max(c.z);
Triangle {
a: a,
b: b,
c: c,
aabb: AABB::with_bounds(min, max),
}
}
}
impl Bounded for Triangle {
fn aabb(&self) -> AABB {
self.aabb
}
}
/// Creates a unit size cube centered at `pos` and pushes the triangles to `shapes`
fn push_cube(pos: Point3<f32>, shapes: &mut Vec<Triangle>) {
let top_front_right = pos + Vector3::new(0.5, 0.5, -0.5);
let top_back_right = pos + Vector3::new(0.5, 0.5, 0.5);
let top_back_left = pos + Vector3::new(-0.5, 0.5, 0.5);
let top_front_left = pos + Vector3::new(-0.5, 0.5, -0.5);
let bottom_front_right = pos + Vector3::new(0.5, -0.5, -0.5);
let bottom_back_right = pos + Vector3::new(0.5, -0.5, 0.5);
let bottom_back_left = pos + Vector3::new(-0.5, -0.5, 0.5);
let bottom_front_left = pos + Vector3::new(-0.5, -0.5, -0.5);
shapes.push(Triangle::new(top_back_right, top_front_right, top_front_left));
shapes.push(Triangle::new(top_front_left, top_back_left, top_back_right));
shapes.push(Triangle::new(bottom_front_left, bottom_front_right, bottom_back_right));
shapes.push(Triangle::new(bottom_back_right, bottom_back_left, bottom_front_left));
shapes.push(Triangle::new(top_back_left, top_front_left, bottom_front_left));
shapes.push(Triangle::new(bottom_front_left, bottom_back_left, top_back_left));
shapes.push(Triangle::new(bottom_front_right, top_front_right, top_back_right));
shapes.push(Triangle::new(top_back_right, bottom_back_right, bottom_front_right));
shapes.push(Triangle::new(top_front_left, top_front_right, bottom_front_right));
shapes.push(Triangle::new(bottom_front_right, bottom_front_left, top_front_left));
shapes.push(Triangle::new(bottom_back_right, top_back_right, top_back_left));
shapes.push(Triangle::new(top_back_left, bottom_back_left, bottom_back_right));
}
/// Implementation of splitmix64.
/// For reference see: http://xoroshiro.di.unimi.it/splitmix64.c
fn splitmix64(x: &mut u64) -> u64 {
*x = x.wrapping_add(0x9E3779B97F4A7C15u64);
let mut z = *x;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9u64);
z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EBu64);
z ^ (z >> 31)
}
fn next_point3(seed: &mut u64) -> Point3<f32> {
let u = splitmix64(seed);
let a = (u >> 48 & 0xFFFFFFFF) as i32 - 0xFFFF;
let b = (u >> 48 & 0xFFFFFFFF) as i32 - 0xFFFF;
let c = a ^ b.rotate_left(6);
Point3::new(a as f32, b as f32, c as f32)
}
pub fn create_n_cubes(n: u64) -> Vec<Triangle> {
let mut vec = Vec::new();
let mut seed = 0;
for _ in 0..n {
push_cube(next_point3(&mut seed), &mut vec);
}
vec
}
pub fn create_ray(seed: &mut u64) -> Ray {
let origin = next_point3(seed);
let direction = next_point3(seed).to_vector();
Ray::new(origin, direction)
}
#[bench]
/// Benchmark the construction of a BVH with 120,000 triangles.
fn bench_build_120k_triangles_bvh(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
b.iter(|| {
BVH::build(&triangles);
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles directly.
fn bench_intersect_120k_triangles_list(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Iterate over the list of triangles
for triangle in &triangles {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles with preceeding `AABB` tests.
fn bench_intersect_120k_triangles_list_aabb(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Iterate over the list of triangles
for triangle in &triangles {
// First test whether the ray intersects the AABB of the triangle
if ray.intersects_aabb(&triangle.aabb()) {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
}
});
}
#[bench]
/// Benchmark intersecting 120,000 triangles using the recursive BVH.
fn bench_intersect_120k_triangles_bvh_recursive(b: &mut ::test::Bencher) {
let triangles = create_n_cubes(10_000);
let bvh = BVH::build(&triangles);
let mut seed = 0;
b.iter(|| {
let ray = create_ray(&mut seed);
// Traverse the BVH recursively
let hits = bvh.traverse_recursive(&ray, &triangles);
// Traverse the resulting list of positive AABB tests
for triangle in &hits {
ray.intersects_triangle(&triangle.a, &triangle.b, &triangle.c);
}
});
}
}
|
use bincode::SizeLimit;
use bincode::rustc_serialize as serializer;
use fillings::BitsVec;
use num_traits::{Num, NumCast, cast};
use sa::{Output, suffix_array_};
use std::fs::File;
use std::path::Path;
// Generate the BWT of input data (calls the given function with the BWT data as it's generated)
pub fn bwt(input: Vec<u8>) -> Vec<u8> {
match suffix_array_(input, 0, /* generate bwt */ true) {
Output::BWT(v) => v,
_ => unreachable!(),
}
}
// Insert (or) Increment a counter at an index
fn insert<T>(vec: &mut BitsVec<usize>, value: T) -> usize
where T: Num + NumCast + PartialOrd + Copy
{
let idx = cast(value).unwrap();
if vec.len() <= idx {
vec.extend_with_element(idx + 1, 0);
}
let old = vec.get(idx);
vec.set(idx, old + 1);
old + 1
}
// Takes a frequency map of bytes and generates the index of first occurrence
// of each byte.
fn generate_occurrence_index(map: &mut BitsVec<usize>) {
let mut idx = 0;
for i in 0..map.len() {
let c = map.get(i);
map.set(i, idx);
idx += c;
}
}
// Invert the BWT data (generate the original data)
pub fn ibwt(input: Vec<u8>) -> Vec<u8> {
// get the byte distribution
let bits = (input.len().next_power_of_two() - 1).count_ones() as usize;
let mut map = BitsVec::new(bits);
for i in &input {
insert(&mut map, *i);
}
generate_occurrence_index(&mut map);
// generate the LF vector
let mut lf = vec![0; input.len()];
for (i, c) in input.iter().enumerate() {
let val = map.get(*c as usize);
lf[i] = val;
map.set(*c as usize, val + 1);
}
let mut idx = 0;
// construct the sequence by traversing through the LF vector
let mut output = vec![0; input.len()];
for i in (0..(input.len() - 1)).rev() {
output[i] = input[idx];
idx = lf[idx];
}
output.pop();
output
}
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct FMIndex {
// BW-transformed data
data: Vec<u8>,
// forward frequency of each character in the BWT data
cache: BitsVec<usize>,
// incremental character frequencies
occ_map: BitsVec<usize>,
// LF-mapping for backward search
lf_vec: BitsVec<usize>,
}
impl FMIndex {
pub fn new(data: Vec<u8>) -> FMIndex {
let mut idx = 0;
// worst case (all bytes are distinct)
let bits = (data.len().next_power_of_two() - 1).count_ones() as usize;
let mut map = BitsVec::new(bits);
let mut count = BitsVec::with_elements(bits, data.len() + 1, 0);
let mut lf_vec = count.clone();
let bwt_data = bwt(data);
// generate the frequency map and forward frequency vector from BWT
for i in &bwt_data {
let value = insert(&mut map, *i);
count.set(idx, value);
idx += 1;
}
generate_occurrence_index(&mut map);
let mut lf_occ_map = map.clone();
// generate the LF vector (just like inverting the BWT)
for (i, c) in bwt_data.iter().enumerate() {
let idx = *c as usize;
let val = lf_occ_map.get(idx);
lf_vec.set(i, val);
lf_occ_map.set(idx, val + 1);
}
let mut i = 0;
let mut counter = bwt_data.len();
// Only difference is that we replace the LF indices with the lengths of prefix
// from a particular position (in other words, the number of times
// it would take us to get to the start of string).
for _ in 0..bwt_data.len() {
let next = lf_vec.get(i);
lf_vec.set(i, counter);
i = next;
counter -= 1;
}
FMIndex {
data: bwt_data,
cache: count,
occ_map: map,
lf_vec: lf_vec,
}
}
pub fn load<P: AsRef<Path>>(path: P) -> Result<FMIndex, ()> {
let mut fd = try!(File::open(path).map_err(|_| ()));
serializer::decode_from(&mut fd, SizeLimit::Infinite).map_err(|_| ())
}
pub fn dump<P: AsRef<Path>>(&self, path: P) -> Result<(), ()> {
let mut fd = try!(File::create(path).map_err(|_| ()));
serializer::encode_into(&self, &mut fd, SizeLimit::Infinite).map_err(|_| ())
}
// Get the index of the nearest occurrence of a character in the BWT data
fn nearest(&self, idx: usize, ch: u8) -> usize {
let mut result = self.occ_map.get(ch as usize);
if result > 0 {
result += (0..idx).rev()
.find(|&i| self.data[i] == ch)
.map(|i| self.cache.get(i) as usize)
.unwrap_or(0);
}
result
}
// Find the positions of occurrences of sub-string in the original data.
pub fn search(&self, query: &str) -> Vec<usize> {
let mut top = 0;
let mut bottom = self.data.len();
for ch in query.as_bytes().iter().rev() {
top = self.nearest(top, *ch);
bottom = self.nearest(bottom, *ch);
}
(top..bottom).map(|idx| {
let i = self.nearest(idx, self.data[idx]);
// wrap around on overflow, which usually occurs only for the
// last index of LF vector (or the first index of original string)
self.lf_vec.get(i) % self.data.len()
}).collect()
}
}
#[cfg(test)]
mod tests {
use super::{FMIndex, bwt, ibwt};
#[test]
fn test_bwt_and_ibwt() {
let text = String::from("ATCTAGGAGATCTGAATCTAGTTCAACTAGCTAGATCTAGAGACAGCTAA");
let bw = bwt(text.as_bytes().to_owned());
let ibw = ibwt(bw.clone());
assert_eq!(String::from("AATCGGAGTTGCTTTG\u{0}AGTAGTGATTTTAAGAAAAAACCCCCCTAAAACG"),
String::from_utf8(bw).unwrap());
assert_eq!(text, String::from_utf8(ibw).unwrap());
}
#[test]
fn test_fm_index() {
let text = String::from("GCGTGCCCAGGGCACTGCCGCTGCAGGCGTAGGCATCGCATCACACGCGT");
let index = FMIndex::new(text.as_bytes().to_owned());
let mut result = index.search("TG");
result.sort();
assert_eq!(result, vec![3, 15, 21]);
let mut result = index.search("GCGT");
result.sort();
assert_eq!(result, vec![0, 26, 46]);
assert_eq!(vec![1], index.search("CGTGCCC"));
}
}
Allocate vectors only when necessary
use bincode::SizeLimit;
use bincode::rustc_serialize as serializer;
use fillings::BitsVec;
use num_traits::{Num, NumCast, cast};
use sa::{Output, suffix_array_};
use std::fs::File;
use std::path::Path;
// Generate the BWT of input data (calls the given function with the BWT data as it's generated)
pub fn bwt(input: Vec<u8>) -> Vec<u8> {
match suffix_array_(input, 0, /* generate bwt */ true) {
Output::BWT(v) => v,
_ => unreachable!(),
}
}
// Insert (or) Increment a counter at an index
fn insert<T>(vec: &mut BitsVec<usize>, value: T) -> usize
where T: Num + NumCast + PartialOrd + Copy
{
let idx = cast(value).unwrap();
if vec.len() <= idx {
vec.extend_with_element(idx + 1, 0);
}
let old = vec.get(idx);
vec.set(idx, old + 1);
old + 1
}
// Takes a frequency map of bytes and generates the index of first occurrence
// of each byte.
fn generate_occurrence_index(map: &mut BitsVec<usize>) {
let mut idx = 0;
for i in 0..map.len() {
let c = map.get(i);
map.set(i, idx);
idx += c;
}
}
// Invert the BWT data (generate the original data)
pub fn ibwt(input: Vec<u8>) -> Vec<u8> {
// get the byte distribution
let bits = (input.len().next_power_of_two() - 1).count_ones() as usize;
let mut map = BitsVec::new(bits);
for i in &input {
insert(&mut map, *i);
}
generate_occurrence_index(&mut map);
// generate the LF vector
let mut lf = vec![0; input.len()];
for (i, c) in input.iter().enumerate() {
let val = map.get(*c as usize);
lf[i] = val;
map.set(*c as usize, val + 1);
}
let mut idx = 0;
// construct the sequence by traversing through the LF vector
let mut output = vec![0; input.len()];
for i in (0..(input.len() - 1)).rev() {
output[i] = input[idx];
idx = lf[idx];
}
output.pop();
output
}
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct FMIndex {
// BW-transformed data
data: Vec<u8>,
// forward frequency of each character in the BWT data
cache: BitsVec<usize>,
// incremental character frequencies
occ_map: BitsVec<usize>,
// LF-mapping for backward search
lf_vec: BitsVec<usize>,
}
impl FMIndex {
pub fn new(data: Vec<u8>) -> FMIndex {
let mut idx = 0;
let length = data.len();
// worst case (all bytes are the same)
let bits = (length.next_power_of_two() - 1).count_ones() as usize;
let bwt_data = bwt(data);
let mut map = BitsVec::new(bits);
let mut count = BitsVec::with_elements(bits, length + 1, 0);
// generate the frequency map and forward frequency vector from BWT
for i in &bwt_data {
let value = insert(&mut map, *i);
count.set(idx, value);
idx += 1;
}
generate_occurrence_index(&mut map);
let mut lf_vec = count.clone();
let mut lf_occ_map = map.clone();
// generate the LF vector (just like inverting the BWT)
for (i, c) in bwt_data.iter().enumerate() {
let idx = *c as usize;
let val = lf_occ_map.get(idx);
lf_vec.set(i, val);
lf_occ_map.set(idx, val + 1);
}
let mut i = 0;
let mut counter = bwt_data.len();
// Only difference is that we replace the LF indices with the lengths of prefix
// from a particular position (in other words, the number of times
// it would take us to get to the start of string).
for _ in 0..bwt_data.len() {
let next = lf_vec.get(i);
lf_vec.set(i, counter);
i = next;
counter -= 1;
}
FMIndex {
data: bwt_data,
cache: count,
occ_map: map,
lf_vec: lf_vec,
}
}
pub fn load<P: AsRef<Path>>(path: P) -> Result<FMIndex, ()> {
let mut fd = try!(File::open(path).map_err(|_| ()));
serializer::decode_from(&mut fd, SizeLimit::Infinite).map_err(|_| ())
}
pub fn dump<P: AsRef<Path>>(&self, path: P) -> Result<(), ()> {
let mut fd = try!(File::create(path).map_err(|_| ()));
serializer::encode_into(&self, &mut fd, SizeLimit::Infinite).map_err(|_| ())
}
// Get the index of the nearest occurrence of a character in the BWT data
fn nearest(&self, idx: usize, ch: u8) -> usize {
let mut result = self.occ_map.get(ch as usize);
if result > 0 {
result += (0..idx).rev()
.find(|&i| self.data[i] == ch)
.map(|i| self.cache.get(i) as usize)
.unwrap_or(0);
}
result
}
// Find the positions of occurrences of sub-string in the original data.
pub fn search(&self, query: &str) -> Vec<usize> {
let mut top = 0;
let mut bottom = self.data.len();
for ch in query.as_bytes().iter().rev() {
top = self.nearest(top, *ch);
bottom = self.nearest(bottom, *ch);
}
(top..bottom).map(|idx| {
let i = self.nearest(idx, self.data[idx]);
// wrap around on overflow, which usually occurs only for the
// last index of LF vector (or the first index of original string)
self.lf_vec.get(i) % self.data.len()
}).collect()
}
}
#[cfg(test)]
mod tests {
use super::{FMIndex, bwt, ibwt};
#[test]
fn test_bwt_and_ibwt() {
let text = String::from("ATCTAGGAGATCTGAATCTAGTTCAACTAGCTAGATCTAGAGACAGCTAA");
let bw = bwt(text.as_bytes().to_owned());
let ibw = ibwt(bw.clone());
assert_eq!(String::from("AATCGGAGTTGCTTTG\u{0}AGTAGTGATTTTAAGAAAAAACCCCCCTAAAACG"),
String::from_utf8(bw).unwrap());
assert_eq!(text, String::from_utf8(ibw).unwrap());
}
#[test]
fn test_fm_index() {
let text = String::from("GCGTGCCCAGGGCACTGCCGCTGCAGGCGTAGGCATCGCATCACACGCGT");
let index = FMIndex::new(text.as_bytes().to_owned());
let mut result = index.search("TG");
result.sort();
assert_eq!(result, vec![3, 15, 21]);
let mut result = index.search("GCGT");
result.sort();
assert_eq!(result, vec![0, 26, 46]);
assert_eq!(vec![1], index.search("CGTGCCC"));
}
}
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use crate::types::{make_ident, Namespace, QualifiedName};
use autocxx_parser::RustPath;
use syn::{
parse::Parse, punctuated::Punctuated, token::Comma, Attribute, FnArg, Ident, ImplItem,
ItemConst, ItemEnum, ItemStruct, ItemType, ItemUse, LitBool, LitInt, ReturnType, Signature,
Type, Visibility,
};
use super::{
analysis::fun::{function_wrapper::CppFunction, ReceiverMutability},
convert_error::{ConvertErrorWithContext, ErrorContext},
ConvertError,
};
#[derive(Copy, Clone, Eq, PartialEq)]
pub(crate) enum TypeKind {
Pod, // trivial. Can be moved and copied in Rust.
NonPod, // has destructor or non-trivial move constructors. Can only hold by UniquePtr
Abstract, // has pure virtual members - can't even generate UniquePtr.
// It's possible that the type itself isn't pure virtual, but it inherits from
// some other type which is pure virtual. Alternatively, maybe we just don't
// know if the base class is pure virtual because it wasn't on the allowlist,
// in which case we'll err on the side of caution.
}
/// An entry which needs to go into an `impl` block for a given type.
pub(crate) struct ImplBlockDetails {
pub(crate) item: ImplItem,
pub(crate) ty: Ident,
}
/// C++ visibility.
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub(crate) enum CppVisibility {
Public,
Protected,
Private,
}
/// Details about a C++ struct.
pub(crate) struct StructDetails {
pub(crate) vis: CppVisibility,
pub(crate) item: ItemStruct,
pub(crate) layout: Option<Layout>,
}
/// Layout of a type, equivalent to the same type in ir/layout.rs in bindgen
#[derive(Clone)]
pub(crate) struct Layout {
/// The size (in bytes) of this layout.
pub(crate) size: usize,
/// The alignment (in bytes) of this layout.
pub(crate) align: usize,
/// Whether this layout's members are packed or not.
pub(crate) packed: bool,
}
impl Parse for Layout {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let size: LitInt = input.parse()?;
input.parse::<syn::token::Comma>()?;
let align: LitInt = input.parse()?;
input.parse::<syn::token::Comma>()?;
let packed: LitBool = input.parse()?;
Ok(Layout {
size: size.base10_parse().unwrap(),
align: align.base10_parse().unwrap(),
packed: packed.value(),
})
}
}
#[derive(Clone)]
pub(crate) enum Virtualness {
None,
Virtual,
PureVirtual,
}
/// Indicates that this function didn't exist originally in the C++
/// but we've created it afresh.
#[derive(Clone)]
pub(crate) enum Synthesis {
MakeUnique,
SubclassConstructor {
subclass: SubclassName,
cpp_impl: Box<CppFunction>,
is_trivial: bool,
},
}
/// A C++ function for which we need to generate bindings, but haven't
/// yet analyzed in depth. This is little more than a `ForeignItemFn`
/// broken down into its constituent parts, plus some metadata from the
/// surrounding bindgen parsing context.
///
/// Some parts of the code synthesize additional functions and then
/// pass them through the same pipeline _as if_ they were discovered
/// during normal bindgen parsing. If that happens, they'll create one
/// of these structures, and typically fill in some of the
/// `synthesized_*` members which are not filled in from bindgen.
#[derive(Clone)]
pub(crate) struct FuncToConvert {
pub(crate) ident: Ident,
pub(crate) doc_attr: Option<Attribute>,
pub(crate) inputs: Punctuated<FnArg, Comma>,
pub(crate) output: ReturnType,
pub(crate) vis: Visibility,
pub(crate) virtualness: Virtualness,
pub(crate) cpp_vis: CppVisibility,
pub(crate) is_move_constructor: bool,
pub(crate) unused_template_param: bool,
pub(crate) return_type_is_reference: bool,
pub(crate) reference_args: HashSet<Ident>,
pub(crate) original_name: Option<String>,
/// Used for static functions only. For all other functons,
/// this is figured out from the receiver type in the inputs.
pub(crate) self_ty: Option<QualifiedName>,
/// If we wish to use a different 'this' type than the original
/// method receiver, e.g. because we're making a subclass
/// constructor, fill it in here.
pub(crate) synthesized_this_type: Option<QualifiedName>,
/// If Some, this function didn't really exist in the original
/// C++ and instead we're synthesizing it.
pub(crate) synthesis: Option<Synthesis>,
}
/// Layers of analysis which may be applied to decorate each API.
/// See description of the purpose of this trait within `Api`.
pub(crate) trait AnalysisPhase {
type TypedefAnalysis;
type StructAnalysis;
type FunAnalysis;
}
/// No analysis has been applied to this API.
pub(crate) struct NullPhase;
impl AnalysisPhase for NullPhase {
type TypedefAnalysis = ();
type StructAnalysis = ();
type FunAnalysis = ();
}
#[derive(Clone)]
pub(crate) enum TypedefKind {
Use(ItemUse),
Type(ItemType),
}
/// Name information for an API. This includes the name by
/// which we know it in Rust, and its C++ name, which may differ.
#[derive(Clone, Hash, PartialEq, Eq)]
pub(crate) struct ApiName {
pub(crate) name: QualifiedName,
cpp_name: Option<String>,
}
impl ApiName {
pub(crate) fn new(ns: &Namespace, id: Ident) -> Self {
Self::new_from_qualified_name(QualifiedName::new(ns, id))
}
pub(crate) fn new_with_cpp_name(ns: &Namespace, id: Ident, cpp_name: Option<String>) -> Self {
Self {
name: QualifiedName::new(ns, id),
cpp_name,
}
}
pub(crate) fn new_from_qualified_name(name: QualifiedName) -> Self {
Self {
name,
cpp_name: None,
}
}
pub(crate) fn new_in_root_namespace(id: Ident) -> Self {
Self::new(&Namespace::new(), id)
}
pub(crate) fn cpp_name(&self) -> String {
self.cpp_name
.as_ref()
.cloned()
.unwrap_or_else(|| self.name.get_final_item().to_string())
}
pub(crate) fn cpp_name_if_present(&self) -> Option<&String> {
self.cpp_name.as_ref()
}
}
impl std::fmt::Debug for ApiName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)?;
if let Some(cpp_name) = &self.cpp_name {
write!(f, " (cpp={})", cpp_name)?;
}
Ok(())
}
}
/// A name representing a subclass.
/// This is a simple newtype wrapper which exists such that
/// we can consistently generate the names of the various subsidiary
/// types which are required both in C++ and Rust codegen.
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub(crate) struct SubclassName(pub(crate) ApiName);
impl SubclassName {
pub(crate) fn new(id: Ident) -> Self {
Self(ApiName::new_in_root_namespace(id))
}
pub(crate) fn from_holder_name(id: &Ident) -> Self {
Self::new(make_ident(id.to_string().strip_suffix("Holder").unwrap()))
}
pub(crate) fn id(&self) -> Ident {
self.0.name.get_final_ident()
}
/// Generate the name for the 'Holder' type
pub(crate) fn holder(&self) -> Ident {
self.with_suffix("Holder")
}
/// Generate the name for the 'Cpp' type
pub(crate) fn cpp(&self) -> QualifiedName {
let id = self.with_suffix("Cpp");
QualifiedName::new(self.0.name.get_namespace(), id)
}
pub(crate) fn cpp_remove_ownership(&self) -> Ident {
self.with_suffix("Cpp_remove_ownership")
}
pub(crate) fn remove_ownership(&self) -> Ident {
self.with_suffix("_remove_ownership")
}
fn with_suffix(&self, suffix: &str) -> Ident {
make_ident(format!("{}{}", self.0.name.get_final_item(), suffix))
}
pub(crate) fn get_super_fn_name(superclass_namespace: &Namespace, id: &str) -> QualifiedName {
let id = make_ident(format!("{}_super", id));
QualifiedName::new(superclass_namespace, id)
}
pub(crate) fn get_methods_trait_name(superclass_name: &QualifiedName) -> QualifiedName {
Self::with_qualified_name_suffix(superclass_name, "methods")
}
pub(crate) fn get_supers_trait_name(superclass_name: &QualifiedName) -> QualifiedName {
Self::with_qualified_name_suffix(superclass_name, "supers")
}
fn with_qualified_name_suffix(name: &QualifiedName, suffix: &str) -> QualifiedName {
let id = make_ident(format!("{}_{}", name.get_final_item(), suffix));
QualifiedName::new(name.get_namespace(), id)
}
}
#[derive(strum_macros::Display)]
/// Different types of API we might encounter.
///
/// This type is parameterized over an `ApiAnalysis`. This is any additional
/// information which we wish to apply to our knowledge of our APIs later
/// during analysis phases.
///
/// This is not as high-level as the equivalent types in `cxx` or `bindgen`,
/// because sometimes we pass on the `bindgen` output directly in the
/// Rust codegen output.
///
/// This derives from [strum_macros::Display] because we want to be
/// able to debug-print the enum discriminant without worrying about
/// the fact that their payloads may not be `Debug` or `Display`.
/// (Specifically, allowing `syn` Types to be `Debug` requires
/// enabling syn's `extra-traits` feature which increases compile time.)
pub(crate) enum Api<T: AnalysisPhase> {
/// A forward declared type for which no definition is available.
ForwardDeclaration { name: ApiName },
/// A synthetic type we've manufactured in order to
/// concretize some templated C++ type.
ConcreteType {
name: ApiName,
rs_definition: Box<Type>,
cpp_definition: String,
},
/// A simple note that we want to make a constructor for
/// a `std::string` on the heap.
StringConstructor { name: ApiName },
/// A function. May include some analysis.
Function {
name: ApiName,
name_for_gc: Option<QualifiedName>,
fun: Box<FuncToConvert>,
analysis: T::FunAnalysis,
},
/// A constant.
Const {
name: ApiName,
const_item: ItemConst,
},
/// A typedef found in the bindgen output which we wish
/// to pass on in our output
Typedef {
name: ApiName,
item: TypedefKind,
old_tyname: Option<QualifiedName>,
analysis: T::TypedefAnalysis,
},
/// An enum encountered in the
/// `bindgen` output.
Enum { name: ApiName, item: ItemEnum },
/// A struct encountered in the
/// `bindgen` output.
Struct {
name: ApiName,
details: Box<StructDetails>,
analysis: T::StructAnalysis,
},
/// A variable-length C integer type (e.g. int, unsigned long).
CType {
name: ApiName,
typename: QualifiedName,
},
/// Some item which couldn't be processed by autocxx for some reason.
/// We will have emitted a warning message about this, but we want
/// to mark that it's ignored so that we don't attempt to process
/// dependent items.
IgnoredItem {
name: ApiName,
err: ConvertError,
ctx: ErrorContext,
},
/// A Rust type which is not a C++ type.
RustType { name: ApiName, path: RustPath },
/// A function for the 'extern Rust' block which is not a C++ type.
RustFn {
name: ApiName,
sig: Signature,
path: RustPath,
},
/// Some function for the extern "Rust" block.
RustSubclassFn {
name: ApiName,
subclass: SubclassName,
details: Box<RustSubclassFnDetails>,
},
/// A Rust subclass of a C++ class.
Subclass {
name: SubclassName,
superclass: QualifiedName,
},
}
pub(crate) struct RustSubclassFnDetails {
pub(crate) params: Punctuated<FnArg, Comma>,
pub(crate) ret: ReturnType,
pub(crate) cpp_impl: CppFunction,
pub(crate) method_name: Ident,
pub(crate) superclass: QualifiedName,
pub(crate) receiver_mutability: ReceiverMutability,
pub(crate) dependency: Option<QualifiedName>,
pub(crate) requires_unsafe: bool,
pub(crate) is_pure_virtual: bool,
}
impl<T: AnalysisPhase> Api<T> {
pub(crate) fn name_info(&self) -> &ApiName {
match self {
Api::ForwardDeclaration { name } => name,
Api::ConcreteType { name, .. } => name,
Api::StringConstructor { name } => name,
Api::Function { name, .. } => name,
Api::Const { name, .. } => name,
Api::Typedef { name, .. } => name,
Api::Enum { name, .. } => name,
Api::Struct { name, .. } => name,
Api::CType { name, .. } => name,
Api::IgnoredItem { name, .. } => name,
Api::RustType { name, .. } => name,
Api::RustFn { name, .. } => name,
Api::RustSubclassFn { name, .. } => name,
Api::Subclass { name, .. } => &name.0,
}
}
/// The name of this API as used in Rust code.
/// For types, it's important that this never changes, since
/// functions or other types may refer to this.
/// Yet for functions, this may not actually be the name
/// used in the [cxx::bridge] mod - see
/// [Api<FnAnalysis>::cxxbridge_name]
pub(crate) fn name(&self) -> &QualifiedName {
&self.name_info().name
}
/// The name recorded for use in C++, if and only if
/// it differs from Rust.
pub(crate) fn cpp_name(&self) -> &Option<String> {
&self.name_info().cpp_name
}
/// The name for use in C++, whether or not it differs
/// from Rust.
pub(crate) fn effective_cpp_name(&self) -> &str {
self.cpp_name()
.as_deref()
.unwrap_or_else(|| self.name().get_final_item())
}
pub(crate) fn valid_types(&self) -> Box<dyn Iterator<Item = QualifiedName>> {
match self {
Api::Subclass { name, .. } => Box::new(
vec![
self.name().clone(),
QualifiedName::new(&Namespace::new(), name.holder()),
]
.into_iter(),
),
_ => Box::new(std::iter::once(self.name().clone())),
}
}
}
impl<T: AnalysisPhase> std::fmt::Debug for Api<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?} (kind={})", self.name_info(), self)
}
}
pub(crate) type UnanalyzedApi = Api<NullPhase>;
impl<T: AnalysisPhase> Api<T> {
pub(crate) fn typedef_unchanged(
name: ApiName,
item: TypedefKind,
old_tyname: Option<QualifiedName>,
analysis: T::TypedefAnalysis,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Typedef {
name,
item,
old_tyname,
analysis,
})))
}
pub(crate) fn struct_unchanged(
name: ApiName,
details: Box<StructDetails>,
analysis: T::StructAnalysis,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Struct {
name,
details,
analysis,
})))
}
pub(crate) fn fun_unchanged(
name: ApiName,
fun: Box<FuncToConvert>,
analysis: T::FunAnalysis,
name_for_gc: Option<QualifiedName>,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Function {
name,
fun,
analysis,
name_for_gc,
})))
}
pub(crate) fn enum_unchanged(
name: ApiName,
item: ItemEnum,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Enum { name, item })))
}
}
Fix over-eager discarding of constructors.
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use crate::types::{make_ident, Namespace, QualifiedName};
use autocxx_parser::RustPath;
use syn::{
parse::Parse, punctuated::Punctuated, token::Comma, Attribute, FnArg, Ident, ImplItem,
ItemConst, ItemEnum, ItemStruct, ItemType, ItemUse, LitBool, LitInt, ReturnType, Signature,
Type, Visibility,
};
use super::{
analysis::fun::{function_wrapper::CppFunction, ReceiverMutability},
convert_error::{ConvertErrorWithContext, ErrorContext},
ConvertError,
};
#[derive(Copy, Clone, Eq, PartialEq)]
pub(crate) enum TypeKind {
Pod, // trivial. Can be moved and copied in Rust.
NonPod, // has destructor or non-trivial move constructors. Can only hold by UniquePtr
Abstract, // has pure virtual members - can't even generate UniquePtr.
// It's possible that the type itself isn't pure virtual, but it inherits from
// some other type which is pure virtual. Alternatively, maybe we just don't
// know if the base class is pure virtual because it wasn't on the allowlist,
// in which case we'll err on the side of caution.
}
/// An entry which needs to go into an `impl` block for a given type.
pub(crate) struct ImplBlockDetails {
pub(crate) item: ImplItem,
pub(crate) ty: Ident,
}
/// C++ visibility.
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub(crate) enum CppVisibility {
Public,
Protected,
Private,
}
/// Details about a C++ struct.
pub(crate) struct StructDetails {
pub(crate) vis: CppVisibility,
pub(crate) item: ItemStruct,
pub(crate) layout: Option<Layout>,
}
/// Layout of a type, equivalent to the same type in ir/layout.rs in bindgen
#[derive(Clone)]
pub(crate) struct Layout {
/// The size (in bytes) of this layout.
pub(crate) size: usize,
/// The alignment (in bytes) of this layout.
pub(crate) align: usize,
/// Whether this layout's members are packed or not.
pub(crate) packed: bool,
}
impl Parse for Layout {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let size: LitInt = input.parse()?;
input.parse::<syn::token::Comma>()?;
let align: LitInt = input.parse()?;
input.parse::<syn::token::Comma>()?;
let packed: LitBool = input.parse()?;
Ok(Layout {
size: size.base10_parse().unwrap(),
align: align.base10_parse().unwrap(),
packed: packed.value(),
})
}
}
#[derive(Clone)]
pub(crate) enum Virtualness {
None,
Virtual,
PureVirtual,
}
/// Indicates that this function didn't exist originally in the C++
/// but we've created it afresh.
#[derive(Clone)]
pub(crate) enum Synthesis {
MakeUnique,
SubclassConstructor {
subclass: SubclassName,
cpp_impl: Box<CppFunction>,
is_trivial: bool,
},
}
/// A C++ function for which we need to generate bindings, but haven't
/// yet analyzed in depth. This is little more than a `ForeignItemFn`
/// broken down into its constituent parts, plus some metadata from the
/// surrounding bindgen parsing context.
///
/// Some parts of the code synthesize additional functions and then
/// pass them through the same pipeline _as if_ they were discovered
/// during normal bindgen parsing. If that happens, they'll create one
/// of these structures, and typically fill in some of the
/// `synthesized_*` members which are not filled in from bindgen.
#[derive(Clone)]
pub(crate) struct FuncToConvert {
pub(crate) ident: Ident,
pub(crate) doc_attr: Option<Attribute>,
pub(crate) inputs: Punctuated<FnArg, Comma>,
pub(crate) output: ReturnType,
pub(crate) vis: Visibility,
pub(crate) virtualness: Virtualness,
pub(crate) cpp_vis: CppVisibility,
pub(crate) is_move_constructor: bool,
pub(crate) unused_template_param: bool,
pub(crate) return_type_is_reference: bool,
pub(crate) reference_args: HashSet<Ident>,
pub(crate) original_name: Option<String>,
/// Used for static functions only. For all other functons,
/// this is figured out from the receiver type in the inputs.
pub(crate) self_ty: Option<QualifiedName>,
/// If we wish to use a different 'this' type than the original
/// method receiver, e.g. because we're making a subclass
/// constructor, fill it in here.
pub(crate) synthesized_this_type: Option<QualifiedName>,
/// If Some, this function didn't really exist in the original
/// C++ and instead we're synthesizing it.
pub(crate) synthesis: Option<Synthesis>,
}
/// Layers of analysis which may be applied to decorate each API.
/// See description of the purpose of this trait within `Api`.
pub(crate) trait AnalysisPhase {
type TypedefAnalysis;
type StructAnalysis;
type FunAnalysis;
}
/// No analysis has been applied to this API.
pub(crate) struct NullPhase;
impl AnalysisPhase for NullPhase {
type TypedefAnalysis = ();
type StructAnalysis = ();
type FunAnalysis = ();
}
#[derive(Clone)]
pub(crate) enum TypedefKind {
Use(ItemUse),
Type(ItemType),
}
/// Name information for an API. This includes the name by
/// which we know it in Rust, and its C++ name, which may differ.
#[derive(Clone, Hash, PartialEq, Eq)]
pub(crate) struct ApiName {
pub(crate) name: QualifiedName,
cpp_name: Option<String>,
}
impl ApiName {
pub(crate) fn new(ns: &Namespace, id: Ident) -> Self {
Self::new_from_qualified_name(QualifiedName::new(ns, id))
}
pub(crate) fn new_with_cpp_name(ns: &Namespace, id: Ident, cpp_name: Option<String>) -> Self {
Self {
name: QualifiedName::new(ns, id),
cpp_name,
}
}
pub(crate) fn new_from_qualified_name(name: QualifiedName) -> Self {
Self {
name,
cpp_name: None,
}
}
pub(crate) fn new_in_root_namespace(id: Ident) -> Self {
Self::new(&Namespace::new(), id)
}
pub(crate) fn cpp_name(&self) -> String {
self.cpp_name
.as_ref()
.cloned()
.unwrap_or_else(|| self.name.get_final_item().to_string())
}
pub(crate) fn cpp_name_if_present(&self) -> Option<&String> {
self.cpp_name.as_ref()
}
}
impl std::fmt::Debug for ApiName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)?;
if let Some(cpp_name) = &self.cpp_name {
write!(f, " (cpp={})", cpp_name)?;
}
Ok(())
}
}
/// A name representing a subclass.
/// This is a simple newtype wrapper which exists such that
/// we can consistently generate the names of the various subsidiary
/// types which are required both in C++ and Rust codegen.
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub(crate) struct SubclassName(pub(crate) ApiName);
impl SubclassName {
pub(crate) fn new(id: Ident) -> Self {
Self(ApiName::new_in_root_namespace(id))
}
pub(crate) fn from_holder_name(id: &Ident) -> Self {
Self::new(make_ident(id.to_string().strip_suffix("Holder").unwrap()))
}
pub(crate) fn id(&self) -> Ident {
self.0.name.get_final_ident()
}
/// Generate the name for the 'Holder' type
pub(crate) fn holder(&self) -> Ident {
self.with_suffix("Holder")
}
/// Generate the name for the 'Cpp' type
pub(crate) fn cpp(&self) -> QualifiedName {
let id = self.with_suffix("Cpp");
QualifiedName::new(self.0.name.get_namespace(), id)
}
pub(crate) fn cpp_remove_ownership(&self) -> Ident {
self.with_suffix("Cpp_remove_ownership")
}
pub(crate) fn remove_ownership(&self) -> Ident {
self.with_suffix("_remove_ownership")
}
fn with_suffix(&self, suffix: &str) -> Ident {
make_ident(format!("{}{}", self.0.name.get_final_item(), suffix))
}
pub(crate) fn get_super_fn_name(superclass_namespace: &Namespace, id: &str) -> QualifiedName {
let id = make_ident(format!("{}_super", id));
QualifiedName::new(superclass_namespace, id)
}
pub(crate) fn get_methods_trait_name(superclass_name: &QualifiedName) -> QualifiedName {
Self::with_qualified_name_suffix(superclass_name, "methods")
}
pub(crate) fn get_supers_trait_name(superclass_name: &QualifiedName) -> QualifiedName {
Self::with_qualified_name_suffix(superclass_name, "supers")
}
fn with_qualified_name_suffix(name: &QualifiedName, suffix: &str) -> QualifiedName {
let id = make_ident(format!("{}_{}", name.get_final_item(), suffix));
QualifiedName::new(name.get_namespace(), id)
}
}
#[derive(strum_macros::Display)]
/// Different types of API we might encounter.
///
/// This type is parameterized over an `ApiAnalysis`. This is any additional
/// information which we wish to apply to our knowledge of our APIs later
/// during analysis phases.
///
/// This is not as high-level as the equivalent types in `cxx` or `bindgen`,
/// because sometimes we pass on the `bindgen` output directly in the
/// Rust codegen output.
///
/// This derives from [strum_macros::Display] because we want to be
/// able to debug-print the enum discriminant without worrying about
/// the fact that their payloads may not be `Debug` or `Display`.
/// (Specifically, allowing `syn` Types to be `Debug` requires
/// enabling syn's `extra-traits` feature which increases compile time.)
pub(crate) enum Api<T: AnalysisPhase> {
/// A forward declared type for which no definition is available.
ForwardDeclaration { name: ApiName },
/// A synthetic type we've manufactured in order to
/// concretize some templated C++ type.
ConcreteType {
name: ApiName,
rs_definition: Box<Type>,
cpp_definition: String,
},
/// A simple note that we want to make a constructor for
/// a `std::string` on the heap.
StringConstructor { name: ApiName },
/// A function. May include some analysis.
Function {
name: ApiName,
name_for_gc: Option<QualifiedName>,
fun: Box<FuncToConvert>,
analysis: T::FunAnalysis,
},
/// A constant.
Const {
name: ApiName,
const_item: ItemConst,
},
/// A typedef found in the bindgen output which we wish
/// to pass on in our output
Typedef {
name: ApiName,
item: TypedefKind,
old_tyname: Option<QualifiedName>,
analysis: T::TypedefAnalysis,
},
/// An enum encountered in the
/// `bindgen` output.
Enum { name: ApiName, item: ItemEnum },
/// A struct encountered in the
/// `bindgen` output.
Struct {
name: ApiName,
details: Box<StructDetails>,
analysis: T::StructAnalysis,
},
/// A variable-length C integer type (e.g. int, unsigned long).
CType {
name: ApiName,
typename: QualifiedName,
},
/// Some item which couldn't be processed by autocxx for some reason.
/// We will have emitted a warning message about this, but we want
/// to mark that it's ignored so that we don't attempt to process
/// dependent items.
IgnoredItem {
name: ApiName,
err: ConvertError,
ctx: ErrorContext,
},
/// A Rust type which is not a C++ type.
RustType { name: ApiName, path: RustPath },
/// A function for the 'extern Rust' block which is not a C++ type.
RustFn {
name: ApiName,
sig: Signature,
path: RustPath,
},
/// Some function for the extern "Rust" block.
RustSubclassFn {
name: ApiName,
subclass: SubclassName,
details: Box<RustSubclassFnDetails>,
},
/// A Rust subclass of a C++ class.
Subclass {
name: SubclassName,
superclass: QualifiedName,
},
}
pub(crate) struct RustSubclassFnDetails {
pub(crate) params: Punctuated<FnArg, Comma>,
pub(crate) ret: ReturnType,
pub(crate) cpp_impl: CppFunction,
pub(crate) method_name: Ident,
pub(crate) superclass: QualifiedName,
pub(crate) receiver_mutability: ReceiverMutability,
pub(crate) dependency: Option<QualifiedName>,
pub(crate) requires_unsafe: bool,
pub(crate) is_pure_virtual: bool,
}
impl<T: AnalysisPhase> Api<T> {
pub(crate) fn name_info(&self) -> &ApiName {
match self {
Api::ForwardDeclaration { name } => name,
Api::ConcreteType { name, .. } => name,
Api::StringConstructor { name } => name,
Api::Function { name, .. } => name,
Api::Const { name, .. } => name,
Api::Typedef { name, .. } => name,
Api::Enum { name, .. } => name,
Api::Struct { name, .. } => name,
Api::CType { name, .. } => name,
Api::IgnoredItem { name, .. } => name,
Api::RustType { name, .. } => name,
Api::RustFn { name, .. } => name,
Api::RustSubclassFn { name, .. } => name,
Api::Subclass { name, .. } => &name.0,
}
}
/// The name of this API as used in Rust code.
/// For types, it's important that this never changes, since
/// functions or other types may refer to this.
/// Yet for functions, this may not actually be the name
/// used in the [cxx::bridge] mod - see
/// [Api<FnAnalysis>::cxxbridge_name]
pub(crate) fn name(&self) -> &QualifiedName {
&self.name_info().name
}
/// The name recorded for use in C++, if and only if
/// it differs from Rust.
pub(crate) fn cpp_name(&self) -> &Option<String> {
&self.name_info().cpp_name
}
/// The name for use in C++, whether or not it differs
/// from Rust.
pub(crate) fn effective_cpp_name(&self) -> &str {
self.cpp_name()
.as_deref()
.unwrap_or_else(|| self.name().get_final_item())
}
pub(crate) fn valid_types(&self) -> Box<dyn Iterator<Item = QualifiedName>> {
match self {
Api::Subclass { name, .. } => Box::new(
vec![
self.name().clone(),
QualifiedName::new(&Namespace::new(), name.holder()),
name.cpp(),
]
.into_iter(),
),
_ => Box::new(std::iter::once(self.name().clone())),
}
}
}
impl<T: AnalysisPhase> std::fmt::Debug for Api<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?} (kind={})", self.name_info(), self)
}
}
pub(crate) type UnanalyzedApi = Api<NullPhase>;
impl<T: AnalysisPhase> Api<T> {
pub(crate) fn typedef_unchanged(
name: ApiName,
item: TypedefKind,
old_tyname: Option<QualifiedName>,
analysis: T::TypedefAnalysis,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Typedef {
name,
item,
old_tyname,
analysis,
})))
}
pub(crate) fn struct_unchanged(
name: ApiName,
details: Box<StructDetails>,
analysis: T::StructAnalysis,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Struct {
name,
details,
analysis,
})))
}
pub(crate) fn fun_unchanged(
name: ApiName,
fun: Box<FuncToConvert>,
analysis: T::FunAnalysis,
name_for_gc: Option<QualifiedName>,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Function {
name,
fun,
analysis,
name_for_gc,
})))
}
pub(crate) fn enum_unchanged(
name: ApiName,
item: ItemEnum,
) -> Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>
where
T: 'static,
{
Ok(Box::new(std::iter::once(Api::Enum { name, item })))
}
}
|
#![deny(warnings)]
extern crate tar;
extern crate tree_magic;
extern crate lzma;
extern crate libflate;
use std::{env, process};
use std::io::{stdin, stdout, stderr, copy, Error, ErrorKind, Result, Read, Write, BufReader};
use std::fs::{self, File};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use tar::{Archive, Builder, EntryType};
use lzma::LzmaReader;
use libflate::gzip::Decoder as GzipDecoder;
fn create_inner<T: Write>(input: &str, ar: &mut Builder<T>) -> Result<()> {
if try!(fs::metadata(input)).is_dir() {
for entry_result in try!(fs::read_dir(input)) {
let entry = try!(entry_result);
if try!(fs::metadata(entry.path())).is_dir() {
try!(create_inner(entry.path().to_str().unwrap(), ar));
} else {
println!("{}", entry.path().display());
try!(ar.append_path(entry.path()));
}
}
} else {
println!("{}", input);
try!(ar.append_path(input));
}
Ok(())
}
fn create(input: &str, tar: &str) -> Result<()> {
if tar == "-" {
create_inner(input, &mut Builder::new(stdout()))
} else {
create_inner(input, &mut Builder::new(try!(File::create(tar))))
}
}
fn list_inner<T: Read>(ar: &mut Archive<T>) -> Result<()> {
for entry_result in try!(ar.entries()) {
let entry = try!(entry_result);
let path = try!(entry.path());
println!("{}", path.display());
}
Ok(())
}
fn list(tar: &str) -> Result<()> {
if tar == "-" {
list_inner(&mut Archive::new(stdin()))
} else {
list_inner(&mut Archive::new(try!(File::open(tar))))
}
}
fn extract_inner<T: Read>(ar: &mut Archive<T>, verbose: bool, strip: usize) -> Result<()> {
for entry_result in try!(ar.entries()) {
let mut entry = try!(entry_result);
let path = {
let path = try!(entry.path());
let mut components = path.components();
for _ in 0..strip {
components.next();
}
components.as_path().to_path_buf()
};
if path == Path::new("") {
continue;
}
match entry.header().entry_type() {
EntryType::Regular => {
let mut file = {
if let Some(parent) = path.parent() {
try!(fs::create_dir_all(parent));
}
try!(
fs::OpenOptions::new()
.read(true)
.write(true)
.truncate(true)
.create(true)
.mode(entry.header().mode().unwrap_or(644))
.open(&path)
)
};
try!(copy(&mut entry, &mut file));
},
EntryType::Directory => {
try!(fs::create_dir_all(&path));
},
other => {
panic!("Unsupported entry type {:?}", other);
}
}
if verbose {
println!("{}", entry.path()?.display());
}
}
Ok(())
}
fn extract(tar: &Path, verbose: bool, strip: usize) -> Result<()> {
if tar == Path::new("-") {
extract_inner(&mut Archive::new(stdin()), verbose, strip)
} else {
let mime = tree_magic::from_filepath(Path::new(&tar));
let file = BufReader::new(File::open(tar)?);
if mime == "application/x-xz" {
extract_inner(&mut Archive::new(LzmaReader::new_decompressor(file)
.map_err(|e| Error::new(ErrorKind::Other, e))?),
verbose, strip)
} else if mime == "application/gzip" {
extract_inner(&mut Archive::new(GzipDecoder::new(file)
.map_err(|e| Error::new(ErrorKind::Other, e))?),
verbose, strip)
} else {
extract_inner(&mut Archive::new(file), verbose, strip)
}
}
}
fn main() {
let mut args = env::args().skip(1);
if let Some(op) = args.next() {
match op.as_str() {
"c" => if let Some(input) = args.next() {
if let Err(err) = create(&input, "-") {
write!(stderr(), "tar: create: failed: {}\n", err).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no input specified: {}\n", op).unwrap();
process::exit(1);
},
"cf" => if let Some(tar) = args.next() {
if let Some(input) = args.next() {
if let Err(err) = create(&input, &tar) {
write!(stderr(), "tar: create: failed: {}\n", err).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no input specified: {}\n", op).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no tarfile specified: {}\n", op).unwrap();
process::exit(1);
},
"t" | "tf" => {
let tar = args.next().unwrap_or("-".to_string());
if let Err(err) = list(&tar) {
write!(stderr(), "tar: list: failed: {}\n", err).unwrap();
process::exit(1);
}
},
"x" | "xf" | "xvf" => {
let mut tar = None;
let mut strip = 0;
while let Some(arg) = args.next() {
if arg == "-C" || arg == "--directory" {
env::set_current_dir(args.next().expect(&format!("{} requires path", arg))).unwrap();
} else if arg.starts_with("--directory=") {
env::set_current_dir(&arg[12..]).unwrap();
} else if arg.starts_with("--strip-components") {
let num = args.next().expect("--strip-components requires an integer");
strip = usize::from_str(&num).expect("--strip-components requires an integer");
} else if arg.starts_with("--strip-components=") {
strip = usize::from_str(&arg[19..]).expect("--strip-components requires an integer");
} else if tar.is_none() {
let mut path = env::current_dir().unwrap();
path.push(arg);
tar = Some(path);
}
}
let tar = tar.unwrap_or(PathBuf::from("-"));
let verbose = op.contains('v');
if let Err(err) = extract(&tar, verbose, strip) {
write!(stderr(), "tar: extract: failed: {}\n", err).unwrap();
process::exit(1);
}
},
_ => {
write!(stderr(), "tar: {}: unknown operation\n", op).unwrap();
write!(stderr(), "tar: need to specify c[f] (create), t[f] (list), or x[f] (extract)\n").unwrap();
process::exit(1);
}
}
} else {
write!(stderr(), "tar: no operation\n").unwrap();
write!(stderr(), "tar: need to specify cf (create), tf (list), or xf (extract)\n").unwrap();
process::exit(1);
}
}
Read symlinks from tar header and recreate
#![deny(warnings)]
extern crate tar;
extern crate tree_magic;
extern crate lzma;
extern crate libflate;
use std::{env, process};
use std::io::{stdin, stdout, stderr, copy, Error, ErrorKind, Result, Read, Write, BufReader};
use std::fs::{self, File};
use std::os::unix::fs::{OpenOptionsExt, symlink};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use tar::{Archive, Builder, EntryType};
use lzma::LzmaReader;
use libflate::gzip::Decoder as GzipDecoder;
fn create_inner<T: Write>(input: &str, ar: &mut Builder<T>) -> Result<()> {
if try!(fs::metadata(input)).is_dir() {
for entry_result in try!(fs::read_dir(input)) {
let entry = try!(entry_result);
if try!(fs::metadata(entry.path())).is_dir() {
try!(create_inner(entry.path().to_str().unwrap(), ar));
} else {
println!("{}", entry.path().display());
try!(ar.append_path(entry.path()));
}
}
} else {
println!("{}", input);
try!(ar.append_path(input));
}
Ok(())
}
fn create(input: &str, tar: &str) -> Result<()> {
if tar == "-" {
create_inner(input, &mut Builder::new(stdout()))
} else {
create_inner(input, &mut Builder::new(try!(File::create(tar))))
}
}
fn list_inner<T: Read>(ar: &mut Archive<T>) -> Result<()> {
for entry_result in try!(ar.entries()) {
let entry = try!(entry_result);
let path = try!(entry.path());
println!("{}", path.display());
}
Ok(())
}
fn list(tar: &str) -> Result<()> {
if tar == "-" {
list_inner(&mut Archive::new(stdin()))
} else {
list_inner(&mut Archive::new(try!(File::open(tar))))
}
}
fn create_symlink(link: PathBuf, target: &Path) -> Result<()> {
//delete existing file to make way for symlink
if link.exists() {
fs::remove_file(link.clone()).expect(&format!("could not overwrite: {:?}", link));
}
symlink(target, link)
}
fn extract_inner<T: Read>(ar: &mut Archive<T>, verbose: bool, strip: usize) -> Result<()> {
for entry_result in try!(ar.entries()) {
let mut entry = try!(entry_result);
let path = {
let path = try!(entry.path());
let mut components = path.components();
for _ in 0..strip {
components.next();
}
components.as_path().to_path_buf()
};
if path == Path::new("") {
continue;
}
match entry.header().entry_type() {
EntryType::Regular => {
let mut file = {
if let Some(parent) = path.parent() {
try!(fs::create_dir_all(parent));
}
try!(
fs::OpenOptions::new()
.read(true)
.write(true)
.truncate(true)
.create(true)
.mode(entry.header().mode().unwrap_or(644))
.open(&path)
)
};
try!(copy(&mut entry, &mut file));
},
EntryType::Directory => {
try!(fs::create_dir_all(&path));
},
EntryType::Symlink => {
if let Some(target) = entry.link_name().expect(&format!("Can't parse symlink target for: {:?}", path)) {
try!(create_symlink(path, &target))
}
},
other => {
panic!("Unsupported entry type {:?}", other);
}
}
if verbose {
println!("{}", entry.path()?.display());
}
}
Ok(())
}
fn extract(tar: &Path, verbose: bool, strip: usize) -> Result<()> {
if tar == Path::new("-") {
extract_inner(&mut Archive::new(stdin()), verbose, strip)
} else {
let mime = tree_magic::from_filepath(Path::new(&tar));
let file = BufReader::new(File::open(tar)?);
if mime == "application/x-xz" {
extract_inner(&mut Archive::new(LzmaReader::new_decompressor(file)
.map_err(|e| Error::new(ErrorKind::Other, e))?),
verbose, strip)
} else if mime == "application/gzip" {
extract_inner(&mut Archive::new(GzipDecoder::new(file)
.map_err(|e| Error::new(ErrorKind::Other, e))?),
verbose, strip)
} else {
extract_inner(&mut Archive::new(file), verbose, strip)
}
}
}
fn main() {
let mut args = env::args().skip(1);
if let Some(op) = args.next() {
match op.as_str() {
"c" => if let Some(input) = args.next() {
if let Err(err) = create(&input, "-") {
write!(stderr(), "tar: create: failed: {}\n", err).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no input specified: {}\n", op).unwrap();
process::exit(1);
},
"cf" => if let Some(tar) = args.next() {
if let Some(input) = args.next() {
if let Err(err) = create(&input, &tar) {
write!(stderr(), "tar: create: failed: {}\n", err).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no input specified: {}\n", op).unwrap();
process::exit(1);
}
} else {
write!(stderr(), "tar: create: no tarfile specified: {}\n", op).unwrap();
process::exit(1);
},
"t" | "tf" => {
let tar = args.next().unwrap_or("-".to_string());
if let Err(err) = list(&tar) {
write!(stderr(), "tar: list: failed: {}\n", err).unwrap();
process::exit(1);
}
},
"x" | "xf" | "xvf" => {
let mut tar = None;
let mut strip = 0;
while let Some(arg) = args.next() {
if arg == "-C" || arg == "--directory" {
env::set_current_dir(args.next().expect(&format!("{} requires path", arg))).unwrap();
} else if arg.starts_with("--directory=") {
env::set_current_dir(&arg[12..]).unwrap();
} else if arg.starts_with("--strip-components") {
let num = args.next().expect("--strip-components requires an integer");
strip = usize::from_str(&num).expect("--strip-components requires an integer");
} else if arg.starts_with("--strip-components=") {
strip = usize::from_str(&arg[19..]).expect("--strip-components requires an integer");
} else if tar.is_none() {
let mut path = env::current_dir().unwrap();
path.push(arg);
tar = Some(path);
}
}
let tar = tar.unwrap_or(PathBuf::from("-"));
let verbose = op.contains('v');
if let Err(err) = extract(&tar, verbose, strip) {
write!(stderr(), "tar: extract: failed: {}\n", err).unwrap();
process::exit(1);
}
},
_ => {
write!(stderr(), "tar: {}: unknown operation\n", op).unwrap();
write!(stderr(), "tar: need to specify c[f] (create), t[f] (list), or x[f] (extract)\n").unwrap();
process::exit(1);
}
}
} else {
write!(stderr(), "tar: no operation\n").unwrap();
write!(stderr(), "tar: need to specify cf (create), tf (list), or xf (extract)\n").unwrap();
process::exit(1);
}
}
|
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use env;
/// Default Binlink Dir
#[cfg(target_os = "windows")]
pub const DEFAULT_BINLINK_DIR: &'static str = "/hab/bin";
#[cfg(not(target_os = "windows"))]
pub const DEFAULT_BINLINK_DIR: &'static str = "/bin";
/// Binlink Dir Environment variable
pub const BINLINK_DIR_ENVVAR: &'static str = "HAB_BINLINK_DIR";
pub fn default_binlink_dir() -> String {
match env::var(BINLINK_DIR_ENVVAR) {
Ok(val) => val,
Err(_) => DEFAULT_BINLINK_DIR.to_string(),
}
}
Use /usr/local/bin as default bin link dir
On newish macs /bin is a protected driectory this change
makes binlinks go into /usr/local/bin.
Signed-off-by: Jon Morrow <464b701a872e97467242b8318ff1f8e7672cc0e8@chef.io>
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use env;
/// Default Binlink Dir
#[cfg(target_os = "windows")]
pub const DEFAULT_BINLINK_DIR: &'static str = "/hab/bin";
#[cfg(target_os = "linux")]
pub const DEFAULT_BINLINK_DIR: &'static str = "/bin";
#[cfg(target_os = "macos")]
pub const DEFAULT_BINLINK_DIR: &'static str = "/usr/local/bin";
/// Binlink Dir Environment variable
pub const BINLINK_DIR_ENVVAR: &'static str = "HAB_BINLINK_DIR";
pub fn default_binlink_dir() -> String {
match env::var(BINLINK_DIR_ENVVAR) {
Ok(val) => val,
Err(_) => DEFAULT_BINLINK_DIR.to_string(),
}
}
|
extern crate rand;
extern crate regex;
extern crate url;
use std::collections::HashSet;
use once_cell::sync::Lazy;
use self::regex::Regex;
use self::url::{Url};
const COLORS: Lazy<HashSet<&'static str>> = sync_lazy! {
let mut set = HashSet::new();
set.insert("black");
set.insert("red");
set.insert("green");
set.insert("yellow");
set.insert("blue");
set.insert("magenta");
set.insert("cyan");
set.insert("white");
set.insert("default");
set
};
pub fn replace_all(input: String, from: &str, to: &str) -> String {
input.replace(from, to)
}
pub fn consolidate_whitespace( input: String ) -> String {
let found = input.find( |c: char| !c.is_whitespace() );
let mut result = String::new();
if let Some(found) = found {
let (leading,rest) = input.split_at(found);
let lastchar = input.chars().rev().next().unwrap();
result.push_str(leading);
let iter = rest.split_whitespace();
for elem in iter {
result.push_str(elem);
result.push(' ');
}
result.pop();
if lastchar.is_whitespace() {
result.push(' ');
}
}
result
}
pub fn to_u(rs_str: String, default_value: u32) -> u32 {
let mut result = rs_str.parse::<u32>();
if result.is_err() {
result = Ok(default_value);
}
result.unwrap()
}
/// Combine a base URL and a link to a new absolute URL.
/// # Examples
/// ```
/// use libnewsboat::utils::absolute_url;
/// assert_eq!(absolute_url("http://foobar/hello/crook/", "bar.html"),
/// "http://foobar/hello/crook/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "/bar.html"),
/// "https://foobar/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "http://quux/bar.html"),
/// "http://quux/bar.html".to_owned());
/// assert_eq!(absolute_url("http://foobar", "bla.html"),
/// "http://foobar/bla.html".to_owned());
/// assert_eq!(absolute_url("http://test:test@foobar:33", "bla2.html"),
/// "http://test:test@foobar:33/bla2.html".to_owned());
/// ```
pub fn absolute_url(base_url: &str, link: &str) -> String {
Url::parse(base_url)
.and_then(|url| url.join(link))
.as_ref()
.map(|url| url.as_str())
.unwrap_or(link)
.to_owned()
}
pub fn is_special_url(url: &str) -> bool {
is_query_url(url) || is_filter_url(url) || is_exec_url(url)
}
/// Check if the given URL is a http(s) URL
/// # Example
/// ```
/// use libnewsboat::utils::is_http_url;
/// assert!(is_http_url("http://example.com"));
/// ```
pub fn is_http_url(url: &str) -> bool {
url.starts_with("https://") || url.starts_with("http://")
}
pub fn is_query_url(url: &str) -> bool {
url.starts_with("query:")
}
pub fn is_filter_url(url: &str) -> bool {
url.starts_with("filter:")
}
pub fn is_exec_url(url: &str) -> bool {
url.starts_with("exec:")
}
pub fn get_default_browser() -> String {
use std::env;
match env::var("BROWSER") {
Ok(val) => return val,
Err(_) => return String::from("lynx"),
}
}
pub fn trim(rs_str: String) -> String {
rs_str.trim().to_string()
}
pub fn trim_end(rs_str: String) -> String {
let x: &[_] = &['\n','\r'];
rs_str.trim_right_matches(x).to_string()
}
pub fn get_random_value(max: u32) -> u32 {
rand::random::<u32>() % max
}
pub fn is_valid_color(color: &str) -> bool {
if COLORS.contains(color) {
return true;
}
if color.starts_with("color0") {
return color == "color0";
}
if color.starts_with("color") {
let num_part = &color[5..];
match num_part.parse::<u8>() {
Ok(_) => return true,
_ => return false,
}
}
false
}
pub fn is_valid_podcast_type(mimetype: &str) -> bool {
let re = Regex::new(r"(audio|video)/.*").unwrap();
let matches = re.is_match(mimetype);
let acceptable = ["application/ogg"];
let found = acceptable.contains(&mimetype);
matches || found
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_replace_all() {
assert_eq!(
replace_all(String::from("aaa"), "a", "b"),
String::from("bbb"));
assert_eq!(
replace_all(String::from("aaa"), "aa", "ba"),
String::from("baa"));
assert_eq!(
replace_all(String::from("aaaaaa"), "aa", "ba"),
String::from("bababa"));
assert_eq!(
replace_all(String::new(), "a", "b"),
String::new());
let input = String::from("aaaa");
assert_eq!(replace_all(input.clone(), "b", "c"), input);
assert_eq!(
replace_all(String::from("this is a normal test text"), " t", " T"),
String::from("this is a normal Test Text"));
assert_eq!(
replace_all(String::from("o o o"), "o", "<o>"),
String::from("<o> <o> <o>"));
}
#[test]
fn t_consolidate_whitespace() {
assert_eq!(
consolidate_whitespace(String::from("LoremIpsum")),
String::from("LoremIpsum"));
assert_eq!(
consolidate_whitespace(String::from("Lorem Ipsum")),
String::from("Lorem Ipsum"));
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum "));
assert_eq!(consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum"));
assert_eq!(consolidate_whitespace(String::new()), String::new());
assert_eq!(consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum "));
assert_eq!(consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum"));
}
#[test]
fn t_to_u() {
assert_eq!(to_u(String::from("0"), 10), 0);
assert_eq!(to_u(String::from("23"), 1), 23);
assert_eq!(to_u(String::from(""), 0), 0);
assert_eq!(to_u(String::from("zero"), 1), 1);
}
#[test]
fn t_is_special_url() {
assert!(is_special_url("query:"));
assert!(is_special_url("query: example"));
assert!(!is_special_url("query"));
assert!(!is_special_url(" query:"));
assert!(is_special_url("filter:"));
assert!(is_special_url("filter: example"));
assert!(!is_special_url("filter"));
assert!(!is_special_url(" filter:"));
assert!(is_special_url("exec:"));
assert!(is_special_url("exec: example"));
assert!(!is_special_url("exec"));
assert!(!is_special_url(" exec:"));
}
#[test]
fn t_is_http_url() {
assert!(is_http_url("https://foo.bar"));
assert!(is_http_url("http://"));
assert!(is_http_url("https://"));
assert!(!is_http_url("htt://foo.bar"));
assert!(!is_http_url("http:/"));
assert!(!is_http_url("foo://bar"));
}
#[test]
fn t_is_query_url() {
assert!(is_query_url("query:"));
assert!(is_query_url("query: example"));
assert!(!is_query_url("query"));
assert!(!is_query_url(" query:"));
}
#[test]
fn t_is_filter_url() {
assert!(is_filter_url("filter:"));
assert!(is_filter_url("filter: example"));
assert!(!is_filter_url("filter"));
assert!(!is_filter_url(" filter:"));
}
#[test]
fn t_is_exec_url() {
assert!(is_exec_url("exec:"));
assert!(is_exec_url("exec: example"));
assert!(!is_exec_url("exec"));
assert!(!is_exec_url(" exec:"));
}
#[test]
fn t_trim() {
assert_eq!(trim(String::from(" xxx\r\n")), "xxx");
assert_eq!(trim(String::from("\n\n abc foobar\n")), "abc foobar");
assert_eq!(trim(String::from("")), "");
assert_eq!(trim(String::from(" \n")), "");
}
#[test]
fn t_trim_end() {
assert_eq!(trim_end(String::from("quux\n")), "quux");
}
#[test]
fn t_is_valid_color() {
let invalid = [
"awesome",
"list",
"of",
"things",
"that",
"aren't",
"colors",
"color0123",
"color1024",
];
for color in &invalid {
assert!(!is_valid_color(color));
}
let valid = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
"default",
"color0",
"color163",
];
for color in &valid {
assert!(is_valid_color(color));
}
}
#[test]
fn t_is_valid_podcast_type() {
assert!(is_valid_podcast_type("audio/mpeg"));
assert!(is_valid_podcast_type("audio/mp3"));
assert!(is_valid_podcast_type("audio/x-mp3"));
assert!(is_valid_podcast_type("audio/ogg"));
assert!(is_valid_podcast_type("application/ogg"));
assert!(!is_valid_podcast_type("image/jpeg"));
assert!(!is_valid_podcast_type("image/png"));
assert!(!is_valid_podcast_type("text/plain"));
assert!(!is_valid_podcast_type("application/zip"));
}
}
Extend absolute_url documentation and add test
extern crate rand;
extern crate regex;
extern crate url;
use std::collections::HashSet;
use once_cell::sync::Lazy;
use self::regex::Regex;
use self::url::{Url};
const COLORS: Lazy<HashSet<&'static str>> = sync_lazy! {
let mut set = HashSet::new();
set.insert("black");
set.insert("red");
set.insert("green");
set.insert("yellow");
set.insert("blue");
set.insert("magenta");
set.insert("cyan");
set.insert("white");
set.insert("default");
set
};
pub fn replace_all(input: String, from: &str, to: &str) -> String {
input.replace(from, to)
}
pub fn consolidate_whitespace( input: String ) -> String {
let found = input.find( |c: char| !c.is_whitespace() );
let mut result = String::new();
if let Some(found) = found {
let (leading,rest) = input.split_at(found);
let lastchar = input.chars().rev().next().unwrap();
result.push_str(leading);
let iter = rest.split_whitespace();
for elem in iter {
result.push_str(elem);
result.push(' ');
}
result.pop();
if lastchar.is_whitespace() {
result.push(' ');
}
}
result
}
pub fn to_u(rs_str: String, default_value: u32) -> u32 {
let mut result = rs_str.parse::<u32>();
if result.is_err() {
result = Ok(default_value);
}
result.unwrap()
}
/// Combine a base URL and a link to a new absolute URL.
/// If the base URL is malformed or joining with the link fails, link will be returned.
/// # Examples
/// ```
/// use libnewsboat::utils::absolute_url;
/// assert_eq!(absolute_url("http://foobar/hello/crook/", "bar.html"),
/// "http://foobar/hello/crook/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "/bar.html"),
/// "https://foobar/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "http://quux/bar.html"),
/// "http://quux/bar.html".to_owned());
/// assert_eq!(absolute_url("http://foobar", "bla.html"),
/// "http://foobar/bla.html".to_owned());
/// assert_eq!(absolute_url("http://test:test@foobar:33", "bla2.html"),
/// "http://test:test@foobar:33/bla2.html".to_owned());
/// assert_eq!(absolute_url("foo", "bar"), "bar".to_owned());
/// ```
pub fn absolute_url(base_url: &str, link: &str) -> String {
Url::parse(base_url)
.and_then(|url| url.join(link))
.as_ref()
.map(|url| url.as_str())
.unwrap_or(link)
.to_owned()
}
pub fn is_special_url(url: &str) -> bool {
is_query_url(url) || is_filter_url(url) || is_exec_url(url)
}
/// Check if the given URL is a http(s) URL
/// # Example
/// ```
/// use libnewsboat::utils::is_http_url;
/// assert!(is_http_url("http://example.com"));
/// ```
pub fn is_http_url(url: &str) -> bool {
url.starts_with("https://") || url.starts_with("http://")
}
pub fn is_query_url(url: &str) -> bool {
url.starts_with("query:")
}
pub fn is_filter_url(url: &str) -> bool {
url.starts_with("filter:")
}
pub fn is_exec_url(url: &str) -> bool {
url.starts_with("exec:")
}
pub fn get_default_browser() -> String {
use std::env;
match env::var("BROWSER") {
Ok(val) => return val,
Err(_) => return String::from("lynx"),
}
}
pub fn trim(rs_str: String) -> String {
rs_str.trim().to_string()
}
pub fn trim_end(rs_str: String) -> String {
let x: &[_] = &['\n','\r'];
rs_str.trim_right_matches(x).to_string()
}
pub fn get_random_value(max: u32) -> u32 {
rand::random::<u32>() % max
}
pub fn is_valid_color(color: &str) -> bool {
if COLORS.contains(color) {
return true;
}
if color.starts_with("color0") {
return color == "color0";
}
if color.starts_with("color") {
let num_part = &color[5..];
match num_part.parse::<u8>() {
Ok(_) => return true,
_ => return false,
}
}
false
}
pub fn is_valid_podcast_type(mimetype: &str) -> bool {
let re = Regex::new(r"(audio|video)/.*").unwrap();
let matches = re.is_match(mimetype);
let acceptable = ["application/ogg"];
let found = acceptable.contains(&mimetype);
matches || found
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_replace_all() {
assert_eq!(
replace_all(String::from("aaa"), "a", "b"),
String::from("bbb"));
assert_eq!(
replace_all(String::from("aaa"), "aa", "ba"),
String::from("baa"));
assert_eq!(
replace_all(String::from("aaaaaa"), "aa", "ba"),
String::from("bababa"));
assert_eq!(
replace_all(String::new(), "a", "b"),
String::new());
let input = String::from("aaaa");
assert_eq!(replace_all(input.clone(), "b", "c"), input);
assert_eq!(
replace_all(String::from("this is a normal test text"), " t", " T"),
String::from("this is a normal Test Text"));
assert_eq!(
replace_all(String::from("o o o"), "o", "<o>"),
String::from("<o> <o> <o>"));
}
#[test]
fn t_consolidate_whitespace() {
assert_eq!(
consolidate_whitespace(String::from("LoremIpsum")),
String::from("LoremIpsum"));
assert_eq!(
consolidate_whitespace(String::from("Lorem Ipsum")),
String::from("Lorem Ipsum"));
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum "));
assert_eq!(consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum"));
assert_eq!(consolidate_whitespace(String::new()), String::new());
assert_eq!(consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum "));
assert_eq!(consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum"));
}
#[test]
fn t_to_u() {
assert_eq!(to_u(String::from("0"), 10), 0);
assert_eq!(to_u(String::from("23"), 1), 23);
assert_eq!(to_u(String::from(""), 0), 0);
assert_eq!(to_u(String::from("zero"), 1), 1);
}
#[test]
fn t_is_special_url() {
assert!(is_special_url("query:"));
assert!(is_special_url("query: example"));
assert!(!is_special_url("query"));
assert!(!is_special_url(" query:"));
assert!(is_special_url("filter:"));
assert!(is_special_url("filter: example"));
assert!(!is_special_url("filter"));
assert!(!is_special_url(" filter:"));
assert!(is_special_url("exec:"));
assert!(is_special_url("exec: example"));
assert!(!is_special_url("exec"));
assert!(!is_special_url(" exec:"));
}
#[test]
fn t_is_http_url() {
assert!(is_http_url("https://foo.bar"));
assert!(is_http_url("http://"));
assert!(is_http_url("https://"));
assert!(!is_http_url("htt://foo.bar"));
assert!(!is_http_url("http:/"));
assert!(!is_http_url("foo://bar"));
}
#[test]
fn t_is_query_url() {
assert!(is_query_url("query:"));
assert!(is_query_url("query: example"));
assert!(!is_query_url("query"));
assert!(!is_query_url(" query:"));
}
#[test]
fn t_is_filter_url() {
assert!(is_filter_url("filter:"));
assert!(is_filter_url("filter: example"));
assert!(!is_filter_url("filter"));
assert!(!is_filter_url(" filter:"));
}
#[test]
fn t_is_exec_url() {
assert!(is_exec_url("exec:"));
assert!(is_exec_url("exec: example"));
assert!(!is_exec_url("exec"));
assert!(!is_exec_url(" exec:"));
}
#[test]
fn t_trim() {
assert_eq!(trim(String::from(" xxx\r\n")), "xxx");
assert_eq!(trim(String::from("\n\n abc foobar\n")), "abc foobar");
assert_eq!(trim(String::from("")), "");
assert_eq!(trim(String::from(" \n")), "");
}
#[test]
fn t_trim_end() {
assert_eq!(trim_end(String::from("quux\n")), "quux");
}
#[test]
fn t_is_valid_color() {
let invalid = [
"awesome",
"list",
"of",
"things",
"that",
"aren't",
"colors",
"color0123",
"color1024",
];
for color in &invalid {
assert!(!is_valid_color(color));
}
let valid = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
"default",
"color0",
"color163",
];
for color in &valid {
assert!(is_valid_color(color));
}
}
#[test]
fn t_is_valid_podcast_type() {
assert!(is_valid_podcast_type("audio/mpeg"));
assert!(is_valid_podcast_type("audio/mp3"));
assert!(is_valid_podcast_type("audio/x-mp3"));
assert!(is_valid_podcast_type("audio/ogg"));
assert!(is_valid_podcast_type("application/ogg"));
assert!(!is_valid_podcast_type("image/jpeg"));
assert!(!is_valid_podcast_type("image/png"));
assert!(!is_valid_podcast_type("text/plain"));
assert!(!is_valid_podcast_type("application/zip"));
}
}
|
use crate::htmlrenderer;
use crate::logger::{self, Level};
use libc::c_ulong;
use percent_encoding::*;
use std::fs::DirBuilder;
use std::io::{self, Write};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use url::Url;
pub fn replace_all(input: String, from: &str, to: &str) -> String {
input.replace(from, to)
}
pub fn consolidate_whitespace(input: String) -> String {
let found = input.find(|c: char| !c.is_whitespace());
let mut result = String::new();
if let Some(found) = found {
let (leading, rest) = input.split_at(found);
let lastchar = input.chars().rev().next().unwrap();
result.push_str(leading);
let iter = rest.split_whitespace();
for elem in iter {
result.push_str(elem);
result.push(' ');
}
result.pop();
if lastchar.is_whitespace() {
result.push(' ');
}
}
result
}
pub fn to_u(rs_str: String, default_value: u32) -> u32 {
let mut result = rs_str.parse::<u32>();
if result.is_err() {
result = Ok(default_value);
}
result.unwrap()
}
/// Combine a base URL and a link to a new absolute URL.
/// If the base URL is malformed or joining with the link fails, link will be returned.
/// # Examples
/// ```
/// use libnewsboat::utils::absolute_url;
/// assert_eq!(absolute_url("http://foobar/hello/crook/", "bar.html"),
/// "http://foobar/hello/crook/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "/bar.html"),
/// "https://foobar/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "http://quux/bar.html"),
/// "http://quux/bar.html".to_owned());
/// assert_eq!(absolute_url("http://foobar", "bla.html"),
/// "http://foobar/bla.html".to_owned());
/// assert_eq!(absolute_url("http://test:test@foobar:33", "bla2.html"),
/// "http://test:test@foobar:33/bla2.html".to_owned());
/// assert_eq!(absolute_url("foo", "bar"), "bar".to_owned());
/// ```
pub fn absolute_url(base_url: &str, link: &str) -> String {
Url::parse(base_url)
.and_then(|url| url.join(link))
.as_ref()
.map(Url::as_str)
.unwrap_or(link)
.to_owned()
}
/// Path to the home directory, if known. Doesn't work on Windows.
#[cfg(not(target_os = "windows"))]
pub fn home_dir() -> Option<PathBuf> {
// This function got deprecated because it examines HOME environment variable even on Windows,
// which is wrong. But Newsboat doesn't support Windows, so we're fine using that.
//
// Cf. https://github.com/rust-lang/rust/issues/28940
#[allow(deprecated)]
std::env::home_dir()
}
/// Replaces tilde (`~`) at the beginning of the path with the path to user's home directory.
pub fn resolve_tilde(path: PathBuf) -> PathBuf {
if let (Some(home), Ok(suffix)) = (home_dir(), path.strip_prefix("~")) {
return home.join(suffix);
}
// Either the `path` doesn't start with tilde, or we couldn't figure out the path to the
// home directory -- either way, it's no big deal. Let's return the original string.
path
}
pub fn resolve_relative(reference: &Path, path: &Path) -> PathBuf {
if path.is_relative() {
// Will only ever panic if reference is `/`, which shouldn't be the case as reference is
// always a file path
return reference.parent().unwrap().join(path);
}
path.to_path_buf()
}
pub fn is_special_url(url: &str) -> bool {
is_query_url(url) || is_filter_url(url) || is_exec_url(url)
}
/// Check if the given URL is a http(s) URL
/// # Example
/// ```
/// use libnewsboat::utils::is_http_url;
/// assert!(is_http_url("http://example.com"));
/// ```
pub fn is_http_url(url: &str) -> bool {
url.starts_with("https://") || url.starts_with("http://")
}
pub fn is_query_url(url: &str) -> bool {
url.starts_with("query:")
}
pub fn is_filter_url(url: &str) -> bool {
url.starts_with("filter:")
}
pub fn is_exec_url(url: &str) -> bool {
url.starts_with("exec:")
}
/// Censor URLs by replacing username and password with '*'
/// ```
/// use libnewsboat::utils::censor_url;
/// assert_eq!(&censor_url(""), "");
/// assert_eq!(&censor_url("foobar"), "foobar");
/// assert_eq!(&censor_url("foobar://xyz/"), "foobar://xyz/");
/// assert_eq!(&censor_url("http://newsbeuter.org/"),
/// "http://newsbeuter.org/");
/// assert_eq!(&censor_url("https://newsbeuter.org/"),
/// "https://newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://@newsbeuter.org/"),
/// "http://newsbeuter.org/");
/// assert_eq!(&censor_url("https://@newsbeuter.org/"),
/// "https://newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://foo:bar@newsbeuter.org/"),
/// "http://*:*@newsbeuter.org/");
/// assert_eq!(&censor_url("https://foo:bar@newsbeuter.org/"),
/// "https://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://aschas@newsbeuter.org/"),
/// "http://*:*@newsbeuter.org/");
/// assert_eq!(&censor_url("https://aschas@newsbeuter.org/"),
/// "https://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("xxx://aschas@newsbeuter.org/"),
/// "xxx://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://foobar"), "http://foobar/");
/// assert_eq!(&censor_url("https://foobar"), "https://foobar/");
///
/// assert_eq!(&censor_url("http://aschas@host"), "http://*:*@host/");
/// assert_eq!(&censor_url("https://aschas@host"), "https://*:*@host/");
///
/// assert_eq!(&censor_url("query:name:age between 1:10"),
/// "query:name:age between 1:10");
/// ```
pub fn censor_url(url: &str) -> String {
if !url.is_empty() && !is_special_url(url) {
Url::parse(url)
.map(|mut url| {
if url.username() != "" || url.password().is_some() {
// can not panic. If either username or password is present we can change both.
url.set_username("*").unwrap();
url.set_password(Some("*")).unwrap();
}
url
})
.as_ref()
.map(Url::as_str)
.unwrap_or(url)
.to_owned()
} else {
url.into()
}
}
/// Quote a string for use with stfl by replacing all occurences of "<" with "<>"
/// ```
/// use libnewsboat::utils::quote_for_stfl;
/// assert_eq!("e_for_stfl("<"), "<>");
/// assert_eq!("e_for_stfl("<<><><><"), "<><>><>><>><>");
/// assert_eq!("e_for_stfl("test"), "test");
/// ```
pub fn quote_for_stfl(string: &str) -> String {
string.replace("<", "<>")
}
/// Get basename from a URL if available else return an empty string
/// ```
/// use libnewsboat::utils::get_basename;
/// assert_eq!(get_basename("https://example.com/"), "");
/// assert_eq!(get_basename("https://example.org/?param=value#fragment"), "");
/// assert_eq!(get_basename("https://example.org/path/to/?param=value#fragment"), "");
/// assert_eq!(get_basename("https://example.org/file.mp3"), "file.mp3");
/// assert_eq!(get_basename("https://example.org/path/to/file.mp3?param=value#fragment"), "file.mp3");
/// ```
pub fn get_basename(input: &str) -> String {
match Url::parse(input) {
Ok(url) => match url.path_segments() {
Some(segments) => segments.last().unwrap().to_string(),
None => String::from(""),
},
Err(_) => String::from(""),
}
}
pub fn get_default_browser() -> String {
use std::env;
env::var("BROWSER").unwrap_or_else(|_| "lynx".to_string())
}
pub fn trim(rs_str: String) -> String {
rs_str.trim().to_string()
}
pub fn trim_end(rs_str: String) -> String {
let x: &[_] = &['\n', '\r'];
rs_str.trim_end_matches(x).to_string()
}
pub fn quote(input: String) -> String {
let mut input = input.replace("\"", "\\\"");
input.insert(0, '"');
input.push('"');
input
}
pub fn quote_if_necessary(input: String) -> String {
match input.find(' ') {
Some(_) => quote(input),
None => input,
}
}
pub fn get_random_value(max: u32) -> u32 {
rand::random::<u32>() % max
}
pub fn is_valid_color(color: &str) -> bool {
const COLORS: [&str; 9] = [
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default",
];
if COLORS.contains(&color) {
true
} else if color.starts_with("color0") {
color == "color0"
} else if color.starts_with("color") {
let num_part = &color[5..];
num_part.parse::<u8>().is_ok()
} else {
false
}
}
pub fn is_valid_attribute(attribute: &str) -> bool {
const VALID_ATTRIBUTES: [&str; 9] = [
"standout",
"underline",
"reverse",
"blink",
"dim",
"bold",
"protect",
"invis",
"default",
];
VALID_ATTRIBUTES.contains(&attribute)
}
pub fn strwidth(rs_str: &str) -> usize {
UnicodeWidthStr::width(rs_str)
}
/// Returns the width of `rs_str` when displayed on screen.
///
/// STFL tags (e.g. `<b>`, `<foobar>`, `</>`) are counted as having 0 width.
/// Escaped less-than sign (`<` escaped as `<>`) is counted as having a width of 1 character.
/// ```
/// use libnewsboat::utils::strwidth_stfl;
/// assert_eq!(strwidth_stfl("a"), 1);
/// assert_eq!(strwidth_stfl("abc<tag>def"), 6);
/// assert_eq!(strwidth_stfl("less-than: <>"), 12);
/// assert_eq!(strwidth_stfl("ABCDEF"), 12);
///```
pub fn strwidth_stfl(rs_str: &str) -> usize {
let mut s = &rs_str[..];
let mut width = 0;
loop {
if let Some(pos) = s.find('<') {
width += strwidth(&s[..pos]);
s = &s[pos..];
if let Some(endpos) = s.find('>') {
if endpos == 1 {
// Found "<>" which stfl uses to encode a literal '<'
width += strwidth("<");
}
s = &s[endpos + 1..];
} else {
// '<' without closing '>' so ignore rest of string
break;
}
} else {
width += strwidth(s);
break;
}
}
width
}
/// Returns a longest substring fits to the given width.
/// Returns an empty string if `str` is an empty string or `max_width` is zero.
///
/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()
/// returns None, the character width is treated as 0.
/// ```
/// use libnewsboat::utils::substr_with_width;
/// assert_eq!(substr_with_width("a", 1), "a");
/// assert_eq!(substr_with_width("a", 2), "a");
/// assert_eq!(substr_with_width("ab", 1), "a");
/// assert_eq!(substr_with_width("abc", 1), "a");
/// assert_eq!(substr_with_width("A\u{3042}B\u{3044}C\u{3046}", 5), "A\u{3042}B")
///```
pub fn substr_with_width(string: &str, max_width: usize) -> String {
let mut result = String::new();
let mut width = 0;
for c in string.chars() {
// Control chars count as width 0
let w = UnicodeWidthChar::width(c).unwrap_or(0);
if width + w > max_width {
break;
}
width += w;
result.push(c);
}
result
}
/// Returns a longest substring fits to the given width.
/// Returns an empty string if `str` is an empty string or `max_width` is zero.
///
/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()
/// returns None, the character width is treated as 0. A STFL tag (e.g. `<b>`, `<foobar>`, `</>`)
/// width is treated as 0, but escaped less-than (`<>`) width is treated as 1.
/// ```
/// use libnewsboat::utils::substr_with_width_stfl;
/// assert_eq!(substr_with_width_stfl("a", 1), "a");
/// assert_eq!(substr_with_width_stfl("a", 2), "a");
/// assert_eq!(substr_with_width_stfl("ab", 1), "a");
/// assert_eq!(substr_with_width_stfl("abc", 1), "a");
/// assert_eq!(substr_with_width_stfl("A\u{3042}B\u{3044}C\u{3046}", 5), "A\u{3042}B")
///```
pub fn substr_with_width_stfl(string: &str, max_width: usize) -> String {
let mut result = String::new();
let mut in_bracket = false;
let mut tagbuf = Vec::<char>::new();
let mut width = 0;
for c in string.chars() {
if in_bracket {
tagbuf.push(c);
if c == '>' {
in_bracket = false;
if tagbuf == ['<', '>'] {
if width + 1 > max_width {
break;
}
result += "<>"; // escaped less-than
tagbuf.clear();
width += 1;
} else {
result += &tagbuf.iter().collect::<String>();
tagbuf.clear();
}
}
} else if c == '<' {
in_bracket = true;
tagbuf.push(c);
} else {
// Control chars count as width 0
let w = UnicodeWidthChar::width(c).unwrap_or(0);
if width + w > max_width {
break;
}
width += w;
result.push(c);
}
}
result
}
/// Remove all soft-hyphens as they can behave unpredictably (see
/// https://github.com/akrennmair/newsbeuter/issues/259#issuecomment-259609490) and inadvertently
/// render as hyphens
pub fn remove_soft_hyphens(text: &mut String) {
text.retain(|c| c != '\u{00AD}')
}
/// An array of "MIME matchers" and their associated LinkTypes
///
/// This is used for two tasks:
///
/// 1. checking if a MIME type is a podcast type (`utils::is_valid_podcast_type`). That involves
/// running all matching functions on given input and checking if any of them returned `true`;
///
/// 2. figuring out the `LinkType` for a particular enclosure, given its MIME type
/// (`utils::podcast_mime_to_link_type`).
type MimeMatcher = (fn(&str) -> bool, htmlrenderer::LinkType);
const PODCAST_MIME_TO_LINKTYPE: [MimeMatcher; 2] = [
(
|mime| {
// RFC 5334, section 10.1 says "historically, some implementations expect .ogg files to be
// solely Vorbis-encoded audio", so let's assume it's audio, not video.
// https://tools.ietf.org/html/rfc5334#section-10.1
mime.starts_with("audio/") || mime == "application/ogg"
},
htmlrenderer::LinkType::Audio,
),
(
|mime| mime.starts_with("video/"),
htmlrenderer::LinkType::Video,
),
];
/// Returns `true` if given MIME type is considered to be a podcast by Newsboat.
pub fn is_valid_podcast_type(mimetype: &str) -> bool {
PODCAST_MIME_TO_LINKTYPE
.iter()
.any(|(matcher, _)| matcher(mimetype))
}
/// Converts podcast's MIME type into an HtmlRenderer's "link type"
///
/// Returns None if given MIME type is not a podcast type. See `is_valid_podcast_type()`.
pub fn podcast_mime_to_link_type(mime_type: &str) -> Option<htmlrenderer::LinkType> {
PODCAST_MIME_TO_LINKTYPE
.iter()
.find_map(|(matcher, link_type)| {
if matcher(mime_type) {
Some(*link_type)
} else {
None
}
})
}
pub fn get_auth_method(method: &str) -> c_ulong {
match method {
"basic" => curl_sys::CURLAUTH_BASIC,
"digest" => curl_sys::CURLAUTH_DIGEST,
"digest_ie" => curl_sys::CURLAUTH_DIGEST_IE,
"gssnegotiate" => curl_sys::CURLAUTH_GSSNEGOTIATE,
"ntlm" => curl_sys::CURLAUTH_NTLM,
"anysafe" => curl_sys::CURLAUTH_ANYSAFE,
"any" | "" => curl_sys::CURLAUTH_ANY,
_ => {
log!(
Level::UserError,
"utils::get_auth_method: you configured an invalid proxy authentication method: {}",
method
);
curl_sys::CURLAUTH_ANY
}
}
}
pub fn unescape_url(rs_str: String) -> Option<String> {
let decoded = percent_decode(rs_str.as_bytes()).decode_utf8();
decoded.ok().map(|s| s.replace("\0", ""))
}
/// Runs given command in a shell, and returns the output (from stdout; stderr is printed to the
/// screen).
pub fn get_command_output(cmd: &str) -> String {
let cmd = Command::new("sh")
.arg("-c")
.arg(cmd)
// Inherit stdin so that the program can ask something of the user (see
// https://github.com/newsboat/newsboat/issues/455 for an example).
.stdin(Stdio::inherit())
.output();
// from_utf8_lossy will convert any bad bytes to U+FFFD
cmd.map(|cmd| String::from_utf8_lossy(&cmd.stdout).into_owned())
.unwrap_or_else(|_| String::from(""))
}
// This function assumes that the user is not interested in command's output (not even errors on
// stderr!), so it redirects everything to /dev/null.
pub fn run_command(cmd: &str, param: &str) {
let child = Command::new(cmd)
.arg(param)
// Prevent the command from blocking Newsboat by asking for input
.stdin(Stdio::null())
// Prevent the command from botching the screen by printing onto it.
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Err(error) = child {
log!(
Level::Debug,
"utils::run_command: spawning a child for \"{}\" failed: {}",
cmd,
error
);
}
// We deliberately *don't* wait for the child to finish.
}
pub fn run_program(cmd_with_args: &[&str], input: &str) -> String {
if cmd_with_args.is_empty() {
return String::new();
}
Command::new(cmd_with_args[0])
.args(&cmd_with_args[1..])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|error| {
log!(
Level::Debug,
"utils::run_program: spawning a child for \"{:?}\" \
with input \"{}\" failed: {}",
cmd_with_args,
input,
error
);
})
.and_then(|mut child| {
if let Some(stdin) = child.stdin.as_mut() {
if let Err(error) = stdin.write_all(input.as_bytes()) {
log!(
Level::Debug,
"utils::run_program: failed to write to child's stdin: {}",
error
);
}
}
child
.wait_with_output()
.map_err(|error| {
log!(
Level::Debug,
"utils::run_program: failed to read child's stdout: {}",
error
);
})
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
})
.unwrap_or_else(|_| String::new())
}
pub fn make_title(rs_str: String) -> String {
/* Sometimes it is possible to construct the title from the URL
* This attempts to do just that. eg:
* http://domain.com/story/yy/mm/dd/title-with-dashes?a=b
*/
// Strip out trailing slashes
let mut result = rs_str.trim_end_matches('/');
// get to the final part of the URI's path and
// extract just the juicy part 'title-with-dashes?a=b'
let v: Vec<&str> = result.rsplitn(2, '/').collect();
result = v[0];
// find where query part of URI starts
// throw away the query part 'title-with-dashes'
let v: Vec<&str> = result.splitn(2, '?').collect();
result = v[0];
// Throw away common webpage suffixes: .html, .php, .aspx, .htm
result = result
.trim_end_matches(".html")
.trim_end_matches(".php")
.trim_end_matches(".aspx")
.trim_end_matches(".htm");
// 'title with dashes'
let result = result.replace('-', " ").replace('_', " ");
//'Title with dashes'
//let result = "";
let mut c = result.chars();
let result = match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
};
// Un-escape any percent-encoding, e.g. "It%27s%202017%21" -> "It's
// 2017!"
match unescape_url(result) {
None => String::new(),
Some(f) => f,
}
}
/// Run the given command interactively with inherited stdin and stdout/stderr. Return the lowest
/// 8 bits of its exit code, or `None` if the command failed to start.
/// ```
/// use libnewsboat::utils::run_interactively;
///
/// let result = run_interactively("echo true", "test");
/// assert_eq!(result, Some(0));
///
/// let result = run_interactively("exit 1", "test");
/// assert_eq!(result, Some(1));
///
/// // Unfortunately, there is no easy way to provoke this function to return `None`, nor to test
/// // that it returns just the lowest 8 bits.
/// ```
pub fn run_interactively(command: &str, caller: &str) -> Option<u8> {
log!(Level::Debug, &format!("{}: running `{}'", caller, command));
Command::new("sh")
.arg("-c")
.arg(command)
.status()
.map_err(|err| {
log!(
Level::Warn,
&format!("{}: Couldn't create child process: {}", caller, err)
)
})
.ok()
.and_then(|exit_status| exit_status.code())
.map(|exit_code| exit_code as u8)
}
/// Get the current working directory.
pub fn getcwd() -> Result<PathBuf, io::Error> {
use std::env;
env::current_dir()
}
pub fn strnaturalcmp(a: &str, b: &str) -> std::cmp::Ordering {
natord::compare(a, b)
}
/// Calculate the number of padding tabs when formatting columns
///
/// The number of tabs will be adjusted by the width of the given string. Usually, a column will
/// consist of 4 tabs, 8 characters each. Each column will consist of at least one tab.
///
/// ```
/// use libnewsboat::utils::gentabs;
///
/// fn genstring(len: usize) -> String {
/// return std::iter::repeat("a").take(len).collect::<String>();
/// }
///
/// assert_eq!(gentabs(""), 4);
/// assert_eq!(gentabs("a"), 4);
/// assert_eq!(gentabs("aa"), 4);
/// assert_eq!(gentabs("aaa"), 4);
/// assert_eq!(gentabs("aaaa"), 4);
/// assert_eq!(gentabs("aaaaa"), 4);
/// assert_eq!(gentabs("aaaaaa"), 4);
/// assert_eq!(gentabs("aaaaaaa"), 4);
/// assert_eq!(gentabs("aaaaaaaa"), 3);
/// assert_eq!(gentabs(&genstring(8)), 3);
/// assert_eq!(gentabs(&genstring(9)), 3);
/// assert_eq!(gentabs(&genstring(15)), 3);
/// assert_eq!(gentabs(&genstring(16)), 2);
/// assert_eq!(gentabs(&genstring(20)), 2);
/// assert_eq!(gentabs(&genstring(24)), 1);
/// assert_eq!(gentabs(&genstring(32)), 1);
/// assert_eq!(gentabs(&genstring(100)), 1);
/// ```
pub fn gentabs(string: &str) -> usize {
let tabcount = strwidth(string) / 8;
if tabcount >= 4 {
1
} else {
4 - tabcount
}
}
/// Recursively create directories if missing and set permissions accordingly.
pub fn mkdir_parents<R: AsRef<Path>>(p: &R, mode: u32) -> io::Result<()> {
DirBuilder::new()
.mode(mode)
.recursive(true) // directories created with same security and permissions
.create(p.as_ref())
}
/// The tag and Git commit ID the program was built from, or a pre-defined value from config.h if
/// there is no Git directory.
pub fn program_version() -> String {
// NEWSBOAT_VERSION is set by this crate's build script, "build.rs"
env!("NEWSBOAT_VERSION").to_string()
}
/// Newsboat's major version number.
pub fn newsboat_major_version() -> u32 {
// This will panic if the version couldn't be parsed, which is virtually impossible as Cargo
// won't even start compilation if it couldn't parse the version.
env!("CARGO_PKG_VERSION_MAJOR").parse::<u32>().unwrap()
}
/// Returns the part of the string before first # character (or the whole input string if there are
/// no # character in it). Pound characters inside double quotes and backticks are ignored.
pub fn strip_comments(line: &str) -> &str {
let mut prev_was_backslash = false;
let mut inside_quotes = false;
let mut inside_backticks = false;
let mut first_pound_chr_idx = line.len();
for (idx, chr) in line.char_indices() {
match chr {
'\\' => {
prev_was_backslash = true;
continue;
}
'"' => {
// If the quote is escaped or we're inside backticks, do nothing
if !prev_was_backslash && !inside_backticks {
inside_quotes = !inside_quotes;
}
}
'`' => {
// If the backtick is escaped, do nothing
if !prev_was_backslash {
inside_backticks = !inside_backticks;
}
}
'#' => {
if !prev_was_backslash && !inside_quotes && !inside_backticks {
first_pound_chr_idx = idx;
break;
}
}
_ => {}
}
// We call `continue` when we run into a backslash; here, we handle all the other
// characters, which clearly *aren't* a backslash
prev_was_backslash = false;
}
&line[0..first_pound_chr_idx]
}
/// Extract filter and url from line separated by ':'.
pub fn extract_filter(line: &str) -> (&str, &str) {
debug_assert!(line.starts_with("filter:"));
// line must start with "filter:"
let line = line.get("filter:".len()..).unwrap();
let (filter, url) = line.split_at(line.find(':').unwrap_or(0));
let url = url.get(1..).unwrap_or("");
log!(
Level::Debug,
"utils::extract_filter: {} -> filter: {} url: {}",
line,
filter,
url
);
(filter, url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_replace_all() {
assert_eq!(
replace_all(String::from("aaa"), "a", "b"),
String::from("bbb")
);
assert_eq!(
replace_all(String::from("aaa"), "aa", "ba"),
String::from("baa")
);
assert_eq!(
replace_all(String::from("aaaaaa"), "aa", "ba"),
String::from("bababa")
);
assert_eq!(replace_all(String::new(), "a", "b"), String::new());
let input = String::from("aaaa");
assert_eq!(replace_all(input.clone(), "b", "c"), input);
assert_eq!(
replace_all(String::from("this is a normal test text"), " t", " T"),
String::from("this is a normal Test Text")
);
assert_eq!(
replace_all(String::from("o o o"), "o", "<o>"),
String::from("<o> <o> <o>")
);
}
#[test]
fn t_consolidate_whitespace() {
assert_eq!(
consolidate_whitespace(String::from("LoremIpsum")),
String::from("LoremIpsum")
);
assert_eq!(
consolidate_whitespace(String::from("Lorem Ipsum")),
String::from("Lorem Ipsum")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum ")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum")
);
assert_eq!(consolidate_whitespace(String::new()), String::new());
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum ")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum")
);
}
#[test]
fn t_to_u() {
assert_eq!(to_u(String::from("0"), 10), 0);
assert_eq!(to_u(String::from("23"), 1), 23);
assert_eq!(to_u(String::from(""), 0), 0);
assert_eq!(to_u(String::from("zero"), 1), 1);
}
#[test]
fn t_is_special_url() {
assert!(is_special_url("query:"));
assert!(is_special_url("query: example"));
assert!(!is_special_url("query"));
assert!(!is_special_url(" query:"));
assert!(is_special_url("filter:"));
assert!(is_special_url("filter: example"));
assert!(!is_special_url("filter"));
assert!(!is_special_url(" filter:"));
assert!(is_special_url("exec:"));
assert!(is_special_url("exec: example"));
assert!(!is_special_url("exec"));
assert!(!is_special_url(" exec:"));
}
#[test]
fn t_is_http_url() {
assert!(is_http_url("https://foo.bar"));
assert!(is_http_url("http://"));
assert!(is_http_url("https://"));
assert!(!is_http_url("htt://foo.bar"));
assert!(!is_http_url("http:/"));
assert!(!is_http_url("foo://bar"));
}
#[test]
fn t_is_query_url() {
assert!(is_query_url("query:"));
assert!(is_query_url("query: example"));
assert!(!is_query_url("query"));
assert!(!is_query_url(" query:"));
}
#[test]
fn t_is_filter_url() {
assert!(is_filter_url("filter:"));
assert!(is_filter_url("filter: example"));
assert!(!is_filter_url("filter"));
assert!(!is_filter_url(" filter:"));
}
#[test]
fn t_is_exec_url() {
assert!(is_exec_url("exec:"));
assert!(is_exec_url("exec: example"));
assert!(!is_exec_url("exec"));
assert!(!is_exec_url(" exec:"));
}
#[test]
fn t_trim() {
assert_eq!(trim(String::from(" xxx\r\n")), "xxx");
assert_eq!(trim(String::from("\n\n abc foobar\n")), "abc foobar");
assert_eq!(trim(String::from("")), "");
assert_eq!(trim(String::from(" \n")), "");
}
#[test]
fn t_trim_end() {
assert_eq!(trim_end(String::from("quux\n")), "quux");
}
#[test]
fn t_quote() {
assert_eq!(quote("".to_string()), "\"\"");
assert_eq!(quote("Hello World!".to_string()), "\"Hello World!\"");
assert_eq!(
quote("\"Hello World!\"".to_string()),
"\"\\\"Hello World!\\\"\""
);
}
#[test]
fn t_quote_if_necessary() {
assert_eq!(quote_if_necessary("".to_string()), "");
assert_eq!(
quote_if_necessary("Hello World!".to_string()),
"\"Hello World!\""
);
}
#[test]
fn t_is_valid_color() {
let invalid = [
"awesome",
"list",
"of",
"things",
"that",
"aren't",
"colors",
"color0123",
"color1024",
];
for color in &invalid {
assert!(!is_valid_color(color));
}
let valid = [
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default",
"color0", "color163",
];
for color in &valid {
assert!(is_valid_color(color));
}
}
#[test]
fn t_strwidth() {
assert_eq!(strwidth(""), 0);
assert_eq!(strwidth("xx"), 2);
assert_eq!(strwidth("\u{F91F}"), 2);
assert_eq!(strwidth("\u{0007}"), 0);
}
#[test]
fn t_strwidth_stfl() {
assert_eq!(strwidth_stfl(""), 0);
assert_eq!(strwidth_stfl("x<hi>x"), 2);
assert_eq!(strwidth_stfl("x<longtag>x</>"), 2);
assert_eq!(strwidth_stfl("x<>x"), 3);
assert_eq!(strwidth_stfl("x<>y<>z"), 5);
assert_eq!(strwidth_stfl("x<>hi>x"), 6);
assert_eq!(strwidth_stfl("\u{F91F}"), 2);
assert_eq!(strwidth_stfl("\u{0007}"), 0);
assert_eq!(strwidth_stfl("<a"), 0); // #415
}
#[test]
fn t_substr_with_width_given_string_empty() {
assert_eq!(substr_with_width("", 0), "");
assert_eq!(substr_with_width("", 1), "");
}
#[test]
fn t_substr_with_width_max_width_zero() {
assert_eq!(substr_with_width("world", 0), "");
assert_eq!(substr_with_width("", 0), "");
}
#[test]
fn t_substr_with_width_max_width_dont_split_codepoints() {
assert_eq!(substr_with_width("ABCDEF", 9), "ABCD");
assert_eq!(substr_with_width("ABC", 4), "AB");
assert_eq!(substr_with_width("a>bcd", 3), "a>b");
assert_eq!(substr_with_width("ABCDE", 10), "ABCDE");
assert_eq!(substr_with_width("abc", 2), "ab");
}
#[test]
fn t_substr_with_width_max_width_does_count_stfl_tag() {
assert_eq!(substr_with_width("ABC<b>DE</b>F", 9), "ABC<b>");
assert_eq!(substr_with_width("<foobar>ABC", 4), "<foo");
assert_eq!(substr_with_width("a<<xyz>>bcd", 3), "a<<");
assert_eq!(substr_with_width("ABC<b>DE", 10), "ABC<b>");
assert_eq!(substr_with_width("a</>b</>c</>", 2), "a<");
}
#[test]
fn t_substr_with_width_max_width_count_marks_as_regular_characters() {
assert_eq!(substr_with_width("<><><>", 2), "<>");
assert_eq!(substr_with_width("a<>b<>c", 3), "a<>");
}
#[test]
fn t_substr_with_width_max_width_non_printable() {
assert_eq!(substr_with_width("\x01\x02abc", 1), "\x01\x02a");
}
#[test]
fn t_substr_with_width_stfl_given_string_empty() {
assert_eq!(substr_with_width_stfl("", 0), "");
assert_eq!(substr_with_width_stfl("", 1), "");
}
#[test]
fn t_substr_with_width_stfl_max_width_zero() {
assert_eq!(substr_with_width_stfl("world", 0), "");
assert_eq!(substr_with_width_stfl("", 0), "");
}
#[test]
fn t_substr_with_width_stfl_max_width_dont_split_codepoints() {
assert_eq!(
substr_with_width_stfl("ABC<b>DE</b>F", 9),
"ABC<b>D"
);
assert_eq!(substr_with_width_stfl("<foobar>ABC", 4), "<foobar>AB");
assert_eq!(substr_with_width_stfl("a<<xyz>>bcd", 3), "a<<xyz>>b"); // tag: "<<xyz>"
assert_eq!(substr_with_width_stfl("ABC<b>DE", 10), "ABC<b>DE");
assert_eq!(substr_with_width_stfl("a</>b</>c</>", 2), "a</>b</>");
}
#[test]
fn t_substr_with_width_stfl_max_width_do_not_count_stfl_tag() {
assert_eq!(
substr_with_width_stfl("ABC<b>DE</b>F", 9),
"ABC<b>D"
);
assert_eq!(substr_with_width_stfl("<foobar>ABC", 4), "<foobar>AB");
assert_eq!(substr_with_width_stfl("a<<xyz>>bcd", 3), "a<<xyz>>b"); // tag: "<<xyz>"
assert_eq!(substr_with_width_stfl("ABC<b>DE", 10), "ABC<b>DE");
assert_eq!(substr_with_width_stfl("a</>b</>c</>", 2), "a</>b</>");
}
#[test]
fn t_substr_with_width_stfl_max_width_count_escaped_less_than_mark() {
assert_eq!(substr_with_width_stfl("<><><>", 2), "<><>");
assert_eq!(substr_with_width_stfl("a<>b<>c", 3), "a<>b");
}
#[test]
fn t_substr_with_width_stfl_max_width_non_printable() {
assert_eq!(substr_with_width_stfl("\x01\x02abc", 1), "\x01\x02a");
}
#[test]
fn t_is_valid_podcast_type() {
assert!(is_valid_podcast_type("audio/mpeg"));
assert!(is_valid_podcast_type("audio/mp3"));
assert!(is_valid_podcast_type("audio/x-mp3"));
assert!(is_valid_podcast_type("audio/ogg"));
assert!(is_valid_podcast_type("video/x-matroska"));
assert!(is_valid_podcast_type("video/webm"));
assert!(is_valid_podcast_type("application/ogg"));
assert!(!is_valid_podcast_type("image/jpeg"));
assert!(!is_valid_podcast_type("image/png"));
assert!(!is_valid_podcast_type("text/plain"));
assert!(!is_valid_podcast_type("application/zip"));
}
#[test]
fn t_podcast_mime_to_link_type() {
use crate::htmlrenderer::LinkType::*;
assert_eq!(podcast_mime_to_link_type("audio/mpeg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/mp3"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/x-mp3"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/ogg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("video/x-matroska"), Some(Video));
assert_eq!(podcast_mime_to_link_type("video/webm"), Some(Video));
assert_eq!(podcast_mime_to_link_type("application/ogg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("image/jpeg"), None);
assert_eq!(podcast_mime_to_link_type("image/png"), None);
assert_eq!(podcast_mime_to_link_type("text/plain"), None);
assert_eq!(podcast_mime_to_link_type("application/zip"), None);
}
#[test]
fn t_is_valid_attribte() {
let invalid = ["foo", "bar", "baz", "quux"];
for attr in &invalid {
assert!(!is_valid_attribute(attr));
}
let valid = [
"standout",
"underline",
"reverse",
"blink",
"dim",
"bold",
"protect",
"invis",
"default",
];
for attr in &valid {
assert!(is_valid_attribute(attr));
}
}
#[test]
fn t_get_auth_method() {
assert_eq!(get_auth_method("any"), curl_sys::CURLAUTH_ANY);
assert_eq!(get_auth_method("ntlm"), curl_sys::CURLAUTH_NTLM);
assert_eq!(get_auth_method("basic"), curl_sys::CURLAUTH_BASIC);
assert_eq!(get_auth_method("digest"), curl_sys::CURLAUTH_DIGEST);
assert_eq!(get_auth_method("digest_ie"), curl_sys::CURLAUTH_DIGEST_IE);
assert_eq!(
get_auth_method("gssnegotiate"),
curl_sys::CURLAUTH_GSSNEGOTIATE
);
assert_eq!(get_auth_method("anysafe"), curl_sys::CURLAUTH_ANYSAFE);
assert_eq!(get_auth_method(""), curl_sys::CURLAUTH_ANY);
assert_eq!(get_auth_method("unknown"), curl_sys::CURLAUTH_ANY);
}
#[test]
fn t_unescape_url() {
assert!(unescape_url(String::from("foo%20bar")).unwrap() == "foo bar");
assert!(
unescape_url(String::from(
"%21%23%24%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D"
))
.unwrap()
== "!#$&'()*+,/:;=?@[]"
);
}
#[test]
fn t_get_command_output() {
assert_eq!(
get_command_output("ls /dev/null"),
"/dev/null\n".to_string()
);
assert_eq!(
get_command_output("a-program-that-is-guaranteed-to-not-exists"),
"".to_string()
);
assert_eq!(get_command_output("echo c\" d e"), "".to_string());
}
#[test]
fn t_run_command_executes_given_command_with_given_argument() {
use std::{thread, time};
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let filepath = {
let mut filepath = tmp.path().to_owned();
filepath.push("sentry");
filepath
};
assert!(!filepath.exists());
run_command("touch", filepath.to_str().unwrap());
// Busy-wait for 100 tries of 10 milliseconds each, waiting for `touch` to
// create the file. Usually it happens quickly, and the loop exists on the
// first try; but sometimes on CI it takes longer for `touch` to finish, so
// we need a slightly longer wait.
for _ in 0..100 {
thread::sleep(time::Duration::from_millis(10));
if filepath.exists() {
break;
}
}
assert!(filepath.exists());
}
#[test]
fn t_run_command_doesnt_wait_for_the_command_to_finish() {
use std::time::{Duration, Instant};
let start = Instant::now();
let five: &str = "5";
run_command("sleep", five);
let runtime = start.elapsed();
assert!(runtime < Duration::from_secs(1));
}
#[test]
fn t_run_program() {
let input1 = "this is a multine-line\ntest string";
assert_eq!(run_program(&["cat"], input1), input1);
assert_eq!(
run_program(&["echo", "-n", "hello world"], ""),
"hello world"
);
}
#[test]
fn t_make_title() {
let mut input = String::from("http://example.com/Item");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("http://example.com/This-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is_the_title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.php");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.html");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.htm");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.aspx");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/items/misc/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/item/");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("http://example.com/item/////////////");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("blahscheme://example.com/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/story/aug/title-with-dashes?a=b");
assert_eq!(make_title(input), String::from("Title with dashes"));
input = String::from("http://example.com/title-with-dashes?a=b&x=y&utf8=✓");
assert_eq!(make_title(input), String::from("Title with dashes"));
input = String::from("https://example.com/It%27s%202017%21");
assert_eq!(make_title(input), String::from("It's 2017!"));
input = String::from("https://example.com/?format=rss");
assert_eq!(make_title(input), String::from(""));
assert_eq!(make_title(String::from("")), String::from(""));
}
#[test]
fn t_resolve_relative() {
assert_eq!(
resolve_relative(Path::new("/foo/bar"), Path::new("/baz")),
Path::new("/baz")
);
assert_eq!(
resolve_relative(Path::new("/config"), Path::new("/config/baz")),
Path::new("/config/baz")
);
assert_eq!(
resolve_relative(Path::new("/foo/bar"), Path::new("baz")),
Path::new("/foo/baz")
);
assert_eq!(
resolve_relative(Path::new("/config"), Path::new("baz")),
Path::new("/baz")
);
}
#[test]
fn t_remove_soft_hyphens_removes_all_00ad_unicode_chars_from_a_string() {
{
// Does nothing if input has no soft hyphens in it
let mut input1 = "hello world!".to_string();
remove_soft_hyphens(&mut input1);
assert_eq!(input1, "hello world!");
}
{
// Removes *all* soft hyphens
let mut data = "hy\u{00AD}phen\u{00AD}a\u{00AD}tion".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "hyphenation");
}
{
// Removes consecutive soft hyphens
let mut data = "don't know why any\u{00AD}\u{00AD}one would do that".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "don't know why anyone would do that");
}
{
// Removes soft hyphen at the beginning of the line
let mut data = "\u{00AD}tion".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "tion");
}
{
// Removes soft hyphen at the end of the line
let mut data = "over\u{00AD}".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "over");
}
}
#[test]
fn t_mkdir_parents() {
use std::fs;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;
let mode: u32 = 0o700;
let tmp_dir = TempDir::new().unwrap();
let path = tmp_dir.path().join("parent/dir");
assert_eq!(path.exists(), false);
let result = mkdir_parents(&path, mode);
assert!(result.is_ok());
assert_eq!(path.exists(), true);
let file_type_mask = 0o7777;
let metadata = fs::metadata(&path).unwrap();
assert_eq!(file_type_mask & metadata.permissions().mode(), mode);
// rerun on existing directories
let result = mkdir_parents(&path, mode);
assert!(result.is_ok());
}
#[test]
fn t_strnaturalcmp() {
use std::cmp::Ordering;
assert_eq!(strnaturalcmp("", ""), Ordering::Equal);
assert_eq!(strnaturalcmp("", "a"), Ordering::Less);
assert_eq!(strnaturalcmp("a", ""), Ordering::Greater);
assert_eq!(strnaturalcmp("a", "a"), Ordering::Equal);
assert_eq!(strnaturalcmp("", "9"), Ordering::Less);
assert_eq!(strnaturalcmp("9", ""), Ordering::Greater);
assert_eq!(strnaturalcmp("1", "1"), Ordering::Equal);
assert_eq!(strnaturalcmp("1", "2"), Ordering::Less);
assert_eq!(strnaturalcmp("3", "2"), Ordering::Greater);
assert_eq!(strnaturalcmp("a1", "a1"), Ordering::Equal);
assert_eq!(strnaturalcmp("a1", "a2"), Ordering::Less);
assert_eq!(strnaturalcmp("a2", "a1"), Ordering::Greater);
assert_eq!(strnaturalcmp("a1a2", "a1a3"), Ordering::Less);
assert_eq!(strnaturalcmp("a1a2", "a1a0"), Ordering::Greater);
assert_eq!(strnaturalcmp("134", "122"), Ordering::Greater);
assert_eq!(strnaturalcmp("12a3", "12a3"), Ordering::Equal);
assert_eq!(strnaturalcmp("12a1", "12a0"), Ordering::Greater);
assert_eq!(strnaturalcmp("12a1", "12a2"), Ordering::Less);
assert_eq!(strnaturalcmp("a", "aa"), Ordering::Less);
assert_eq!(strnaturalcmp("aaa", "aa"), Ordering::Greater);
assert_eq!(strnaturalcmp("Alpha 2", "Alpha 2"), Ordering::Equal);
assert_eq!(strnaturalcmp("Alpha 2", "Alpha 2A"), Ordering::Less);
assert_eq!(strnaturalcmp("Alpha 2 B", "Alpha 2"), Ordering::Greater);
assert_eq!(strnaturalcmp("aa10", "aa2"), Ordering::Greater);
}
#[test]
fn t_strip_comments() {
// no comments in line
assert_eq!(strip_comments(""), "");
assert_eq!(strip_comments("\t\n"), "\t\n");
assert_eq!(strip_comments("some directive "), "some directive ");
// fully commented line
assert_eq!(strip_comments("#"), "");
assert_eq!(strip_comments("# #"), "");
assert_eq!(strip_comments("# comment"), "");
// partially commented line
assert_eq!(strip_comments("directive # comment"), "directive ");
assert_eq!(
strip_comments("directive # comment # another"),
"directive "
);
assert_eq!(strip_comments("directive#comment"), "directive");
// ignores # characters inside double quotes (#652)
let expected = r#"highlight article "[-=+#_*~]{3,}.*" green default"#;
let input = expected.to_owned() + "# this is a comment";
assert_eq!(strip_comments(&input), expected);
let expected =
r#"highlight all "(https?|ftp)://[\-\.,/%~_:?&=\#a-zA-Z0-9]+" blue default bold"#;
let input = expected.to_owned() + "#heresacomment";
assert_eq!(strip_comments(&input), expected);
// Escaped double quote inside double quotes is not treated as closing quote
let expected = r#"test "here \"goes # nothing\" etc" hehe"#;
let input = expected.to_owned() + "# and here is a comment";
assert_eq!(strip_comments(&input), expected);
// Ignores # characters inside backticks
let expected = r#"one `two # three` four"#;
let input = expected.to_owned() + "# and a comment, of course";
assert_eq!(strip_comments(&input), expected);
// Escaped backtick inside backticks is not treated as closing
let expected = r#"some `other \` tricky # test` hehe"#;
let input = expected.to_owned() + "#here goescomment";
assert_eq!(strip_comments(&input), expected);
// Ignores escaped # characters (\\#)
let expected = r#"one two \# three four"#;
let input = expected.to_owned() + "# and a comment";
assert_eq!(strip_comments(&input), expected);
}
#[test]
fn t_extract_filter() {
let expected = ("~/bin/script.sh", "https://newsboat.org");
let input = "filter:~/bin/script.sh:https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("", "https://newsboat.org");
let input = "filter::https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("https", "//newsboat.org");
let input = "filter:https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("foo", "");
let input = "filter:foo:";
assert_eq!(extract_filter(input), expected);
let expected = ("", "");
let input = "filter:";
assert_eq!(extract_filter(input), expected);
}
}
utils.rs: make run_command double fork
Before this commit, newsboat would spawn process that would turn into
zombies and linger around until newsboat was closed.
use crate::htmlrenderer;
use crate::logger::{self, Level};
use libc::{c_ulong, close, execvp, exit, fork, waitpid};
use percent_encoding::*;
use std::ffi::CString;
use std::fs::DirBuilder;
use std::io::{self, Write};
use std::os::unix::fs::DirBuilderExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::ptr;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use url::Url;
pub fn replace_all(input: String, from: &str, to: &str) -> String {
input.replace(from, to)
}
pub fn consolidate_whitespace(input: String) -> String {
let found = input.find(|c: char| !c.is_whitespace());
let mut result = String::new();
if let Some(found) = found {
let (leading, rest) = input.split_at(found);
let lastchar = input.chars().rev().next().unwrap();
result.push_str(leading);
let iter = rest.split_whitespace();
for elem in iter {
result.push_str(elem);
result.push(' ');
}
result.pop();
if lastchar.is_whitespace() {
result.push(' ');
}
}
result
}
pub fn to_u(rs_str: String, default_value: u32) -> u32 {
let mut result = rs_str.parse::<u32>();
if result.is_err() {
result = Ok(default_value);
}
result.unwrap()
}
/// Combine a base URL and a link to a new absolute URL.
/// If the base URL is malformed or joining with the link fails, link will be returned.
/// # Examples
/// ```
/// use libnewsboat::utils::absolute_url;
/// assert_eq!(absolute_url("http://foobar/hello/crook/", "bar.html"),
/// "http://foobar/hello/crook/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "/bar.html"),
/// "https://foobar/bar.html".to_owned());
/// assert_eq!(absolute_url("https://foobar/foo/", "http://quux/bar.html"),
/// "http://quux/bar.html".to_owned());
/// assert_eq!(absolute_url("http://foobar", "bla.html"),
/// "http://foobar/bla.html".to_owned());
/// assert_eq!(absolute_url("http://test:test@foobar:33", "bla2.html"),
/// "http://test:test@foobar:33/bla2.html".to_owned());
/// assert_eq!(absolute_url("foo", "bar"), "bar".to_owned());
/// ```
pub fn absolute_url(base_url: &str, link: &str) -> String {
Url::parse(base_url)
.and_then(|url| url.join(link))
.as_ref()
.map(Url::as_str)
.unwrap_or(link)
.to_owned()
}
/// Path to the home directory, if known. Doesn't work on Windows.
#[cfg(not(target_os = "windows"))]
pub fn home_dir() -> Option<PathBuf> {
// This function got deprecated because it examines HOME environment variable even on Windows,
// which is wrong. But Newsboat doesn't support Windows, so we're fine using that.
//
// Cf. https://github.com/rust-lang/rust/issues/28940
#[allow(deprecated)]
std::env::home_dir()
}
/// Replaces tilde (`~`) at the beginning of the path with the path to user's home directory.
pub fn resolve_tilde(path: PathBuf) -> PathBuf {
if let (Some(home), Ok(suffix)) = (home_dir(), path.strip_prefix("~")) {
return home.join(suffix);
}
// Either the `path` doesn't start with tilde, or we couldn't figure out the path to the
// home directory -- either way, it's no big deal. Let's return the original string.
path
}
pub fn resolve_relative(reference: &Path, path: &Path) -> PathBuf {
if path.is_relative() {
// Will only ever panic if reference is `/`, which shouldn't be the case as reference is
// always a file path
return reference.parent().unwrap().join(path);
}
path.to_path_buf()
}
pub fn is_special_url(url: &str) -> bool {
is_query_url(url) || is_filter_url(url) || is_exec_url(url)
}
/// Check if the given URL is a http(s) URL
/// # Example
/// ```
/// use libnewsboat::utils::is_http_url;
/// assert!(is_http_url("http://example.com"));
/// ```
pub fn is_http_url(url: &str) -> bool {
url.starts_with("https://") || url.starts_with("http://")
}
pub fn is_query_url(url: &str) -> bool {
url.starts_with("query:")
}
pub fn is_filter_url(url: &str) -> bool {
url.starts_with("filter:")
}
pub fn is_exec_url(url: &str) -> bool {
url.starts_with("exec:")
}
/// Censor URLs by replacing username and password with '*'
/// ```
/// use libnewsboat::utils::censor_url;
/// assert_eq!(&censor_url(""), "");
/// assert_eq!(&censor_url("foobar"), "foobar");
/// assert_eq!(&censor_url("foobar://xyz/"), "foobar://xyz/");
/// assert_eq!(&censor_url("http://newsbeuter.org/"),
/// "http://newsbeuter.org/");
/// assert_eq!(&censor_url("https://newsbeuter.org/"),
/// "https://newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://@newsbeuter.org/"),
/// "http://newsbeuter.org/");
/// assert_eq!(&censor_url("https://@newsbeuter.org/"),
/// "https://newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://foo:bar@newsbeuter.org/"),
/// "http://*:*@newsbeuter.org/");
/// assert_eq!(&censor_url("https://foo:bar@newsbeuter.org/"),
/// "https://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://aschas@newsbeuter.org/"),
/// "http://*:*@newsbeuter.org/");
/// assert_eq!(&censor_url("https://aschas@newsbeuter.org/"),
/// "https://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("xxx://aschas@newsbeuter.org/"),
/// "xxx://*:*@newsbeuter.org/");
///
/// assert_eq!(&censor_url("http://foobar"), "http://foobar/");
/// assert_eq!(&censor_url("https://foobar"), "https://foobar/");
///
/// assert_eq!(&censor_url("http://aschas@host"), "http://*:*@host/");
/// assert_eq!(&censor_url("https://aschas@host"), "https://*:*@host/");
///
/// assert_eq!(&censor_url("query:name:age between 1:10"),
/// "query:name:age between 1:10");
/// ```
pub fn censor_url(url: &str) -> String {
if !url.is_empty() && !is_special_url(url) {
Url::parse(url)
.map(|mut url| {
if url.username() != "" || url.password().is_some() {
// can not panic. If either username or password is present we can change both.
url.set_username("*").unwrap();
url.set_password(Some("*")).unwrap();
}
url
})
.as_ref()
.map(Url::as_str)
.unwrap_or(url)
.to_owned()
} else {
url.into()
}
}
/// Quote a string for use with stfl by replacing all occurences of "<" with "<>"
/// ```
/// use libnewsboat::utils::quote_for_stfl;
/// assert_eq!("e_for_stfl("<"), "<>");
/// assert_eq!("e_for_stfl("<<><><><"), "<><>><>><>><>");
/// assert_eq!("e_for_stfl("test"), "test");
/// ```
pub fn quote_for_stfl(string: &str) -> String {
string.replace("<", "<>")
}
/// Get basename from a URL if available else return an empty string
/// ```
/// use libnewsboat::utils::get_basename;
/// assert_eq!(get_basename("https://example.com/"), "");
/// assert_eq!(get_basename("https://example.org/?param=value#fragment"), "");
/// assert_eq!(get_basename("https://example.org/path/to/?param=value#fragment"), "");
/// assert_eq!(get_basename("https://example.org/file.mp3"), "file.mp3");
/// assert_eq!(get_basename("https://example.org/path/to/file.mp3?param=value#fragment"), "file.mp3");
/// ```
pub fn get_basename(input: &str) -> String {
match Url::parse(input) {
Ok(url) => match url.path_segments() {
Some(segments) => segments.last().unwrap().to_string(),
None => String::from(""),
},
Err(_) => String::from(""),
}
}
pub fn get_default_browser() -> String {
use std::env;
env::var("BROWSER").unwrap_or_else(|_| "lynx".to_string())
}
pub fn trim(rs_str: String) -> String {
rs_str.trim().to_string()
}
pub fn trim_end(rs_str: String) -> String {
let x: &[_] = &['\n', '\r'];
rs_str.trim_end_matches(x).to_string()
}
pub fn quote(input: String) -> String {
let mut input = input.replace("\"", "\\\"");
input.insert(0, '"');
input.push('"');
input
}
pub fn quote_if_necessary(input: String) -> String {
match input.find(' ') {
Some(_) => quote(input),
None => input,
}
}
pub fn get_random_value(max: u32) -> u32 {
rand::random::<u32>() % max
}
pub fn is_valid_color(color: &str) -> bool {
const COLORS: [&str; 9] = [
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default",
];
if COLORS.contains(&color) {
true
} else if color.starts_with("color0") {
color == "color0"
} else if color.starts_with("color") {
let num_part = &color[5..];
num_part.parse::<u8>().is_ok()
} else {
false
}
}
pub fn is_valid_attribute(attribute: &str) -> bool {
const VALID_ATTRIBUTES: [&str; 9] = [
"standout",
"underline",
"reverse",
"blink",
"dim",
"bold",
"protect",
"invis",
"default",
];
VALID_ATTRIBUTES.contains(&attribute)
}
pub fn strwidth(rs_str: &str) -> usize {
UnicodeWidthStr::width(rs_str)
}
/// Returns the width of `rs_str` when displayed on screen.
///
/// STFL tags (e.g. `<b>`, `<foobar>`, `</>`) are counted as having 0 width.
/// Escaped less-than sign (`<` escaped as `<>`) is counted as having a width of 1 character.
/// ```
/// use libnewsboat::utils::strwidth_stfl;
/// assert_eq!(strwidth_stfl("a"), 1);
/// assert_eq!(strwidth_stfl("abc<tag>def"), 6);
/// assert_eq!(strwidth_stfl("less-than: <>"), 12);
/// assert_eq!(strwidth_stfl("ABCDEF"), 12);
///```
pub fn strwidth_stfl(rs_str: &str) -> usize {
let mut s = &rs_str[..];
let mut width = 0;
loop {
if let Some(pos) = s.find('<') {
width += strwidth(&s[..pos]);
s = &s[pos..];
if let Some(endpos) = s.find('>') {
if endpos == 1 {
// Found "<>" which stfl uses to encode a literal '<'
width += strwidth("<");
}
s = &s[endpos + 1..];
} else {
// '<' without closing '>' so ignore rest of string
break;
}
} else {
width += strwidth(s);
break;
}
}
width
}
/// Returns a longest substring fits to the given width.
/// Returns an empty string if `str` is an empty string or `max_width` is zero.
///
/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()
/// returns None, the character width is treated as 0.
/// ```
/// use libnewsboat::utils::substr_with_width;
/// assert_eq!(substr_with_width("a", 1), "a");
/// assert_eq!(substr_with_width("a", 2), "a");
/// assert_eq!(substr_with_width("ab", 1), "a");
/// assert_eq!(substr_with_width("abc", 1), "a");
/// assert_eq!(substr_with_width("A\u{3042}B\u{3044}C\u{3046}", 5), "A\u{3042}B")
///```
pub fn substr_with_width(string: &str, max_width: usize) -> String {
let mut result = String::new();
let mut width = 0;
for c in string.chars() {
// Control chars count as width 0
let w = UnicodeWidthChar::width(c).unwrap_or(0);
if width + w > max_width {
break;
}
width += w;
result.push(c);
}
result
}
/// Returns a longest substring fits to the given width.
/// Returns an empty string if `str` is an empty string or `max_width` is zero.
///
/// Each chararacter width is calculated with UnicodeWidthChar::width. If UnicodeWidthChar::width()
/// returns None, the character width is treated as 0. A STFL tag (e.g. `<b>`, `<foobar>`, `</>`)
/// width is treated as 0, but escaped less-than (`<>`) width is treated as 1.
/// ```
/// use libnewsboat::utils::substr_with_width_stfl;
/// assert_eq!(substr_with_width_stfl("a", 1), "a");
/// assert_eq!(substr_with_width_stfl("a", 2), "a");
/// assert_eq!(substr_with_width_stfl("ab", 1), "a");
/// assert_eq!(substr_with_width_stfl("abc", 1), "a");
/// assert_eq!(substr_with_width_stfl("A\u{3042}B\u{3044}C\u{3046}", 5), "A\u{3042}B")
///```
pub fn substr_with_width_stfl(string: &str, max_width: usize) -> String {
let mut result = String::new();
let mut in_bracket = false;
let mut tagbuf = Vec::<char>::new();
let mut width = 0;
for c in string.chars() {
if in_bracket {
tagbuf.push(c);
if c == '>' {
in_bracket = false;
if tagbuf == ['<', '>'] {
if width + 1 > max_width {
break;
}
result += "<>"; // escaped less-than
tagbuf.clear();
width += 1;
} else {
result += &tagbuf.iter().collect::<String>();
tagbuf.clear();
}
}
} else if c == '<' {
in_bracket = true;
tagbuf.push(c);
} else {
// Control chars count as width 0
let w = UnicodeWidthChar::width(c).unwrap_or(0);
if width + w > max_width {
break;
}
width += w;
result.push(c);
}
}
result
}
/// Remove all soft-hyphens as they can behave unpredictably (see
/// https://github.com/akrennmair/newsbeuter/issues/259#issuecomment-259609490) and inadvertently
/// render as hyphens
pub fn remove_soft_hyphens(text: &mut String) {
text.retain(|c| c != '\u{00AD}')
}
/// An array of "MIME matchers" and their associated LinkTypes
///
/// This is used for two tasks:
///
/// 1. checking if a MIME type is a podcast type (`utils::is_valid_podcast_type`). That involves
/// running all matching functions on given input and checking if any of them returned `true`;
///
/// 2. figuring out the `LinkType` for a particular enclosure, given its MIME type
/// (`utils::podcast_mime_to_link_type`).
type MimeMatcher = (fn(&str) -> bool, htmlrenderer::LinkType);
const PODCAST_MIME_TO_LINKTYPE: [MimeMatcher; 2] = [
(
|mime| {
// RFC 5334, section 10.1 says "historically, some implementations expect .ogg files to be
// solely Vorbis-encoded audio", so let's assume it's audio, not video.
// https://tools.ietf.org/html/rfc5334#section-10.1
mime.starts_with("audio/") || mime == "application/ogg"
},
htmlrenderer::LinkType::Audio,
),
(
|mime| mime.starts_with("video/"),
htmlrenderer::LinkType::Video,
),
];
/// Returns `true` if given MIME type is considered to be a podcast by Newsboat.
pub fn is_valid_podcast_type(mimetype: &str) -> bool {
PODCAST_MIME_TO_LINKTYPE
.iter()
.any(|(matcher, _)| matcher(mimetype))
}
/// Converts podcast's MIME type into an HtmlRenderer's "link type"
///
/// Returns None if given MIME type is not a podcast type. See `is_valid_podcast_type()`.
pub fn podcast_mime_to_link_type(mime_type: &str) -> Option<htmlrenderer::LinkType> {
PODCAST_MIME_TO_LINKTYPE
.iter()
.find_map(|(matcher, link_type)| {
if matcher(mime_type) {
Some(*link_type)
} else {
None
}
})
}
pub fn get_auth_method(method: &str) -> c_ulong {
match method {
"basic" => curl_sys::CURLAUTH_BASIC,
"digest" => curl_sys::CURLAUTH_DIGEST,
"digest_ie" => curl_sys::CURLAUTH_DIGEST_IE,
"gssnegotiate" => curl_sys::CURLAUTH_GSSNEGOTIATE,
"ntlm" => curl_sys::CURLAUTH_NTLM,
"anysafe" => curl_sys::CURLAUTH_ANYSAFE,
"any" | "" => curl_sys::CURLAUTH_ANY,
_ => {
log!(
Level::UserError,
"utils::get_auth_method: you configured an invalid proxy authentication method: {}",
method
);
curl_sys::CURLAUTH_ANY
}
}
}
pub fn unescape_url(rs_str: String) -> Option<String> {
let decoded = percent_decode(rs_str.as_bytes()).decode_utf8();
decoded.ok().map(|s| s.replace("\0", ""))
}
/// Runs given command in a shell, and returns the output (from stdout; stderr is printed to the
/// screen).
pub fn get_command_output(cmd: &str) -> String {
let cmd = Command::new("sh")
.arg("-c")
.arg(cmd)
// Inherit stdin so that the program can ask something of the user (see
// https://github.com/newsboat/newsboat/issues/455 for an example).
.stdin(Stdio::inherit())
.output();
// from_utf8_lossy will convert any bad bytes to U+FFFD
cmd.map(|cmd| String::from_utf8_lossy(&cmd.stdout).into_owned())
.unwrap_or_else(|_| String::from(""))
}
// This function assumes that the user is not interested in the command's output (not even errors
// on stderr!), so it will close the spawned command's fds.
// This used to be a simple std::process::Command::Spawn(), but this caused child processes to not
// be reaped, hence the addition of double forking to this function.
// Spawn() was replaced with a direct call to fork+execvp because it interacted badly with the
// fork() call.
pub fn run_command(cmd: &str, param: &str) {
unsafe {
let forked_pid = fork();
match forked_pid {
-1 => {
// Parent process, fork failed.
log!(
Level::Debug,
"utils::run_command: failed to fork. Aborting run_command."
);
return;
}
0 => {
// Child process, continue and spawn the command.
}
_ => {
// Parent process, fork succeeded: reap child and return.
let mut status = 0;
if waitpid(forked_pid, &mut status, 0) == -1 {
log!(Level::Debug, "utils::run_command: waitpid failed.");
}
return;
}
}
if fork() == 0 {
// Grand-child
match (CString::new(cmd), CString::new(param)) {
(Ok(c_cmd), Ok(c_param)) => {
// close our fds to avoid clobbering the screen and exec the command
close(0);
close(1);
close(2);
let c_arg = [c_cmd.as_ptr(), c_param.as_ptr(), ptr::null()];
execvp(c_cmd.as_ptr(), c_arg.as_ptr());
}
_ => log!(
Level::UserError,
"Conversion of \"{}\" and/or \"{}\" to CString failed.",
cmd,
param
),
};
}
// Child process or grand child in case of failure to execvp, in both cases nothing to do.
exit(0);
}
}
pub fn run_program(cmd_with_args: &[&str], input: &str) -> String {
if cmd_with_args.is_empty() {
return String::new();
}
Command::new(cmd_with_args[0])
.args(&cmd_with_args[1..])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|error| {
log!(
Level::Debug,
"utils::run_program: spawning a child for \"{:?}\" \
with input \"{}\" failed: {}",
cmd_with_args,
input,
error
);
})
.and_then(|mut child| {
if let Some(stdin) = child.stdin.as_mut() {
if let Err(error) = stdin.write_all(input.as_bytes()) {
log!(
Level::Debug,
"utils::run_program: failed to write to child's stdin: {}",
error
);
}
}
child
.wait_with_output()
.map_err(|error| {
log!(
Level::Debug,
"utils::run_program: failed to read child's stdout: {}",
error
);
})
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
})
.unwrap_or_else(|_| String::new())
}
pub fn make_title(rs_str: String) -> String {
/* Sometimes it is possible to construct the title from the URL
* This attempts to do just that. eg:
* http://domain.com/story/yy/mm/dd/title-with-dashes?a=b
*/
// Strip out trailing slashes
let mut result = rs_str.trim_end_matches('/');
// get to the final part of the URI's path and
// extract just the juicy part 'title-with-dashes?a=b'
let v: Vec<&str> = result.rsplitn(2, '/').collect();
result = v[0];
// find where query part of URI starts
// throw away the query part 'title-with-dashes'
let v: Vec<&str> = result.splitn(2, '?').collect();
result = v[0];
// Throw away common webpage suffixes: .html, .php, .aspx, .htm
result = result
.trim_end_matches(".html")
.trim_end_matches(".php")
.trim_end_matches(".aspx")
.trim_end_matches(".htm");
// 'title with dashes'
let result = result.replace('-', " ").replace('_', " ");
//'Title with dashes'
//let result = "";
let mut c = result.chars();
let result = match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
};
// Un-escape any percent-encoding, e.g. "It%27s%202017%21" -> "It's
// 2017!"
match unescape_url(result) {
None => String::new(),
Some(f) => f,
}
}
/// Run the given command interactively with inherited stdin and stdout/stderr. Return the lowest
/// 8 bits of its exit code, or `None` if the command failed to start.
/// ```
/// use libnewsboat::utils::run_interactively;
///
/// let result = run_interactively("echo true", "test");
/// assert_eq!(result, Some(0));
///
/// let result = run_interactively("exit 1", "test");
/// assert_eq!(result, Some(1));
///
/// // Unfortunately, there is no easy way to provoke this function to return `None`, nor to test
/// // that it returns just the lowest 8 bits.
/// ```
pub fn run_interactively(command: &str, caller: &str) -> Option<u8> {
log!(Level::Debug, &format!("{}: running `{}'", caller, command));
Command::new("sh")
.arg("-c")
.arg(command)
.status()
.map_err(|err| {
log!(
Level::Warn,
&format!("{}: Couldn't create child process: {}", caller, err)
)
})
.ok()
.and_then(|exit_status| exit_status.code())
.map(|exit_code| exit_code as u8)
}
/// Get the current working directory.
pub fn getcwd() -> Result<PathBuf, io::Error> {
use std::env;
env::current_dir()
}
pub fn strnaturalcmp(a: &str, b: &str) -> std::cmp::Ordering {
natord::compare(a, b)
}
/// Calculate the number of padding tabs when formatting columns
///
/// The number of tabs will be adjusted by the width of the given string. Usually, a column will
/// consist of 4 tabs, 8 characters each. Each column will consist of at least one tab.
///
/// ```
/// use libnewsboat::utils::gentabs;
///
/// fn genstring(len: usize) -> String {
/// return std::iter::repeat("a").take(len).collect::<String>();
/// }
///
/// assert_eq!(gentabs(""), 4);
/// assert_eq!(gentabs("a"), 4);
/// assert_eq!(gentabs("aa"), 4);
/// assert_eq!(gentabs("aaa"), 4);
/// assert_eq!(gentabs("aaaa"), 4);
/// assert_eq!(gentabs("aaaaa"), 4);
/// assert_eq!(gentabs("aaaaaa"), 4);
/// assert_eq!(gentabs("aaaaaaa"), 4);
/// assert_eq!(gentabs("aaaaaaaa"), 3);
/// assert_eq!(gentabs(&genstring(8)), 3);
/// assert_eq!(gentabs(&genstring(9)), 3);
/// assert_eq!(gentabs(&genstring(15)), 3);
/// assert_eq!(gentabs(&genstring(16)), 2);
/// assert_eq!(gentabs(&genstring(20)), 2);
/// assert_eq!(gentabs(&genstring(24)), 1);
/// assert_eq!(gentabs(&genstring(32)), 1);
/// assert_eq!(gentabs(&genstring(100)), 1);
/// ```
pub fn gentabs(string: &str) -> usize {
let tabcount = strwidth(string) / 8;
if tabcount >= 4 {
1
} else {
4 - tabcount
}
}
/// Recursively create directories if missing and set permissions accordingly.
pub fn mkdir_parents<R: AsRef<Path>>(p: &R, mode: u32) -> io::Result<()> {
DirBuilder::new()
.mode(mode)
.recursive(true) // directories created with same security and permissions
.create(p.as_ref())
}
/// The tag and Git commit ID the program was built from, or a pre-defined value from config.h if
/// there is no Git directory.
pub fn program_version() -> String {
// NEWSBOAT_VERSION is set by this crate's build script, "build.rs"
env!("NEWSBOAT_VERSION").to_string()
}
/// Newsboat's major version number.
pub fn newsboat_major_version() -> u32 {
// This will panic if the version couldn't be parsed, which is virtually impossible as Cargo
// won't even start compilation if it couldn't parse the version.
env!("CARGO_PKG_VERSION_MAJOR").parse::<u32>().unwrap()
}
/// Returns the part of the string before first # character (or the whole input string if there are
/// no # character in it). Pound characters inside double quotes and backticks are ignored.
pub fn strip_comments(line: &str) -> &str {
let mut prev_was_backslash = false;
let mut inside_quotes = false;
let mut inside_backticks = false;
let mut first_pound_chr_idx = line.len();
for (idx, chr) in line.char_indices() {
match chr {
'\\' => {
prev_was_backslash = true;
continue;
}
'"' => {
// If the quote is escaped or we're inside backticks, do nothing
if !prev_was_backslash && !inside_backticks {
inside_quotes = !inside_quotes;
}
}
'`' => {
// If the backtick is escaped, do nothing
if !prev_was_backslash {
inside_backticks = !inside_backticks;
}
}
'#' => {
if !prev_was_backslash && !inside_quotes && !inside_backticks {
first_pound_chr_idx = idx;
break;
}
}
_ => {}
}
// We call `continue` when we run into a backslash; here, we handle all the other
// characters, which clearly *aren't* a backslash
prev_was_backslash = false;
}
&line[0..first_pound_chr_idx]
}
/// Extract filter and url from line separated by ':'.
pub fn extract_filter(line: &str) -> (&str, &str) {
debug_assert!(line.starts_with("filter:"));
// line must start with "filter:"
let line = line.get("filter:".len()..).unwrap();
let (filter, url) = line.split_at(line.find(':').unwrap_or(0));
let url = url.get(1..).unwrap_or("");
log!(
Level::Debug,
"utils::extract_filter: {} -> filter: {} url: {}",
line,
filter,
url
);
(filter, url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_replace_all() {
assert_eq!(
replace_all(String::from("aaa"), "a", "b"),
String::from("bbb")
);
assert_eq!(
replace_all(String::from("aaa"), "aa", "ba"),
String::from("baa")
);
assert_eq!(
replace_all(String::from("aaaaaa"), "aa", "ba"),
String::from("bababa")
);
assert_eq!(replace_all(String::new(), "a", "b"), String::new());
let input = String::from("aaaa");
assert_eq!(replace_all(input.clone(), "b", "c"), input);
assert_eq!(
replace_all(String::from("this is a normal test text"), " t", " T"),
String::from("this is a normal Test Text")
);
assert_eq!(
replace_all(String::from("o o o"), "o", "<o>"),
String::from("<o> <o> <o>")
);
}
#[test]
fn t_consolidate_whitespace() {
assert_eq!(
consolidate_whitespace(String::from("LoremIpsum")),
String::from("LoremIpsum")
);
assert_eq!(
consolidate_whitespace(String::from("Lorem Ipsum")),
String::from("Lorem Ipsum")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum ")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum")
);
assert_eq!(consolidate_whitespace(String::new()), String::new());
assert_eq!(
consolidate_whitespace(String::from(" Lorem \t\tIpsum \t ")),
String::from(" Lorem Ipsum ")
);
assert_eq!(
consolidate_whitespace(String::from(" Lorem \r\n\r\n\tIpsum")),
String::from(" Lorem Ipsum")
);
}
#[test]
fn t_to_u() {
assert_eq!(to_u(String::from("0"), 10), 0);
assert_eq!(to_u(String::from("23"), 1), 23);
assert_eq!(to_u(String::from(""), 0), 0);
assert_eq!(to_u(String::from("zero"), 1), 1);
}
#[test]
fn t_is_special_url() {
assert!(is_special_url("query:"));
assert!(is_special_url("query: example"));
assert!(!is_special_url("query"));
assert!(!is_special_url(" query:"));
assert!(is_special_url("filter:"));
assert!(is_special_url("filter: example"));
assert!(!is_special_url("filter"));
assert!(!is_special_url(" filter:"));
assert!(is_special_url("exec:"));
assert!(is_special_url("exec: example"));
assert!(!is_special_url("exec"));
assert!(!is_special_url(" exec:"));
}
#[test]
fn t_is_http_url() {
assert!(is_http_url("https://foo.bar"));
assert!(is_http_url("http://"));
assert!(is_http_url("https://"));
assert!(!is_http_url("htt://foo.bar"));
assert!(!is_http_url("http:/"));
assert!(!is_http_url("foo://bar"));
}
#[test]
fn t_is_query_url() {
assert!(is_query_url("query:"));
assert!(is_query_url("query: example"));
assert!(!is_query_url("query"));
assert!(!is_query_url(" query:"));
}
#[test]
fn t_is_filter_url() {
assert!(is_filter_url("filter:"));
assert!(is_filter_url("filter: example"));
assert!(!is_filter_url("filter"));
assert!(!is_filter_url(" filter:"));
}
#[test]
fn t_is_exec_url() {
assert!(is_exec_url("exec:"));
assert!(is_exec_url("exec: example"));
assert!(!is_exec_url("exec"));
assert!(!is_exec_url(" exec:"));
}
#[test]
fn t_trim() {
assert_eq!(trim(String::from(" xxx\r\n")), "xxx");
assert_eq!(trim(String::from("\n\n abc foobar\n")), "abc foobar");
assert_eq!(trim(String::from("")), "");
assert_eq!(trim(String::from(" \n")), "");
}
#[test]
fn t_trim_end() {
assert_eq!(trim_end(String::from("quux\n")), "quux");
}
#[test]
fn t_quote() {
assert_eq!(quote("".to_string()), "\"\"");
assert_eq!(quote("Hello World!".to_string()), "\"Hello World!\"");
assert_eq!(
quote("\"Hello World!\"".to_string()),
"\"\\\"Hello World!\\\"\""
);
}
#[test]
fn t_quote_if_necessary() {
assert_eq!(quote_if_necessary("".to_string()), "");
assert_eq!(
quote_if_necessary("Hello World!".to_string()),
"\"Hello World!\""
);
}
#[test]
fn t_is_valid_color() {
let invalid = [
"awesome",
"list",
"of",
"things",
"that",
"aren't",
"colors",
"color0123",
"color1024",
];
for color in &invalid {
assert!(!is_valid_color(color));
}
let valid = [
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default",
"color0", "color163",
];
for color in &valid {
assert!(is_valid_color(color));
}
}
#[test]
fn t_strwidth() {
assert_eq!(strwidth(""), 0);
assert_eq!(strwidth("xx"), 2);
assert_eq!(strwidth("\u{F91F}"), 2);
assert_eq!(strwidth("\u{0007}"), 0);
}
#[test]
fn t_strwidth_stfl() {
assert_eq!(strwidth_stfl(""), 0);
assert_eq!(strwidth_stfl("x<hi>x"), 2);
assert_eq!(strwidth_stfl("x<longtag>x</>"), 2);
assert_eq!(strwidth_stfl("x<>x"), 3);
assert_eq!(strwidth_stfl("x<>y<>z"), 5);
assert_eq!(strwidth_stfl("x<>hi>x"), 6);
assert_eq!(strwidth_stfl("\u{F91F}"), 2);
assert_eq!(strwidth_stfl("\u{0007}"), 0);
assert_eq!(strwidth_stfl("<a"), 0); // #415
}
#[test]
fn t_substr_with_width_given_string_empty() {
assert_eq!(substr_with_width("", 0), "");
assert_eq!(substr_with_width("", 1), "");
}
#[test]
fn t_substr_with_width_max_width_zero() {
assert_eq!(substr_with_width("world", 0), "");
assert_eq!(substr_with_width("", 0), "");
}
#[test]
fn t_substr_with_width_max_width_dont_split_codepoints() {
assert_eq!(substr_with_width("ABCDEF", 9), "ABCD");
assert_eq!(substr_with_width("ABC", 4), "AB");
assert_eq!(substr_with_width("a>bcd", 3), "a>b");
assert_eq!(substr_with_width("ABCDE", 10), "ABCDE");
assert_eq!(substr_with_width("abc", 2), "ab");
}
#[test]
fn t_substr_with_width_max_width_does_count_stfl_tag() {
assert_eq!(substr_with_width("ABC<b>DE</b>F", 9), "ABC<b>");
assert_eq!(substr_with_width("<foobar>ABC", 4), "<foo");
assert_eq!(substr_with_width("a<<xyz>>bcd", 3), "a<<");
assert_eq!(substr_with_width("ABC<b>DE", 10), "ABC<b>");
assert_eq!(substr_with_width("a</>b</>c</>", 2), "a<");
}
#[test]
fn t_substr_with_width_max_width_count_marks_as_regular_characters() {
assert_eq!(substr_with_width("<><><>", 2), "<>");
assert_eq!(substr_with_width("a<>b<>c", 3), "a<>");
}
#[test]
fn t_substr_with_width_max_width_non_printable() {
assert_eq!(substr_with_width("\x01\x02abc", 1), "\x01\x02a");
}
#[test]
fn t_substr_with_width_stfl_given_string_empty() {
assert_eq!(substr_with_width_stfl("", 0), "");
assert_eq!(substr_with_width_stfl("", 1), "");
}
#[test]
fn t_substr_with_width_stfl_max_width_zero() {
assert_eq!(substr_with_width_stfl("world", 0), "");
assert_eq!(substr_with_width_stfl("", 0), "");
}
#[test]
fn t_substr_with_width_stfl_max_width_dont_split_codepoints() {
assert_eq!(
substr_with_width_stfl("ABC<b>DE</b>F", 9),
"ABC<b>D"
);
assert_eq!(substr_with_width_stfl("<foobar>ABC", 4), "<foobar>AB");
assert_eq!(substr_with_width_stfl("a<<xyz>>bcd", 3), "a<<xyz>>b"); // tag: "<<xyz>"
assert_eq!(substr_with_width_stfl("ABC<b>DE", 10), "ABC<b>DE");
assert_eq!(substr_with_width_stfl("a</>b</>c</>", 2), "a</>b</>");
}
#[test]
fn t_substr_with_width_stfl_max_width_do_not_count_stfl_tag() {
assert_eq!(
substr_with_width_stfl("ABC<b>DE</b>F", 9),
"ABC<b>D"
);
assert_eq!(substr_with_width_stfl("<foobar>ABC", 4), "<foobar>AB");
assert_eq!(substr_with_width_stfl("a<<xyz>>bcd", 3), "a<<xyz>>b"); // tag: "<<xyz>"
assert_eq!(substr_with_width_stfl("ABC<b>DE", 10), "ABC<b>DE");
assert_eq!(substr_with_width_stfl("a</>b</>c</>", 2), "a</>b</>");
}
#[test]
fn t_substr_with_width_stfl_max_width_count_escaped_less_than_mark() {
assert_eq!(substr_with_width_stfl("<><><>", 2), "<><>");
assert_eq!(substr_with_width_stfl("a<>b<>c", 3), "a<>b");
}
#[test]
fn t_substr_with_width_stfl_max_width_non_printable() {
assert_eq!(substr_with_width_stfl("\x01\x02abc", 1), "\x01\x02a");
}
#[test]
fn t_is_valid_podcast_type() {
assert!(is_valid_podcast_type("audio/mpeg"));
assert!(is_valid_podcast_type("audio/mp3"));
assert!(is_valid_podcast_type("audio/x-mp3"));
assert!(is_valid_podcast_type("audio/ogg"));
assert!(is_valid_podcast_type("video/x-matroska"));
assert!(is_valid_podcast_type("video/webm"));
assert!(is_valid_podcast_type("application/ogg"));
assert!(!is_valid_podcast_type("image/jpeg"));
assert!(!is_valid_podcast_type("image/png"));
assert!(!is_valid_podcast_type("text/plain"));
assert!(!is_valid_podcast_type("application/zip"));
}
#[test]
fn t_podcast_mime_to_link_type() {
use crate::htmlrenderer::LinkType::*;
assert_eq!(podcast_mime_to_link_type("audio/mpeg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/mp3"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/x-mp3"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("audio/ogg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("video/x-matroska"), Some(Video));
assert_eq!(podcast_mime_to_link_type("video/webm"), Some(Video));
assert_eq!(podcast_mime_to_link_type("application/ogg"), Some(Audio));
assert_eq!(podcast_mime_to_link_type("image/jpeg"), None);
assert_eq!(podcast_mime_to_link_type("image/png"), None);
assert_eq!(podcast_mime_to_link_type("text/plain"), None);
assert_eq!(podcast_mime_to_link_type("application/zip"), None);
}
#[test]
fn t_is_valid_attribte() {
let invalid = ["foo", "bar", "baz", "quux"];
for attr in &invalid {
assert!(!is_valid_attribute(attr));
}
let valid = [
"standout",
"underline",
"reverse",
"blink",
"dim",
"bold",
"protect",
"invis",
"default",
];
for attr in &valid {
assert!(is_valid_attribute(attr));
}
}
#[test]
fn t_get_auth_method() {
assert_eq!(get_auth_method("any"), curl_sys::CURLAUTH_ANY);
assert_eq!(get_auth_method("ntlm"), curl_sys::CURLAUTH_NTLM);
assert_eq!(get_auth_method("basic"), curl_sys::CURLAUTH_BASIC);
assert_eq!(get_auth_method("digest"), curl_sys::CURLAUTH_DIGEST);
assert_eq!(get_auth_method("digest_ie"), curl_sys::CURLAUTH_DIGEST_IE);
assert_eq!(
get_auth_method("gssnegotiate"),
curl_sys::CURLAUTH_GSSNEGOTIATE
);
assert_eq!(get_auth_method("anysafe"), curl_sys::CURLAUTH_ANYSAFE);
assert_eq!(get_auth_method(""), curl_sys::CURLAUTH_ANY);
assert_eq!(get_auth_method("unknown"), curl_sys::CURLAUTH_ANY);
}
#[test]
fn t_unescape_url() {
assert!(unescape_url(String::from("foo%20bar")).unwrap() == "foo bar");
assert!(
unescape_url(String::from(
"%21%23%24%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D"
))
.unwrap()
== "!#$&'()*+,/:;=?@[]"
);
}
#[test]
fn t_get_command_output() {
assert_eq!(
get_command_output("ls /dev/null"),
"/dev/null\n".to_string()
);
assert_eq!(
get_command_output("a-program-that-is-guaranteed-to-not-exists"),
"".to_string()
);
assert_eq!(get_command_output("echo c\" d e"), "".to_string());
}
#[test]
fn t_run_command_executes_given_command_with_given_argument() {
use std::{thread, time};
use tempfile::TempDir;
let tmp = TempDir::new().unwrap();
let filepath = {
let mut filepath = tmp.path().to_owned();
filepath.push("sentry");
filepath
};
assert!(!filepath.exists());
run_command("touch", filepath.to_str().unwrap());
// Busy-wait for 100 tries of 10 milliseconds each, waiting for `touch` to
// create the file. Usually it happens quickly, and the loop exists on the
// first try; but sometimes on CI it takes longer for `touch` to finish, so
// we need a slightly longer wait.
for _ in 0..100 {
thread::sleep(time::Duration::from_millis(10));
if filepath.exists() {
break;
}
}
assert!(filepath.exists());
}
#[test]
fn t_run_command_doesnt_wait_for_the_command_to_finish() {
use std::time::{Duration, Instant};
let start = Instant::now();
let five: &str = "5";
run_command("sleep", five);
let runtime = start.elapsed();
assert!(runtime < Duration::from_secs(1));
}
#[test]
fn t_run_program() {
let input1 = "this is a multine-line\ntest string";
assert_eq!(run_program(&["cat"], input1), input1);
assert_eq!(
run_program(&["echo", "-n", "hello world"], ""),
"hello world"
);
}
#[test]
fn t_make_title() {
let mut input = String::from("http://example.com/Item");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("http://example.com/This-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is_the_title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.php");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.html");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.htm");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/This_is-the_title.aspx");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/items/misc/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/item/");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("http://example.com/item/////////////");
assert_eq!(make_title(input), String::from("Item"));
input = String::from("blahscheme://example.com/this-is-the-title");
assert_eq!(make_title(input), String::from("This is the title"));
input = String::from("http://example.com/story/aug/title-with-dashes?a=b");
assert_eq!(make_title(input), String::from("Title with dashes"));
input = String::from("http://example.com/title-with-dashes?a=b&x=y&utf8=✓");
assert_eq!(make_title(input), String::from("Title with dashes"));
input = String::from("https://example.com/It%27s%202017%21");
assert_eq!(make_title(input), String::from("It's 2017!"));
input = String::from("https://example.com/?format=rss");
assert_eq!(make_title(input), String::from(""));
assert_eq!(make_title(String::from("")), String::from(""));
}
#[test]
fn t_resolve_relative() {
assert_eq!(
resolve_relative(Path::new("/foo/bar"), Path::new("/baz")),
Path::new("/baz")
);
assert_eq!(
resolve_relative(Path::new("/config"), Path::new("/config/baz")),
Path::new("/config/baz")
);
assert_eq!(
resolve_relative(Path::new("/foo/bar"), Path::new("baz")),
Path::new("/foo/baz")
);
assert_eq!(
resolve_relative(Path::new("/config"), Path::new("baz")),
Path::new("/baz")
);
}
#[test]
fn t_remove_soft_hyphens_removes_all_00ad_unicode_chars_from_a_string() {
{
// Does nothing if input has no soft hyphens in it
let mut input1 = "hello world!".to_string();
remove_soft_hyphens(&mut input1);
assert_eq!(input1, "hello world!");
}
{
// Removes *all* soft hyphens
let mut data = "hy\u{00AD}phen\u{00AD}a\u{00AD}tion".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "hyphenation");
}
{
// Removes consecutive soft hyphens
let mut data = "don't know why any\u{00AD}\u{00AD}one would do that".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "don't know why anyone would do that");
}
{
// Removes soft hyphen at the beginning of the line
let mut data = "\u{00AD}tion".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "tion");
}
{
// Removes soft hyphen at the end of the line
let mut data = "over\u{00AD}".to_string();
remove_soft_hyphens(&mut data);
assert_eq!(data, "over");
}
}
#[test]
fn t_mkdir_parents() {
use std::fs;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;
let mode: u32 = 0o700;
let tmp_dir = TempDir::new().unwrap();
let path = tmp_dir.path().join("parent/dir");
assert_eq!(path.exists(), false);
let result = mkdir_parents(&path, mode);
assert!(result.is_ok());
assert_eq!(path.exists(), true);
let file_type_mask = 0o7777;
let metadata = fs::metadata(&path).unwrap();
assert_eq!(file_type_mask & metadata.permissions().mode(), mode);
// rerun on existing directories
let result = mkdir_parents(&path, mode);
assert!(result.is_ok());
}
#[test]
fn t_strnaturalcmp() {
use std::cmp::Ordering;
assert_eq!(strnaturalcmp("", ""), Ordering::Equal);
assert_eq!(strnaturalcmp("", "a"), Ordering::Less);
assert_eq!(strnaturalcmp("a", ""), Ordering::Greater);
assert_eq!(strnaturalcmp("a", "a"), Ordering::Equal);
assert_eq!(strnaturalcmp("", "9"), Ordering::Less);
assert_eq!(strnaturalcmp("9", ""), Ordering::Greater);
assert_eq!(strnaturalcmp("1", "1"), Ordering::Equal);
assert_eq!(strnaturalcmp("1", "2"), Ordering::Less);
assert_eq!(strnaturalcmp("3", "2"), Ordering::Greater);
assert_eq!(strnaturalcmp("a1", "a1"), Ordering::Equal);
assert_eq!(strnaturalcmp("a1", "a2"), Ordering::Less);
assert_eq!(strnaturalcmp("a2", "a1"), Ordering::Greater);
assert_eq!(strnaturalcmp("a1a2", "a1a3"), Ordering::Less);
assert_eq!(strnaturalcmp("a1a2", "a1a0"), Ordering::Greater);
assert_eq!(strnaturalcmp("134", "122"), Ordering::Greater);
assert_eq!(strnaturalcmp("12a3", "12a3"), Ordering::Equal);
assert_eq!(strnaturalcmp("12a1", "12a0"), Ordering::Greater);
assert_eq!(strnaturalcmp("12a1", "12a2"), Ordering::Less);
assert_eq!(strnaturalcmp("a", "aa"), Ordering::Less);
assert_eq!(strnaturalcmp("aaa", "aa"), Ordering::Greater);
assert_eq!(strnaturalcmp("Alpha 2", "Alpha 2"), Ordering::Equal);
assert_eq!(strnaturalcmp("Alpha 2", "Alpha 2A"), Ordering::Less);
assert_eq!(strnaturalcmp("Alpha 2 B", "Alpha 2"), Ordering::Greater);
assert_eq!(strnaturalcmp("aa10", "aa2"), Ordering::Greater);
}
#[test]
fn t_strip_comments() {
// no comments in line
assert_eq!(strip_comments(""), "");
assert_eq!(strip_comments("\t\n"), "\t\n");
assert_eq!(strip_comments("some directive "), "some directive ");
// fully commented line
assert_eq!(strip_comments("#"), "");
assert_eq!(strip_comments("# #"), "");
assert_eq!(strip_comments("# comment"), "");
// partially commented line
assert_eq!(strip_comments("directive # comment"), "directive ");
assert_eq!(
strip_comments("directive # comment # another"),
"directive "
);
assert_eq!(strip_comments("directive#comment"), "directive");
// ignores # characters inside double quotes (#652)
let expected = r#"highlight article "[-=+#_*~]{3,}.*" green default"#;
let input = expected.to_owned() + "# this is a comment";
assert_eq!(strip_comments(&input), expected);
let expected =
r#"highlight all "(https?|ftp)://[\-\.,/%~_:?&=\#a-zA-Z0-9]+" blue default bold"#;
let input = expected.to_owned() + "#heresacomment";
assert_eq!(strip_comments(&input), expected);
// Escaped double quote inside double quotes is not treated as closing quote
let expected = r#"test "here \"goes # nothing\" etc" hehe"#;
let input = expected.to_owned() + "# and here is a comment";
assert_eq!(strip_comments(&input), expected);
// Ignores # characters inside backticks
let expected = r#"one `two # three` four"#;
let input = expected.to_owned() + "# and a comment, of course";
assert_eq!(strip_comments(&input), expected);
// Escaped backtick inside backticks is not treated as closing
let expected = r#"some `other \` tricky # test` hehe"#;
let input = expected.to_owned() + "#here goescomment";
assert_eq!(strip_comments(&input), expected);
// Ignores escaped # characters (\\#)
let expected = r#"one two \# three four"#;
let input = expected.to_owned() + "# and a comment";
assert_eq!(strip_comments(&input), expected);
}
#[test]
fn t_extract_filter() {
let expected = ("~/bin/script.sh", "https://newsboat.org");
let input = "filter:~/bin/script.sh:https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("", "https://newsboat.org");
let input = "filter::https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("https", "//newsboat.org");
let input = "filter:https://newsboat.org";
assert_eq!(extract_filter(input), expected);
let expected = ("foo", "");
let input = "filter:foo:";
assert_eq!(extract_filter(input), expected);
let expected = ("", "");
let input = "filter:";
assert_eq!(extract_filter(input), expected);
}
}
|
//! The `pact_verifier` crate provides the core logic to performing verification of providers.
//! It implements the V3 Pact specification (https://github.com/pact-foundation/pact-specification/tree/version-3).
#![type_length_limit="4776643"]
#![warn(missing_docs)]
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use ansi_term::*;
use ansi_term::Colour::*;
use futures::prelude::*;
use futures::stream::StreamExt;
use itertools::Itertools;
use log::*;
use maplit::*;
use regex::Regex;
use serde_json::Value;
pub use callback_executors::NullRequestFilterExecutor;
use callback_executors::RequestFilterExecutor;
use pact_matching::*;
use pact_matching::models::*;
use pact_matching::models::generators::GeneratorTestMode;
use pact_matching::models::http_utils::HttpAuth;
use pact_matching::models::provider_states::*;
use crate::callback_executors::{ProviderStateError, ProviderStateExecutor};
use crate::messages::{display_message_result, verify_message_from_provider};
use crate::pact_broker::{Link, PactVerificationContext, publish_verification_results, TestResult};
pub use crate::pact_broker::{ConsumerVersionSelector, PactsForVerificationRequest};
use crate::provider_client::{make_provider_request, provider_client_error_to_string};
use crate::request_response::display_request_response_result;
use std::sync::Arc;
mod provider_client;
mod pact_broker;
pub mod callback_executors;
mod request_response;
mod messages;
/// Source for loading pacts
#[derive(Debug, Clone)]
pub enum PactSource {
/// Unknown pact source
Unknown,
/// Load the pact from a pact file
File(String),
/// Load all the pacts from a Directory
Dir(String),
/// Load the pact from a URL
URL(String, Option<HttpAuth>),
/// Load all pacts with the provider name from the pact broker url
BrokerUrl(String, String, Option<HttpAuth>, Vec<Link>),
/// Load pacts with the newer pacts for verification API
BrokerWithDynamicConfiguration {
/// Name of the provider as named in the Pact Broker
provider_name: String,
///Base URL of the Pact Broker from which to retrieve the pacts
broker_url: String,
/// Allow pacts which are in pending state to be verified without causing the overall task to fail. For more information, see https://pact.io/pending
enable_pending: bool,
/// Allow pacts that don't match given consumer selectors (or tags) to be verified, without causing the overall task to fail. For more information, see https://pact.io/wip
include_wip_pacts_since: Option<String>,
/// Provider tags to use in determining pending status for return pacts
provider_tags: Vec<String>,
/// The set of selectors that identifies which pacts to verify
selectors: Vec<ConsumerVersionSelector>,
/// HTTP authentication details for accessing the Pact Broker
auth: Option<HttpAuth>,
/// Links to the specific Pact resources. Internal field
links: Vec<Link>
}
}
impl Display for PactSource {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
PactSource::File(ref file) => write!(f, "File({})", file),
PactSource::Dir(ref dir) => write!(f, "Dir({})", dir),
PactSource::URL(ref url, _) => write!(f, "URL({})", url),
PactSource::BrokerUrl(ref provider_name, ref broker_url, _, _) => {
write!(f, "PactBroker({}, provider_name='{}')", broker_url, provider_name)
}
PactSource::BrokerWithDynamicConfiguration { ref provider_name, ref broker_url,ref enable_pending, ref include_wip_pacts_since, ref provider_tags, ref selectors, ref auth, links: _ } => {
if let Some(auth) = auth {
write!(f, "PactBrokerWithDynamicConfiguration({}, provider_name='{}', enable_ending={}, include_wip_since={:?}, provider_tagcs={:?}, consumer_version_selectors='{:?}, auth={}')", broker_url, provider_name, enable_pending, include_wip_pacts_since, provider_tags, selectors, auth)
} else {
write!(f, "PactBrokerWithDynamicConfiguration({}, provider_name='{}', enable_ending={}, include_wip_since={:?}, provider_tagcs={:?}, consumer_version_selectors='{:?}, auth=None')", broker_url, provider_name, enable_pending, include_wip_pacts_since, provider_tags, selectors)
}
}
_ => write!(f, "Unknown")
}
}
}
/// Information about the Provider to verify
#[derive(Debug, Clone)]
pub struct ProviderInfo {
/// Provider Name
pub name: String,
/// Provider protocol, defaults to HTTP
pub protocol: String,
/// Hostname of the provider
pub host: String,
/// Port the provider is running on, defaults to 8080
pub port: Option<u16>,
/// Base path for the provider, defaults to /
pub path: String
}
impl Default for ProviderInfo {
/// Create a default provider info
fn default() -> ProviderInfo {
ProviderInfo {
name: s!("provider"),
protocol: s!("http"),
host: s!("localhost"),
port: Some(8080),
path: s!("/")
}
}
}
/// Result of performing a match
pub enum MismatchResult {
/// Response mismatches
Mismatches {
/// Mismatches that occurred
mismatches: Vec<Mismatch>,
/// Expected Response/Message
expected: Box<dyn Interaction>,
/// Actual Response/Message
actual: Box<dyn Interaction>,
/// Interaction ID if fetched from a pact broker
interaction_id: Option<String>
},
/// Error occurred
Error(String, Option<String>)
}
impl MismatchResult {
/// Return the interaction ID associated with the error, if any
pub fn interaction_id(&self) -> Option<String> {
match *self {
MismatchResult::Mismatches { ref interaction_id, .. } => interaction_id.clone(),
MismatchResult::Error(_, ref interaction_id) => interaction_id.clone()
}
}
}
impl From<ProviderStateError> for MismatchResult {
fn from(error: ProviderStateError) -> Self {
MismatchResult::Error(error.description, error.interaction_id)
}
}
impl Debug for MismatchResult {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
MismatchResult::Mismatches { mismatches, expected, actual, interaction_id } => {
if let Some(ref expected_reqres) = expected.as_request_response() {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", expected_reqres)
.field("actual", &actual.as_request_response().unwrap())
.field("interaction_id", interaction_id)
.finish()
} else if let Some(ref expected_message) = expected.as_message() {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", expected_message)
.field("actual", &actual.as_message().unwrap())
.field("interaction_id", interaction_id)
.finish()
} else {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", &"<UKNOWN TYPE>".to_string())
.field("actual", &"<UKNOWN TYPE>".to_string())
.field("interaction_id", interaction_id)
.finish()
}
},
MismatchResult::Error(error, opt) => {
f.debug_tuple("MismatchResult::Error").field(error).field(opt).finish()
}
}
}
}
impl Clone for MismatchResult {
fn clone(&self) -> Self {
match self {
MismatchResult::Mismatches { mismatches, expected, actual, interaction_id } => {
if let Some(ref expected_reqres) = expected.as_request_response() {
MismatchResult::Mismatches {
mismatches: mismatches.clone(),
expected: Box::new(expected_reqres.clone()),
actual: Box::new(actual.as_request_response().unwrap().clone()),
interaction_id: interaction_id.clone()
}
} else if let Some(ref expected_message) = expected.as_message() {
MismatchResult::Mismatches {
mismatches: mismatches.clone(),
expected: Box::new(expected_message.clone()),
actual: Box::new(actual.as_message().unwrap().clone()),
interaction_id: interaction_id.clone()
}
} else {
panic!("Cannot clone this MismatchResult::Mismatches as the expected and actual values are an unknown type")
}
},
MismatchResult::Error(error, opt) => {
MismatchResult::Error(error.clone(), opt.clone())
}
}
}
}
async fn verify_response_from_provider<F: RequestFilterExecutor>(
provider: &ProviderInfo,
interaction: &RequestResponseInteraction,
options: &VerificationOptions<F>,
client: &reqwest::Client,
verification_context: &HashMap<&str, Value>
) -> Result<(), MismatchResult> {
let expected_response = &interaction.response;
match make_provider_request(provider, &pact_matching::generate_request(&interaction.request, &GeneratorTestMode::Provider, &verification_context), options, client).await {
Ok(ref actual_response) => {
let mismatches = match_response(expected_response.clone(), actual_response.clone());
if mismatches.is_empty() {
Ok(())
} else {
Err(MismatchResult::Mismatches {
mismatches,
expected: Box::new(interaction.clone()),
actual: Box::new(RequestResponseInteraction { response: actual_response.clone(), .. RequestResponseInteraction::default() }),
interaction_id: interaction.id.clone()
})
}
},
Err(err) => {
Err(MismatchResult::Error(provider_client_error_to_string(err), interaction.id.clone()))
}
}
}
async fn execute_state_change<S: ProviderStateExecutor>(
provider_state: &ProviderState,
setup: bool,
interaction_id: Option<String>,
client: &reqwest::Client,
provider_state_executor: &S
) -> Result<HashMap<String, Value>, MismatchResult> {
if setup {
println!(" Given {}", Style::new().bold().paint(provider_state.name.clone()));
}
let result = provider_state_executor.call(interaction_id, provider_state, setup, Some(client)).await;
log::debug!("State Change: \"{:?}\" -> {:?}", provider_state, result);
result.map_err(|err| MismatchResult::Error(err.description, err.interaction_id))
}
async fn verify_interaction<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider: &ProviderInfo,
interaction: &dyn Interaction,
options: &VerificationOptions<F>,
provider_state_executor: &S
) -> Result<(), MismatchResult> {
let client = Arc::new(reqwest::Client::builder()
.danger_accept_invalid_certs(options.disable_ssl_verification)
.build()
.unwrap_or(reqwest::Client::new()));
let mut provider_states_results = hashmap!{};
let sc_results = futures::stream::iter(
interaction.provider_states().iter().map(|state| (state, client.clone())))
.then(|(state, client)| {
let state_name = state.name.clone();
info!("Running provider state change handler '{}' for '{}'", state_name, interaction.description());
async move {
execute_state_change(&state, true, interaction.id(), &client, provider_state_executor)
.map_err(|err| {
error!("Provider state change for '{}' has failed - {:?}", state_name, err);
err
}).await
}
}).collect::<Vec<Result<HashMap<String, Value>, MismatchResult>>>().await;
if sc_results.iter().any(|result| result.is_err()) {
return Err(MismatchResult::Error("One or more of the state change handlers has failed".to_string(), interaction.id()))
} else {
for result in sc_results {
if result.is_ok() {
for (k, v) in result.unwrap() {
provider_states_results.insert(k, v);
}
}
}
};
info!("Running provider verification for '{}'", interaction.description());
let result = futures::future::ready((provider_states_results.iter()
.map(|(k, v)| (k.as_str(), v.clone())).collect(), client.clone()))
.then(|(context, client)| async move {
let mut result = Err(MismatchResult::Error("No interaction was verified".into(), None));
if let Some(interaction) = interaction.as_request_response() {
result = verify_response_from_provider(provider, &interaction, options, &client, &context).await;
}
if let Some(interaction) = interaction.as_message() {
result = verify_message_from_provider(provider, &interaction, options, &client, &context).await;
}
result
}).await;
if !interaction.provider_states().is_empty() {
let sc_teardown_result = futures::stream::iter(
interaction.provider_states().iter().map(|state| (state, client.clone())))
.then(|(state, client)| async move {
let state_name = state.name.clone();
info!("Running provider state change handler '{}' for '{}'", state_name, interaction.description());
execute_state_change(&state, false, interaction.id(), &client, provider_state_executor)
.map_err(|err| {
error!("Provider state change teardown for '{}' has failed - {:?}", state.name, err);
err
}).await
}).collect::<Vec<Result<HashMap<String, Value>, MismatchResult>>>().await;
if sc_teardown_result.iter().any(|result| result.is_err()) {
return Err(MismatchResult::Error("One or more of the state change handlers has failed during teardown phase".to_string(), interaction.id()))
}
}
result
}
fn display_result(
status: u16,
status_result: ANSIGenericString<str>,
header_results: Option<Vec<(String, String, ANSIGenericString<str>)>>,
body_result: ANSIGenericString<str>
) {
println!(" returns a response which");
println!(" has status code {} ({})", Style::new().bold().paint(format!("{}", status)),
status_result);
if let Some(header_results) = header_results {
println!(" includes headers");
for (key, value, result) in header_results {
println!(" \"{}\" with value \"{}\" ({})", Style::new().bold().paint(key),
Style::new().bold().paint(value), result);
}
}
println!(" has a matching body ({})", body_result);
}
fn walkdir(dir: &Path) -> io::Result<Vec<io::Result<Box<dyn Pact>>>> {
let mut pacts = vec![];
log::debug!("Scanning {:?}", dir);
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
walkdir(&path)?;
} else {
pacts.push(read_pact(&path))
}
}
Ok(pacts)
}
fn display_body_mismatch(expected: &Box<dyn Interaction>, actual: &Box<dyn Interaction>, path: &str) {
if expected.content_type().unwrap_or_default().is_json() {
println!("{}", pact_matching::json::display_diff(
&expected.contents().str_value().to_string(),
&actual.contents().str_value().to_string(),
path, " "));
}
}
/// Filter information used to filter the interactions that are verified
#[derive(Debug, Clone)]
pub enum FilterInfo {
/// No filter, all interactions will be verified
None,
/// Filter on the interaction description
Description(String),
/// Filter on the interaction provider state
State(String),
/// Filter on both the interaction description and provider state
DescriptionAndState(String, String)
}
impl FilterInfo {
/// If this filter is filtering on description
pub fn has_description(&self) -> bool {
match *self {
FilterInfo::Description(_) => true,
FilterInfo::DescriptionAndState(_, _) => true,
_ => false
}
}
/// If this filter is filtering on provider state
pub fn has_state(&self) -> bool {
match *self {
FilterInfo::State(_) => true,
FilterInfo::DescriptionAndState(_, _) => true,
_ => false
}
}
/// Value of the state to filter
pub fn state(&self) -> String {
match *self {
FilterInfo::State(ref s) => s.clone(),
FilterInfo::DescriptionAndState(_, ref s) => s.clone(),
_ => s!("")
}
}
/// Value of the description to filter
pub fn description(&self) -> String {
match *self {
FilterInfo::Description(ref s) => s.clone(),
FilterInfo::DescriptionAndState(ref s, _) => s.clone(),
_ => s!("")
}
}
/// If the filter matches the interaction provider state using a regular expression. If the
/// filter value is the empty string, then it will match interactions with no provider state.
///
/// # Panics
/// If the state filter value can't be parsed as a regular expression
pub fn match_state(&self, interaction: &dyn Interaction) -> bool {
if !interaction.provider_states().is_empty() {
if self.state().is_empty() {
false
} else {
let re = Regex::new(&self.state()).unwrap();
interaction.provider_states().iter().any(|state| re.is_match(&state.name))
}
} else {
self.has_state() && self.state().is_empty()
}
}
/// If the filter matches the interaction description using a regular expression
///
/// # Panics
/// If the description filter value can't be parsed as a regular expression
pub fn match_description(&self, interaction: &dyn Interaction) -> bool {
let re = Regex::new(&self.description()).unwrap();
re.is_match(&interaction.description())
}
}
fn filter_interaction(interaction: &dyn Interaction, filter: &FilterInfo) -> bool {
if filter.has_description() && filter.has_state() {
filter.match_description(interaction) && filter.match_state(interaction)
} else if filter.has_description() {
filter.match_description(interaction)
} else if filter.has_state() {
filter.match_state(interaction)
} else {
true
}
}
fn filter_consumers(consumers: &[String], res: &Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>) -> bool {
consumers.is_empty() || res.is_err() || consumers.contains(&res.as_ref().unwrap().0.consumer().name)
}
/// Options to use when running the verification
#[derive(Debug, Clone)]
pub struct VerificationOptions<F> where F: RequestFilterExecutor {
/// If results should be published back to the broker
pub publish: bool,
/// Provider version being published
pub provider_version: Option<String>,
/// Build URL to associate with the published results
pub build_url: Option<String>,
/// Request filter callback
pub request_filter: Option<Box<F>>,
/// Tags to use when publishing results
pub provider_tags: Vec<String>,
/// Ignore invalid/self-signed SSL certificates
pub disable_ssl_verification: bool
}
impl <F: RequestFilterExecutor> Default for VerificationOptions<F> {
fn default() -> Self {
VerificationOptions {
publish: false,
provider_version: None,
build_url: None,
request_filter: None,
provider_tags: vec![],
disable_ssl_verification: false
}
}
}
const VERIFICATION_NOTICE_BEFORE: &str = "before_verification";
const VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_PUBLISH: &str = "after_verification:success_true_published_true";
const VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_NO_PUBLISH: &str = "after_verification:success_true_published_false";
const VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_PUBLISH: &str = "after_verification:success_false_published_true";
const VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_NO_PUBLISH: &str = "after_verification:success_false_published_false";
fn display_notices(context: &Option<PactVerificationContext>, stage: &str) {
if let Some(c) = context {
for notice in &c.verification_properties.notices {
if let Some(when) = notice.get("when") {
if when.as_str() == stage {
println!("{}", notice.get("text").unwrap_or(&"".to_string()));
}
}
}
}
}
/// Verify the provider with the given pact sources.
pub fn verify_provider<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: ProviderInfo,
source: Vec<PactSource>,
filter: FilterInfo,
consumers: Vec<String>,
options: VerificationOptions<F>,
provider_state_executor: &S
) -> bool {
match tokio::runtime::Builder::new().threaded_scheduler().enable_all().build() {
Ok(mut runtime) => runtime.block_on(
verify_provider_async(provider_info, source, filter, consumers, options, provider_state_executor)),
Err(err) => {
error!("Verify provider process failed to start the tokio runtime: {}", err);
false
}
}
}
/// Verify the provider with the given pact sources (async version)
pub async fn verify_provider_async<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: ProviderInfo,
source: Vec<PactSource>,
filter: FilterInfo,
consumers: Vec<String>,
options: VerificationOptions<F>,
provider_state_executor: &S
) -> bool {
let pact_results = fetch_pacts(source, consumers).await;
let mut pending_errors: Vec<(String, MismatchResult)> = vec![];
let mut all_errors: Vec<(String, MismatchResult)> = vec![];
for pact_result in pact_results {
match pact_result {
Ok((pact, context, pact_source)) => {
let pending = match &context {
Some(context) => context.verification_properties.pending,
None => false
};
display_notices(&context, VERIFICATION_NOTICE_BEFORE);
println!("\nVerifying a pact between {} and {}",
Style::new().bold().paint(pact.consumer().name.clone()),
Style::new().bold().paint(pact.provider().name.clone()));
if pact.interactions().is_empty() {
println!(" {}", Yellow.paint("WARNING: Pact file has no interactions"));
} else {
let errors = verify_pact(&provider_info, &filter, pact, &options, provider_state_executor).await;
for error in errors.clone() {
if pending {
pending_errors.push(error);
} else {
all_errors.push(error);
}
}
if options.publish {
publish_result(&errors, &pact_source, &options).await;
if !all_errors.is_empty() || !pending_errors.is_empty() {
display_notices(&context, VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_PUBLISH);
} else {
display_notices(&context, VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_PUBLISH);
}
} else {
if !all_errors.is_empty() || pending_errors.is_empty() {
display_notices(&context, VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_NO_PUBLISH);
} else {
display_notices(&context, VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_NO_PUBLISH);
}
}
}
},
Err(err) => {
log::error!("Failed to load pact - {}", Red.paint(err.to_string()));
all_errors.push((s!("Failed to load pact"), MismatchResult::Error(err.to_string(), None)));
}
}
};
if !pending_errors.is_empty() {
println!("\nPending Failures:\n");
print_errors(&pending_errors);
println!("\nThere were {} non-fatal pact failures on pending pacts (see docs.pact.io/pending for more)\n", pending_errors.len());
}
if !all_errors.is_empty() {
println!("\nFailures:\n");
print_errors(&all_errors);
println!("\nThere were {} pact failures\n", all_errors.len());
false
} else {
true
}
}
fn print_errors(errors: &Vec<(String, MismatchResult)>) {
for (i, &(ref description, ref mismatch)) in errors.iter().enumerate() {
match *mismatch {
MismatchResult::Error(ref err, _) => println!("{}) {} - {}\n", i + 1, description, err),
MismatchResult::Mismatches { ref mismatches, ref expected, ref actual, .. } => {
println!("{}) {}", i + 1, description);
let mut j = 1;
for (_, mut mismatches) in &mismatches.into_iter().group_by(|m| m.mismatch_type()) {
let mismatch = mismatches.next().unwrap();
println!(" {}.{}) {}", i + 1, j, mismatch.summary());
println!(" {}", mismatch.ansi_description());
for mismatch in mismatches {
println!(" {}", mismatch.ansi_description());
}
if let Mismatch::BodyMismatch{ref path, ..} = mismatch {
display_body_mismatch(expected, actual, path);
}
j += 1;
}
}
}
}
}
async fn fetch_pact(source: PactSource) -> Vec<Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>> {
match source {
PactSource::File(ref file) => vec![read_pact(Path::new(&file))
.map_err(|err| format!("Failed to load pact '{}' - {}", file, err))
.map(|pact| (pact, None, source))],
PactSource::Dir(ref dir) => match walkdir(Path::new(dir)) {
Ok(pact_results) => pact_results.into_iter().map(|pact_result| {
match pact_result {
Ok(pact) => Ok((pact, None, source.clone())),
Err(err) => Err(format!("Failed to load pact from '{}' - {}", dir, err))
}
}).collect(),
Err(err) => vec![Err(format!("Could not load pacts from directory '{}' - {}", dir, err))]
},
PactSource::URL(ref url, ref auth) => vec![load_pact_from_url(url, auth)
.map_err(|err| format!("Failed to load pact '{}' - {}", url, err))
.map(|pact| (pact, None, source))],
PactSource::BrokerUrl(ref provider_name, ref broker_url, ref auth, _) => {
let result = pact_broker::fetch_pacts_from_broker(
broker_url.clone(),
provider_name.clone(),
auth.clone()
).await;
match result {
Ok(ref pacts) => {
let mut buffer = vec![];
for result in pacts.iter() {
match result {
Ok((pact, _, links)) => {
log::debug!("Got pact with links {:?}", links);
if let Ok(pact) = pact.as_request_response_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, None, PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
if let Ok(pact) = pact.as_message_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, None, PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
},
&Err(ref err) => buffer.push(Err(format!("Failed to load pact from '{}' - {:?}", broker_url, err)))
}
}
buffer
},
Err(err) => vec![Err(format!("Could not load pacts from the pact broker '{}' - {:?}", broker_url, err))]
}
},
PactSource::BrokerWithDynamicConfiguration { provider_name, broker_url, enable_pending, include_wip_pacts_since, provider_tags, selectors, auth, links: _ } => {
let result = pact_broker::fetch_pacts_dynamically_from_broker(
broker_url.clone(),
provider_name.clone(),
enable_pending,
include_wip_pacts_since,
provider_tags,
selectors,
auth.clone()
).await;
match result {
Ok(ref pacts) => {
let mut buffer = vec![];
for result in pacts.iter() {
match result {
Ok((pact, context, links)) => {
log::debug!("Got pact with links {:?}", links);
if let Ok(pact) = pact.as_request_response_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, context.clone(), PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
if let Ok(pact) = pact.as_message_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, context.clone(), PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
},
&Err(ref err) => buffer.push(Err(format!("Failed to load pact from '{}' - {:?}", broker_url, err)))
}
}
buffer
},
Err(err) => vec![Err(format!("Could not load pacts from the pact broker '{}' - {:?}", broker_url, err))]
}
},
_ => vec![Err("Could not load pacts, unknown pact source".to_string())]
}
}
async fn fetch_pacts(source: Vec<PactSource>, consumers: Vec<String>)
-> Vec<Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>> {
futures::stream::iter(source)
.then(|pact_source| async {
futures::stream::iter(fetch_pact(pact_source).await)
})
.flatten()
.filter(|res| futures::future::ready(filter_consumers(&consumers, res)))
.collect()
.await
}
async fn verify_pact<'a, F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: &ProviderInfo,
filter: &FilterInfo,
pact: Box<dyn Pact + 'a>,
options: &VerificationOptions<F>,
provider_state_executor: &S
) -> Vec<(String, MismatchResult)> {
let mut errors: Vec<(String, MismatchResult)> = vec![];
let results: Vec<(&dyn Interaction, Result<(), MismatchResult>)> = futures::stream::iter(
pact.interactions().iter().cloned()
)
.filter(|interaction| futures::future::ready(filter_interaction(*interaction, filter)))
.then( |interaction| async move {
verify_interaction(provider_info, interaction.clone(), options, provider_state_executor)
.then(|result| futures::future::ready((interaction, result)))
.await
})
.collect()
.await;
for (interaction, match_result) in results {
let mut description = format!("Verifying a pact between {} and {}",
pact.consumer().name.clone(), pact.provider().name.clone());
if let Some((first, elements)) = interaction.provider_states().split_first() {
description.push_str(&format!(" Given {}", first.name));
for state in elements {
description.push_str(&format!(" And {}", state.name));
}
}
description.push_str(" - ");
description.push_str(&interaction.description());
println!(" {}", interaction.description());
if let Some(interaction) = interaction.as_request_response() {
display_request_response_result(&mut errors, &interaction, &match_result, &description)
}
if let Some(interaction) = interaction.as_message() {
display_message_result(&mut errors, &interaction, &match_result, &description)
}
}
println!();
errors
}
async fn publish_result<F: RequestFilterExecutor>(
errors: &[(String, MismatchResult)],
source: &PactSource,
options: &VerificationOptions<F>
) {
if let PactSource::BrokerUrl(_, broker_url, auth, links) = source.clone() {
log::info!("Publishing verification results back to the Pact Broker");
let result = if errors.is_empty() {
log::debug!("Publishing a successful result to {}", source);
TestResult::Ok
} else {
log::debug!("Publishing a failure result to {}", source);
TestResult::Failed(Vec::from(errors))
};
let provider_version = options.provider_version.clone().unwrap();
let publish_result = publish_verification_results(
links,
broker_url.clone(),
auth.clone(),
result,
provider_version,
options.build_url.clone(),
options.provider_tags.clone()
).await;
match publish_result {
Ok(_) => log::info!("Results published to Pact Broker"),
Err(ref err) => log::error!("Publishing of verification results failed with an error: {}", err)
};
}
}
#[cfg(test)]
mod tests;
fix: using `clone` on a double-reference
//! The `pact_verifier` crate provides the core logic to performing verification of providers.
//! It implements the V3 Pact specification (https://github.com/pact-foundation/pact-specification/tree/version-3).
#![type_length_limit="4776643"]
#![warn(missing_docs)]
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use ansi_term::*;
use ansi_term::Colour::*;
use futures::prelude::*;
use futures::stream::StreamExt;
use itertools::Itertools;
use log::*;
use maplit::*;
use regex::Regex;
use serde_json::Value;
pub use callback_executors::NullRequestFilterExecutor;
use callback_executors::RequestFilterExecutor;
use pact_matching::*;
use pact_matching::models::*;
use pact_matching::models::generators::GeneratorTestMode;
use pact_matching::models::http_utils::HttpAuth;
use pact_matching::models::provider_states::*;
use crate::callback_executors::{ProviderStateError, ProviderStateExecutor};
use crate::messages::{display_message_result, verify_message_from_provider};
use crate::pact_broker::{Link, PactVerificationContext, publish_verification_results, TestResult};
pub use crate::pact_broker::{ConsumerVersionSelector, PactsForVerificationRequest};
use crate::provider_client::{make_provider_request, provider_client_error_to_string};
use crate::request_response::display_request_response_result;
use std::sync::Arc;
mod provider_client;
mod pact_broker;
pub mod callback_executors;
mod request_response;
mod messages;
/// Source for loading pacts
#[derive(Debug, Clone)]
pub enum PactSource {
/// Unknown pact source
Unknown,
/// Load the pact from a pact file
File(String),
/// Load all the pacts from a Directory
Dir(String),
/// Load the pact from a URL
URL(String, Option<HttpAuth>),
/// Load all pacts with the provider name from the pact broker url
BrokerUrl(String, String, Option<HttpAuth>, Vec<Link>),
/// Load pacts with the newer pacts for verification API
BrokerWithDynamicConfiguration {
/// Name of the provider as named in the Pact Broker
provider_name: String,
///Base URL of the Pact Broker from which to retrieve the pacts
broker_url: String,
/// Allow pacts which are in pending state to be verified without causing the overall task to fail. For more information, see https://pact.io/pending
enable_pending: bool,
/// Allow pacts that don't match given consumer selectors (or tags) to be verified, without causing the overall task to fail. For more information, see https://pact.io/wip
include_wip_pacts_since: Option<String>,
/// Provider tags to use in determining pending status for return pacts
provider_tags: Vec<String>,
/// The set of selectors that identifies which pacts to verify
selectors: Vec<ConsumerVersionSelector>,
/// HTTP authentication details for accessing the Pact Broker
auth: Option<HttpAuth>,
/// Links to the specific Pact resources. Internal field
links: Vec<Link>
}
}
impl Display for PactSource {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
PactSource::File(ref file) => write!(f, "File({})", file),
PactSource::Dir(ref dir) => write!(f, "Dir({})", dir),
PactSource::URL(ref url, _) => write!(f, "URL({})", url),
PactSource::BrokerUrl(ref provider_name, ref broker_url, _, _) => {
write!(f, "PactBroker({}, provider_name='{}')", broker_url, provider_name)
}
PactSource::BrokerWithDynamicConfiguration { ref provider_name, ref broker_url,ref enable_pending, ref include_wip_pacts_since, ref provider_tags, ref selectors, ref auth, links: _ } => {
if let Some(auth) = auth {
write!(f, "PactBrokerWithDynamicConfiguration({}, provider_name='{}', enable_ending={}, include_wip_since={:?}, provider_tagcs={:?}, consumer_version_selectors='{:?}, auth={}')", broker_url, provider_name, enable_pending, include_wip_pacts_since, provider_tags, selectors, auth)
} else {
write!(f, "PactBrokerWithDynamicConfiguration({}, provider_name='{}', enable_ending={}, include_wip_since={:?}, provider_tagcs={:?}, consumer_version_selectors='{:?}, auth=None')", broker_url, provider_name, enable_pending, include_wip_pacts_since, provider_tags, selectors)
}
}
_ => write!(f, "Unknown")
}
}
}
/// Information about the Provider to verify
#[derive(Debug, Clone)]
pub struct ProviderInfo {
/// Provider Name
pub name: String,
/// Provider protocol, defaults to HTTP
pub protocol: String,
/// Hostname of the provider
pub host: String,
/// Port the provider is running on, defaults to 8080
pub port: Option<u16>,
/// Base path for the provider, defaults to /
pub path: String
}
impl Default for ProviderInfo {
/// Create a default provider info
fn default() -> ProviderInfo {
ProviderInfo {
name: s!("provider"),
protocol: s!("http"),
host: s!("localhost"),
port: Some(8080),
path: s!("/")
}
}
}
/// Result of performing a match
pub enum MismatchResult {
/// Response mismatches
Mismatches {
/// Mismatches that occurred
mismatches: Vec<Mismatch>,
/// Expected Response/Message
expected: Box<dyn Interaction>,
/// Actual Response/Message
actual: Box<dyn Interaction>,
/// Interaction ID if fetched from a pact broker
interaction_id: Option<String>
},
/// Error occurred
Error(String, Option<String>)
}
impl MismatchResult {
/// Return the interaction ID associated with the error, if any
pub fn interaction_id(&self) -> Option<String> {
match *self {
MismatchResult::Mismatches { ref interaction_id, .. } => interaction_id.clone(),
MismatchResult::Error(_, ref interaction_id) => interaction_id.clone()
}
}
}
impl From<ProviderStateError> for MismatchResult {
fn from(error: ProviderStateError) -> Self {
MismatchResult::Error(error.description, error.interaction_id)
}
}
impl Debug for MismatchResult {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
MismatchResult::Mismatches { mismatches, expected, actual, interaction_id } => {
if let Some(ref expected_reqres) = expected.as_request_response() {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", expected_reqres)
.field("actual", &actual.as_request_response().unwrap())
.field("interaction_id", interaction_id)
.finish()
} else if let Some(ref expected_message) = expected.as_message() {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", expected_message)
.field("actual", &actual.as_message().unwrap())
.field("interaction_id", interaction_id)
.finish()
} else {
f.debug_struct("MismatchResult::Mismatches")
.field("mismatches", mismatches)
.field("expected", &"<UKNOWN TYPE>".to_string())
.field("actual", &"<UKNOWN TYPE>".to_string())
.field("interaction_id", interaction_id)
.finish()
}
},
MismatchResult::Error(error, opt) => {
f.debug_tuple("MismatchResult::Error").field(error).field(opt).finish()
}
}
}
}
impl Clone for MismatchResult {
fn clone(&self) -> Self {
match self {
MismatchResult::Mismatches { mismatches, expected, actual, interaction_id } => {
if let Some(ref expected_reqres) = expected.as_request_response() {
MismatchResult::Mismatches {
mismatches: mismatches.clone(),
expected: Box::new(expected_reqres.clone()),
actual: Box::new(actual.as_request_response().unwrap().clone()),
interaction_id: interaction_id.clone()
}
} else if let Some(ref expected_message) = expected.as_message() {
MismatchResult::Mismatches {
mismatches: mismatches.clone(),
expected: Box::new(expected_message.clone()),
actual: Box::new(actual.as_message().unwrap().clone()),
interaction_id: interaction_id.clone()
}
} else {
panic!("Cannot clone this MismatchResult::Mismatches as the expected and actual values are an unknown type")
}
},
MismatchResult::Error(error, opt) => {
MismatchResult::Error(error.clone(), opt.clone())
}
}
}
}
async fn verify_response_from_provider<F: RequestFilterExecutor>(
provider: &ProviderInfo,
interaction: &RequestResponseInteraction,
options: &VerificationOptions<F>,
client: &reqwest::Client,
verification_context: &HashMap<&str, Value>
) -> Result<(), MismatchResult> {
let expected_response = &interaction.response;
match make_provider_request(provider, &pact_matching::generate_request(&interaction.request, &GeneratorTestMode::Provider, &verification_context), options, client).await {
Ok(ref actual_response) => {
let mismatches = match_response(expected_response.clone(), actual_response.clone());
if mismatches.is_empty() {
Ok(())
} else {
Err(MismatchResult::Mismatches {
mismatches,
expected: Box::new(interaction.clone()),
actual: Box::new(RequestResponseInteraction { response: actual_response.clone(), .. RequestResponseInteraction::default() }),
interaction_id: interaction.id.clone()
})
}
},
Err(err) => {
Err(MismatchResult::Error(provider_client_error_to_string(err), interaction.id.clone()))
}
}
}
async fn execute_state_change<S: ProviderStateExecutor>(
provider_state: &ProviderState,
setup: bool,
interaction_id: Option<String>,
client: &reqwest::Client,
provider_state_executor: &S
) -> Result<HashMap<String, Value>, MismatchResult> {
if setup {
println!(" Given {}", Style::new().bold().paint(provider_state.name.clone()));
}
let result = provider_state_executor.call(interaction_id, provider_state, setup, Some(client)).await;
log::debug!("State Change: \"{:?}\" -> {:?}", provider_state, result);
result.map_err(|err| MismatchResult::Error(err.description, err.interaction_id))
}
async fn verify_interaction<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider: &ProviderInfo,
interaction: &dyn Interaction,
options: &VerificationOptions<F>,
provider_state_executor: &S
) -> Result<(), MismatchResult> {
let client = Arc::new(reqwest::Client::builder()
.danger_accept_invalid_certs(options.disable_ssl_verification)
.build()
.unwrap_or(reqwest::Client::new()));
let mut provider_states_results = hashmap!{};
let sc_results = futures::stream::iter(
interaction.provider_states().iter().map(|state| (state, client.clone())))
.then(|(state, client)| {
let state_name = state.name.clone();
info!("Running provider state change handler '{}' for '{}'", state_name, interaction.description());
async move {
execute_state_change(&state, true, interaction.id(), &client, provider_state_executor)
.map_err(|err| {
error!("Provider state change for '{}' has failed - {:?}", state_name, err);
err
}).await
}
}).collect::<Vec<Result<HashMap<String, Value>, MismatchResult>>>().await;
if sc_results.iter().any(|result| result.is_err()) {
return Err(MismatchResult::Error("One or more of the state change handlers has failed".to_string(), interaction.id()))
} else {
for result in sc_results {
if result.is_ok() {
for (k, v) in result.unwrap() {
provider_states_results.insert(k, v);
}
}
}
};
info!("Running provider verification for '{}'", interaction.description());
let result = futures::future::ready((provider_states_results.iter()
.map(|(k, v)| (k.as_str(), v.clone())).collect(), client.clone()))
.then(|(context, client)| async move {
let mut result = Err(MismatchResult::Error("No interaction was verified".into(), None));
if let Some(interaction) = interaction.as_request_response() {
result = verify_response_from_provider(provider, &interaction, options, &client, &context).await;
}
if let Some(interaction) = interaction.as_message() {
result = verify_message_from_provider(provider, &interaction, options, &client, &context).await;
}
result
}).await;
if !interaction.provider_states().is_empty() {
let sc_teardown_result = futures::stream::iter(
interaction.provider_states().iter().map(|state| (state, client.clone())))
.then(|(state, client)| async move {
let state_name = state.name.clone();
info!("Running provider state change handler '{}' for '{}'", state_name, interaction.description());
execute_state_change(&state, false, interaction.id(), &client, provider_state_executor)
.map_err(|err| {
error!("Provider state change teardown for '{}' has failed - {:?}", state.name, err);
err
}).await
}).collect::<Vec<Result<HashMap<String, Value>, MismatchResult>>>().await;
if sc_teardown_result.iter().any(|result| result.is_err()) {
return Err(MismatchResult::Error("One or more of the state change handlers has failed during teardown phase".to_string(), interaction.id()))
}
}
result
}
fn display_result(
status: u16,
status_result: ANSIGenericString<str>,
header_results: Option<Vec<(String, String, ANSIGenericString<str>)>>,
body_result: ANSIGenericString<str>
) {
println!(" returns a response which");
println!(" has status code {} ({})", Style::new().bold().paint(format!("{}", status)),
status_result);
if let Some(header_results) = header_results {
println!(" includes headers");
for (key, value, result) in header_results {
println!(" \"{}\" with value \"{}\" ({})", Style::new().bold().paint(key),
Style::new().bold().paint(value), result);
}
}
println!(" has a matching body ({})", body_result);
}
fn walkdir(dir: &Path) -> io::Result<Vec<io::Result<Box<dyn Pact>>>> {
let mut pacts = vec![];
log::debug!("Scanning {:?}", dir);
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
walkdir(&path)?;
} else {
pacts.push(read_pact(&path))
}
}
Ok(pacts)
}
fn display_body_mismatch(expected: &Box<dyn Interaction>, actual: &Box<dyn Interaction>, path: &str) {
if expected.content_type().unwrap_or_default().is_json() {
println!("{}", pact_matching::json::display_diff(
&expected.contents().str_value().to_string(),
&actual.contents().str_value().to_string(),
path, " "));
}
}
/// Filter information used to filter the interactions that are verified
#[derive(Debug, Clone)]
pub enum FilterInfo {
/// No filter, all interactions will be verified
None,
/// Filter on the interaction description
Description(String),
/// Filter on the interaction provider state
State(String),
/// Filter on both the interaction description and provider state
DescriptionAndState(String, String)
}
impl FilterInfo {
/// If this filter is filtering on description
pub fn has_description(&self) -> bool {
match *self {
FilterInfo::Description(_) => true,
FilterInfo::DescriptionAndState(_, _) => true,
_ => false
}
}
/// If this filter is filtering on provider state
pub fn has_state(&self) -> bool {
match *self {
FilterInfo::State(_) => true,
FilterInfo::DescriptionAndState(_, _) => true,
_ => false
}
}
/// Value of the state to filter
pub fn state(&self) -> String {
match *self {
FilterInfo::State(ref s) => s.clone(),
FilterInfo::DescriptionAndState(_, ref s) => s.clone(),
_ => s!("")
}
}
/// Value of the description to filter
pub fn description(&self) -> String {
match *self {
FilterInfo::Description(ref s) => s.clone(),
FilterInfo::DescriptionAndState(ref s, _) => s.clone(),
_ => s!("")
}
}
/// If the filter matches the interaction provider state using a regular expression. If the
/// filter value is the empty string, then it will match interactions with no provider state.
///
/// # Panics
/// If the state filter value can't be parsed as a regular expression
pub fn match_state(&self, interaction: &dyn Interaction) -> bool {
if !interaction.provider_states().is_empty() {
if self.state().is_empty() {
false
} else {
let re = Regex::new(&self.state()).unwrap();
interaction.provider_states().iter().any(|state| re.is_match(&state.name))
}
} else {
self.has_state() && self.state().is_empty()
}
}
/// If the filter matches the interaction description using a regular expression
///
/// # Panics
/// If the description filter value can't be parsed as a regular expression
pub fn match_description(&self, interaction: &dyn Interaction) -> bool {
let re = Regex::new(&self.description()).unwrap();
re.is_match(&interaction.description())
}
}
fn filter_interaction(interaction: &dyn Interaction, filter: &FilterInfo) -> bool {
if filter.has_description() && filter.has_state() {
filter.match_description(interaction) && filter.match_state(interaction)
} else if filter.has_description() {
filter.match_description(interaction)
} else if filter.has_state() {
filter.match_state(interaction)
} else {
true
}
}
fn filter_consumers(consumers: &[String], res: &Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>) -> bool {
consumers.is_empty() || res.is_err() || consumers.contains(&res.as_ref().unwrap().0.consumer().name)
}
/// Options to use when running the verification
#[derive(Debug, Clone)]
pub struct VerificationOptions<F> where F: RequestFilterExecutor {
/// If results should be published back to the broker
pub publish: bool,
/// Provider version being published
pub provider_version: Option<String>,
/// Build URL to associate with the published results
pub build_url: Option<String>,
/// Request filter callback
pub request_filter: Option<Box<F>>,
/// Tags to use when publishing results
pub provider_tags: Vec<String>,
/// Ignore invalid/self-signed SSL certificates
pub disable_ssl_verification: bool
}
impl <F: RequestFilterExecutor> Default for VerificationOptions<F> {
fn default() -> Self {
VerificationOptions {
publish: false,
provider_version: None,
build_url: None,
request_filter: None,
provider_tags: vec![],
disable_ssl_verification: false
}
}
}
const VERIFICATION_NOTICE_BEFORE: &str = "before_verification";
const VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_PUBLISH: &str = "after_verification:success_true_published_true";
const VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_NO_PUBLISH: &str = "after_verification:success_true_published_false";
const VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_PUBLISH: &str = "after_verification:success_false_published_true";
const VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_NO_PUBLISH: &str = "after_verification:success_false_published_false";
fn display_notices(context: &Option<PactVerificationContext>, stage: &str) {
if let Some(c) = context {
for notice in &c.verification_properties.notices {
if let Some(when) = notice.get("when") {
if when.as_str() == stage {
println!("{}", notice.get("text").unwrap_or(&"".to_string()));
}
}
}
}
}
/// Verify the provider with the given pact sources.
pub fn verify_provider<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: ProviderInfo,
source: Vec<PactSource>,
filter: FilterInfo,
consumers: Vec<String>,
options: VerificationOptions<F>,
provider_state_executor: &S
) -> bool {
match tokio::runtime::Builder::new().threaded_scheduler().enable_all().build() {
Ok(mut runtime) => runtime.block_on(
verify_provider_async(provider_info, source, filter, consumers, options, provider_state_executor)),
Err(err) => {
error!("Verify provider process failed to start the tokio runtime: {}", err);
false
}
}
}
/// Verify the provider with the given pact sources (async version)
pub async fn verify_provider_async<F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: ProviderInfo,
source: Vec<PactSource>,
filter: FilterInfo,
consumers: Vec<String>,
options: VerificationOptions<F>,
provider_state_executor: &S
) -> bool {
let pact_results = fetch_pacts(source, consumers).await;
let mut pending_errors: Vec<(String, MismatchResult)> = vec![];
let mut all_errors: Vec<(String, MismatchResult)> = vec![];
for pact_result in pact_results {
match pact_result {
Ok((pact, context, pact_source)) => {
let pending = match &context {
Some(context) => context.verification_properties.pending,
None => false
};
display_notices(&context, VERIFICATION_NOTICE_BEFORE);
println!("\nVerifying a pact between {} and {}",
Style::new().bold().paint(pact.consumer().name.clone()),
Style::new().bold().paint(pact.provider().name.clone()));
if pact.interactions().is_empty() {
println!(" {}", Yellow.paint("WARNING: Pact file has no interactions"));
} else {
let errors = verify_pact(&provider_info, &filter, pact, &options, provider_state_executor).await;
for error in errors.clone() {
if pending {
pending_errors.push(error);
} else {
all_errors.push(error);
}
}
if options.publish {
publish_result(&errors, &pact_source, &options).await;
if !all_errors.is_empty() || !pending_errors.is_empty() {
display_notices(&context, VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_PUBLISH);
} else {
display_notices(&context, VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_PUBLISH);
}
} else {
if !all_errors.is_empty() || pending_errors.is_empty() {
display_notices(&context, VERIFICATION_NOTICE_AFTER_ERROR_RESULT_AND_NO_PUBLISH);
} else {
display_notices(&context, VERIFICATION_NOTICE_AFTER_SUCCESSFUL_RESULT_AND_NO_PUBLISH);
}
}
}
},
Err(err) => {
log::error!("Failed to load pact - {}", Red.paint(err.to_string()));
all_errors.push((s!("Failed to load pact"), MismatchResult::Error(err.to_string(), None)));
}
}
};
if !pending_errors.is_empty() {
println!("\nPending Failures:\n");
print_errors(&pending_errors);
println!("\nThere were {} non-fatal pact failures on pending pacts (see docs.pact.io/pending for more)\n", pending_errors.len());
}
if !all_errors.is_empty() {
println!("\nFailures:\n");
print_errors(&all_errors);
println!("\nThere were {} pact failures\n", all_errors.len());
false
} else {
true
}
}
fn print_errors(errors: &Vec<(String, MismatchResult)>) {
for (i, &(ref description, ref mismatch)) in errors.iter().enumerate() {
match *mismatch {
MismatchResult::Error(ref err, _) => println!("{}) {} - {}\n", i + 1, description, err),
MismatchResult::Mismatches { ref mismatches, ref expected, ref actual, .. } => {
println!("{}) {}", i + 1, description);
let mut j = 1;
for (_, mut mismatches) in &mismatches.into_iter().group_by(|m| m.mismatch_type()) {
let mismatch = mismatches.next().unwrap();
println!(" {}.{}) {}", i + 1, j, mismatch.summary());
println!(" {}", mismatch.ansi_description());
for mismatch in mismatches {
println!(" {}", mismatch.ansi_description());
}
if let Mismatch::BodyMismatch{ref path, ..} = mismatch {
display_body_mismatch(expected, actual, path);
}
j += 1;
}
}
}
}
}
async fn fetch_pact(source: PactSource) -> Vec<Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>> {
match source {
PactSource::File(ref file) => vec![read_pact(Path::new(&file))
.map_err(|err| format!("Failed to load pact '{}' - {}", file, err))
.map(|pact| (pact, None, source))],
PactSource::Dir(ref dir) => match walkdir(Path::new(dir)) {
Ok(pact_results) => pact_results.into_iter().map(|pact_result| {
match pact_result {
Ok(pact) => Ok((pact, None, source.clone())),
Err(err) => Err(format!("Failed to load pact from '{}' - {}", dir, err))
}
}).collect(),
Err(err) => vec![Err(format!("Could not load pacts from directory '{}' - {}", dir, err))]
},
PactSource::URL(ref url, ref auth) => vec![load_pact_from_url(url, auth)
.map_err(|err| format!("Failed to load pact '{}' - {}", url, err))
.map(|pact| (pact, None, source))],
PactSource::BrokerUrl(ref provider_name, ref broker_url, ref auth, _) => {
let result = pact_broker::fetch_pacts_from_broker(
broker_url.clone(),
provider_name.clone(),
auth.clone()
).await;
match result {
Ok(ref pacts) => {
let mut buffer = vec![];
for result in pacts.iter() {
match result {
Ok((pact, _, links)) => {
log::debug!("Got pact with links {:?}", links);
if let Ok(pact) = pact.as_request_response_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, None, PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
if let Ok(pact) = pact.as_message_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, None, PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
},
&Err(ref err) => buffer.push(Err(format!("Failed to load pact from '{}' - {:?}", broker_url, err)))
}
}
buffer
},
Err(err) => vec![Err(format!("Could not load pacts from the pact broker '{}' - {:?}", broker_url, err))]
}
},
PactSource::BrokerWithDynamicConfiguration { provider_name, broker_url, enable_pending, include_wip_pacts_since, provider_tags, selectors, auth, links: _ } => {
let result = pact_broker::fetch_pacts_dynamically_from_broker(
broker_url.clone(),
provider_name.clone(),
enable_pending,
include_wip_pacts_since,
provider_tags,
selectors,
auth.clone()
).await;
match result {
Ok(ref pacts) => {
let mut buffer = vec![];
for result in pacts.iter() {
match result {
Ok((pact, context, links)) => {
log::debug!("Got pact with links {:?}", links);
if let Ok(pact) = pact.as_request_response_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, context.clone(), PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
if let Ok(pact) = pact.as_message_pact() {
buffer.push(Ok((Box::new(pact) as Box<dyn Pact>, context.clone(), PactSource::BrokerUrl(provider_name.clone(), broker_url.clone(), auth.clone(), links.clone()))))
}
},
&Err(ref err) => buffer.push(Err(format!("Failed to load pact from '{}' - {:?}", broker_url, err)))
}
}
buffer
},
Err(err) => vec![Err(format!("Could not load pacts from the pact broker '{}' - {:?}", broker_url, err))]
}
},
_ => vec![Err("Could not load pacts, unknown pact source".to_string())]
}
}
async fn fetch_pacts(source: Vec<PactSource>, consumers: Vec<String>)
-> Vec<Result<(Box<dyn Pact>, Option<PactVerificationContext>, PactSource), String>> {
futures::stream::iter(source)
.then(|pact_source| async {
futures::stream::iter(fetch_pact(pact_source).await)
})
.flatten()
.filter(|res| futures::future::ready(filter_consumers(&consumers, res)))
.collect()
.await
}
async fn verify_pact<'a, F: RequestFilterExecutor, S: ProviderStateExecutor>(
provider_info: &ProviderInfo,
filter: &FilterInfo,
pact: Box<dyn Pact + 'a>,
options: &VerificationOptions<F>,
provider_state_executor: &S
) -> Vec<(String, MismatchResult)> {
let mut errors: Vec<(String, MismatchResult)> = vec![];
let results: Vec<(&dyn Interaction, Result<(), MismatchResult>)> = futures::stream::iter(
pact.interactions().iter().cloned()
)
.filter(|interaction| futures::future::ready(filter_interaction(*interaction, filter)))
.then( |interaction| async move {
verify_interaction(provider_info, interaction, options, provider_state_executor)
.then(|result| futures::future::ready((interaction, result)))
.await
})
.collect()
.await;
for (interaction, match_result) in results {
let mut description = format!("Verifying a pact between {} and {}",
pact.consumer().name.clone(), pact.provider().name.clone());
if let Some((first, elements)) = interaction.provider_states().split_first() {
description.push_str(&format!(" Given {}", first.name));
for state in elements {
description.push_str(&format!(" And {}", state.name));
}
}
description.push_str(" - ");
description.push_str(&interaction.description());
println!(" {}", interaction.description());
if let Some(interaction) = interaction.as_request_response() {
display_request_response_result(&mut errors, &interaction, &match_result, &description)
}
if let Some(interaction) = interaction.as_message() {
display_message_result(&mut errors, &interaction, &match_result, &description)
}
}
println!();
errors
}
async fn publish_result<F: RequestFilterExecutor>(
errors: &[(String, MismatchResult)],
source: &PactSource,
options: &VerificationOptions<F>
) {
if let PactSource::BrokerUrl(_, broker_url, auth, links) = source.clone() {
log::info!("Publishing verification results back to the Pact Broker");
let result = if errors.is_empty() {
log::debug!("Publishing a successful result to {}", source);
TestResult::Ok
} else {
log::debug!("Publishing a failure result to {}", source);
TestResult::Failed(Vec::from(errors))
};
let provider_version = options.provider_version.clone().unwrap();
let publish_result = publish_verification_results(
links,
broker_url.clone(),
auth.clone(),
result,
provider_version,
options.build_url.clone(),
options.provider_tags.clone()
).await;
match publish_result {
Ok(_) => log::info!("Results published to Pact Broker"),
Err(ref err) => log::error!("Publishing of verification results failed with an error: {}", err)
};
}
}
#[cfg(test)]
mod tests;
|
use std::cell::RefCell;
use std::rc::Rc;
use super::client::Client;
use super::ipv4_packet::IPv4Packet;
use super::route::{Route, RouteKey};
const TAG: &'static str = "Router";
pub struct Router {
client: Rc<RefCell<Client>>,
routes: Vec<Route>,
}
impl Router {
pub fn send_to_network(&mut self, ipv4_packet: &IPv4Packet) {
if !ipv4_packet.is_valid() {
warn!(target: TAG, "Dropping invalid packet");
}
// TODO
}
fn get_route_for(&mut self, ipv4_packet: &IPv4Packet) -> usize {
let key = RouteKey::from_packet(ipv4_packet);
match self.find_route_index(&key) {
Some(index) => index,
None => {
let route = Route::new(&self.client, key, ipv4_packet);
let index = self.routes.len();
self.routes.push(route);
index
}
}
}
fn find_route_index(&self, key: &RouteKey) -> Option<usize> {
None
}
}
Improve Router skeleton
use std::cell::RefCell;
use std::rc::Rc;
use log::LogLevel;
use super::client::Client;
use super::ipv4_packet::IPv4Packet;
use super::route::{Route, RouteKey};
const TAG: &'static str = "Router";
pub struct Router {
client: Rc<RefCell<Client>>,
routes: Vec<Route>,
}
impl Router {
pub fn send_to_network(&mut self, ipv4_packet: &IPv4Packet) {
if !ipv4_packet.is_valid() {
warn!(target: TAG, "Dropping invalid packet");
if log_enabled!(target: TAG, LogLevel::Trace) {
// TODO log binary
}
} else {
let route = self.get_route(ipv4_packet);
// route.send_to_network(ipv4_packet);
}
}
fn get_route(&mut self, ipv4_packet: &IPv4Packet) -> &Route {
let key = RouteKey::from_packet(ipv4_packet);
let index = match self.find_route_index(&key) {
Some(index) => index,
None => {
let route = Route::new(&self.client, key, ipv4_packet);
let index = self.routes.len();
self.routes.push(route);
index
}
};
self.routes.get(index).unwrap()
}
fn find_route_index(&self, key: &RouteKey) -> Option<usize> {
None
}
}
|
//! Implementation of a Micro Transport Protocol library.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
//!
//! TODO
//! ----
//!
//! - congestion control
//! - proper connection closing
//! - automatically send FIN (or should it be RST?) on `drop` if not already closed
//! - setters and getters that hide header field endianness conversion
//! - SACK extension
//! - handle packet loss
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacketHeader {
UtpPacketHeader {
wnd_size: new_wnd_size.to_be(),
.. self.clone()
}
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: self.header.wnd_size(new_wnd_size),
payload: self.payload.clone(),
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_buffer: Vec<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE).wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(resp.bytes().as_slice(), $src));
debug!("sent {}", resp.header);
})
)
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.send_to(packet.bytes().as_slice(), dst);
debug!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..BUF_SIZE];
let (_len, addr) = match self.socket.recv_from(buf) {
Ok(v) => v,
Err(e) => fail!("{}", e),
};
assert!(_len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(_len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an incorrect reply",
detail: None,
});
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
debug!("connected to: {} {}", addr, self.connected_to);
self.state = CS_CONNECTED;
self.seq_nr += 1;
Ok(self)
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
let dst = self.connected_to;
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {}", packet);
self.state = CS_FIN_SENT;
// Receive JAKE
let mut buf = [0u8, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
debug!("received {}", resp);
assert!(resp.get_type() == ST_STATE);
// Set socket state
self.state = CS_CLOSED;
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed, TimedOut};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
use std::io::{IoError, ConnectionReset};
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// TODO: move this to handle_packet?
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
// Check if the packet is out of order (that is, it's sequence number
// does not immediately follow the ACK number)
if packet.get_type() != ST_STATE && packet.get_type() != ST_SYN
&& self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, Int::from_be(packet.header.seq_nr));
// Add to buffer but do not acknowledge until all packets between
// ack_nr + 1 and curr_packet.seq_nr - 1 are received
self.insert_into_buffer(packet);
return Ok((0, self.connected_to));
}
match self.handle_packet(packet.clone()) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
for i in range(0u, min(buf.len(), read - HEADER_SIZE)) {
buf[i] = b[i + HEADER_SIZE];
}
// Empty buffer if possible
let mut read = read - HEADER_SIZE;
while !self.incoming_buffer.is_empty() &&
self.ack_nr + 1 == Int::from_be(self.incoming_buffer[0].header.seq_nr) {
let packet = self.incoming_buffer.shift().unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[read] = packet.payload[i];
read += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Send data on socket to the given address. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
debug!("Pushing packet into send buffer: {}", packet);
self.send_buffer.push(packet.clone());
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
self.seq_nr += 1;
}
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => Some(self.prepare_reply(&packet.header, ST_STATE)),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.header.ack_nr == Int::from_be(self.last_acked) {
self.duplicate_ack_count += 1;
} else {
self.last_acked = Int::from_be(packet.header.ack_nr);
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_buffer.is_empty() && self.duplicate_ack_count == 3 {
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1) {
None => fail!("Received request to resend packets since {} but none was found in send buffer!", Int::from_be(packet.header.ack_nr) + 1),
Some(position) => {
for _ in range(0u, position + 1) {
let to_send = self.send_buffer.shift().unwrap();
debug!("resending: {}", to_send);
self.socket.send_to(to_send.bytes().as_slice(), self.connected_to);
}
},
}
}
// Success, advance send window
while !self.send_buffer.is_empty() &&
Int::from_be(self.send_buffer[0].header.seq_nr) <= self.last_acked {
self.send_buffer.shift();
}
None
},
ST_RESET => { // TODO
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
self.incoming_buffer.insert(i, packet);
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 500,
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
self.socket.send_to(buf, dst)
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::Closed;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf, clientAddr) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
use std::io::test::next_test_ip4;
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
use super::UtpStream;
use std::io::test::next_test_ip4;
let serverAddr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(serverAddr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use super::UtpStream;
use std::io::test::next_test_ip4;
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
use std::io::test::next_test_ip4;
use super::UtpStream;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
let mut i = 0;
for data in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet);
i += 1;
}
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 2).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[3].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[4].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::test::next_test_ip4;
use std::io::net::udp::UdpSocket;
use super::UtpSocket;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UdpSocket::bind(clientAddr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = Int::from_be(test_syn_pkt.header.seq_nr);
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, serverAddr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
iotry!(client.send_to(d.as_slice(), serverAddr));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (Int::from_be(data_packet.header.seq_nr) - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), clientAddr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(Int::from_be(packet.header.seq_nr), Int::from_be(data_packet.header.seq_nr));
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
iotry!(client.send_to(d.as_slice(), serverAddr));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
}
Small cleanup.
//! Implementation of a Micro Transport Protocol library.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
//!
//! TODO
//! ----
//!
//! - congestion control
//! - proper connection closing
//! - automatically send FIN (or should it be RST?) on `drop` if not already closed
//! - setters and getters that hide header field endianness conversion
//! - SACK extension
//! - handle packet loss
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacketHeader {
UtpPacketHeader {
wnd_size: new_wnd_size.to_be(),
.. self.clone()
}
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: self.header.wnd_size(new_wnd_size),
payload: self.payload.clone(),
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_buffer: Vec<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE).wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(resp.bytes().as_slice(), $src));
debug!("sent {}", resp.header);
})
)
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.send_to(packet.bytes().as_slice(), dst);
debug!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..BUF_SIZE];
let (_len, addr) = match self.socket.recv_from(buf) {
Ok(v) => v,
Err(e) => fail!("{}", e),
};
assert!(_len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(_len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an incorrect reply",
detail: None,
});
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
debug!("connected to: {} {}", addr, self.connected_to);
self.state = CS_CONNECTED;
self.seq_nr += 1;
Ok(self)
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
let dst = self.connected_to;
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {}", packet);
self.state = CS_FIN_SENT;
// Receive JAKE
let mut buf = [0u8, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
debug!("received {}", resp);
assert!(resp.get_type() == ST_STATE);
// Set socket state
self.state = CS_CLOSED;
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed, TimedOut, ConnectionReset};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// TODO: move this to handle_packet?
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
// Check if the packet is out of order (that is, it's sequence number
// does not immediately follow the ACK number)
if packet.get_type() != ST_STATE && packet.get_type() != ST_SYN
&& self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, Int::from_be(packet.header.seq_nr));
// Add to buffer but do not acknowledge until all packets between
// ack_nr + 1 and curr_packet.seq_nr - 1 are received
self.insert_into_buffer(packet);
return Ok((0, self.connected_to));
}
match self.handle_packet(packet.clone()) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
for i in range(0u, min(buf.len(), read - HEADER_SIZE)) {
buf[i] = b[i + HEADER_SIZE];
}
// Empty buffer if possible
let mut read = read - HEADER_SIZE;
while !self.incoming_buffer.is_empty() &&
self.ack_nr + 1 == Int::from_be(self.incoming_buffer[0].header.seq_nr) {
let packet = self.incoming_buffer.shift().unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[read] = packet.payload[i];
read += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Send data on socket to the given address. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
debug!("Pushing packet into send buffer: {}", packet);
self.send_buffer.push(packet.clone());
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
self.seq_nr += 1;
}
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => Some(self.prepare_reply(&packet.header, ST_STATE)),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.header.ack_nr == Int::from_be(self.last_acked) {
self.duplicate_ack_count += 1;
} else {
self.last_acked = Int::from_be(packet.header.ack_nr);
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_buffer.is_empty() && self.duplicate_ack_count == 3 {
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1) {
None => fail!("Received request to resend packets since {} but none was found in send buffer!", Int::from_be(packet.header.ack_nr) + 1),
Some(position) => {
for _ in range(0u, position + 1) {
let to_send = self.send_buffer.shift().unwrap();
debug!("resending: {}", to_send);
self.socket.send_to(to_send.bytes().as_slice(), self.connected_to);
}
},
}
}
// Success, advance send window
while !self.send_buffer.is_empty() &&
Int::from_be(self.send_buffer[0].header.seq_nr) <= self.last_acked {
self.send_buffer.shift();
}
None
},
ST_RESET => { // TODO
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
self.incoming_buffer.insert(i, packet);
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 500,
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
self.socket.send_to(buf, dst)
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::Closed;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf, clientAddr) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
use std::io::test::next_test_ip4;
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
use super::UtpStream;
use std::io::test::next_test_ip4;
let serverAddr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(serverAddr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use super::UtpStream;
use std::io::test::next_test_ip4;
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
use std::io::test::next_test_ip4;
use super::UtpStream;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
let mut i = 0;
for data in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet);
i += 1;
}
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 2).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[3].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[4].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::test::next_test_ip4;
use std::io::net::udp::UdpSocket;
use super::UtpSocket;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UdpSocket::bind(clientAddr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = Int::from_be(test_syn_pkt.header.seq_nr);
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, serverAddr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
iotry!(client.send_to(d.as_slice(), serverAddr));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (Int::from_be(data_packet.header.seq_nr) - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), clientAddr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(Int::from_be(packet.header.seq_nr), Int::from_be(data_packet.header.seq_nr));
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
iotry!(client.send_to(d.as_slice(), serverAddr));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
}
|
//! Implementation of the Micro Transport Protocol.[^spec]
//!
//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html
// __________ ____ ____
// /_ __/ __ \/ __ \/ __ \
// / / / / / / / / / / / /
// / / / /_/ / /_/ / /_/ /
// /_/ \____/_____/\____/
//
// - Lossy UDP socket for testing purposes: send and receive ops are wrappers
// that stochastically drop or reorder packets.
// - Congestion control (LEDBAT -- RFC6817)
// - Sending FIN on drop
// - Setters and getters that hide header field endianness conversion
// - Handle packet loss
// - Path MTU discovery (RFC4821)
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
use std::collections::{DList, Deque};
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
/// Lazy iterator over bits of a vector of bytes, starting with the LSB
/// (least-significat bit) of the first element of the vector.
struct BitIterator { object: Vec<u8>, current_byte: uint, current_bit: uint }
impl BitIterator {
fn new(obj: Vec<u8>) -> BitIterator {
BitIterator { object: obj, current_byte: 0, current_bit: 0 }
}
}
impl Iterator<u8> for BitIterator {
fn next(&mut self) -> Option<u8> {
let result = self.object[self.current_byte] >> self.current_bit & 0x1;
if self.current_bit + 1 == std::u8::BITS {
self.current_byte += 1;
}
self.current_bit = (self.current_bit + 1) % std::u8::BITS;
if self.current_byte == self.object.len() {
return None;
} else {
return Some(result);
}
}
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[deriving(PartialEq,Eq,Show,Clone)]
enum UtpExtensionType {
SelectiveAckExtension = 1,
}
#[deriving(Clone)]
struct UtpExtension {
ty: UtpExtensionType,
data: Vec<u8>,
}
impl UtpExtension {
fn len(&self) -> uint {
1 + self.data.len()
}
fn to_bytes(&self) -> Vec<u8> {
(vec!(self.data.len() as u8)).append(self.data.as_slice())
}
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
extensions: Vec<UtpExtension>,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
extensions: Vec::new(),
payload: Vec::new(),
}
}
#[inline]
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
#[inline]
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
#[inline(always)]
fn seq_nr(&self) -> u16 {
Int::from_be(self.header.seq_nr)
}
#[inline(always)]
fn ack_nr(&self) -> u16 {
Int::from_be(self.header.ack_nr)
}
#[inline(always)]
fn connection_id(&self) -> u16 {
Int::from_be(self.header.connection_id)
}
#[inline]
fn set_wnd_size(&mut self, new_wnd_size: u32) {
self.header.wnd_size = new_wnd_size.to_be();
}
fn wnd_size(&self) -> u32 {
Int::from_be(self.header.wnd_size)
}
/// Set Selective ACK field in packet header and add appropriate data.
///
/// If None is passed, the SACK extension is disabled and the respective
/// data is flushed. Otherwise, the SACK extension is enabled and the
/// vector `v` is taken as the extension's payload.
///
/// The length of the SACK extension is expressed in bytes, which
/// must be a multiple of 4 and at least 4.
fn set_sack(&mut self, v: Option<Vec<u8>>) {
match v {
None => {
self.header.extension = 0;
self.extensions = Vec::new();
},
Some(bv) => {
// The length of the SACK extension is expressed in bytes, which
// must be a multiple of 4 and at least 4.
assert!(bv.len() >= 4);
assert!(bv.len() % 4 == 0);
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: bv,
};
self.extensions.push(extension);
self.header.extension |= SelectiveAckExtension as u8;
}
}
}
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
for extension in self.extensions.iter() {
buf.push(0u8); // next extension id
buf.push_all(extension.to_bytes().as_slice());
}
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
let ext_len = self.extensions.iter().fold(0, |acc, ext| acc + ext.len() + 1);
self.header.len() + self.payload.len() + ext_len
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
let header = UtpPacketHeader::decode(buf);
let mut extensions = Vec::new();
let mut idx = HEADER_SIZE;
let mut kind = header.extension;
// Consume known extensions and skip over unknown ones
while idx < buf.len() && kind != 0 {
let len = buf[idx + 1] as uint;
let extension_start = idx + 2;
let payload_start = extension_start + len;
if kind == SelectiveAckExtension as u8 { // or more generally, a known kind
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: Vec::from_slice(buf.slice(extension_start, payload_start)),
};
extensions.push(extension);
}
kind = buf[idx];
idx += payload_start;
}
let mut payload;
if idx < buf.len() {
payload = Vec::from_slice(buf.slice_from(idx));
} else {
payload = Vec::new();
}
UtpPacket {
header: header,
extensions: extensions,
payload: payload,
}
}
/// Return a clone of this object without the payload
fn shallow_clone(&self) -> UtpPacket {
UtpPacket {
header: self.header.clone(),
extensions: self.extensions.clone(),
payload: Vec::new(),
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_window: Vec<UtpPacket>,
unsent_queue: DList<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
pending_data: Vec<u8>,
max_window: uint,
curr_window: uint,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: DList::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
pending_data: Vec::new(),
max_window: 0,
curr_window: 0,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
let mut len = 0;
let mut addr = self.connected_to;
let mut buf = [0, ..BUF_SIZE];
for _ in range(0u, 5) {
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
try!(self.socket.send_to(packet.bytes().as_slice(), other));
self.state = CS_SYN_SENT;
// Validate response
self.socket.set_read_timeout(Some(500));
match self.socket.recv_from(buf) {
Ok((read, src)) => { len = read; addr = src; break; },
Err(ref e) if e.kind == std::io::TimedOut => continue,
Err(e) => fail!("{}", e),
};
}
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
self.ack_nr = packet.seq_nr();
self.state = CS_CONNECTED;
self.seq_nr += 1;
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8, ..BUF_SIZE];
while !self.send_window.is_empty() {
match self.recv_from(buf) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = CS_FIN_SENT;
// Receive JAKE
while self.state != CS_CLOSED {
match self.recv_from(buf) {
Ok(_) => {},
Err(ref e) if e.kind == std::io::EndOfFile => self.state = CS_CLOSED,
Err(e) => fail!("{}", e),
};
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::io::{IoError, EndOfFile, Closed};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
match self.flush_incoming_buffer(buf, 0) {
0 => self.recv(buf),
read => Ok((read, self.connected_to)),
}
}
fn recv(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::io::{IoError, TimedOut, ConnectionReset};
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
if self.state != CS_NEW {
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
}
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
let shallow_clone = packet.shallow_clone();
if packet.get_type() == ST_DATA && self.ack_nr < packet.seq_nr() {
self.insert_into_buffer(packet);
}
match self.handle_packet(shallow_clone) {
Some(pkt) => {
let mut pkt = pkt;
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf, 0);
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8], start: uint) -> uint {
let mut idx = start;
if !self.pending_data.is_empty() {
let len = buf.copy_from(self.pending_data.as_slice());
if len == self.pending_data.len() {
self.pending_data.clear();
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
self.ack_nr = packet.seq_nr();
return idx + len;
} else {
self.pending_data = Vec::from_slice(self.pending_data.slice_from(len));
idx += len;
}
}
while !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr()) {
for i in range(0u, self.incoming_buffer[0].payload.len()) {
if idx < buf.len() {
buf[idx] = self.incoming_buffer[0].payload[i];
} else {
self.pending_data.push(self.incoming_buffer[0].payload[i]);
}
idx += 1;
}
if idx >= buf.len() {
return buf.len();
}
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
self.ack_nr = packet.seq_nr();
}
return idx;
}
/// Send data on socket to the remote peer. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8]) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
self.unsent_queue.push(packet);
self.seq_nr += 1;
}
// Flush unsent packet queue
self.send();
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
/// Send every packet in the unsent packet queue.
fn send(&mut self) {
let dst = self.connected_to;
loop {
while self.send_window.len() > 100 {
let mut buf = [0, ..BUF_SIZE];
self.recv_from(buf);
}
let packet = match self.unsent_queue.pop_front() {
None => break,
Some(packet) => packet,
};
match self.socket.send_to(packet.bytes().as_slice(), dst) {
Ok(_) => {},
Err(ref e) => fail!("{}", e),
}
debug!("sent {}", packet);
self.curr_window += packet.len();
self.send_window.push(packet);
}
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8]) -> IoResult<()> {
self.send_to(buf)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == packet.seq_nr() {
self.ack_nr = packet.seq_nr();
}
self.max_window = packet.wnd_size() as uint;
debug!("self.max_window: {}", self.max_window);
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = packet.seq_nr();
self.seq_nr = random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => {
let mut reply = self.prepare_reply(&packet.header, ST_STATE);
if self.ack_nr + 1 < packet.seq_nr() {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let mut stashed = self.incoming_buffer.iter()
.map(|pkt| pkt.seq_nr())
.filter(|&seq_nr| seq_nr > self.ack_nr);
let mut sack = Vec::new();
for seq_nr in stashed {
let diff = seq_nr - self.ack_nr - 2;
let byte = (diff / 8) as uint;
let bit = (diff % 8) as uint;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.grow((len / 4 + 1) * 4 - len, &0);
}
if sack.len() > 0 {
reply.set_sack(Some(sack));
}
}
Some(reply)
},
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// If all packets are received and handled
if self.pending_data.is_empty() &&
self.incoming_buffer.is_empty() &&
self.ack_nr == packet.seq_nr()
{
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
} else {
debug!("FIN received but there are missing packets");
None
}
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.ty == SelectiveAckExtension {
let bits = BitIterator::new(extension.data.clone());
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
let packet = self.send_window.iter().find(|pkt| pkt.seq_nr() == packet.ack_nr() + 1).unwrap();
debug!("sending {}", packet);
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
}
let bits = BitIterator::new(extension.data.clone());
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = packet.ack_nr() + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if seq_nr < self.seq_nr {
debug!("SACK: packet {} lost", seq_nr);
match self.send_window.iter().find(|pkt| pkt.seq_nr() == seq_nr) {
None => debug!("Packet {} not found", seq_nr),
Some(packet) => {
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet);
}
}
} else {
break;
}
}
} else {
debug!("Unknown extension {}, ignoring", extension.ty);
}
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 {
for packet in self.send_window.iter().take_while(|pkt| pkt.seq_nr() <= packet.ack_nr() + 1) {
debug!("resending: {}", packet);
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
// Success, advance send window
match self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
None => (),
Some(position) => {
for _ in range(0, position + 1) {
let packet = self.send_window.remove(0).unwrap();
self.curr_window -= packet.len();
}
}
}
debug!("self.curr_window: {}", self.curr_window);
if self.state == CS_FIN_SENT &&
packet.ack_nr() == self.seq_nr {
self.state = CS_CLOSED;
}
None
},
ST_RESET => {
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if pkt.seq_nr() >= packet.seq_nr() {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].header.seq_nr == packet.header.seq_nr {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.socket.send_to(buf)
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket, UtpStream};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
use std::io::test::next_test_ip4;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(pkt.connection_id(), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(pkt.seq_nr(), 15090);
assert_eq!(pkt.ack_nr(), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_decode_packet_with_extension() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(packet.connection_id(), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(packet.seq_nr(), 43859);
assert_eq!(packet.ack_nr(), 15093);
assert_eq!(packet.len(), buf.len());
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_decode_packet_with_unknown_extensions() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0xff, 0x04, 0x00, 0x00, 0x00, 0x00, // Imaginary extension
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(packet.connection_id(), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(packet.seq_nr(), 43859);
assert_eq!(packet.ack_nr(), 15093);
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, server_addr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::{Closed, EndOfFile};
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::Closed;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(client_addr));
let server = iotry!(UtpSocket::bind(server_addr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(server_addr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
for (i, data) in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3).enumerate() {
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
}
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(window[3].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[2].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[1].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[0].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[4].bytes().as_slice(), server_addr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::net::udp::UdpSocket;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UdpSocket::bind(client_addr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = test_syn_pkt.seq_nr();
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, server_addr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(d.as_slice()));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (data_packet.seq_nr() - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), client_addr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(d.as_slice()));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Set a much smaller than usual timeout, for quicker test completion
server.timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = UtpPacket::new();
packet.header.seq_nr = 1;
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 128;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 128);
packet.header.seq_nr = 3;
packet.header.timestamp_microseconds = 256;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].header.seq_nr, 3);
assert_eq!(socket.incoming_buffer[2].header.timestamp_microseconds, 256);
// Replace a packet with a more recent version
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 456;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in range(0u, 2) {
packet.header.timestamp_microseconds = super::now_microseconds();
iotry!(s.send_to(packet.bytes().as_slice(), server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in range(0u, 1) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
iotry!(client.close());
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1,2,3);
match stream.read_to_end() {
Ok(data) => {
println!("{}", data);
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_selective_ack_response() {
let server_addr = next_test_ip4();
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
// Client
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
client.socket.timeout = 50;
// Stream.write
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(server_addr));
let mut buf = [0, ..BUF_SIZE];
// Connect
iotry!(server.recv_from(buf));
// Discard packets
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
// Generate SACK
let mut packet = UtpPacket::new();
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (server.ack_nr - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.set_type(ST_STATE);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut stream = UtpStream { socket: server };
let read = iotry!(stream.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_correct_packet_loss() {
let (client_addr, server_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpStream::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = UtpPacket::new();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.payload = Vec::from_slice(chunk);
packet.set_type(ST_DATA);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
use std::io::EndOfFile;
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
let len = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != CS_CLOSED {
let mut small_buffer = [0, ..512];
match server.recv_from(small_buffer) {
Ok((0, _src)) => (),
Ok((len, _src)) => read.push_all(small_buffer.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => fail!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
}
Slightly cleaned up code.
//! Implementation of the Micro Transport Protocol.[^spec]
//!
//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html
// __________ ____ ____
// /_ __/ __ \/ __ \/ __ \
// / / / / / / / / / / / /
// / / / /_/ / /_/ / /_/ /
// /_/ \____/_____/\____/
//
// - Lossy UDP socket for testing purposes: send and receive ops are wrappers
// that stochastically drop or reorder packets.
// - Congestion control (LEDBAT -- RFC6817)
// - Sending FIN on drop
// - Setters and getters that hide header field endianness conversion
// - Handle packet loss
// - Path MTU discovery (RFC4821)
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
use std::collections::{DList, Deque};
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
/// Lazy iterator over bits of a vector of bytes, starting with the LSB
/// (least-significat bit) of the first element of the vector.
struct BitIterator { object: Vec<u8>, current_byte: uint, current_bit: uint }
impl BitIterator {
fn new(obj: Vec<u8>) -> BitIterator {
BitIterator { object: obj, current_byte: 0, current_bit: 0 }
}
}
impl Iterator<u8> for BitIterator {
fn next(&mut self) -> Option<u8> {
let result = self.object[self.current_byte] >> self.current_bit & 0x1;
if self.current_bit + 1 == std::u8::BITS {
self.current_byte += 1;
}
self.current_bit = (self.current_bit + 1) % std::u8::BITS;
if self.current_byte == self.object.len() {
return None;
} else {
return Some(result);
}
}
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[deriving(PartialEq,Eq,Show,Clone)]
enum UtpExtensionType {
SelectiveAckExtension = 1,
}
#[deriving(Clone)]
struct UtpExtension {
ty: UtpExtensionType,
data: Vec<u8>,
}
impl UtpExtension {
fn len(&self) -> uint {
1 + self.data.len()
}
fn to_bytes(&self) -> Vec<u8> {
(vec!(self.data.len() as u8)).append(self.data.as_slice())
}
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
extensions: Vec<UtpExtension>,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
extensions: Vec::new(),
payload: Vec::new(),
}
}
#[inline]
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
#[inline]
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
#[inline(always)]
fn seq_nr(&self) -> u16 {
Int::from_be(self.header.seq_nr)
}
#[inline(always)]
fn ack_nr(&self) -> u16 {
Int::from_be(self.header.ack_nr)
}
#[inline(always)]
fn connection_id(&self) -> u16 {
Int::from_be(self.header.connection_id)
}
#[inline]
fn set_wnd_size(&mut self, new_wnd_size: u32) {
self.header.wnd_size = new_wnd_size.to_be();
}
fn wnd_size(&self) -> u32 {
Int::from_be(self.header.wnd_size)
}
/// Set Selective ACK field in packet header and add appropriate data.
///
/// If None is passed, the SACK extension is disabled and the respective
/// data is flushed. Otherwise, the SACK extension is enabled and the
/// vector `v` is taken as the extension's payload.
///
/// The length of the SACK extension is expressed in bytes, which
/// must be a multiple of 4 and at least 4.
fn set_sack(&mut self, v: Option<Vec<u8>>) {
match v {
None => {
self.header.extension = 0;
self.extensions = Vec::new();
},
Some(bv) => {
// The length of the SACK extension is expressed in bytes, which
// must be a multiple of 4 and at least 4.
assert!(bv.len() >= 4);
assert!(bv.len() % 4 == 0);
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: bv,
};
self.extensions.push(extension);
self.header.extension |= SelectiveAckExtension as u8;
}
}
}
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
for extension in self.extensions.iter() {
buf.push(0u8); // next extension id
buf.push_all(extension.to_bytes().as_slice());
}
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
let ext_len = self.extensions.iter().fold(0, |acc, ext| acc + ext.len() + 1);
self.header.len() + self.payload.len() + ext_len
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
let header = UtpPacketHeader::decode(buf);
let mut extensions = Vec::new();
let mut idx = HEADER_SIZE;
let mut kind = header.extension;
// Consume known extensions and skip over unknown ones
while idx < buf.len() && kind != 0 {
let len = buf[idx + 1] as uint;
let extension_start = idx + 2;
let payload_start = extension_start + len;
if kind == SelectiveAckExtension as u8 { // or more generally, a known kind
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: Vec::from_slice(buf.slice(extension_start, payload_start)),
};
extensions.push(extension);
}
kind = buf[idx];
idx += payload_start;
}
let mut payload;
if idx < buf.len() {
payload = Vec::from_slice(buf.slice_from(idx));
} else {
payload = Vec::new();
}
UtpPacket {
header: header,
extensions: extensions,
payload: payload,
}
}
/// Return a clone of this object without the payload
fn shallow_clone(&self) -> UtpPacket {
UtpPacket {
header: self.header.clone(),
extensions: self.extensions.clone(),
payload: Vec::new(),
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_window: Vec<UtpPacket>,
unsent_queue: DList<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
pending_data: Vec<u8>,
max_window: uint,
curr_window: uint,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_window: Vec::new(),
unsent_queue: DList::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
pending_data: Vec::new(),
max_window: 0,
curr_window: 0,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
let mut len = 0;
let mut addr = self.connected_to;
let mut buf = [0, ..BUF_SIZE];
for _ in range(0u, 5) {
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
try!(self.socket.send_to(packet.bytes().as_slice(), other));
self.state = CS_SYN_SENT;
// Validate response
self.socket.set_read_timeout(Some(500));
match self.socket.recv_from(buf) {
Ok((read, src)) => { len = read; addr = src; break; },
Err(ref e) if e.kind == std::io::TimedOut => continue,
Err(e) => fail!("{}", e),
};
}
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
self.ack_nr = packet.seq_nr();
self.state = CS_CONNECTED;
self.seq_nr += 1;
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8, ..BUF_SIZE];
while !self.send_window.is_empty() {
match self.recv_from(buf) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = CS_FIN_SENT;
// Receive JAKE
while self.state != CS_CLOSED {
match self.recv_from(buf) {
Ok(_) => {},
Err(ref e) if e.kind == std::io::EndOfFile => self.state = CS_CLOSED,
Err(e) => fail!("{}", e),
};
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::io::{IoError, EndOfFile, Closed};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
match self.flush_incoming_buffer(buf, 0) {
0 => self.recv(buf),
read => Ok((read, self.connected_to)),
}
}
fn recv(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::io::{IoError, TimedOut, ConnectionReset};
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
if self.state != CS_NEW {
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
}
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
let shallow_clone = packet.shallow_clone();
if packet.get_type() == ST_DATA && self.ack_nr < packet.seq_nr() {
self.insert_into_buffer(packet);
}
match self.handle_packet(shallow_clone) {
Some(pkt) => {
let mut pkt = pkt;
pkt.set_wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf, 0);
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8], start: uint) -> uint {
let mut idx = start;
if !self.pending_data.is_empty() {
let len = buf.clone_from_slice(self.pending_data.as_slice());
if len == self.pending_data.len() {
self.pending_data.clear();
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
self.ack_nr = packet.seq_nr();
return idx + len;
} else {
self.pending_data = Vec::from_slice(self.pending_data.slice_from(len));
}
}
while !self.incoming_buffer.is_empty() &&
(self.ack_nr == self.incoming_buffer[0].seq_nr() ||
self.ack_nr + 1 == self.incoming_buffer[0].seq_nr())
{
let len = std::cmp::min(buf.len() - idx, self.incoming_buffer[0].payload.len());
for i in range(0, len) {
buf[idx] = self.incoming_buffer[0].payload[i];
idx += 1;
}
if self.incoming_buffer[0].payload.len() == len {
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
self.ack_nr = packet.seq_nr();
} else {
self.pending_data.push_all(self.incoming_buffer[0].payload.slice_from(len));
}
if buf.len() == idx {
return idx;
}
}
return idx;
}
/// Send data on socket to the remote peer. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8]) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
self.unsent_queue.push(packet);
self.seq_nr += 1;
}
// Flush unsent packet queue
self.send();
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
/// Send every packet in the unsent packet queue.
fn send(&mut self) {
let dst = self.connected_to;
loop {
while self.send_window.len() > 100 {
let mut buf = [0, ..BUF_SIZE];
self.recv_from(buf);
}
let packet = match self.unsent_queue.pop_front() {
None => break,
Some(packet) => packet,
};
match self.socket.send_to(packet.bytes().as_slice(), dst) {
Ok(_) => {},
Err(ref e) => fail!("{}", e),
}
debug!("sent {}", packet);
self.curr_window += packet.len();
self.send_window.push(packet);
}
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8]) -> IoResult<()> {
self.send_to(buf)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(packet.connection_id() == self.sender_connection_id ||
packet.connection_id() == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == packet.seq_nr() {
self.ack_nr = packet.seq_nr();
}
self.max_window = packet.wnd_size() as uint;
debug!("self.max_window: {}", self.max_window);
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = packet.seq_nr();
self.seq_nr = random();
self.receiver_connection_id = packet.connection_id() + 1;
self.sender_connection_id = packet.connection_id();
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => {
let mut reply = self.prepare_reply(&packet.header, ST_STATE);
if self.ack_nr + 1 < packet.seq_nr() {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, packet.seq_nr());
// Set SACK extension payload if the packet is not in order
let mut stashed = self.incoming_buffer.iter()
.map(|pkt| pkt.seq_nr())
.filter(|&seq_nr| seq_nr > self.ack_nr);
let mut sack = Vec::new();
for seq_nr in stashed {
let diff = seq_nr - self.ack_nr - 2;
let byte = (diff / 8) as uint;
let bit = (diff % 8) as uint;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.grow((len / 4 + 1) * 4 - len, &0);
}
if sack.len() > 0 {
reply.set_sack(Some(sack));
}
}
Some(reply)
},
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// If all packets are received and handled
if self.pending_data.is_empty() &&
self.incoming_buffer.is_empty() &&
self.ack_nr == packet.seq_nr()
{
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
} else {
debug!("FIN received but there are missing packets");
None
}
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.ack_nr() == self.last_acked {
self.duplicate_ack_count += 1;
} else {
self.last_acked = packet.ack_nr();
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.ty == SelectiveAckExtension {
let bits = BitIterator::new(extension.data.clone());
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
let packet = self.send_window.iter().find(|pkt| pkt.seq_nr() == packet.ack_nr() + 1).unwrap();
debug!("sending {}", packet);
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
}
let bits = BitIterator::new(extension.data.clone());
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = packet.ack_nr() + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if seq_nr < self.seq_nr {
debug!("SACK: packet {} lost", seq_nr);
match self.send_window.iter().find(|pkt| pkt.seq_nr() == seq_nr) {
None => debug!("Packet {} not found", seq_nr),
Some(packet) => {
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet);
}
}
} else {
break;
}
}
} else {
debug!("Unknown extension {}, ignoring", extension.ty);
}
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_window.is_empty() && self.duplicate_ack_count == 3 {
for packet in self.send_window.iter().take_while(|pkt| pkt.seq_nr() <= packet.ack_nr() + 1) {
debug!("resending: {}", packet);
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
// Success, advance send window
match self.send_window.iter()
.position(|pkt| pkt.seq_nr() == self.last_acked)
{
None => (),
Some(position) => {
for _ in range(0, position + 1) {
let packet = self.send_window.remove(0).unwrap();
self.curr_window -= packet.len();
}
}
}
debug!("self.curr_window: {}", self.curr_window);
if self.state == CS_FIN_SENT &&
packet.ack_nr() == self.seq_nr {
self.state = CS_CLOSED;
}
None
},
ST_RESET => {
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if pkt.seq_nr() >= packet.seq_nr() {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].header.seq_nr == packet.header.seq_nr {
self.incoming_buffer.remove(i);
}
self.incoming_buffer.insert(i, packet);
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.socket.send_to(buf)
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket, UtpStream};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
use std::io::test::next_test_ip4;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(pkt.connection_id(), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(pkt.seq_nr(), 15090);
assert_eq!(pkt.ack_nr(), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_decode_packet_with_extension() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(packet.connection_id(), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(packet.seq_nr(), 43859);
assert_eq!(packet.ack_nr(), 15093);
assert_eq!(packet.len(), buf.len());
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_decode_packet_with_unknown_extensions() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0xff, 0x04, 0x00, 0x00, 0x00, 0x00, // Imaginary extension
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(packet.connection_id(), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(packet.seq_nr(), 43859);
assert_eq!(packet.ack_nr(), 15093);
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, server_addr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::{Closed, EndOfFile};
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::Closed;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(client_addr));
let server = iotry!(UtpSocket::bind(server_addr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(response.connection_id() == initial_connection_id);
assert!(response.connection_id() == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(response.ack_nr() == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(response.seq_nr() == old_response.seq_nr());
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == old_packet.seq_nr() + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
let server_addr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(server_addr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let server_addr = next_test_ip4();
let mut server = UtpStream::bind(server_addr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
// Establish connection
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (old_packet.seq_nr() + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
for (i, data) in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3).enumerate() {
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet.clone());
client.send_window.push(packet.clone());
client.seq_nr += 1;
}
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
client.seq_nr += 1;
iotry!(s.send_to(window[3].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[2].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[1].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[0].bytes().as_slice(), server_addr));
iotry!(s.send_to(window[4].bytes().as_slice(), server_addr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::net::udp::UdpSocket;
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UdpSocket::bind(client_addr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = test_syn_pkt.seq_nr();
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, server_addr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
iotry!(client.send_to(d.as_slice()));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (data_packet.seq_nr() - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), client_addr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(packet.seq_nr(), data_packet.seq_nr());
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, server_addr);
iotry!(client.send_to(d.as_slice()));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, client_addr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Set a much smaller than usual timeout, for quicker test completion
server.timeout = 50;
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let server_addr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(server_addr));
let mut packet = UtpPacket::new();
packet.header.seq_nr = 1;
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 128;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 128);
packet.header.seq_nr = 3;
packet.header.timestamp_microseconds = 256;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].header.seq_nr, 3);
assert_eq!(socket.incoming_buffer[2].header.timestamp_microseconds, 256);
// Replace a packet with a more recent version
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 456;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (server_addr, client_addr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(client_addr));
let mut server = iotry!(UtpSocket::bind(server_addr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut packet = UtpPacket::new();
packet.set_wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in range(0u, 2) {
packet.header.timestamp_microseconds = super::now_microseconds();
iotry!(s.send_to(packet.bytes().as_slice(), server_addr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in range(0u, 1) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
iotry!(client.close());
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1,2,3);
match stream.read_to_end() {
Ok(data) => {
println!("{}", data);
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_selective_ack_response() {
let server_addr = next_test_ip4();
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
// Client
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
client.socket.timeout = 50;
// Stream.write
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(server_addr));
let mut buf = [0, ..BUF_SIZE];
// Connect
iotry!(server.recv_from(buf));
// Discard packets
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
// Generate SACK
let mut packet = UtpPacket::new();
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (server.ack_nr - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.set_type(ST_STATE);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut stream = UtpStream { socket: server };
let read = iotry!(stream.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_correct_packet_loss() {
let (client_addr, server_addr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpStream::bind(server_addr));
let client = iotry!(UtpSocket::bind(client_addr));
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(client.connect(server_addr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = UtpPacket::new();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.payload = Vec::from_slice(chunk);
packet.set_type(ST_DATA);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.send_window.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
#[test]
fn test_tolerance_to_small_buffers() {
use std::io::EndOfFile;
let server_addr = next_test_ip4();
let mut server = iotry!(UtpSocket::bind(server_addr));
let len = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(UtpStream::connect(server_addr));
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
let mut read = Vec::new();
while server.state != CS_CLOSED {
let mut small_buffer = [0, ..512];
match server.recv_from(small_buffer) {
Ok((0, _src)) => (),
Ok((len, _src)) => read.push_all(small_buffer.slice_to(len)),
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => fail!("{}", e),
}
}
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
}
|
//! Implementation of the Micro Transport Protocol.[^spec]
//!
//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html
// __________ ____ ____
// /_ __/ __ \/ __ \/ __ \
// / / / / / / / / / / / /
// / / / /_/ / /_/ / /_/ /
// /_/ \____/_____/\____/
//
// - Lossy UDP socket for testing purposes: send and receive ops are wrappers
// that stochastically drop or reorder packets.
// - Congestion control (LEDBAT -- RFC6817)
// - Setters and getters that hide header field endianness conversion
// - Handle packet loss
// - Path MTU discovery (RFC4821)
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
/// Lazy iterator over bits of a vector of bytes, starting with the LSB
/// (least-significat bit) of the first element of the vector.
struct BitIterator { object: Vec<u8>, current_byte: uint, current_bit: uint }
impl BitIterator {
fn new(obj: Vec<u8>) -> BitIterator {
BitIterator { object: obj, current_byte: 0, current_bit: 0 }
}
}
impl Iterator<u8> for BitIterator {
fn next(&mut self) -> Option<u8> {
let result = self.object[self.current_byte] >> self.current_bit & 0x1;
if self.current_bit + 1 == std::u8::BITS {
self.current_byte += 1;
}
self.current_bit = (self.current_bit + 1) % std::u8::BITS;
if self.current_byte == self.object.len() {
return None;
} else {
return Some(result);
}
}
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[deriving(PartialEq,Eq,Show,Clone)]
enum UtpExtensionType {
SelectiveAckExtension = 1,
}
#[deriving(Clone)]
struct UtpExtension {
ty: UtpExtensionType,
data: Vec<u8>,
}
impl UtpExtension {
fn len(&self) -> uint {
1 + self.data.len()
}
fn to_bytes(&self) -> Vec<u8> {
(vec!(self.data.len() as u8)).append(self.data.as_slice())
}
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacketHeader {
UtpPacketHeader {
wnd_size: new_wnd_size.to_be(),
.. self.clone()
}
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
extensions: Vec<UtpExtension>,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
extensions: Vec::new(),
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: self.header.wnd_size(new_wnd_size),
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
/// Set Selective ACK field in packet header and add appropriate data.
///
/// If None is passed, the SACK extension is disabled and the respective
/// data is flushed. Otherwise, the SACK extension is enabled and the
/// vector `v` is taken as the extension's payload.
///
/// The length of the SACK extension is expressed in bytes, which
/// must be a multiple of 4 and at least 4.
fn set_sack(&mut self, v: Option<Vec<u8>>) {
match v {
None => {
self.header.extension = 0;
self.extensions = Vec::new();
},
Some(bv) => {
// The length of the SACK extension is expressed in bytes, which
// must be a multiple of 4 and at least 4.
assert!(bv.len() >= 4);
assert!(bv.len() % 4 == 0);
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: bv,
};
self.extensions.push(extension);
self.header.extension |= SelectiveAckExtension as u8;
}
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
for extension in self.extensions.iter() {
buf.push(0u8); // next extension id
buf.push_all(extension.to_bytes().as_slice());
}
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
let ext_len = self.extensions.iter().fold(0, |acc, ext| acc + ext.len() + 1);
self.header.len() + self.payload.len() + ext_len
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
let header = UtpPacketHeader::decode(buf);
let mut extensions = Vec::new();
let mut idx = HEADER_SIZE;
let mut kind = header.extension;
// Consume known extensions and skip over unknown ones
while idx < buf.len() && kind != 0 {
// Ignoring next extension type at buf[HEADER_SIZE]
let len = buf[idx + 1] as uint;
let extension_start = idx + 2;
let payload_start = extension_start + len;
if kind == SelectiveAckExtension as u8 { // or more generally, a known kind
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: Vec::from_slice(buf.slice(extension_start, payload_start)),
};
extensions.push(extension);
}
kind = buf[idx];
idx += payload_start;
}
let mut payload;
if idx < buf.len() {
payload = Vec::from_slice(buf.slice_from(idx));
} else {
payload = Vec::new();
}
UtpPacket {
header: header,
extensions: extensions,
payload: payload,
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_buffer: Vec<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
// Send packet
let mut buf = [0, ..BUF_SIZE];
let (len, addr) = try!(self.packet_send(&packet, buf));
self.state = CS_SYN_SENT;
// Validate response
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.state = CS_CONNECTED;
self.seq_nr += 1;
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Send `packet` and write reply to `buf`.
///
/// This method abstracts away the (send packet, receive acknowledgment)
/// cycle and deals with timeouts.
fn packet_send(&mut self, packet: &UtpPacket, buf: &mut [u8])
-> IoResult<(uint, SocketAddr)> {
use std::io::{IoError, TimedOut};
for _ in range(0u, 5) {
let dst = self.connected_to;
let mut packet = packet.clone();
packet.header.timestamp_microseconds = now_microseconds().to_be();
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {}", packet.header);
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
let (len, addr) = match self.socket.recv_from(buf) {
Ok(v) => v,
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
continue;
}
Err(e) => fail!("{}", e),
};
return Ok((len, addr));
}
return Err(IoError {
kind: TimedOut,
desc: "Connection timed out",
detail: None,
});
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8, ..BUF_SIZE];
while !self.send_buffer.is_empty() {
match self.recv_from(buf) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = CS_FIN_SENT;
// Receive JAKE
while self.state != CS_CLOSED {
match self.recv_from(buf) {
Ok(_) => {},
Err(ref e) if e.kind == std::io::EndOfFile => self.state = CS_CLOSED,
Err(e) => fail!("{}", e),
};
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed, TimedOut, ConnectionReset};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
debug!("setting read timeout of {} ms", self.timeout);
if self.state != CS_NEW {
self.socket.set_read_timeout(Some(self.timeout as u64));
}
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// TODO: move this to handle_packet?
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
// Copy received payload to output buffer if packet isn't a duplicate
let mut read = packet.payload.len();
if self.ack_nr < Int::from_be(packet.header.seq_nr) {
for i in range(0u, min(buf.len(), read)) {
buf[i] = b[i + HEADER_SIZE];
}
} else {
read = 0;
}
if self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
read = 0;
}
match self.handle_packet(packet) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf, read);
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8], start: uint) -> uint {
let mut idx = start;
while !self.incoming_buffer.is_empty() &&
self.ack_nr + 1 == Int::from_be(self.incoming_buffer[0].header.seq_nr) {
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[idx] = packet.payload[i];
idx += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
return idx;
}
/// Send data on socket to the given address. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
// FIXME: this is an extremely primitive pacing mechanism
while self.send_buffer.len() > 10 {
if self.duplicate_ack_count == 3 {
self.socket.send_to(self.send_buffer[0].bytes().as_slice(), self.connected_to.clone());
}
let mut buf = [0, ..BUF_SIZE];
try!(self.recv_from(buf));
}
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
debug!("Pushing packet into send buffer: {}", packet);
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
self.send_buffer.push(packet);
self.seq_nr += 1;
}
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => {
let mut reply = self.prepare_reply(&packet.header, ST_STATE);
if self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, Int::from_be(packet.header.seq_nr));
self.insert_into_buffer(packet.clone());
// Set SACK extension payload if the packet is not in order
let mut stashed = self.incoming_buffer.iter()
.map(|pkt| Int::from_be(pkt.header.seq_nr))
.filter(|&seq_nr| seq_nr > self.ack_nr);
let mut sack = Vec::new();
for seq_nr in stashed {
let diff = seq_nr - self.ack_nr - 2;
let byte = (diff / 8) as uint;
let bit = (diff % 8) as uint;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.grow((len / 4 + 1) * 4 - len, &0);
}
reply.set_sack(Some(sack));
}
Some(reply)
},
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.header.ack_nr == Int::from_be(self.last_acked) {
self.duplicate_ack_count += 1;
} else {
self.last_acked = Int::from_be(packet.header.ack_nr);
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.ty == SelectiveAckExtension {
let bits = BitIterator::new(extension.data.clone());
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
let packet = self.send_buffer.iter().find(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1).unwrap();
debug!("sending {}", packet);
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
}
let bits = BitIterator::new(extension.data.clone());
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = Int::from_be(packet.header.ack_nr) + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if seq_nr < self.seq_nr {
debug!("SACK: packet {} lost", seq_nr);
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == seq_nr) {
None => fail!("Packet {} not found", seq_nr),
Some(v) => {
let to_send = &self.send_buffer[v];
match self.socket.send_to(to_send.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", to_send);
}
}
} else {
break;
}
}
} else {
fail!("Unknown extension");
}
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_buffer.is_empty() && self.duplicate_ack_count == 3 {
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1) {
None => fail!("Received request to resend packets since {} but none was found in send buffer!", Int::from_be(packet.header.ack_nr) + 1),
Some(position) => {
for i in range(0u, position + 1) {
let ref to_send = self.send_buffer[i];
debug!("resending: {}", to_send);
match self.socket.send_to(to_send.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
},
}
}
// Success, advance send window
while !self.send_buffer.is_empty() &&
Int::from_be(self.send_buffer[0].header.seq_nr) <= self.last_acked {
self.send_buffer.remove(0);
}
if self.state == CS_FIN_SENT &&
Int::from_be(packet.header.ack_nr) == self.seq_nr {
self.state = CS_CLOSED;
}
None
},
ST_RESET => { // TODO
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].header.seq_nr == packet.header.seq_nr {
self.incoming_buffer.remove(i);
self.incoming_buffer.insert(i, packet);
} else {
self.incoming_buffer.insert(i, packet);
}
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 500,
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
match self.close() {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
self.socket.send_to(buf, dst)
}
}
impl Drop for UtpStream {
fn drop(&mut self) {
match self.close() {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket, UtpStream};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
use std::io::test::next_test_ip4;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_decode_packet_with_extension() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(Int::from_be(packet.header.connection_id), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(Int::from_be(packet.header.seq_nr), 43859);
assert_eq!(Int::from_be(packet.header.ack_nr), 15093);
assert_eq!(packet.len(), buf.len());
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::Closed;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf, clientAddr) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
let serverAddr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(serverAddr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut window: Vec<UtpPacket> = Vec::new();
let mut i = 0;
for data in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet.clone());
client.send_buffer.push(packet.clone());
i += 1;
}
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[3].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[4].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::net::udp::UdpSocket;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UdpSocket::bind(clientAddr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = Int::from_be(test_syn_pkt.header.seq_nr);
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, serverAddr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
let mut buf = [0, ..BUF_SIZE];
iotry!(client.recv_from(buf));
let packet = UtpPacket::decode(buf);
debug!("received {}", packet);
let mut reply = UtpPacket::new();
reply.header.seq_nr = (Int::from_be(UtpPacket::decode(test_syn_raw).header.seq_nr) + 1).to_be();
reply.header.ack_nr = packet.header.seq_nr;
reply.header.connection_id = packet.header.connection_id;
reply.set_type(ST_STATE);
iotry!(client.send_to(reply.bytes().as_slice(), serverAddr));
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
iotry!(client.send_to(d.as_slice(), serverAddr));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (Int::from_be(data_packet.header.seq_nr) - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), clientAddr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(Int::from_be(packet.header.seq_nr), Int::from_be(data_packet.header.seq_nr));
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
iotry!(client.send_to(d.as_slice(), serverAddr));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new();
packet.header.seq_nr = 1;
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 128;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 128);
packet.header.seq_nr = 3;
packet.header.timestamp_microseconds = 256;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].header.seq_nr, 3);
assert_eq!(socket.incoming_buffer[2].header.timestamp_microseconds, 256);
// Replace a packet with a more recent version
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 456;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in range(0u, 2) {
packet.header.timestamp_microseconds = super::now_microseconds();
iotry!(s.send_to(packet.bytes().as_slice(), serverAddr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in range(0u, 1) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
iotry!(client.close());
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1,2,3);
match stream.read_to_end() {
Ok(data) => {
println!("{}", data);
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_selective_ack_response() {
let serverAddr = next_test_ip4();
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
// Client
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
// Stream.write
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(serverAddr));
let mut buf = [0, ..BUF_SIZE];
// Connect
iotry!(server.recv_from(buf));
// Discard packets
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
// Generate SACK
let mut packet = UtpPacket::new();
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (server.ack_nr - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.set_type(ST_STATE);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut stream = UtpStream { socket: server };
let read = iotry!(stream.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_correct_packet_loss() {
let (clientAddr, serverAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpStream::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = UtpPacket::new();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.payload = Vec::from_slice(chunk);
packet.set_type(ST_DATA);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.send_buffer.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
}
Add test for decoding packets with unknown extensions.
//! Implementation of the Micro Transport Protocol.[^spec]
//!
//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html
// __________ ____ ____
// /_ __/ __ \/ __ \/ __ \
// / / / / / / / / / / / /
// / / / /_/ / /_/ / /_/ /
// /_/ \____/_____/\____/
//
// - Lossy UDP socket for testing purposes: send and receive ops are wrappers
// that stochastically drop or reorder packets.
// - Congestion control (LEDBAT -- RFC6817)
// - Setters and getters that hide header field endianness conversion
// - Handle packet loss
// - Path MTU discovery (RFC4821)
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
// For simplicity's sake, let us assume no packet will ever exceed the
// Ethernet maximum transfer unit of 1500 bytes.
static BUF_SIZE: uint = 1500;
macro_rules! u8_to_unsigned_be(
($src:ident[$start:expr..$end:expr] -> $t:ty) => ({
let mut result: $t = 0;
for i in range(0u, $end-$start+1).rev() {
result = result | $src[$start+i] as $t << i*8;
}
result
})
)
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
/// Lazy iterator over bits of a vector of bytes, starting with the LSB
/// (least-significat bit) of the first element of the vector.
struct BitIterator { object: Vec<u8>, current_byte: uint, current_bit: uint }
impl BitIterator {
fn new(obj: Vec<u8>) -> BitIterator {
BitIterator { object: obj, current_byte: 0, current_bit: 0 }
}
}
impl Iterator<u8> for BitIterator {
fn next(&mut self) -> Option<u8> {
let result = self.object[self.current_byte] >> self.current_bit & 0x1;
if self.current_bit + 1 == std::u8::BITS {
self.current_byte += 1;
}
self.current_bit = (self.current_bit + 1) % std::u8::BITS;
if self.current_byte == self.object.len() {
return None;
} else {
return Some(result);
}
}
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[deriving(PartialEq,Eq,Show,Clone)]
enum UtpExtensionType {
SelectiveAckExtension = 1,
}
#[deriving(Clone)]
struct UtpExtension {
ty: UtpExtensionType,
data: Vec<u8>,
}
impl UtpExtension {
fn len(&self) -> uint {
1 + self.data.len()
}
fn to_bytes(&self) -> Vec<u8> {
(vec!(self.data.len() as u8)).append(self.data.as_slice())
}
}
#[allow(dead_code)]
#[deriving(Clone)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacketHeader {
UtpPacketHeader {
wnd_size: new_wnd_size.to_be(),
.. self.clone()
}
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: u8_to_unsigned_be!(buf[2..3] -> u16),
timestamp_microseconds: u8_to_unsigned_be!(buf[4..7] -> u32),
timestamp_difference_microseconds: u8_to_unsigned_be!(buf[8..11] -> u32),
wnd_size: u8_to_unsigned_be!(buf[12..15] -> u32),
seq_nr: u8_to_unsigned_be!(buf[16..17] -> u16),
ack_nr: u8_to_unsigned_be!(buf[18..19] -> u16),
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
extensions: Vec<UtpExtension>,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
extensions: Vec::new(),
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: self.header.wnd_size(new_wnd_size),
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
/// Set Selective ACK field in packet header and add appropriate data.
///
/// If None is passed, the SACK extension is disabled and the respective
/// data is flushed. Otherwise, the SACK extension is enabled and the
/// vector `v` is taken as the extension's payload.
///
/// The length of the SACK extension is expressed in bytes, which
/// must be a multiple of 4 and at least 4.
fn set_sack(&mut self, v: Option<Vec<u8>>) {
match v {
None => {
self.header.extension = 0;
self.extensions = Vec::new();
},
Some(bv) => {
// The length of the SACK extension is expressed in bytes, which
// must be a multiple of 4 and at least 4.
assert!(bv.len() >= 4);
assert!(bv.len() % 4 == 0);
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: bv,
};
self.extensions.push(extension);
self.header.extension |= SelectiveAckExtension as u8;
}
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
for extension in self.extensions.iter() {
buf.push(0u8); // next extension id
buf.push_all(extension.to_bytes().as_slice());
}
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
let ext_len = self.extensions.iter().fold(0, |acc, ext| acc + ext.len() + 1);
self.header.len() + self.payload.len() + ext_len
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
let header = UtpPacketHeader::decode(buf);
let mut extensions = Vec::new();
let mut idx = HEADER_SIZE;
let mut kind = header.extension;
// Consume known extensions and skip over unknown ones
while idx < buf.len() && kind != 0 {
// Ignoring next extension type at buf[HEADER_SIZE]
let len = buf[idx + 1] as uint;
let extension_start = idx + 2;
let payload_start = extension_start + len;
if kind == SelectiveAckExtension as u8 { // or more generally, a known kind
let extension = UtpExtension {
ty: SelectiveAckExtension,
data: Vec::from_slice(buf.slice(extension_start, payload_start)),
};
extensions.push(extension);
}
kind = buf[idx];
idx += payload_start;
}
let mut payload;
if idx < buf.len() {
payload = Vec::from_slice(buf.slice_from(idx));
} else {
payload = Vec::new();
}
UtpPacket {
header: header,
extensions: extensions,
payload: payload,
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
extensions: self.extensions.clone(),
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_FIN_SENT,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
// Received but not acknowledged packets
incoming_buffer: Vec<UtpPacket>,
// Sent but not yet acknowledged packets
send_buffer: Vec<UtpPacket>,
duplicate_ack_count: uint,
last_acked: u16,
last_acked_timestamp: u32,
rtt: int,
rtt_variance: int,
timeout: int,
}
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 1000,
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> IoResult<UtpSocket> {
use std::io::{IoError, ConnectionFailed};
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
// Send packet
let mut buf = [0, ..BUF_SIZE];
let (len, addr) = try!(self.packet_send(&packet, buf));
self.state = CS_SYN_SENT;
// Validate response
assert!(len == HEADER_SIZE);
assert!(addr == self.connected_to);
let packet = UtpPacket::decode(buf.slice_to(len));
if packet.get_type() != ST_STATE {
return Err(IoError {
kind: ConnectionFailed,
desc: "The remote peer sent an invalid reply",
detail: None,
});
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.state = CS_CONNECTED;
self.seq_nr += 1;
debug!("connected to: {}", self.connected_to);
return Ok(self);
}
/// Send `packet` and write reply to `buf`.
///
/// This method abstracts away the (send packet, receive acknowledgment)
/// cycle and deals with timeouts.
fn packet_send(&mut self, packet: &UtpPacket, buf: &mut [u8])
-> IoResult<(uint, SocketAddr)> {
use std::io::{IoError, TimedOut};
for _ in range(0u, 5) {
let dst = self.connected_to;
let mut packet = packet.clone();
packet.header.timestamp_microseconds = now_microseconds().to_be();
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
debug!("sent {}", packet.header);
debug!("setting read timeout of {} ms", self.timeout);
self.socket.set_read_timeout(Some(self.timeout as u64));
let (len, addr) = match self.socket.recv_from(buf) {
Ok(v) => v,
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
continue;
}
Err(e) => fail!("{}", e),
};
return Ok((len, addr));
}
return Err(IoError {
kind: TimedOut,
desc: "Connection timed out",
detail: None,
});
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
// Wait for acknowledgment on pending sent packets
let mut buf = [0u8, ..BUF_SIZE];
while !self.send_buffer.is_empty() {
match self.recv_from(buf) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
try!(self.socket.send_to(packet.bytes().as_slice(), self.connected_to));
self.state = CS_FIN_SENT;
// Receive JAKE
while self.state != CS_CLOSED {
match self.recv_from(buf) {
Ok(_) => {},
Err(ref e) if e.kind == std::io::EndOfFile => self.state = CS_CLOSED,
Err(e) => fail!("{}", e),
};
}
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed, TimedOut, ConnectionReset};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
debug!("setting read timeout of {} ms", self.timeout);
if self.state != CS_NEW {
self.socket.set_read_timeout(Some(self.timeout as u64));
}
let (read, src) = match self.socket.recv_from(b) {
Err(ref e) if e.kind == TimedOut => {
debug!("recv_from timed out");
self.timeout = self.timeout * 2;
self.send_fast_resend_request();
return Ok((0, self.connected_to));
},
Ok(x) => x,
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// TODO: move this to handle_packet?
if packet.get_type() == ST_SYN {
self.connected_to = src;
}
// Copy received payload to output buffer if packet isn't a duplicate
let mut read = packet.payload.len();
if self.ack_nr < Int::from_be(packet.header.seq_nr) {
for i in range(0u, min(buf.len(), read)) {
buf[i] = b[i + HEADER_SIZE];
}
} else {
read = 0;
}
if self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
read = 0;
}
match self.handle_packet(packet) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
// Flush incoming buffer if possible
let read = self.flush_incoming_buffer(buf, read);
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Discards sequential, ordered packets in incoming buffer, starting from
/// the most recently acknowledged to the most recent, as long as there are
/// no missing packets. The discarded packets' payload is written to the
/// slice `buf`, starting in position `start`.
/// Returns the last written index.
fn flush_incoming_buffer(&mut self, buf: &mut [u8], start: uint) -> uint {
let mut idx = start;
while !self.incoming_buffer.is_empty() &&
self.ack_nr + 1 == Int::from_be(self.incoming_buffer[0].header.seq_nr) {
let packet = self.incoming_buffer.remove(0).unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[idx] = packet.payload[i];
idx += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
return idx;
}
/// Send data on socket to the given address. Returns nothing on success.
//
// # Implementation details
//
// This method inserts packets into the send buffer and keeps trying to
// advance the send window until an ACK corresponding to the last packet is
// received.
//
// Note that the buffer passed to `send_to` might exceed the maximum packet
// size, which will result in the data being split over several packets.
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
use std::io::{IoError, Closed};
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
for chunk in buf.chunks(BUF_SIZE) {
// FIXME: this is an extremely primitive pacing mechanism
while self.send_buffer.len() > 10 {
if self.duplicate_ack_count == 3 {
self.socket.send_to(self.send_buffer[0].bytes().as_slice(), self.connected_to.clone());
}
let mut buf = [0, ..BUF_SIZE];
try!(self.recv_from(buf));
}
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(chunk);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
debug!("Pushing packet into send buffer: {}", packet);
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
self.send_buffer.push(packet);
self.seq_nr += 1;
}
// Consume acknowledgements until latest packet
let mut buf = [0, ..BUF_SIZE];
while self.last_acked < self.seq_nr - 1 {
try!(self.recv_from(buf));
}
Ok(())
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Send fast resend request.
///
/// Sends three identical ACK/STATE packets to the remote host, signalling a
/// fast resend request.
fn send_fast_resend_request(&mut self) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
for _ in range(0u, 3) {
let t = now_microseconds();
packet.header.timestamp_microseconds = t.to_be();
packet.header.timestamp_difference_microseconds = (t - self.last_acked_timestamp).to_be();
match self.socket.send_to(packet.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", packet.header);
}
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
// Acknowledge only if the packet strictly follows the previous one
if self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.ack_nr = Int::from_be(packet.header.seq_nr);
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => {
let mut reply = self.prepare_reply(&packet.header, ST_STATE);
if self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, Int::from_be(packet.header.seq_nr));
self.insert_into_buffer(packet.clone());
// Set SACK extension payload if the packet is not in order
let mut stashed = self.incoming_buffer.iter()
.map(|pkt| Int::from_be(pkt.header.seq_nr))
.filter(|&seq_nr| seq_nr > self.ack_nr);
let mut sack = Vec::new();
for seq_nr in stashed {
let diff = seq_nr - self.ack_nr - 2;
let byte = (diff / 8) as uint;
let bit = (diff % 8) as uint;
if byte >= sack.len() {
sack.push(0u8);
}
let mut bitarray = sack.pop().unwrap();
bitarray |= 1 << bit;
sack.push(bitarray);
}
// Make sure the amount of elements in the SACK vector is a
// multiple of 4
if sack.len() % 4 != 0 {
let len = sack.len();
sack.grow((len / 4 + 1) * 4 - len, &0);
}
reply.set_sack(Some(sack));
}
Some(reply)
},
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => {
let packet_rtt = Int::from_be(packet.header.timestamp_difference_microseconds) as int;
let delta = self.rtt - packet_rtt;
self.rtt_variance += (std::num::abs(delta) - self.rtt_variance) / 4;
self.rtt += (packet_rtt - self.rtt) / 8;
self.timeout = std::cmp::max(self.rtt + self.rtt_variance * 4, 500);
debug!("packet_rtt: {}", packet_rtt);
debug!("delta: {}", delta);
debug!("self.rtt_variance: {}", self.rtt_variance);
debug!("self.rtt: {}", self.rtt);
debug!("self.timeout: {}", self.timeout);
if packet.header.ack_nr == Int::from_be(self.last_acked) {
self.duplicate_ack_count += 1;
} else {
self.last_acked = Int::from_be(packet.header.ack_nr);
self.last_acked_timestamp = now_microseconds();
self.duplicate_ack_count = 1;
}
// Process extensions, if any
for extension in packet.extensions.iter() {
if extension.ty == SelectiveAckExtension {
let bits = BitIterator::new(extension.data.clone());
// If three or more packets are acknowledged past the implicit missing one,
// assume it was lost.
if bits.filter(|&bit| bit == 1).count() >= 3 {
let packet = self.send_buffer.iter().find(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1).unwrap();
debug!("sending {}", packet);
self.socket.send_to(packet.bytes().as_slice(), self.connected_to);
}
let bits = BitIterator::new(extension.data.clone());
for (idx, received) in bits.map(|bit| bit == 1).enumerate() {
let seq_nr = Int::from_be(packet.header.ack_nr) + 2 + idx as u16;
if received {
debug!("SACK: packet {} received", seq_nr);
} else if seq_nr < self.seq_nr {
debug!("SACK: packet {} lost", seq_nr);
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == seq_nr) {
None => fail!("Packet {} not found", seq_nr),
Some(v) => {
let to_send = &self.send_buffer[v];
match self.socket.send_to(to_send.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
debug!("sent {}", to_send);
}
}
} else {
break;
}
}
} else {
fail!("Unknown extension");
}
}
// Three duplicate ACKs, must resend packets since `ack_nr + 1`
// TODO: checking if the send buffer isn't empty isn't a
// foolproof way to differentiate between triple-ACK and three
// keep alives spread in time
if !self.send_buffer.is_empty() && self.duplicate_ack_count == 3 {
match self.send_buffer.iter().position(|pkt| Int::from_be(pkt.header.seq_nr) == Int::from_be(packet.header.ack_nr) + 1) {
None => fail!("Received request to resend packets since {} but none was found in send buffer!", Int::from_be(packet.header.ack_nr) + 1),
Some(position) => {
for i in range(0u, position + 1) {
let ref to_send = self.send_buffer[i];
debug!("resending: {}", to_send);
match self.socket.send_to(to_send.bytes().as_slice(), self.connected_to) {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
},
}
}
// Success, advance send window
while !self.send_buffer.is_empty() &&
Int::from_be(self.send_buffer[0].header.seq_nr) <= self.last_acked {
self.send_buffer.remove(0);
}
if self.state == CS_FIN_SENT &&
Int::from_be(packet.header.ack_nr) == self.seq_nr {
self.state = CS_CLOSED;
}
None
},
ST_RESET => { // TODO
self.state = CS_RST_RECEIVED;
None
},
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
///
/// Inserting a duplicate of a packet will replace the one in the buffer if
/// it's more recent (larger timestamp).
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.incoming_buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
if !self.incoming_buffer.is_empty() && i < self.incoming_buffer.len() &&
self.incoming_buffer[i].header.seq_nr == packet.header.seq_nr {
self.incoming_buffer.remove(i);
self.incoming_buffer.insert(i, packet);
} else {
self.incoming_buffer.insert(i, packet);
}
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
incoming_buffer: Vec::new(),
send_buffer: Vec::new(),
duplicate_ack_count: 0,
last_acked: 0,
last_acked_timestamp: 0,
rtt: 0,
rtt_variance: 0,
timeout: 500,
}
}
}
impl Drop for UtpSocket {
fn drop(&mut self) {
match self.close() {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> IoResult<UtpStream> {
use std::io::net::ip::Ipv4Addr;
// Port 0 means the operating system gets to choose it
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 0 };
let socket = match UtpSocket::bind(my_addr) {
Ok(s) => s,
Err(e) => return Err(e),
};
match socket.connect(dst) {
Ok(socket) => Ok(UtpStream { socket: socket }),
Err(e) => Err(e),
}
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
self.socket.send_to(buf, dst)
}
}
impl Drop for UtpStream {
fn drop(&mut self) {
match self.close() {
Ok(_) => {},
Err(e) => fail!("{}", e),
}
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket, UtpStream};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
use std::io::test::next_test_ip4;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_decode_packet_with_extension() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(Int::from_be(packet.header.connection_id), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(Int::from_be(packet.header.seq_nr), 43859);
assert_eq!(Int::from_be(packet.header.ack_nr), 15093);
assert_eq!(packet.len(), buf.len());
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_decode_packet_with_unknown_extensions() {
use super::SelectiveAckExtension;
let buf = [0x21, 0x01, 0x41, 0xa7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0xdc, 0xab, 0x53, 0x3a, 0xf5,
0xff, 0x04, 0x00, 0x00, 0x00, 0x00, // Imaginary extension
0x00, 0x04, 0x00, 0x00, 0x00, 0x00];
let packet = UtpPacket::decode(buf);
assert_eq!(packet.header.get_version(), 1);
assert_eq!(packet.header.get_type(), ST_STATE);
assert_eq!(packet.header.extension, 1);
assert_eq!(Int::from_be(packet.header.connection_id), 16807);
assert_eq!(Int::from_be(packet.header.timestamp_microseconds), 0);
assert_eq!(Int::from_be(packet.header.timestamp_difference_microseconds), 0);
assert_eq!(Int::from_be(packet.header.wnd_size), 1500);
assert_eq!(Int::from_be(packet.header.seq_nr), 43859);
assert_eq!(Int::from_be(packet.header.ack_nr), 15093);
assert!(packet.payload.is_empty());
assert!(packet.extensions.len() == 1);
assert!(packet.extensions[0].ty == SelectiveAckExtension);
assert!(packet.extensions[0].data == vec!(0,0,0,0));
assert!(packet.extensions[0].len() == 1 + packet.extensions[0].data.len());
assert!(packet.extensions[0].len() == 5);
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_sendto_on_closed_socket() {
use std::io::Closed;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut buf = [0u8, ..BUF_SIZE];
let mut client = client;
iotry!(client.recv_from(buf));
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let (_read, _src) = iotry!(server.recv_from(buf));
assert!(server.state == CS_CONNECTED);
iotry!(server.close());
expect_eq!(server.state, CS_CLOSED);
// Trying to send to the socket after closing it raises an
// error
match server.send_to(buf, clientAddr) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
let serverAddr = next_test_ip4();
let mut server = iotry!(UtpStream::bind(serverAddr));
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = Vec::from_fn(len, |idx| idx as u8);
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut window: Vec<UtpPacket> = Vec::new();
let mut i = 0;
for data in Vec::from_fn(12, |idx| idx as u8 + 1).as_slice().chunks(3) {
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = Vec::from_slice(data);
window.push(packet.clone());
client.send_buffer.push(packet.clone());
i += 1;
}
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + i).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[3].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[4].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = Vec::from_fn(12, |idx| idx as u8 + 1);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_socket_should_not_buffer_syn_packets() {
use std::io::net::udp::UdpSocket;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UdpSocket::bind(clientAddr));
let test_syn_raw = [0x41, 0x00, 0x41, 0xa7, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x3a,
0xf1, 0x00, 0x00];
let test_syn_pkt = UtpPacket::decode(test_syn_raw);
let seq_nr = Int::from_be(test_syn_pkt.header.seq_nr);
spawn(proc() {
let mut client = client;
iotry!(client.send_to(test_syn_raw, serverAddr));
client.set_timeout(Some(10));
let mut buf = [0, ..BUF_SIZE];
let packet = match client.recv_from(buf) {
Ok((nread, _src)) => UtpPacket::decode(buf.slice_to(nread)),
Err(e) => fail!("{}", e),
};
expect_eq!(packet.header.ack_nr, seq_nr.to_be());
let mut buf = [0, ..BUF_SIZE];
iotry!(client.recv_from(buf));
let packet = UtpPacket::decode(buf);
debug!("received {}", packet);
let mut reply = UtpPacket::new();
reply.header.seq_nr = (Int::from_be(UtpPacket::decode(test_syn_raw).header.seq_nr) + 1).to_be();
reply.header.ack_nr = packet.header.seq_nr;
reply.header.connection_id = packet.header.connection_id;
reply.set_type(ST_STATE);
iotry!(client.send_to(reply.bytes().as_slice(), serverAddr));
drop(client);
});
let mut server = server;
let mut buf = [0, ..20];
iotry!(server.recv_from(buf));
assert!(server.ack_nr != 0);
expect_eq!(server.ack_nr, seq_nr);
assert!(server.incoming_buffer.is_empty());
}
#[test]
fn test_response_to_triple_ack() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpSocket::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
// Fits in a packet
static len: uint = 1024;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
expect_eq!(len, data.len());
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
iotry!(client.send_to(d.as_slice(), serverAddr));
iotry!(client.close());
});
let mut buf = [0, ..BUF_SIZE];
// Expect SYN
iotry!(server.recv_from(buf));
// Receive data
let mut data_packet;
match server.socket.recv_from(buf) {
Ok((read, _src)) => {
data_packet = UtpPacket::decode(buf.slice_to(read));
assert!(data_packet.get_type() == ST_DATA);
expect_eq!(data_packet.payload, data);
assert_eq!(data_packet.payload.len(), data.len());
},
Err(e) => fail!("{}", e),
}
let data_packet = data_packet;
// Send triple ACK
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (Int::from_be(data_packet.header.seq_nr) - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
for _ in range(0u, 3) {
iotry!(server.socket.send_to(packet.bytes().as_slice(), clientAddr));
}
// Receive data again and check that it's the same we reported as missing
match server.socket.recv_from(buf) {
Ok((0, _)) => fail!("Received 0 bytes from socket"),
Ok((read, _src)) => {
let packet = UtpPacket::decode(buf.slice_to(read));
assert_eq!(packet.get_type(), ST_DATA);
assert_eq!(Int::from_be(packet.header.seq_nr), Int::from_be(data_packet.header.seq_nr));
assert!(packet.payload == data_packet.payload);
let response = server.handle_packet(packet).unwrap();
iotry!(server.socket.send_to(response.bytes().as_slice(), server.connected_to));
},
Err(e) => fail!("{}", e),
}
// Receive close
iotry!(server.recv_from(buf));
}
#[test]
fn test_socket_timeout_request() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
let len = 512;
let data = Vec::from_fn(len, |idx| idx as u8);
let d = data.clone();
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
assert_eq!(client.connected_to, serverAddr);
iotry!(client.send_to(d.as_slice(), serverAddr));
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert_eq!(server.connected_to, clientAddr);
assert!(server.state == CS_CONNECTED);
// Purposefully read from UDP socket directly and discard it, in order
// to behave as if the packet was lost and thus trigger the timeout
// handling in the *next* call to `UtpSocket.recv_from`.
iotry!(server.socket.recv_from(buf));
// Now wait for the previously discarded packet
loop {
match server.recv_from(buf) {
Ok((0, _)) => continue,
Ok(_) => break,
Err(e) => fail!("{}", e),
}
}
drop(server);
}
#[test]
fn test_sorted_buffer_insertion() {
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new();
packet.header.seq_nr = 1;
assert!(socket.incoming_buffer.is_empty());
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 1);
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 128;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 2);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 128);
packet.header.seq_nr = 3;
packet.header.timestamp_microseconds = 256;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[2].header.seq_nr, 3);
assert_eq!(socket.incoming_buffer[2].header.timestamp_microseconds, 256);
// Replace a packet with a more recent version
packet.header.seq_nr = 2;
packet.header.timestamp_microseconds = 456;
socket.insert_into_buffer(packet.clone());
assert_eq!(socket.incoming_buffer.len(), 3);
assert_eq!(socket.incoming_buffer[1].header.seq_nr, 2);
assert_eq!(socket.incoming_buffer[1].header.timestamp_microseconds, 456);
}
#[test]
fn test_duplicate_packet_handling() {
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
assert!(client.state == CS_CONNECTED);
let mut s = client.socket.clone();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
// Send two copies of the packet, with different timestamps
for _ in range(0u, 2) {
packet.header.timestamp_microseconds = super::now_microseconds();
iotry!(s.send_to(packet.bytes().as_slice(), serverAddr));
}
client.seq_nr += 1;
// Receive one ACK
for _ in range(0u, 1) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
iotry!(client.close());
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1,2,3);
match stream.read_to_end() {
Ok(data) => {
println!("{}", data);
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
#[test]
fn test_selective_ack_response() {
let serverAddr = next_test_ip4();
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
// Client
spawn(proc() {
let mut client = iotry!(UtpStream::connect(serverAddr));
// Stream.write
iotry!(client.write(to_send.as_slice()));
iotry!(client.close());
});
// Server
let mut server = iotry!(UtpSocket::bind(serverAddr));
let mut buf = [0, ..BUF_SIZE];
// Connect
iotry!(server.recv_from(buf));
// Discard packets
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
iotry!(server.socket.recv_from(buf));
// Generate SACK
let mut packet = UtpPacket::new();
packet.header.seq_nr = server.seq_nr.to_be();
packet.header.ack_nr = (server.ack_nr - 1).to_be();
packet.header.connection_id = server.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.set_type(ST_STATE);
packet.set_sack(Some(vec!(12, 0, 0, 0)));
// Send SACK
iotry!(server.socket.send_to(packet.bytes().as_slice(), server.connected_to.clone()));
// Expect to receive "missing" packets
let mut stream = UtpStream { socket: server };
let read = iotry!(stream.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_correct_packet_loss() {
let (clientAddr, serverAddr) = (next_test_ip4(), next_test_ip4());
let mut server = iotry!(UtpStream::bind(serverAddr));
let client = iotry!(UtpSocket::bind(clientAddr));
let len = 1024 * 10;
let data = Vec::from_fn(len, |idx| idx as u8);
let to_send = data.clone();
spawn(proc() {
let mut client = iotry!(client.connect(serverAddr));
// Send everything except the odd chunks
let chunks = to_send.as_slice().chunks(BUF_SIZE);
let dst = client.connected_to;
for (index, chunk) in chunks.enumerate() {
let mut packet = UtpPacket::new();
packet.header.seq_nr = client.seq_nr.to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.timestamp_microseconds = super::now_microseconds().to_be();
packet.payload = Vec::from_slice(chunk);
packet.set_type(ST_DATA);
if index % 2 == 0 {
iotry!(client.socket.send_to(packet.bytes().as_slice(), dst));
}
client.send_buffer.push(packet);
client.seq_nr += 1;
}
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert_eq!(read.len(), data.len());
assert_eq!(read, data);
}
}
|
//! Implementation of a Micro Transport Protocol library.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
//!
//! TODO
//! ----
//!
//! - congestion control
//! - proper connection closing
//! - automatically send FIN (or should it be RST?) on `drop` if not already closed
//! - setters and getters that hide header field endianness conversion
//! - SACK extension
//! - handle packet loss
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
static BUF_SIZE: uint = 4096;
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[allow(dead_code)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: buf[3] as u16 << 8 | buf[2] as u16,
timestamp_microseconds: buf[7] as u32 << 24 | buf[6] as u32 << 16 | buf[5] as u32 << 8 | buf[4] as u32,
timestamp_difference_microseconds: buf[11] as u32 << 24 | buf[10] as u32 << 16 | buf[9] as u32 << 8 | buf[8] as u32,
wnd_size: buf[15] as u32 << 24 | buf[14] as u32 << 16 | buf[13] as u32 << 8 | buf[12] as u32,
seq_nr: buf[17] as u16 << 8 | buf[16] as u16,
ack_nr: buf[19] as u16 << 8 | buf[18] as u16,
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: self.header.type_ver,
extension: self.header.extension,
connection_id: self.header.connection_id,
timestamp_microseconds: self.header.timestamp_microseconds,
timestamp_difference_microseconds: self.header.timestamp_difference_microseconds,
wnd_size: new_wnd_size.to_be(),
seq_nr: self.header.seq_nr,
ack_nr: self.header.ack_nr,
},
payload: self.payload.clone(),
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
buffer: Vec<UtpPacket>,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE).wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(resp.bytes().as_slice(), $src));
debug!("sent {}", resp.header);
})
)
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
buffer: Vec::new(),
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> UtpSocket {
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.send_to(packet.bytes().as_slice(), dst);
debug!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..BUF_SIZE];
let (_len, addr) = match self.recv_from(buf) {
Ok(v) => v,
Err(e) => fail!("{}", e),
};
assert!(_len == 0);
assert!(addr == self.connected_to);
debug!("connected to: {} {}", addr, self.connected_to);
self.state = CS_CONNECTED;
self.seq_nr += 1;
self
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
let dst = self.connected_to;
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
// Receive JAKE
let mut buf = [0u8, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
assert!(resp.get_type() == ST_STATE);
// Set socket state
self.state = CS_CLOSED;
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
let (read, src) = try!(self.socket.recv_from(b));
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
use std::io::{IoError, ConnectionReset};
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// TODO: Deal with duplicates
// Did we miss any packets?
if packet.get_type() != ST_STATE && self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is too much behind received packet seq_nr ({})!", self.ack_nr, Int::from_be(packet.header.seq_nr));
// Add to buffer but do not acknowledge until all packets between ack_nr + 1 and curr_packet.seq_nr - 1 are received
self.insert_into_buffer(packet);
return Ok((0, self.connected_to));
}
match self.handle_packet(packet.clone()) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
for i in range(0u, min(buf.len(), read - HEADER_SIZE)) {
buf[i] = b[i + HEADER_SIZE];
}
// Empty buffer if possible
let current_packet_seq_nr = Int::from_be(packet.header.seq_nr);
let mut read = read - HEADER_SIZE;
while !self.buffer.is_empty() && current_packet_seq_nr + 1 == Int::from_be(self.buffer[0].header.seq_nr) {
let packet = self.buffer.shift().unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[read] = packet.payload[i];
read += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Send data on socket to the given address. Returns nothing on success.
//
// TODO: return error on send after connection closed (RST or FIN + all
// packets received)
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(buf);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
let r = self.socket.send_to(packet.bytes().as_slice(), dst);
// Expect ACK
let mut buf = [0, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
debug!("received {}", resp.header);
assert_eq!(resp.get_type(), ST_STATE);
assert_eq!(Int::from_be(resp.header.ack_nr), self.seq_nr);
// Success, increment sequence number
if buf.len() > 0 {
self.seq_nr += 1;
}
r
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
if packet.get_type() == ST_STATE ||
self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => Some(self.prepare_reply(&packet.header, ST_STATE)),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => None,
ST_RESET => /* TODO */ None,
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
self.buffer.insert(i, packet);
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
buffer: Vec::new(),
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> UtpStream {
use std::io::net::ip::{Ipv4Addr};
use std::rand::random;
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: random() };
let socket = UtpSocket::bind(my_addr).unwrap().connect(dst);
UtpStream { socket: socket }
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
for chunk in buf.chunks(BUF_SIZE) {
try!(self.socket.send_to(chunk, dst));
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
use std::io::test::next_test_ip4;
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
use super::UtpStream;
use std::io::test::next_test_ip4;
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Fits in a packet
static len: uint = 1024;
let data = range(0, len).map(|x:uint| x as u8).collect::<Vec<_>>();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data: Vec<u8> = range(0, len).map(|x:uint| x as u8).collect();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use super::UtpStream;
use std::io::test::next_test_ip4;
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = range(0, len).map(|x:uint| x as u8).collect();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
use std::io::test::next_test_ip4;
use super::UtpStream;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 1).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(4,5,6);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 2).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1, 2, 3, 4, 5, 6);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
}
Reformat comments.
//! Implementation of a Micro Transport Protocol library.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
//!
//! TODO
//! ----
//!
//! - congestion control
//! - proper connection closing
//! - automatically send FIN (or should it be RST?) on `drop` if not already closed
//! - setters and getters that hide header field endianness conversion
//! - SACK extension
//! - handle packet loss
#![crate_name = "utp"]
#![license = "MIT/ASL2"]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![feature(macro_rules, phase)]
#![deny(missing_doc)]
extern crate time;
#[phase(plugin, link)] extern crate log;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
static BUF_SIZE: uint = 4096;
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
#[allow(dead_code)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(&self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(&self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preserving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: buf[3] as u16 << 8 | buf[2] as u16,
timestamp_microseconds: buf[7] as u32 << 24 | buf[6] as u32 << 16 | buf[5] as u32 << 8 | buf[4] as u32,
timestamp_difference_microseconds: buf[11] as u32 << 24 | buf[10] as u32 << 16 | buf[9] as u32 << 8 | buf[8] as u32,
wnd_size: buf[15] as u32 << 24 | buf[14] as u32 << 16 | buf[13] as u32 << 8 | buf[12] as u32,
seq_nr: buf[17] as u16 << 8 | buf[16] as u16,
ack_nr: buf[19] as u16 << 8 | buf[18] as u16,
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
// TODO: Read up on pointers and ownership
fn get_type(&self) -> UtpPacketType {
self.header.get_type()
}
fn wnd_size(&self, new_wnd_size: u32) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: self.header.type_ver,
extension: self.header.extension,
connection_id: self.header.connection_id,
timestamp_microseconds: self.header.timestamp_microseconds,
timestamp_difference_microseconds: self.header.timestamp_difference_microseconds,
wnd_size: new_wnd_size.to_be(),
seq_nr: self.header.seq_nr,
ack_nr: self.header.ack_nr,
},
payload: self.payload.clone(),
}
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
/// Decode a byte slice and construct the equivalent UtpPacket.
///
/// Note that this method makes no attempt to guess the payload size, saving
/// all except the initial 20 bytes corresponding to the header as payload.
/// It's the caller's responsability to use an appropriately sized buffer.
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
impl Clone for UtpPacket {
fn clone(&self) -> UtpPacket {
UtpPacket {
header: self.header,
payload: self.payload.clone(),
}
}
}
impl fmt::Show for UtpPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.header.fmt(f)
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq,Show)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
CS_RST_RECEIVED,
CS_CLOSED,
CS_EOF,
}
/// A uTP (Micro Transport Protocol) socket.
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
buffer: Vec<UtpPacket>,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE).wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(resp.bytes().as_slice(), $src));
debug!("sent {}", resp.header);
})
)
impl UtpSocket {
/// Create a UTP socket from the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let connection_id = random::<u16>();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: connection_id,
sender_connection_id: connection_id + 1,
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
buffer: Vec::new(),
}),
Err(e) => Err(e)
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(mut self, other: SocketAddr) -> UtpSocket {
self.connected_to = other;
assert_eq!(self.receiver_connection_id + 1, self.sender_connection_id);
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = self.receiver_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.send_to(packet.bytes().as_slice(), dst);
debug!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..BUF_SIZE];
let (_len, addr) = match self.recv_from(buf) {
Ok(v) => v,
Err(e) => fail!("{}", e),
};
assert!(_len == 0);
assert!(addr == self.connected_to);
debug!("connected to: {} {}", addr, self.connected_to);
self.state = CS_CONNECTED;
self.seq_nr += 1;
self
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.header.connection_id = self.sender_connection_id.to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.set_type(ST_FIN);
// Send FIN
let dst = self.connected_to;
try!(self.socket.send_to(packet.bytes().as_slice(), dst));
// Receive JAKE
let mut buf = [0u8, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
assert!(resp.get_type() == ST_STATE);
// Set socket state
self.state = CS_CLOSED;
Ok(())
}
/// Receive data from socket.
///
/// On success, returns the number of bytes read and the sender's address.
/// Returns CS_EOF after receiving a FIN packet when the remaining
/// inflight packets are consumed. Subsequent calls return CS_CLOSED.
#[unstable]
pub fn recv_from(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
use std::cmp::min;
use std::io::{IoError, EndOfFile, Closed};
if self.state == CS_EOF {
self.state = CS_CLOSED;
return Err(IoError {
kind: EndOfFile,
desc: "End of file reached",
detail: None,
});
}
if self.state == CS_CLOSED {
return Err(IoError {
kind: Closed,
desc: "Connection closed",
detail: None,
});
}
let mut b = [0, ..BUF_SIZE + HEADER_SIZE];
let (read, src) = try!(self.socket.recv_from(b));
let packet = UtpPacket::decode(b.slice_to(read));
debug!("received {}", packet.header);
if packet.get_type() == ST_RESET {
use std::io::{IoError, ConnectionReset};
return Err(IoError {
kind: ConnectionReset,
desc: "Remote host aborted connection (incorrect connection id)",
detail: None,
});
}
// Check if the packet is out of order (that is, it's sequence number
// does not immediately follow the ACK number)
if packet.get_type() != ST_STATE && self.ack_nr + 1 < Int::from_be(packet.header.seq_nr) {
debug!("current ack_nr ({}) is behind received packet seq_nr ({})",
self.ack_nr, Int::from_be(packet.header.seq_nr));
// Add to buffer but do not acknowledge until all packets between
// ack_nr + 1 and curr_packet.seq_nr - 1 are received
self.insert_into_buffer(packet);
return Ok((0, self.connected_to));
}
match self.handle_packet(packet.clone()) {
Some(pkt) => {
let pkt = pkt.wnd_size(BUF_SIZE as u32);
try!(self.socket.send_to(pkt.bytes().as_slice(), src));
debug!("sent {}", pkt.header);
},
None => {}
};
for i in range(0u, min(buf.len(), read - HEADER_SIZE)) {
buf[i] = b[i + HEADER_SIZE];
}
// Empty buffer if possible
let current_packet_seq_nr = Int::from_be(packet.header.seq_nr);
let mut read = read - HEADER_SIZE;
while !self.buffer.is_empty() && current_packet_seq_nr + 1 == Int::from_be(self.buffer[0].header.seq_nr) {
let packet = self.buffer.shift().unwrap();
debug!("Removing packet from buffer: {}", packet);
for i in range(0u, packet.payload.len()) {
buf[read] = packet.payload[i];
read += 1;
}
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
Ok((read, src))
}
#[allow(missing_doc)]
#[deprecated = "renamed to `recv_from`"]
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
self.recv_from(buf)
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro - other_t_micro).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
/// Send data on socket to the given address. Returns nothing on success.
//
// TODO: return error on send after connection closed (RST or FIN + all
// packets received)
#[unstable]
pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(buf);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
let r = self.socket.send_to(packet.bytes().as_slice(), dst);
// Expect ACK
let mut buf = [0, ..BUF_SIZE];
try!(self.socket.recv_from(buf));
let resp = UtpPacket::decode(buf);
debug!("received {}", resp.header);
assert_eq!(resp.get_type(), ST_STATE);
assert_eq!(Int::from_be(resp.header.ack_nr), self.seq_nr);
// Success, increment sequence number
if buf.len() > 0 {
self.seq_nr += 1;
}
r
}
#[allow(missing_doc)]
#[deprecated = "renamed to `send_to`"]
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
self.send_to(buf, dst)
}
/// Handle incoming packet, updating socket state accordingly.
///
/// Returns appropriate reply packet, if needed.
fn handle_packet(&mut self, packet: UtpPacket) -> Option<UtpPacket> {
// Reset connection if connection id doesn't match and this isn't a SYN
if packet.get_type() != ST_SYN &&
!(Int::from_be(packet.header.connection_id) == self.sender_connection_id ||
Int::from_be(packet.header.connection_id) == self.receiver_connection_id) {
return Some(self.prepare_reply(&packet.header, ST_RESET));
}
if packet.get_type() == ST_STATE ||
self.ack_nr + 1 == Int::from_be(packet.header.seq_nr) {
self.ack_nr = Int::from_be(packet.header.seq_nr);
}
match packet.header.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(packet.header.connection_id) + 1;
self.sender_connection_id = Int::from_be(packet.header.connection_id);
self.state = CS_CONNECTED;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_DATA => Some(self.prepare_reply(&packet.header, ST_STATE)),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
// TODO: check if no packets are missing
// If all packets are received
self.state = CS_EOF;
Some(self.prepare_reply(&packet.header, ST_STATE))
}
ST_STATE => None,
ST_RESET => /* TODO */ None,
}
}
/// Insert a packet into the socket's buffer.
///
/// The packet is inserted in such a way that the buffer is
/// ordered ascendingly by their sequence number. This allows
/// storing packets that were received out of order.
fn insert_into_buffer(&mut self, packet: UtpPacket) {
let mut i = 0;
for pkt in self.buffer.iter() {
if Int::from_be(pkt.header.seq_nr) >= Int::from_be(packet.header.seq_nr) {
break;
}
i += 1;
}
self.buffer.insert(i, packet);
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: self.receiver_connection_id,
sender_connection_id: self.sender_connection_id,
seq_nr: self.seq_nr,
ack_nr: self.ack_nr,
state: self.state,
buffer: Vec::new(),
}
}
}
/// Stream interface for UtpSocket.
pub struct UtpStream {
socket: UtpSocket,
}
impl UtpStream {
/// Create a uTP stream listening on the given address.
#[unstable]
pub fn bind(addr: SocketAddr) -> IoResult<UtpStream> {
let socket = UtpSocket::bind(addr);
match socket {
Ok(s) => Ok(UtpStream { socket: s }),
Err(e) => Err(e),
}
}
/// Open a uTP connection to a remote host by hostname or IP address.
#[unstable]
pub fn connect(dst: SocketAddr) -> UtpStream {
use std::io::net::ip::{Ipv4Addr};
use std::rand::random;
let my_addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: random() };
let socket = UtpSocket::bind(my_addr).unwrap().connect(dst);
UtpStream { socket: socket }
}
/// Gracefully close connection to peer.
///
/// This method allows both peers to receive all packets still in
/// flight.
#[unstable]
pub fn close(&mut self) -> IoResult<()> {
self.socket.close()
}
}
impl Reader for UtpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match self.socket.recv_from(buf) {
Ok((read, _src)) => Ok(read),
Err(e) => Err(e),
}
}
}
impl Writer for UtpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let dst = self.socket.connected_to;
for chunk in buf.chunks(BUF_SIZE) {
try!(self.socket.send_to(chunk, dst));
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::{UtpSocket, UtpPacket};
use super::{ST_STATE, ST_FIN, ST_DATA, ST_RESET, ST_SYN};
use super::{BUF_SIZE, HEADER_SIZE};
use super::{CS_CONNECTED, CS_NEW, CS_CLOSED, CS_EOF};
use std::rand::random;
macro_rules! expect_eq(
($left:expr, $right:expr) => (
if !($left == $right) {
fail!("expected {}, got {}", $right, $left);
}
);
)
macro_rules! iotry(
($e:expr) => (match $e { Ok(e) => e, Err(e) => fail!("{}", e) })
)
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
#[test]
fn test_socket_ipv4() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
drop(client);
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
drop(server);
}
#[test]
fn test_recvfrom_on_closed_socket() {
use std::io::test::next_test_ip4;
use std::io::{Closed, EndOfFile};
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
spawn(proc() {
let mut client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
assert_eq!(client.close(), Ok(()));
drop(client);
});
// Make the server listen for incoming connections
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
assert!(server.state == CS_CONNECTED);
// Closing the connection is fine
match server.recv_from(buf) {
Err(e) => fail!("{}", e),
_ => {},
}
expect_eq!(server.state, CS_EOF);
// Trying to listen on the socket after closing it raises an
// EOF error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, EndOfFile),
v => fail!("expected {}, got {}", EndOfFile, v),
}
expect_eq!(server.state, CS_CLOSED);
// Trying again raises a Closed error
match server.recv_from(buf) {
Err(e) => expect_eq!(e.kind, Closed),
v => fail!("expected {}, got {}", Closed, v),
}
drop(server);
}
#[test]
fn test_acks_on_socket() {
use std::io::test::next_test_ip4;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let (tx, rx) = channel();
let client = iotry!(UtpSocket::bind(clientAddr));
let server = iotry!(UtpSocket::bind(serverAddr));
spawn(proc() {
// Make the server listen for incoming connections
let mut server = server;
let mut buf = [0u8, ..BUF_SIZE];
let _resp = server.recv_from(buf);
tx.send(server.seq_nr);
// Close the connection
iotry!(server.recv_from(buf));
drop(server);
});
let mut client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
let sender_seq_nr = rx.recv();
let ack_nr = client.ack_nr;
assert!(ack_nr != 0);
assert!(ack_nr == sender_seq_nr);
assert_eq!(client.close(), Ok(()));
// The reply to both connect (SYN) and close (FIN) should be
// STATE packets, which don't increase the sequence number
// and, hence, the receiver's acknowledgement number.
assert!(client.ack_nr == ack_nr);
drop(client);
}
#[test]
fn test_handle_packet() {
use std::io::test::next_test_ip4;
//fn test_connection_setup() {
let initial_connection_id: u16 = random();
let sender_connection_id = initial_connection_id + 1;
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let sent = packet.header;
// Do we have a response?
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
// Is is of the correct type?
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Same connection id on both ends during connection establishment
assert!(response.header.connection_id == sent.connection_id);
// Response acknowledges SYN
assert!(response.header.ack_nr == sent.seq_nr);
// No payload?
assert!(response.payload.is_empty());
//}
// ---------------------------------
// fn test_connection_usage() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// Sender (i.e., who initated connection and sent SYN) has connection id
// equal to initial connection id + 1
// Receiver (i.e., who accepted connection) has connection id equal to
// initial connection id
assert!(Int::from_be(response.header.connection_id) == initial_connection_id);
assert!(Int::from_be(response.header.connection_id) == Int::from_be(sent.connection_id) - 1);
// Previous packets should be ack'ed
assert!(Int::from_be(response.header.ack_nr) == Int::from_be(sent.seq_nr));
// Responses with no payload should not increase the sequence number
assert!(response.payload.is_empty());
assert!(Int::from_be(response.header.seq_nr) == Int::from_be(old_response.header.seq_nr));
// }
//fn test_connection_teardown() {
let old_packet = packet;
let old_response = response;
let mut packet = UtpPacket::new();
packet.set_type(ST_FIN);
packet.header.connection_id = sender_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let sent = packet.header;
let response = socket.handle_packet(packet);
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
// FIN packets have no payload but the sequence number shouldn't increase
assert!(Int::from_be(sent.seq_nr) == Int::from_be(old_packet.header.seq_nr) + 1);
// Nor should the ACK packet's sequence number
assert!(response.header.seq_nr == old_response.header.seq_nr);
// FIN should be acknowledged
assert!(response.header.ack_nr == sent.seq_nr);
//}
}
#[test]
fn test_response_to_keepalive_ack() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
// Send a second keepalive packet, identical to the previous one
let response = socket.handle_packet(packet.clone());
assert!(response.is_none());
}
#[test]
fn test_response_to_wrong_connection_id() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
assert!(response.unwrap().get_type() == ST_STATE);
// Now, disrupt connection with a packet with an incorrect connection id
let new_connection_id = initial_connection_id.to_le();
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_STATE);
packet.header.connection_id = new_connection_id;
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_RESET);
assert!(response.header.ack_nr == packet.header.seq_nr);
}
#[test]
fn test_utp_stream() {
use super::UtpStream;
use std::io::test::next_test_ip4;
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.close());
});
iotry!(server.read_to_end());
}
#[test]
fn test_utp_stream_small_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Fits in a packet
static len: uint = 1024;
let data = range(0, len).map(|x:uint| x as u8).collect::<Vec<_>>();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_large_data() {
use super::UtpStream;
use std::io::test::next_test_ip4;
// Has to be sent over several packets
static len: uint = 1024 * 1024;
let data: Vec<u8> = range(0, len).map(|x:uint| x as u8).collect();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
let read = iotry!(server.read_to_end());
assert!(!read.is_empty());
expect_eq!(read.len(), data.len());
expect_eq!(read, data);
}
#[test]
fn test_utp_stream_successive_reads() {
use super::UtpStream;
use std::io::test::next_test_ip4;
use std::io::Closed;
static len: uint = 1024;
let data: Vec<u8> = range(0, len).map(|x:uint| x as u8).collect();
expect_eq!(len, data.len());
let d = data.clone();
let serverAddr = next_test_ip4();
let mut server = UtpStream::bind(serverAddr);
spawn(proc() {
let mut client = UtpStream::connect(serverAddr);
iotry!(client.write(d.as_slice()));
iotry!(client.close());
});
iotry!(server.read_to_end());
let mut buf = [0u8, ..4096];
match server.read(buf) {
Err(ref e) if e.kind == Closed => {},
_ => fail!("should have failed with Closed"),
};
}
#[test]
fn test_unordered_packets() {
use std::io::test::next_test_ip4;
// Boilerplate test setup
let initial_connection_id: u16 = random();
let serverAddr = next_test_ip4();
let mut socket = iotry!(UtpSocket::bind(serverAddr));
// Establish connection
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_SYN);
packet.header.connection_id = initial_connection_id.to_be();
let response = socket.handle_packet(packet.clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.get_type() == ST_STATE);
let old_packet = packet;
let old_response = response;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 1).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = initial_connection_id.to_be();
packet.header.seq_nr = (Int::from_be(old_packet.header.seq_nr) + 2).to_be();
packet.header.ack_nr = old_response.header.seq_nr;
packet.payload = vec!(4,5,6);
window.push(packet);
// Send packets in reverse order
let response = socket.handle_packet(window[1].clone());
assert!(response.is_some());
let response = response.unwrap();
assert!(response.header.ack_nr != window[1].header.seq_nr);
let response = socket.handle_packet(window[0].clone());
assert!(response.is_some());
}
#[test]
fn test_socket_unordered_packets() {
use std::io::test::next_test_ip4;
use super::UtpStream;
let (serverAddr, clientAddr) = (next_test_ip4(), next_test_ip4());
let client = iotry!(UtpSocket::bind(clientAddr));
let mut server = iotry!(UtpSocket::bind(serverAddr));
assert!(server.state == CS_NEW);
assert!(client.state == CS_NEW);
// Check proper difference in client's send connection id and receive connection id
assert_eq!(client.sender_connection_id, client.receiver_connection_id + 1);
spawn(proc() {
let client = client.connect(serverAddr);
assert!(client.state == CS_CONNECTED);
let mut s = client.socket;
let mut window: Vec<UtpPacket> = Vec::new();
// Now, send a keepalive packet
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(1,2,3);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_DATA);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 1).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
packet.payload = vec!(4,5,6);
window.push(packet);
let mut packet = UtpPacket::new().wnd_size(BUF_SIZE as u32);
packet.set_type(ST_FIN);
packet.header.connection_id = client.sender_connection_id.to_be();
packet.header.seq_nr = (client.seq_nr + 2).to_be();
packet.header.ack_nr = client.ack_nr.to_be();
window.push(packet);
iotry!(s.send_to(window[1].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[0].bytes().as_slice(), serverAddr));
iotry!(s.send_to(window[2].bytes().as_slice(), serverAddr));
for _ in range(0u, 2) {
let mut buf = [0, ..BUF_SIZE];
iotry!(s.recv_from(buf));
}
});
let mut buf = [0u8, ..BUF_SIZE];
match server.recv_from(buf) {
e => println!("{}", e),
}
// After establishing a new connection, the server's ids are a mirror of the client's.
assert_eq!(server.receiver_connection_id, server.sender_connection_id + 1);
assert!(server.state == CS_CONNECTED);
let mut stream = UtpStream { socket: server };
let expected: Vec<u8> = vec!(1, 2, 3, 4, 5, 6);
match stream.read_to_end() {
Ok(data) => {
expect_eq!(data.len(), expected.len());
expect_eq!(data, expected);
},
Err(e) => fail!("{}", e),
}
}
}
|
pub use self::parse_mode::ParseMode;
pub use self::chat_action::ChatAction;
mod parse_mode;
mod chat_action;
mod file;
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde_json;
use serde_json::Value;
use bot::chat_action::get_chat_action;
use bot::parse_mode::get_parse_mode;
use error::{Result, check_for_error};
use error::Error::JsonNotFound;
use marker::ReplyMarkup;
use objects::{Update, Message, Contact, InlineKeyboardMarkup, User, UserProfilePhotos, File};
/// A `Bot` which will do all the API calls.
///
/// The `Bot` will be given access to in a `Command` with which you can do all
/// the API interactions in your `Command`s.
#[derive(Debug)]
pub struct Bot {
pub id: i64,
pub first_name: String,
pub last_name: Option<String>,
pub username: String,
pub bot_url: String,
client: Client,
}
impl Bot {
/// Constructs a new `Bot`.
pub fn new(bot_url: String) -> Result<Self> {
debug!("Going to construct a new Bot...");
let client = Client::new()?;
let me = Bot::get_me(&client, &bot_url)?;
let id = me.id;
let first_name = me.first_name;
let last_name = me.last_name;
let username = me.username.expect("Cannot find username of the bot");
Ok(Bot {
id: id,
first_name: first_name,
last_name: last_name,
username: username,
client: client,
bot_url: bot_url,
})
}
/// API call which gets the information about your bot.
pub fn get_me(client: &Client, bot_url: &str) -> Result<User> {
debug!("Calling get_me...");
let path = ["getMe"];
let url = ::construct_api_url(bot_url, &path);
let mut data = client.get(&url)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let user_json = rjson.get("result").ok_or(JsonNotFound)?;
let user: User = serde_json::from_value(user_json.clone())?;
Ok(user)
}
/// API call which will get called to get the updates for your bot.
pub fn get_updates(
&self,
offset: i32,
limit: Option<i32>,
timeout: Option<i32>,
network_delay: Option<f32>,
) -> Result<Option<Vec<Update>>> {
debug!("Calling get_updates...");
let limit = limit.unwrap_or(100);
let timeout = timeout.unwrap_or(0);
let network_delay = network_delay.unwrap_or(0.0);
let path = ["getUpdates"];
let path_url = ::construct_api_url(&self.bot_url, &path);
let url = format!(
"{}?offset={}&limit={}&timeout={}&network_delay={}",
path_url,
offset,
limit,
timeout,
network_delay
);
let mut data = self.client.get(&url)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let updates_json = rjson.get("result");
if let Some(result) = updates_json {
let updates: Vec<Update> = serde_json::from_value(result.clone())?;
Ok(Some(updates))
} else {
Ok(None)
}
}
/// API call which will send a message to a chat which your bot participates in.
pub fn send_message<M: ReplyMarkup>(
&self,
chat_id: &i64,
text: &str,
parse_mode: Option<&ParseMode>,
disable_web_page_preview: Option<&bool>,
disable_notification: Option<&bool>,
reply_to_message_id: Option<&i64>,
reply_markup: Option<M>,
) -> Result<Message> {
debug!("Calling send_message...");
let chat_id: &str = &chat_id.to_string();
let parse_mode = &get_parse_mode(parse_mode.unwrap_or(&ParseMode::Text));
let disable_web_page_preview: &str =
&disable_web_page_preview.unwrap_or(&false).to_string();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let reply_to_message_id: &str = &reply_to_message_id.map(|i| i.to_string()).unwrap_or(
"None"
.to_string(),
);
let reply_markup = &Box::new(reply_markup)
.map(|r| serde_json::to_string(&r).unwrap_or("".to_string()))
.unwrap_or("".to_string());
let path = ["sendMessage"];
let params = [
("chat_id", chat_id),
("text", text),
("parse_mode", parse_mode),
("disable_web_page_preview", disable_web_page_preview),
("disable_notification", disable_notification),
("reply_to_message_id", reply_to_message_id),
("reply_markup", reply_markup),
];
self.call(&path, ¶ms)
}
/// API call which will reply to a message directed to your bot.
pub fn reply_to_message(&self, update: &Update, text: &str) -> Result<Message> {
debug!("Calling reply_to_message...");
let message = update.clone().message.unwrap();
let message_id = message.message_id;
let chat_id = message.chat.id;
self.send_message(
&chat_id,
text,
None,
None,
None,
Some(&message_id),
::NO_MARKUP,
)
}
/// API call which will forward a message.
pub fn forward_message(
&self,
update: &Update,
chat_id: &i64,
disable_notification: Option<&bool>,
) -> Result<Message> {
debug!("Calling forward_message...");
let message = update.clone().message.unwrap();
let chat_id: &str = &chat_id.to_string();
let from_chat_id: &str = &message.chat.id.to_string();
let message_id: &str = &message.message_id.to_string();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let path = ["forwardMessage"];
let params = [
("chat_id", chat_id),
("from_chat_id", from_chat_id),
("disable_notification", disable_notification),
("message_id", message_id),
];
self.call(&path, ¶ms)
}
/// API call which will show the given chat action to the users.
pub fn send_chat_action(&self, chat_id: &i64, action: &ChatAction) -> Result<bool> {
debug!("Calling send_chat_action...");
let chat_id: &str = &chat_id.to_string();
let action = &get_chat_action(action);
let path = ["sendChatAction"];
let params = [("chat_id", chat_id), ("action", action)];
self.call(&path, ¶ms)
}
/// API call which will send the given contact.
pub fn send_contact(
&self,
chat_id: &i64,
contact: &Contact,
disable_notification: Option<&bool>,
reply_to_message_id: Option<&i64>,
reply_markup: Option<&InlineKeyboardMarkup>,
) -> Result<Message> {
debug!("Calling send_contact...");
let chat_id: &str = &chat_id.to_string();
let phone_number = &contact.phone_number;
let first_name = &contact.first_name;
let last_name = &contact.clone().last_name.unwrap();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let reply_to_message_id: &str = &reply_to_message_id.map(|i| i.to_string()).unwrap_or(
"None"
.to_string(),
);
let reply_markup = &reply_markup
.and_then(|r| serde_json::to_string(r).ok())
.unwrap_or("".to_string());
let path = ["sendContact"];
let params = [
("chat_id", chat_id),
("phone_number", phone_number),
("first_name", first_name),
("last_name", last_name),
("disable_notification", disable_notification),
("reply_to_message_id", reply_to_message_id),
("reply_markup", reply_markup),
];
self.call(&path, ¶ms)
}
/// API call which will get a list of profile pictures for a user.
pub fn get_user_profile_photos(
&self,
user_id: &i64,
offset: Option<&i64>,
limit: Option<&i64>,
) -> Result<UserProfilePhotos> {
debug!("Calling get_user_profile_photos...");
let user_id: &str = &user_id.to_string();
let offset: &str = &offset.map(|i| i.to_string()).unwrap_or("None".to_string());
let limit: &str = &limit.map(|i| i.to_string()).unwrap_or("None".to_string());
let path = ["getUserProfilePhotos"];
let params = [("user_id", user_id), ("offset", offset), ("limit", limit)];
self.call(&path, ¶ms)
}
/// API call which will get basic info about a file and prepare it for donwloading.
pub fn get_file(&self, file_id: &str) -> Result<File> {
debug!("Calling get_file...");
let path = ["getFile"];
let params = [("file_id", file_id)];
self.call(&path, ¶ms)
}
/// The actual networking done for sending messages.
fn call<T: DeserializeOwned>(&self, path: &[&str], params: &[(&str, &str)]) -> Result<T> {
debug!("Posting message...");
let url = ::construct_api_url(&self.bot_url, path);
let mut data = self.client.post(&url)?.form(¶ms)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let object_json = rjson.get("result").ok_or(JsonNotFound)?;
let object = serde_json::from_value::<T>(object_json.clone())?;
Ok(object)
}
}
Adding kickChatMember
pub use self::parse_mode::ParseMode;
pub use self::chat_action::ChatAction;
mod parse_mode;
mod chat_action;
mod file;
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde_json;
use serde_json::Value;
use bot::chat_action::get_chat_action;
use bot::parse_mode::get_parse_mode;
use error::{Result, check_for_error};
use error::Error::JsonNotFound;
use marker::ReplyMarkup;
use objects::{Update, Message, Contact, InlineKeyboardMarkup, User, UserProfilePhotos, File};
/// A `Bot` which will do all the API calls.
///
/// The `Bot` will be given access to in a `Command` with which you can do all
/// the API interactions in your `Command`s.
#[derive(Debug)]
pub struct Bot {
pub id: i64,
pub first_name: String,
pub last_name: Option<String>,
pub username: String,
pub bot_url: String,
client: Client,
}
impl Bot {
/// Constructs a new `Bot`.
pub fn new(bot_url: String) -> Result<Self> {
debug!("Going to construct a new Bot...");
let client = Client::new()?;
let me = Bot::get_me(&client, &bot_url)?;
let id = me.id;
let first_name = me.first_name;
let last_name = me.last_name;
let username = me.username.expect("Cannot find username of the bot");
Ok(Bot {
id: id,
first_name: first_name,
last_name: last_name,
username: username,
client: client,
bot_url: bot_url,
})
}
/// API call which gets the information about your bot.
pub fn get_me(client: &Client, bot_url: &str) -> Result<User> {
debug!("Calling get_me...");
let path = ["getMe"];
let url = ::construct_api_url(bot_url, &path);
let mut data = client.get(&url)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let user_json = rjson.get("result").ok_or(JsonNotFound)?;
let user: User = serde_json::from_value(user_json.clone())?;
Ok(user)
}
/// API call which will get called to get the updates for your bot.
pub fn get_updates(
&self,
offset: i32,
limit: Option<i32>,
timeout: Option<i32>,
network_delay: Option<f32>,
) -> Result<Option<Vec<Update>>> {
debug!("Calling get_updates...");
let limit = limit.unwrap_or(100);
let timeout = timeout.unwrap_or(0);
let network_delay = network_delay.unwrap_or(0.0);
let path = ["getUpdates"];
let path_url = ::construct_api_url(&self.bot_url, &path);
let url = format!(
"{}?offset={}&limit={}&timeout={}&network_delay={}",
path_url,
offset,
limit,
timeout,
network_delay
);
let mut data = self.client.get(&url)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let updates_json = rjson.get("result");
if let Some(result) = updates_json {
let updates: Vec<Update> = serde_json::from_value(result.clone())?;
Ok(Some(updates))
} else {
Ok(None)
}
}
/// API call which will send a message to a chat which your bot participates in.
pub fn send_message<M: ReplyMarkup>(
&self,
chat_id: &i64,
text: &str,
parse_mode: Option<&ParseMode>,
disable_web_page_preview: Option<&bool>,
disable_notification: Option<&bool>,
reply_to_message_id: Option<&i64>,
reply_markup: Option<M>,
) -> Result<Message> {
debug!("Calling send_message...");
let chat_id: &str = &chat_id.to_string();
let parse_mode = &get_parse_mode(parse_mode.unwrap_or(&ParseMode::Text));
let disable_web_page_preview: &str =
&disable_web_page_preview.unwrap_or(&false).to_string();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let reply_to_message_id: &str = &reply_to_message_id.map(|i| i.to_string()).unwrap_or(
"None"
.to_string(),
);
let reply_markup = &Box::new(reply_markup)
.map(|r| serde_json::to_string(&r).unwrap_or("".to_string()))
.unwrap_or("".to_string());
let path = ["sendMessage"];
let params = [
("chat_id", chat_id),
("text", text),
("parse_mode", parse_mode),
("disable_web_page_preview", disable_web_page_preview),
("disable_notification", disable_notification),
("reply_to_message_id", reply_to_message_id),
("reply_markup", reply_markup),
];
self.call(&path, ¶ms)
}
/// API call which will reply to a message directed to your bot.
pub fn reply_to_message(&self, update: &Update, text: &str) -> Result<Message> {
debug!("Calling reply_to_message...");
let message = update.clone().message.unwrap();
let message_id = message.message_id;
let chat_id = message.chat.id;
self.send_message(
&chat_id,
text,
None,
None,
None,
Some(&message_id),
::NO_MARKUP,
)
}
/// API call which will forward a message.
pub fn forward_message(
&self,
update: &Update,
chat_id: &i64,
disable_notification: Option<&bool>,
) -> Result<Message> {
debug!("Calling forward_message...");
let message = update.clone().message.unwrap();
let chat_id: &str = &chat_id.to_string();
let from_chat_id: &str = &message.chat.id.to_string();
let message_id: &str = &message.message_id.to_string();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let path = ["forwardMessage"];
let params = [
("chat_id", chat_id),
("from_chat_id", from_chat_id),
("disable_notification", disable_notification),
("message_id", message_id),
];
self.call(&path, ¶ms)
}
/// API call which will show the given chat action to the users.
pub fn send_chat_action(&self, chat_id: &i64, action: &ChatAction) -> Result<bool> {
debug!("Calling send_chat_action...");
let chat_id: &str = &chat_id.to_string();
let action = &get_chat_action(action);
let path = ["sendChatAction"];
let params = [("chat_id", chat_id), ("action", action)];
self.call(&path, ¶ms)
}
/// API call which will send the given contact.
pub fn send_contact(
&self,
chat_id: &i64,
contact: &Contact,
disable_notification: Option<&bool>,
reply_to_message_id: Option<&i64>,
reply_markup: Option<&InlineKeyboardMarkup>,
) -> Result<Message> {
debug!("Calling send_contact...");
let chat_id: &str = &chat_id.to_string();
let phone_number = &contact.phone_number;
let first_name = &contact.first_name;
let last_name = &contact.clone().last_name.unwrap();
let disable_notification: &str = &disable_notification.unwrap_or(&false).to_string();
let reply_to_message_id: &str = &reply_to_message_id.map(|i| i.to_string()).unwrap_or(
"None"
.to_string(),
);
let reply_markup = &reply_markup
.and_then(|r| serde_json::to_string(r).ok())
.unwrap_or("".to_string());
let path = ["sendContact"];
let params = [
("chat_id", chat_id),
("phone_number", phone_number),
("first_name", first_name),
("last_name", last_name),
("disable_notification", disable_notification),
("reply_to_message_id", reply_to_message_id),
("reply_markup", reply_markup),
];
self.call(&path, ¶ms)
}
/// API call which will get a list of profile pictures for a user.
pub fn get_user_profile_photos(
&self,
user_id: &i64,
offset: Option<&i64>,
limit: Option<&i64>,
) -> Result<UserProfilePhotos> {
debug!("Calling get_user_profile_photos...");
let user_id: &str = &user_id.to_string();
let offset: &str = &offset.map(|i| i.to_string()).unwrap_or("None".to_string());
let limit: &str = &limit.map(|i| i.to_string()).unwrap_or("None".to_string());
let path = ["getUserProfilePhotos"];
let params = [("user_id", user_id), ("offset", offset), ("limit", limit)];
self.call(&path, ¶ms)
}
/// API call which will get basic info about a file and prepare it for donwloading.
pub fn get_file(&self, file_id: &str) -> Result<File> {
debug!("Calling get_file...");
let path = ["getFile"];
let params = [("file_id", file_id)];
self.call(&path, ¶ms)
}
/// API call which will kick a user from a group, supergroup or a channel. The bot must be
/// an administrator in the chat for this call to succeed.
pub fn kick_chat_member(
&self,
chat_id: &i64,
user_id: &i64,
until_date: Option<i64>,
) -> Result<bool> {
debug!("Calling kick_chat_member...");
let chat_id: &str = &chat_id.to_string();
let user_id: &str = &user_id.to_string();
let until_date: &str = &until_date.map(|i| i.to_string()).unwrap_or(
"None".to_string(),
);
let path = ["kickChatMember"];
let params = [
("chat_id", chat_id),
("user_id", user_id),
("until_date", until_date),
];
self.call(&path, ¶ms)
}
/// The actual networking done for sending messages.
fn call<T: DeserializeOwned>(&self, path: &[&str], params: &[(&str, &str)]) -> Result<T> {
debug!("Making API call...");
let url = ::construct_api_url(&self.bot_url, path);
let mut data = self.client.post(&url)?.form(¶ms)?.send()?;
let rjson: Value = check_for_error(data.json()?)?;
let object_json = rjson.get("result").ok_or(JsonNotFound)?;
let object = serde_json::from_value::<T>(object_json.clone())?;
Ok(object)
}
}
|
use crate::{Event, Image, ImageError, MsfIndex, TrackType};
use std::path::Path;
use chdr::{ChdError, ChdFile};
use chdr::metadata::CdTrackInfo;
use log::debug;
use thiserror::Error;
const BYTES_PER_SECTOR: u32 = 2352 + 96;
// TODO: Can we really assume that the first track's pregap is always
// two seconds long?
const FIRST_TRACK_PREGAP: u32 = 150;
#[derive(Debug)]
struct Track {
start_lba: u32,
track_type: TrackType,
// Tracks are padded to multiples of 4 sectors in CHDs.
// This is the number of padding sectors that has to be taken
// into account when calculating the LBAs for a particular track.
padding_offset: u32,
track_info: CdTrackInfo,
}
#[derive(Debug, Error)]
pub enum ChdImageError {
#[error(transparent)]
ChdError(#[from] ChdError),
#[error("CHD file does not seem like a CDROM image (wrong hunk size)")]
WrongHunkSize,
#[error("Wrong buffer size, needs to be 2352 bytes")]
WrongBufferSize,
#[error("Unsupported sector format: {0}")]
UnsupportedSectorFormat(String)
}
pub struct ChdImage {
chd: ChdFile,
tracks: Vec<Track>,
hunk: Vec<u8>,
current_hunk_no: u32,
current_lba: u32,
// Starts counting from 0
current_track: usize,
sectors_per_hunk: u32,
}
impl ChdImage {
pub fn open<P>(path: P) -> Result<ChdImage, ChdImageError>
where P: AsRef<Path>
{
let mut chd = ChdFile::open(path)?;
if chd.hunk_len() % BYTES_PER_SECTOR != 0 {
return Err(ChdImageError::WrongHunkSize);
}
let mut hunk = vec![0; chd.hunk_len() as usize];
chd.read_hunk(0, &mut hunk[..])?;
let sectors_per_hunk = chd.hunk_len() / BYTES_PER_SECTOR;
let mut tracks = Vec::new();
if let Ok(chd_tracks) = chd.cd_tracks() {
let mut current_lba = FIRST_TRACK_PREGAP;
let mut total_padding = 0;
for chd_track in chd_tracks {
let track_type = match chd_track.track_type.as_str() {
"MODE1_RAW" => TrackType::Mode1,
"MODE2_RAW" => TrackType::Mode2,
"AUDIO" => TrackType::Audio,
_ => return Err(ChdImageError::UnsupportedSectorFormat(chd_track.track_type)),
};
let start_lba = current_lba;
current_lba += chd_track.frames;
let padding_offset = total_padding;
total_padding += chd_track.frames % 4;
tracks.push(Track {
start_lba,
track_type,
padding_offset,
track_info: chd_track
});
}
}
Ok(ChdImage {
chd,
hunk,
current_hunk_no: 0,
current_lba: 150,
current_track: 0,
sectors_per_hunk,
tracks,
})
}
fn update_current_track(&mut self, lba: u32) -> Result<(), ImageError> {
let current_track = &self.tracks[self.current_track];
let current_track_range_end = current_track.start_lba + current_track.track_info.frames;
if !(current_track.start_lba..current_track_range_end).contains(&lba) {
if let Some(index) = self.tracks.iter().position(
|x| lba >= x.start_lba && lba < (x.start_lba + x.track_info.frames)
) {
self.current_track = index;
Ok(())
} else {
Err(ImageError::OutOfRange)
}
} else {
Ok(())
}
}
fn set_location_lba(&mut self, lba: u32) -> Result<(), ImageError> {
self.current_lba = lba;
// TODO: Can we really assume that the first track's pregap is always
// two seconds long?
if lba < FIRST_TRACK_PREGAP {
self.current_track = 0;
return Ok(());
}
self.update_current_track(lba)?;
let current_track = &self.tracks[self.current_track];
let lba = lba + current_track.padding_offset - FIRST_TRACK_PREGAP;
debug!("set_location_lba {}", lba);
let hunk_no = lba / self.sectors_per_hunk;
if hunk_no > self.chd.num_hunks() {
return Err(ImageError::OutOfRange);
}
if hunk_no != self.current_hunk_no {
let res = self.chd.read_hunk(hunk_no, &mut self.hunk[..]);
if let Err(e) = res {
return Err(ChdImageError::from(e).into());
}
self.current_hunk_no = hunk_no;
}
Ok(())
}
}
impl Image for ChdImage {
fn num_tracks(&self) -> usize {
self.tracks.len()
}
fn current_subchannel_q_valid(&self) -> bool {
// TODO
true
}
fn current_track(&self) -> Result<u8, ImageError> {
Ok(self.current_track as u8 + 1)
}
fn current_index(&self) -> Result<u8, ImageError> {
let current_track = &self.tracks[self.current_track];
let track_local_lba = self.current_lba - current_track.start_lba;
let index = if track_local_lba > current_track.track_info.pregap.unwrap_or(0) {
1
} else {
0
};
Ok(index)
}
fn current_track_local_msf(&self) -> Result<MsfIndex, ImageError> {
let current_track = &self.tracks[self.current_track];
let index01_lba =
current_track.start_lba + current_track.track_info.pregap.unwrap_or(150);
if self.current_lba < index01_lba {
// Negative MSFs are (100,0,0) - x
let reference = 100 * 60 * 75;
let offset = index01_lba - self.current_lba;
Ok(MsfIndex::from_lba(reference - offset)?)
} else {
Ok(MsfIndex::from_lba(self.current_lba - index01_lba)?)
}
}
fn current_global_msf(&self) -> Result<MsfIndex, ImageError> {
Ok(MsfIndex::from_lba(self.current_lba)?)
}
fn current_track_type(&self) -> Result<TrackType, ImageError> {
let current_track = &self.tracks[self.current_track];
Ok(current_track.track_type)
}
fn first_track_type(&self) -> TrackType {
self.tracks.first().unwrap().track_type
}
fn track_start(&self, track: u8) -> Result<MsfIndex, ImageError> {
// Track 0: Special case for PlayStation, return length of whole disc
// TODO: Make this less ugly?
if track == 0 {
let len = self.chd.num_hunks() * self.chd.hunk_len();
let num_sectors = FIRST_TRACK_PREGAP + len / BYTES_PER_SECTOR;
Ok(MsfIndex::from_lba(num_sectors)?)
} else if track <= self.tracks.len() as u8 {
let track = &self.tracks[track as usize - 1];
let start_lba_index01 =
track.start_lba + track.track_info.pregap.unwrap_or(150);
debug!("track_start: {:?} {:?}", track, MsfIndex::from_lba(start_lba_index01));
Ok(MsfIndex::from_lba(start_lba_index01)?)
} else {
Err(ImageError::OutOfRange)
}
}
fn set_location(&mut self, target: MsfIndex) -> Result<(), ImageError> {
self.set_location_lba(target.to_lba())
}
fn set_location_to_track(&mut self, track: u8) -> Result<(), ImageError> {
debug!("set_location_to_track {}", track);
let track_start = self.track_start(track)?;
self.set_location(track_start)?;
Ok(())
}
fn advance_position(&mut self) -> Result<Option<Event>, ImageError> {
let res = self.set_location_lba(self.current_lba + 1);
if let Err(e) = res {
if let ImageError::OutOfRange = e {
Ok(Some(Event::EndOfDisc))
} else {
Err(e)
}
} else {
Ok(None)
}
}
fn copy_current_sector(&self, buf: &mut[u8]) -> Result<(), ImageError> {
if buf.len() != 2352 {
return Err(ChdImageError::WrongBufferSize.into())
}
if self.current_lba < FIRST_TRACK_PREGAP {
buf.fill(0);
return Ok(());
}
let current_track = &self.tracks[self.current_track];
let current_file_lba = self.current_lba + current_track.padding_offset - FIRST_TRACK_PREGAP;
let sector_in_hunk = current_file_lba % self.sectors_per_hunk;
let sector_start = (sector_in_hunk * BYTES_PER_SECTOR) as usize;
let sector = &self.hunk[sector_start..sector_start + 2352];
buf.clone_from_slice(sector);
if self.current_track_type().unwrap() == TrackType::Audio {
for x in buf.chunks_exact_mut(2) {
x.swap(0, 1);
}
}
Ok(())
}
}
Remove handling of CHD track padding
When testing with Tomb Raider 2 (PSX), this cut off the beginning
of voice lines. No idea whether I just handled it wrong, whether
it's already handled in libchdr or whether the padding info is
just deprecated or something...
use crate::{Event, Image, ImageError, MsfIndex, TrackType};
use std::path::Path;
use chdr::{ChdError, ChdFile};
use chdr::metadata::CdTrackInfo;
use log::debug;
use thiserror::Error;
const BYTES_PER_SECTOR: u32 = 2352 + 96;
// TODO: Can we really assume that the first track's pregap is always
// two seconds long?
const FIRST_TRACK_PREGAP: u32 = 150;
#[derive(Debug)]
struct Track {
start_lba: u32,
track_type: TrackType,
track_info: CdTrackInfo,
}
#[derive(Debug, Error)]
pub enum ChdImageError {
#[error(transparent)]
ChdError(#[from] ChdError),
#[error("CHD file does not seem like a CDROM image (wrong hunk size)")]
WrongHunkSize,
#[error("Wrong buffer size, needs to be 2352 bytes")]
WrongBufferSize,
#[error("Unsupported sector format: {0}")]
UnsupportedSectorFormat(String)
}
pub struct ChdImage {
chd: ChdFile,
tracks: Vec<Track>,
hunk: Vec<u8>,
current_hunk_no: u32,
current_lba: u32,
// Starts counting from 0
current_track: usize,
sectors_per_hunk: u32,
}
impl ChdImage {
pub fn open<P>(path: P) -> Result<ChdImage, ChdImageError>
where P: AsRef<Path>
{
let mut chd = ChdFile::open(path)?;
if chd.hunk_len() % BYTES_PER_SECTOR != 0 {
return Err(ChdImageError::WrongHunkSize);
}
let mut hunk = vec![0; chd.hunk_len() as usize];
chd.read_hunk(0, &mut hunk[..])?;
let sectors_per_hunk = chd.hunk_len() / BYTES_PER_SECTOR;
let mut tracks = Vec::new();
if let Ok(chd_tracks) = chd.cd_tracks() {
let mut current_lba = FIRST_TRACK_PREGAP;
for chd_track in chd_tracks {
let track_type = match chd_track.track_type.as_str() {
"MODE1_RAW" => TrackType::Mode1,
"MODE2_RAW" => TrackType::Mode2,
"AUDIO" => TrackType::Audio,
_ => return Err(ChdImageError::UnsupportedSectorFormat(chd_track.track_type)),
};
let start_lba = current_lba;
current_lba += chd_track.frames;
tracks.push(Track {
start_lba,
track_type,
track_info: chd_track
});
}
}
Ok(ChdImage {
chd,
hunk,
current_hunk_no: 0,
current_lba: 150,
current_track: 0,
sectors_per_hunk,
tracks,
})
}
fn update_current_track(&mut self, lba: u32) -> Result<(), ImageError> {
let current_track = &self.tracks[self.current_track];
let current_track_range_end = current_track.start_lba + current_track.track_info.frames;
if !(current_track.start_lba..current_track_range_end).contains(&lba) {
if let Some(index) = self.tracks.iter().position(
|x| lba >= x.start_lba && lba < (x.start_lba + x.track_info.frames)
) {
self.current_track = index;
Ok(())
} else {
Err(ImageError::OutOfRange)
}
} else {
Ok(())
}
}
fn set_location_lba(&mut self, lba: u32) -> Result<(), ImageError> {
self.current_lba = lba;
// TODO: Can we really assume that the first track's pregap is always
// two seconds long?
if lba < FIRST_TRACK_PREGAP {
self.current_track = 0;
return Ok(());
}
self.update_current_track(lba)?;
let lba = lba - FIRST_TRACK_PREGAP;
debug!("set_location_lba {}", lba);
let hunk_no = lba / self.sectors_per_hunk;
if hunk_no > self.chd.num_hunks() {
return Err(ImageError::OutOfRange);
}
if hunk_no != self.current_hunk_no {
let res = self.chd.read_hunk(hunk_no, &mut self.hunk[..]);
if let Err(e) = res {
return Err(ChdImageError::from(e).into());
}
self.current_hunk_no = hunk_no;
}
Ok(())
}
}
impl Image for ChdImage {
fn num_tracks(&self) -> usize {
self.tracks.len()
}
fn current_subchannel_q_valid(&self) -> bool {
// TODO
true
}
fn current_track(&self) -> Result<u8, ImageError> {
Ok(self.current_track as u8 + 1)
}
fn current_index(&self) -> Result<u8, ImageError> {
let current_track = &self.tracks[self.current_track];
let track_local_lba = self.current_lba - current_track.start_lba;
let index = if track_local_lba > current_track.track_info.pregap.unwrap_or(0) {
1
} else {
0
};
Ok(index)
}
fn current_track_local_msf(&self) -> Result<MsfIndex, ImageError> {
let current_track = &self.tracks[self.current_track];
let index01_lba =
current_track.start_lba + current_track.track_info.pregap.unwrap_or(150);
if self.current_lba < index01_lba {
// Negative MSFs are (100,0,0) - x
let reference = 100 * 60 * 75;
let offset = index01_lba - self.current_lba;
Ok(MsfIndex::from_lba(reference - offset)?)
} else {
Ok(MsfIndex::from_lba(self.current_lba - index01_lba)?)
}
}
fn current_global_msf(&self) -> Result<MsfIndex, ImageError> {
Ok(MsfIndex::from_lba(self.current_lba)?)
}
fn current_track_type(&self) -> Result<TrackType, ImageError> {
let current_track = &self.tracks[self.current_track];
Ok(current_track.track_type)
}
fn first_track_type(&self) -> TrackType {
self.tracks.first().unwrap().track_type
}
fn track_start(&self, track: u8) -> Result<MsfIndex, ImageError> {
// Track 0: Special case for PlayStation, return length of whole disc
// TODO: Make this less ugly?
if track == 0 {
let len = self.chd.num_hunks() * self.chd.hunk_len();
let num_sectors = FIRST_TRACK_PREGAP + len / BYTES_PER_SECTOR;
Ok(MsfIndex::from_lba(num_sectors)?)
} else if track <= self.tracks.len() as u8 {
let track = &self.tracks[track as usize - 1];
let start_lba_index01 =
track.start_lba + track.track_info.pregap.unwrap_or(150);
debug!("track_start: {:?} {:?}", track, MsfIndex::from_lba(start_lba_index01));
Ok(MsfIndex::from_lba(start_lba_index01)?)
} else {
Err(ImageError::OutOfRange)
}
}
fn set_location(&mut self, target: MsfIndex) -> Result<(), ImageError> {
self.set_location_lba(target.to_lba())
}
fn set_location_to_track(&mut self, track: u8) -> Result<(), ImageError> {
debug!("set_location_to_track {}", track);
let track_start = self.track_start(track)?;
self.set_location(track_start)?;
Ok(())
}
fn advance_position(&mut self) -> Result<Option<Event>, ImageError> {
let res = self.set_location_lba(self.current_lba + 1);
if let Err(e) = res {
if let ImageError::OutOfRange = e {
Ok(Some(Event::EndOfDisc))
} else {
Err(e)
}
} else {
Ok(None)
}
}
fn copy_current_sector(&self, buf: &mut[u8]) -> Result<(), ImageError> {
if buf.len() != 2352 {
return Err(ChdImageError::WrongBufferSize.into())
}
if self.current_lba < FIRST_TRACK_PREGAP {
buf.fill(0);
return Ok(());
}
let current_file_lba = self.current_lba - FIRST_TRACK_PREGAP;
let sector_in_hunk = current_file_lba % self.sectors_per_hunk;
let sector_start = (sector_in_hunk * BYTES_PER_SECTOR) as usize;
let sector = &self.hunk[sector_start..sector_start + 2352];
buf.clone_from_slice(sector);
if self.current_track_type().unwrap() == TrackType::Audio {
for x in buf.chunks_exact_mut(2) {
x.swap(0, 1);
}
}
Ok(())
}
} |
#![feature(macro_rules)]
//! Implementation of a Micro Transport Protocol library,
//! with both client and server modes.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
use std::io::net::ip::{Ipv4Addr, SocketAddr};
mod libtorresmo {
extern crate time;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
impl fmt::Show for UtpPacketType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
ST_DATA => "ST_DATA",
ST_FIN => "ST_FIN",
ST_STATE => "ST_STATE",
ST_RESET => "ST_RESET",
ST_SYN => "ST_SYN",
};
write!(f, "{}", s)
}
}
#[allow(dead_code)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preseving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: buf[3] as u16 << 8 | buf[2] as u16,
timestamp_microseconds: buf[7] as u32 << 24 | buf[6] as u32 << 16 | buf[5] as u32 << 8 | buf[4] as u32,
timestamp_difference_microseconds: buf[11] as u32 << 24 | buf[10] as u32 << 16 | buf[9] as u32 << 8 | buf[8] as u32,
wnd_size: buf[15] as u32 << 24 | buf[14] as u32 << 16 | buf[13] as u32 << 8 | buf[12] as u32,
seq_nr: buf[17] as u16 << 8 | buf[16] as u16,
ack_nr: buf[19] as u16 << 8 | buf[18] as u16,
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
fn get_type(self) -> UtpPacketType {
self.header.get_type()
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
}
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE);
try!(self.socket.sendto(resp.bytes().as_slice(), $src));
println!("sent {}", resp.header);
})
)
impl UtpSocket {
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let r: u16 = random();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: r.to_be(),
sender_connection_id: (r + 1).to_be(),
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
}),
Err(e) => Err(e)
}
}
pub fn connect(mut self, other: SocketAddr) -> UtpSocket {
self.connected_to = other;
/*
let stream = UtpStream::new(s, other);
stream.connect()
*/
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = (self.sender_connection_id - 1).to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.sendto(packet.bytes().as_slice(), dst);
println!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..512];
let (_len, addr) = self.recvfrom(buf).unwrap();
println!("Connected to: {} {}", addr, self.connected_to);
assert!(addr == self.connected_to);
self.seq_nr += 1;
self
}
/// TODO: return error on recv after connection closed (RST or FIN + all
/// packets received)
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
let mut b = [0, ..512];
let response = self.socket.recvfrom(b);
let _src: SocketAddr;
let read;
match response {
Ok((nread, src)) => { read = nread; _src = src },
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b);
let x = packet.header;
println!("received {}", packet.header);
self.ack_nr = Int::from_be(x.seq_nr);
match packet.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(x.connection_id) + 1;
self.sender_connection_id = Int::from_be(x.connection_id);
reply_with_ack!(&x, _src);
// Packets with no payload don't increase seq_nr
//self.seq_nr += 1;
self.state = CS_CONNECTED;
}
ST_DATA => reply_with_ack!(&x, _src),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
reply_with_ack!(&x, _src);
}
_ => {}
};
for i in range(0u, ::std::cmp::min(buf.len(), read-HEADER_SIZE)) {
buf[i] = b[i+HEADER_SIZE];
}
println!("{}", Vec::from_slice(buf.slice(0,read-HEADER_SIZE)));
Ok((read-HEADER_SIZE, _src))
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro.to_le() - other_t_micro.to_le()).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(buf);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
let r = self.socket.sendto(packet.bytes().as_slice(), dst);
// Expect ACK
let mut buf = [0, ..512];
try!(self.socket.recvfrom(buf));
let resp = UtpPacket::decode(buf);
println!("received {}", resp.header);
let x = resp.header;
assert_eq!(resp.get_type(), ST_STATE);
assert_eq!(Int::from_be(x.ack_nr), self.seq_nr);
// Success, increment sequence number
if buf.len() > 0 {
self.seq_nr += 1;
}
r
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
let r: u16 = random();
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: r.to_be(),
sender_connection_id: (r + 1).to_be(),
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
}
}
}
}
fn usage() {
println!("Usage: torresmo [-s|-c] <address> <port>");
}
fn main() {
use libtorresmo::UtpSocket;
use std::from_str::FromStr;
// Defaults
let mut addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 8080 };
let args = std::os::args();
if args.len() == 4 {
addr = SocketAddr {
ip: FromStr::from_str(args.get(2).as_slice()).unwrap(),
port: FromStr::from_str(args.get(3).as_slice()).unwrap(),
};
}
match args.get(1).as_slice() {
"-s" => {
let mut buf = [0, ..512];
let mut sock = UtpSocket::bind(addr).unwrap();
println!("Serving on {}", addr);
loop {
match sock.recvfrom(buf) {
Ok((read, _src)) => {
spawn(proc() {
let buf = buf.slice(0, read);
let path = Path::new("output.txt");
let mut file = match std::io::File::open_mode(&path, std::io::Open, std::io::ReadWrite) {
Ok(f) => f,
Err(e) => fail!("file error: {}", e),
};
match file.write(buf) {
Ok(_) => {}
Err(e) => fail!("error writing to file: {}", e),
};
/*
let mut stream = sock.connect(src);
let payload = String::from_str("Hello\n").into_bytes();
// Send uTP packet
let _ = stream.write(payload.as_slice());
*/
})
}
Err(_) => {}
}
}
}
"-c" => {
let sock = UtpSocket::bind(SocketAddr { ip: Ipv4Addr(127,0,0,1), port: std::rand::random() }).unwrap();
let mut stream = sock.connect(addr);
let buf = [0xF, ..512];
let _ = stream.sendto(buf, addr);
//let _ = stream.write([0]);
//let mut buf = [0, ..512];
//stream.read(buf);
//let stream = stream.terminate();
drop(stream);
}
_ => usage(),
}
}
Print socket error and abort.
#![feature(macro_rules)]
//! Implementation of a Micro Transport Protocol library,
//! with both client and server modes.
//!
//! http://www.bittorrent.org/beps/bep_0029.html
use std::io::net::ip::{Ipv4Addr, SocketAddr};
mod libtorresmo {
extern crate time;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::SocketAddr;
use std::io::IoResult;
use std::mem::transmute;
use std::rand::random;
use std::fmt;
static HEADER_SIZE: uint = 20;
#[test]
fn test_packet_decode() {
let buf = [0x21, 0x00, 0x41, 0xa8, 0x99, 0x2f, 0xd0, 0x2a, 0x9f, 0x4a,
0x26, 0x21, 0x00, 0x10, 0x00, 0x00, 0x3a, 0xf2, 0x6c, 0x79];
let pkt = UtpPacket::decode(buf);
assert_eq!(pkt.header.get_version(), 1);
assert_eq!(pkt.header.get_type(), ST_STATE);
assert_eq!(pkt.header.extension, 0);
assert_eq!(Int::from_be(pkt.header.connection_id), 16808);
assert_eq!(Int::from_be(pkt.header.timestamp_microseconds), 2570047530);
assert_eq!(Int::from_be(pkt.header.timestamp_difference_microseconds), 2672436769);
assert_eq!(Int::from_be(pkt.header.wnd_size), ::std::num::pow(2u32, 20));
assert_eq!(Int::from_be(pkt.header.seq_nr), 15090);
assert_eq!(Int::from_be(pkt.header.ack_nr), 27769);
assert_eq!(pkt.len(), buf.len());
assert!(pkt.payload.is_empty());
}
#[test]
fn test_packet_encode() {
let payload = Vec::from_slice("Hello\n".as_bytes());
let (timestamp, timestamp_diff): (u32, u32) = (15270793, 1707040186);
let (connection_id, seq_nr, ack_nr): (u16, u16, u16) = (16808, 15090, 17096);
let window_size: u32 = 1048576;
let mut pkt = UtpPacket::new();
pkt.set_type(ST_DATA);
pkt.header.timestamp_microseconds = timestamp.to_be();
pkt.header.timestamp_difference_microseconds = timestamp_diff.to_be();
pkt.header.connection_id = connection_id.to_be();
pkt.header.seq_nr = seq_nr.to_be();
pkt.header.ack_nr = ack_nr.to_be();
pkt.header.wnd_size = window_size.to_be();
pkt.payload = payload.clone();
let header = pkt.header;
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(pkt.len(), buf.len());
assert_eq!(pkt.len(), HEADER_SIZE + payload.len());
assert_eq!(pkt.payload, payload);
assert_eq!(header.get_version(), 1);
assert_eq!(header.get_type(), ST_DATA);
assert_eq!(header.extension, 0);
assert_eq!(Int::from_be(header.connection_id), connection_id);
assert_eq!(Int::from_be(header.seq_nr), seq_nr);
assert_eq!(Int::from_be(header.ack_nr), ack_nr);
assert_eq!(Int::from_be(header.wnd_size), window_size);
assert_eq!(Int::from_be(header.timestamp_microseconds), timestamp);
assert_eq!(Int::from_be(header.timestamp_difference_microseconds), timestamp_diff);
assert_eq!(pkt.bytes(), Vec::from_slice(buf));
}
#[test]
fn test_reversible() {
let buf: &[u8] = [0x01, 0x00, 0x41, 0xa8, 0x00, 0xe9, 0x03, 0x89,
0x65, 0xbf, 0x5d, 0xba, 0x00, 0x10, 0x00, 0x00,
0x3a, 0xf2, 0x42, 0xc8, 0x48, 0x65, 0x6c, 0x6c,
0x6f, 0x0a];
assert_eq!(UtpPacket::decode(buf).bytes().as_slice(), buf);
}
/// Return current time in microseconds since the UNIX epoch.
fn now_microseconds() -> u32 {
let t = time::get_time();
(t.sec * 1_000_000) as u32 + (t.nsec/1000) as u32
}
#[allow(dead_code,non_camel_case_types)]
#[deriving(PartialEq,Eq)]
enum UtpPacketType {
ST_DATA = 0,
ST_FIN = 1,
ST_STATE = 2,
ST_RESET = 3,
ST_SYN = 4,
}
impl fmt::Show for UtpPacketType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
ST_DATA => "ST_DATA",
ST_FIN => "ST_FIN",
ST_STATE => "ST_STATE",
ST_RESET => "ST_RESET",
ST_SYN => "ST_SYN",
};
write!(f, "{}", s)
}
}
#[allow(dead_code)]
#[packed]
struct UtpPacketHeader {
type_ver: u8, // type: u4, ver: u4
extension: u8,
connection_id: u16,
timestamp_microseconds: u32,
timestamp_difference_microseconds: u32,
wnd_size: u32,
seq_nr: u16,
ack_nr: u16,
}
impl UtpPacketHeader {
/// Set type of packet to the specified type.
fn set_type(&mut self, t: UtpPacketType) {
let version = 0x0F & self.type_ver;
self.type_ver = t as u8 << 4 | version;
}
fn get_type(self) -> UtpPacketType {
let t: UtpPacketType = unsafe { transmute(self.type_ver >> 4) };
t
}
fn get_version(self) -> u8 {
self.type_ver & 0x0F
}
/// Return packet header as a slice of bytes.
fn bytes(&self) -> &[u8] {
let buf: &[u8, ..HEADER_SIZE] = unsafe { transmute(self) };
return buf.as_slice();
}
fn len(&self) -> uint {
return HEADER_SIZE;
}
/// Read byte buffer and return corresponding packet header.
/// It assumes the fields are in network (big-endian) byte order,
/// preseving it.
fn decode(buf: &[u8]) -> UtpPacketHeader {
UtpPacketHeader {
type_ver: buf[0],
extension: buf[1],
connection_id: buf[3] as u16 << 8 | buf[2] as u16,
timestamp_microseconds: buf[7] as u32 << 24 | buf[6] as u32 << 16 | buf[5] as u32 << 8 | buf[4] as u32,
timestamp_difference_microseconds: buf[11] as u32 << 24 | buf[10] as u32 << 16 | buf[9] as u32 << 8 | buf[8] as u32,
wnd_size: buf[15] as u32 << 24 | buf[14] as u32 << 16 | buf[13] as u32 << 8 | buf[12] as u32,
seq_nr: buf[17] as u16 << 8 | buf[16] as u16,
ack_nr: buf[19] as u16 << 8 | buf[18] as u16,
}
}
}
impl fmt::Show for UtpPacketHeader {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(type: {}, version: {}, extension: {}, \
connection_id: {}, timestamp_microseconds: {}, \
timestamp_difference_microseconds: {}, wnd_size: {}, \
seq_nr: {}, ack_nr: {})",
self.get_type(),
Int::from_be(self.get_version()),
Int::from_be(self.extension),
Int::from_be(self.connection_id),
Int::from_be(self.timestamp_microseconds),
Int::from_be(self.timestamp_difference_microseconds),
Int::from_be(self.wnd_size),
Int::from_be(self.seq_nr),
Int::from_be(self.ack_nr),
)
}
}
#[allow(dead_code)]
struct UtpPacket {
header: UtpPacketHeader,
payload: Vec<u8>,
}
impl UtpPacket {
/// Construct a new, empty packet.
fn new() -> UtpPacket {
UtpPacket {
header: UtpPacketHeader {
type_ver: ST_DATA as u8 << 4 | 1,
extension: 0,
connection_id: 0,
timestamp_microseconds: 0,
timestamp_difference_microseconds: 0,
wnd_size: 0,
seq_nr: 0,
ack_nr: 0,
},
payload: Vec::new(),
}
}
fn set_type(&mut self, t: UtpPacketType) {
self.header.set_type(t);
}
fn get_type(self) -> UtpPacketType {
self.header.get_type()
}
/// TODO: return slice
fn bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.len());
buf.push_all(self.header.bytes());
buf.push_all(self.payload.as_slice());
return buf;
}
fn len(&self) -> uint {
self.header.len() + self.payload.len()
}
fn decode(buf: &[u8]) -> UtpPacket {
UtpPacket {
header: UtpPacketHeader::decode(buf),
payload: Vec::from_slice(buf.slice(HEADER_SIZE, buf.len()))
}
}
}
#[allow(non_camel_case_types)]
#[deriving(PartialEq,Eq)]
enum UtpSocketState {
CS_NEW,
CS_CONNECTED,
CS_SYN_SENT,
CS_FIN_RECEIVED,
}
pub struct UtpSocket {
socket: UdpSocket,
connected_to: SocketAddr,
sender_connection_id: u16,
receiver_connection_id: u16,
seq_nr: u16,
ack_nr: u16,
state: UtpSocketState,
}
macro_rules! reply_with_ack(
($header:expr, $src:expr) => ({
let resp = self.prepare_reply($header, ST_STATE);
try!(self.socket.sendto(resp.bytes().as_slice(), $src));
println!("sent {}", resp.header);
})
)
impl UtpSocket {
pub fn bind(addr: SocketAddr) -> IoResult<UtpSocket> {
let skt = UdpSocket::bind(addr);
let r: u16 = random();
match skt {
Ok(x) => Ok(UtpSocket {
socket: x,
connected_to: addr,
receiver_connection_id: r.to_be(),
sender_connection_id: (r + 1).to_be(),
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
}),
Err(e) => Err(e)
}
}
pub fn connect(mut self, other: SocketAddr) -> UtpSocket {
self.connected_to = other;
/*
let stream = UtpStream::new(s, other);
stream.connect()
*/
let mut packet = UtpPacket::new();
packet.set_type(ST_SYN);
packet.header.connection_id = (self.sender_connection_id - 1).to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.timestamp_microseconds = now_microseconds().to_be();
// Send packet
let dst = self.connected_to;
let _result = self.socket.sendto(packet.bytes().as_slice(), dst);
println!("sent {}", packet.header);
self.state = CS_SYN_SENT;
let mut buf = [0, ..512];
let (_len, addr) = self.recvfrom(buf).unwrap();
println!("Connected to: {} {}", addr, self.connected_to);
assert!(addr == self.connected_to);
self.seq_nr += 1;
self
}
/// TODO: return error on recv after connection closed (RST or FIN + all
/// packets received)
pub fn recvfrom(&mut self, buf: &mut[u8]) -> IoResult<(uint,SocketAddr)> {
let mut b = [0, ..512];
let response = self.socket.recvfrom(b);
let _src: SocketAddr;
let read;
match response {
Ok((nread, src)) => { read = nread; _src = src },
Err(e) => return Err(e),
};
let packet = UtpPacket::decode(b);
let x = packet.header;
println!("received {}", packet.header);
self.ack_nr = Int::from_be(x.seq_nr);
match packet.get_type() {
ST_SYN => { // Respond with an ACK and populate own fields
// Update socket information for new connections
self.seq_nr = random();
self.receiver_connection_id = Int::from_be(x.connection_id) + 1;
self.sender_connection_id = Int::from_be(x.connection_id);
reply_with_ack!(&x, _src);
// Packets with no payload don't increase seq_nr
//self.seq_nr += 1;
self.state = CS_CONNECTED;
}
ST_DATA => reply_with_ack!(&x, _src),
ST_FIN => {
self.state = CS_FIN_RECEIVED;
reply_with_ack!(&x, _src);
}
_ => {}
};
for i in range(0u, ::std::cmp::min(buf.len(), read-HEADER_SIZE)) {
buf[i] = b[i+HEADER_SIZE];
}
println!("{}", Vec::from_slice(buf.slice(0,read-HEADER_SIZE)));
Ok((read-HEADER_SIZE, _src))
}
fn prepare_reply(&self, original: &UtpPacketHeader, t: UtpPacketType) -> UtpPacket {
let mut resp = UtpPacket::new();
resp.set_type(t);
let self_t_micro: u32 = now_microseconds();
let other_t_micro: u32 = Int::from_be(original.timestamp_microseconds);
resp.header.timestamp_microseconds = self_t_micro.to_be();
resp.header.timestamp_difference_microseconds = (self_t_micro.to_le() - other_t_micro.to_le()).to_be();
resp.header.connection_id = self.sender_connection_id.to_be();
resp.header.seq_nr = self.seq_nr.to_be();
resp.header.ack_nr = self.ack_nr.to_be();
resp
}
pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
let mut packet = UtpPacket::new();
packet.set_type(ST_DATA);
packet.payload = Vec::from_slice(buf);
packet.header.timestamp_microseconds = now_microseconds().to_be();
packet.header.seq_nr = self.seq_nr.to_be();
packet.header.ack_nr = self.ack_nr.to_be();
packet.header.connection_id = self.sender_connection_id.to_be();
let r = self.socket.sendto(packet.bytes().as_slice(), dst);
// Expect ACK
let mut buf = [0, ..512];
try!(self.socket.recvfrom(buf));
let resp = UtpPacket::decode(buf);
println!("received {}", resp.header);
let x = resp.header;
assert_eq!(resp.get_type(), ST_STATE);
assert_eq!(Int::from_be(x.ack_nr), self.seq_nr);
// Success, increment sequence number
if buf.len() > 0 {
self.seq_nr += 1;
}
r
}
}
impl Clone for UtpSocket {
fn clone(&self) -> UtpSocket {
let r: u16 = random();
UtpSocket {
socket: self.socket.clone(),
connected_to: self.connected_to,
receiver_connection_id: r.to_be(),
sender_connection_id: (r + 1).to_be(),
seq_nr: 1,
ack_nr: 0,
state: CS_NEW,
}
}
}
}
fn usage() {
println!("Usage: torresmo [-s|-c] <address> <port>");
}
fn main() {
use libtorresmo::UtpSocket;
use std::from_str::FromStr;
// Defaults
let mut addr = SocketAddr { ip: Ipv4Addr(127,0,0,1), port: 8080 };
let args = std::os::args();
if args.len() == 4 {
addr = SocketAddr {
ip: FromStr::from_str(args.get(2).as_slice()).unwrap(),
port: FromStr::from_str(args.get(3).as_slice()).unwrap(),
};
}
match args.get(1).as_slice() {
"-s" => {
let mut buf = [0, ..512];
let mut sock = UtpSocket::bind(addr).unwrap();
println!("Serving on {}", addr);
loop {
match sock.recvfrom(buf) {
Ok((read, _src)) => {
spawn(proc() {
let buf = buf.slice(0, read);
let path = Path::new("output.txt");
let mut file = match std::io::File::open_mode(&path, std::io::Open, std::io::ReadWrite) {
Ok(f) => f,
Err(e) => fail!("file error: {}", e),
};
match file.write(buf) {
Ok(_) => {}
Err(e) => fail!("error writing to file: {}", e),
};
/*
let mut stream = sock.connect(src);
let payload = String::from_str("Hello\n").into_bytes();
// Send uTP packet
let _ = stream.write(payload.as_slice());
*/
})
}
Err(e) => { println!("{}", e); break; }
}
}
}
"-c" => {
let sock = UtpSocket::bind(SocketAddr { ip: Ipv4Addr(127,0,0,1), port: std::rand::random() }).unwrap();
let mut stream = sock.connect(addr);
let buf = [0xF, ..512];
let _ = stream.sendto(buf, addr);
//let _ = stream.write([0]);
//let mut buf = [0, ..512];
//stream.read(buf);
//let stream = stream.terminate();
drop(stream);
}
_ => usage(),
}
}
|
//! CLI arguments and library Args struct
//!
//! Use `ArgsBuilder` preferentially as that will shield you from breaking changes resulting from
//! added fields and some field type changes.
//!
//! # Examples
//!
//! ```
//! # use watchexec::cli::ArgsBuilder;
//! ArgsBuilder::default()
//! .cmd(vec!["echo hello world".into()])
//! .paths(vec![".".into()])
//! .build()
//! .expect("mission failed");
//! ```
use crate::error;
use clap::{App, Arg, Error};
use std::{
ffi::OsString,
path::{PathBuf, MAIN_SEPARATOR},
process::Command,
};
/// Arguments to the watcher
#[derive(Builder, Clone, Debug)]
#[builder(setter(into, strip_option))]
#[builder(build_fn(validate = "Self::validate"))]
pub struct Args {
/// Command to execute in popen3 format (first program, rest arguments).
pub cmd: Vec<String>,
/// List of paths to watch for changes.
pub paths: Vec<PathBuf>,
/// Positive filters (trigger only on matching changes). Glob format.
#[builder(default)]
pub filters: Vec<String>,
/// Negative filters (do not trigger on matching changes). Glob format.
#[builder(default)]
pub ignores: Vec<String>,
/// Clear the screen before each run.
#[builder(default)]
pub clear_screen: bool,
/// If Some, send that signal (e.g. SIGHUP) to the child on change.
#[builder(default)]
pub signal: Option<String>,
/// If true, kill the child if it's still running when a change comes in.
#[builder(default)]
pub restart: bool,
/// Interval to debounce the changes. (milliseconds)
#[builder(default = "500")]
pub debounce: u64,
/// Enable debug/verbose logging.
#[builder(default)]
pub debug: bool,
/// Run the commands right after starting.
#[builder(default = "true")]
pub run_initially: bool,
/// Do not wrap the commands in a shell.
#[builder(default)]
pub no_shell: bool,
/// Ignore metadata changes.
#[builder(default)]
pub no_meta: bool,
/// Do not set WATCHEXEC_*_PATH environment variables for child process.
#[builder(default)]
pub no_environment: bool,
/// Skip auto-loading .gitignore files
#[builder(default)]
pub no_vcs_ignore: bool,
/// Skip auto-loading .ignore files
#[builder(default)]
pub no_ignore: bool,
/// For testing only, always set to false.
#[builder(setter(skip))]
#[builder(default)]
pub once: bool,
/// Force using the polling backend.
#[builder(default)]
pub poll: bool,
/// Interval for polling. (milliseconds)
#[builder(default = "2")]
pub poll_interval: u32,
#[builder(default)]
pub watch_when_idle: bool,
}
impl ArgsBuilder {
fn validate(&self) -> Result<(), String> {
if self.cmd.as_ref().map_or(true, Vec::is_empty) {
return Err("cmd must not be empty".into());
}
if self.paths.as_ref().map_or(true, Vec::is_empty) {
return Err("paths must not be empty".into());
}
Ok(())
}
}
#[cfg(target_family = "windows")]
pub fn clear_screen() {
let _ = Command::new("cmd")
.arg("/c")
.arg("tput reset || cls")
.status();
}
#[cfg(target_family = "unix")]
pub fn clear_screen() {
let _ = Command::new("tput").arg("reset").status();
}
pub fn get_args() -> error::Result<Args> {
get_args_impl(None::<&[&str]>)
}
pub fn get_args_from<I, T>(from: I) -> error::Result<Args>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
get_args_impl(Some(from))
}
fn get_args_impl<I, T>(from: Option<I>) -> error::Result<Args>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let app = App::new("watchexec")
.version(crate_version!())
.about("Execute commands when watched files change")
.arg(Arg::with_name("command")
.help("Command to execute")
.multiple(true)
.required(true))
.arg(Arg::with_name("extensions")
.help("Comma-separated list of file extensions to watch (js,css,html)")
.short("e")
.long("exts")
.takes_value(true))
.arg(Arg::with_name("path")
.help("Watch a specific directory")
.short("w")
.long("watch")
.number_of_values(1)
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("clear")
.help("Clear screen before executing command")
.short("c")
.long("clear"))
.arg(Arg::with_name("restart")
.help("Restart the process if it's still running")
.short("r")
.long("restart"))
.arg(Arg::with_name("signal")
.help("Send signal to process upon changes, e.g. SIGHUP")
.short("s")
.long("signal")
.takes_value(true)
.number_of_values(1)
.value_name("signal"))
.arg(Arg::with_name("kill")
.help("Send SIGKILL to child processes (deprecated, use -s SIGKILL instead)")
.short("k")
.long("kill"))
.arg(Arg::with_name("debounce")
.help("Set the timeout between detected change and command execution, defaults to 500ms")
.takes_value(true)
.value_name("milliseconds")
.short("d")
.long("debounce"))
.arg(Arg::with_name("verbose")
.help("Print debugging messages to stderr")
.short("v")
.long("verbose"))
.arg(Arg::with_name("filter")
.help("Ignore all modifications except those matching the pattern")
.short("f")
.long("filter")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("ignore")
.help("Ignore modifications to paths matching the pattern")
.short("i")
.long("ignore")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("no-vcs-ignore")
.help("Skip auto-loading of .gitignore files for filtering")
.long("no-vcs-ignore"))
.arg(Arg::with_name("no-ignore")
.help("Skip auto-loading of ignore files (.gitignore, .ignore, etc.) for filtering")
.long("no-ignore"))
.arg(Arg::with_name("no-default-ignore")
.help("Skip auto-ignoring of commonly ignored globs")
.long("no-default-ignore"))
.arg(Arg::with_name("postpone")
.help("Wait until first change to execute command")
.short("p")
.long("postpone"))
.arg(Arg::with_name("poll")
.help("Force polling mode (interval in milliseconds)")
.long("force-poll")
.value_name("interval"))
.arg(Arg::with_name("no-shell")
.help("Do not wrap command in 'sh -c' resp. 'cmd.exe /C'")
.short("n")
.long("no-shell"))
.arg(Arg::with_name("no-meta")
.help("Ignore metadata changes")
.long("no-meta"))
.arg(Arg::with_name("no-environment")
.help("Do not set WATCHEXEC_*_PATH environment variables for child process")
.long("no-environment"))
.arg(Arg::with_name("once").short("1").hidden(true))
.arg(Arg::with_name("watch-when-idle")
.help("Ignore events while the process is still running")
.short("W")
.long("watch-when-idle"));
let args = match from {
None => app.get_matches(),
Some(i) => app.get_matches_from(i),
};
let cmd: Vec<String> = values_t!(args.values_of("command"), String)?;
let paths = values_t!(args.values_of("path"), String)
.unwrap_or_else(|_| vec![".".into()])
.iter()
.map(|string_path| string_path.into())
.collect();
// Treat --kill as --signal SIGKILL (for compatibility with older syntax)
let signal = if args.is_present("kill") {
Some("SIGKILL".to_string())
} else {
// Convert Option<&str> to Option<String>
args.value_of("signal").map(str::to_string)
};
let mut filters = values_t!(args.values_of("filter"), String).unwrap_or_else(|_| Vec::new());
if let Some(extensions) = args.values_of("extensions") {
for exts in extensions {
filters.extend(exts.split(',').filter_map(|ext| {
if ext.is_empty() {
None
} else {
Some(format!("*.{}", ext.replace(".", "")))
}
}));
}
}
let mut ignores = vec![];
let default_ignores = vec![
format!("**{}.DS_Store", MAIN_SEPARATOR),
String::from("*.py[co]"),
String::from("#*#"),
String::from(".#*"),
String::from(".*.kate-swp"),
String::from(".*.sw?"),
String::from(".*.sw?x"),
format!("**{}.git{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
format!("**{}.hg{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
format!("**{}.svn{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
];
if args.occurrences_of("no-default-ignore") == 0 {
ignores.extend(default_ignores)
};
ignores.extend(values_t!(args.values_of("ignore"), String).unwrap_or_else(|_| Vec::new()));
let poll_interval = if args.occurrences_of("poll") > 0 {
value_t!(args.value_of("poll"), u32).unwrap_or_else(|e| e.exit())
} else {
1000
};
let debounce = if args.occurrences_of("debounce") > 0 {
value_t!(args.value_of("debounce"), u64).unwrap_or_else(|e| e.exit())
} else {
500
};
if signal.is_some() && args.is_present("postpone") {
// TODO: Error::argument_conflict() might be the better fit, usage was unclear, though
Error::value_validation_auto("--postpone and --signal are mutually exclusive".to_string())
.exit();
}
if signal.is_some() && args.is_present("kill") {
// TODO: Error::argument_conflict() might be the better fit, usage was unclear, though
Error::value_validation_auto("--kill and --signal is ambiguous.\n Hint: Use only '--signal SIGKILL' without --kill".to_string())
.exit();
}
Ok(Args {
cmd,
paths,
filters,
ignores,
signal,
clear_screen: args.is_present("clear"),
restart: args.is_present("restart"),
debounce,
debug: args.is_present("verbose"),
run_initially: !args.is_present("postpone"),
no_shell: args.is_present("no-shell"),
no_meta: args.is_present("no-meta"),
no_environment: args.is_present("no-environment"),
no_vcs_ignore: args.is_present("no-vcs-ignore"),
no_ignore: args.is_present("no-ignore"),
once: args.is_present("once"),
poll: args.occurrences_of("poll") > 0,
poll_interval,
watch_when_idle: args.is_present("watch-when-idle"),
})
}
Add soft deprecation on Args.debug
//! CLI arguments and library Args struct
//!
//! Use `ArgsBuilder` preferentially as that will shield you from breaking changes resulting from
//! added fields and some field type changes.
//!
//! # Examples
//!
//! ```
//! # use watchexec::cli::ArgsBuilder;
//! ArgsBuilder::default()
//! .cmd(vec!["echo hello world".into()])
//! .paths(vec![".".into()])
//! .build()
//! .expect("mission failed");
//! ```
use crate::error;
use clap::{App, Arg, Error};
use std::{
ffi::OsString,
path::{PathBuf, MAIN_SEPARATOR},
process::Command,
};
/// Arguments to the watcher
#[derive(Builder, Clone, Debug)]
#[builder(setter(into, strip_option))]
#[builder(build_fn(validate = "Self::validate"))]
pub struct Args {
/// Command to execute in popen3 format (first program, rest arguments).
pub cmd: Vec<String>,
/// List of paths to watch for changes.
pub paths: Vec<PathBuf>,
/// Positive filters (trigger only on matching changes). Glob format.
#[builder(default)]
pub filters: Vec<String>,
/// Negative filters (do not trigger on matching changes). Glob format.
#[builder(default)]
pub ignores: Vec<String>,
/// Clear the screen before each run.
#[builder(default)]
pub clear_screen: bool,
/// If Some, send that signal (e.g. SIGHUP) to the child on change.
#[builder(default)]
pub signal: Option<String>,
/// If true, kill the child if it's still running when a change comes in.
#[builder(default)]
pub restart: bool,
/// Interval to debounce the changes. (milliseconds)
#[builder(default = "500")]
pub debounce: u64,
/// Enable debug/verbose logging. No longer used as of 1.14.0 (soft-deprecated).
///
/// Debug messages are printed via debug! so configure your logger appropriately instead.
#[builder(default)]
pub debug: bool,
/// Run the commands right after starting.
#[builder(default = "true")]
pub run_initially: bool,
/// Do not wrap the commands in a shell.
#[builder(default)]
pub no_shell: bool,
/// Ignore metadata changes.
#[builder(default)]
pub no_meta: bool,
/// Do not set WATCHEXEC_*_PATH environment variables for child process.
#[builder(default)]
pub no_environment: bool,
/// Skip auto-loading .gitignore files
#[builder(default)]
pub no_vcs_ignore: bool,
/// Skip auto-loading .ignore files
#[builder(default)]
pub no_ignore: bool,
/// For testing only, always set to false.
#[builder(setter(skip))]
#[builder(default)]
pub once: bool,
/// Force using the polling backend.
#[builder(default)]
pub poll: bool,
/// Interval for polling. (milliseconds)
#[builder(default = "2")]
pub poll_interval: u32,
#[builder(default)]
pub watch_when_idle: bool,
}
impl ArgsBuilder {
fn validate(&self) -> Result<(), String> {
if self.cmd.as_ref().map_or(true, Vec::is_empty) {
return Err("cmd must not be empty".into());
}
if self.paths.as_ref().map_or(true, Vec::is_empty) {
return Err("paths must not be empty".into());
}
Ok(())
}
}
#[cfg(target_family = "windows")]
pub fn clear_screen() {
let _ = Command::new("cmd")
.arg("/c")
.arg("tput reset || cls")
.status();
}
#[cfg(target_family = "unix")]
pub fn clear_screen() {
let _ = Command::new("tput").arg("reset").status();
}
pub fn get_args() -> error::Result<Args> {
get_args_impl(None::<&[&str]>)
}
pub fn get_args_from<I, T>(from: I) -> error::Result<Args>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
get_args_impl(Some(from))
}
fn get_args_impl<I, T>(from: Option<I>) -> error::Result<Args>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let app = App::new("watchexec")
.version(crate_version!())
.about("Execute commands when watched files change")
.arg(Arg::with_name("command")
.help("Command to execute")
.multiple(true)
.required(true))
.arg(Arg::with_name("extensions")
.help("Comma-separated list of file extensions to watch (js,css,html)")
.short("e")
.long("exts")
.takes_value(true))
.arg(Arg::with_name("path")
.help("Watch a specific directory")
.short("w")
.long("watch")
.number_of_values(1)
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("clear")
.help("Clear screen before executing command")
.short("c")
.long("clear"))
.arg(Arg::with_name("restart")
.help("Restart the process if it's still running")
.short("r")
.long("restart"))
.arg(Arg::with_name("signal")
.help("Send signal to process upon changes, e.g. SIGHUP")
.short("s")
.long("signal")
.takes_value(true)
.number_of_values(1)
.value_name("signal"))
.arg(Arg::with_name("kill")
.help("Send SIGKILL to child processes (deprecated, use -s SIGKILL instead)")
.short("k")
.long("kill"))
.arg(Arg::with_name("debounce")
.help("Set the timeout between detected change and command execution, defaults to 500ms")
.takes_value(true)
.value_name("milliseconds")
.short("d")
.long("debounce"))
.arg(Arg::with_name("verbose")
.help("Print debugging messages to stderr")
.short("v")
.long("verbose"))
.arg(Arg::with_name("filter")
.help("Ignore all modifications except those matching the pattern")
.short("f")
.long("filter")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("ignore")
.help("Ignore modifications to paths matching the pattern")
.short("i")
.long("ignore")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.value_name("pattern"))
.arg(Arg::with_name("no-vcs-ignore")
.help("Skip auto-loading of .gitignore files for filtering")
.long("no-vcs-ignore"))
.arg(Arg::with_name("no-ignore")
.help("Skip auto-loading of ignore files (.gitignore, .ignore, etc.) for filtering")
.long("no-ignore"))
.arg(Arg::with_name("no-default-ignore")
.help("Skip auto-ignoring of commonly ignored globs")
.long("no-default-ignore"))
.arg(Arg::with_name("postpone")
.help("Wait until first change to execute command")
.short("p")
.long("postpone"))
.arg(Arg::with_name("poll")
.help("Force polling mode (interval in milliseconds)")
.long("force-poll")
.value_name("interval"))
.arg(Arg::with_name("no-shell")
.help("Do not wrap command in 'sh -c' resp. 'cmd.exe /C'")
.short("n")
.long("no-shell"))
.arg(Arg::with_name("no-meta")
.help("Ignore metadata changes")
.long("no-meta"))
.arg(Arg::with_name("no-environment")
.help("Do not set WATCHEXEC_*_PATH environment variables for child process")
.long("no-environment"))
.arg(Arg::with_name("once").short("1").hidden(true))
.arg(Arg::with_name("watch-when-idle")
.help("Ignore events while the process is still running")
.short("W")
.long("watch-when-idle"));
let args = match from {
None => app.get_matches(),
Some(i) => app.get_matches_from(i),
};
let cmd: Vec<String> = values_t!(args.values_of("command"), String)?;
let paths = values_t!(args.values_of("path"), String)
.unwrap_or_else(|_| vec![".".into()])
.iter()
.map(|string_path| string_path.into())
.collect();
// Treat --kill as --signal SIGKILL (for compatibility with older syntax)
let signal = if args.is_present("kill") {
Some("SIGKILL".to_string())
} else {
// Convert Option<&str> to Option<String>
args.value_of("signal").map(str::to_string)
};
let mut filters = values_t!(args.values_of("filter"), String).unwrap_or_else(|_| Vec::new());
if let Some(extensions) = args.values_of("extensions") {
for exts in extensions {
filters.extend(exts.split(',').filter_map(|ext| {
if ext.is_empty() {
None
} else {
Some(format!("*.{}", ext.replace(".", "")))
}
}));
}
}
let mut ignores = vec![];
let default_ignores = vec![
format!("**{}.DS_Store", MAIN_SEPARATOR),
String::from("*.py[co]"),
String::from("#*#"),
String::from(".#*"),
String::from(".*.kate-swp"),
String::from(".*.sw?"),
String::from(".*.sw?x"),
format!("**{}.git{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
format!("**{}.hg{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
format!("**{}.svn{}**", MAIN_SEPARATOR, MAIN_SEPARATOR),
];
if args.occurrences_of("no-default-ignore") == 0 {
ignores.extend(default_ignores)
};
ignores.extend(values_t!(args.values_of("ignore"), String).unwrap_or_else(|_| Vec::new()));
let poll_interval = if args.occurrences_of("poll") > 0 {
value_t!(args.value_of("poll"), u32).unwrap_or_else(|e| e.exit())
} else {
1000
};
let debounce = if args.occurrences_of("debounce") > 0 {
value_t!(args.value_of("debounce"), u64).unwrap_or_else(|e| e.exit())
} else {
500
};
if signal.is_some() && args.is_present("postpone") {
// TODO: Error::argument_conflict() might be the better fit, usage was unclear, though
Error::value_validation_auto("--postpone and --signal are mutually exclusive".to_string())
.exit();
}
if signal.is_some() && args.is_present("kill") {
// TODO: Error::argument_conflict() might be the better fit, usage was unclear, though
Error::value_validation_auto("--kill and --signal is ambiguous.\n Hint: Use only '--signal SIGKILL' without --kill".to_string())
.exit();
}
Ok(Args {
cmd,
paths,
filters,
ignores,
signal,
clear_screen: args.is_present("clear"),
restart: args.is_present("restart"),
debounce,
debug: args.is_present("verbose"),
run_initially: !args.is_present("postpone"),
no_shell: args.is_present("no-shell"),
no_meta: args.is_present("no-meta"),
no_environment: args.is_present("no-environment"),
no_vcs_ignore: args.is_present("no-vcs-ignore"),
no_ignore: args.is_present("no-ignore"),
once: args.is_present("once"),
poll: args.occurrences_of("poll") > 0,
poll_interval,
watch_when_idle: args.is_present("watch-when-idle"),
})
}
|
use memory::{Memory, low_nibble, high_nibble, low_byte, high_byte};
use extensions::Incrementor;
use ops::{mod};
use std::num::One;
pub struct Cpu<'a> {
reg: Registers,
mem: &'a mut Memory
}
impl<'a> Cpu<'a> {
pub fn new(memory: &'a mut Memory) -> Cpu<'a> {
return Cpu{reg: Registers::new(), mem: memory}
}
/// Execute a cycle on the cpu
pub fn tick(&mut self) {
let instr = self.fetch_instruction();
let a = self.reg.a.read();
let b = self.reg.b.read();
let c = self.reg.c.read();
let d = self.reg.d.read();
let e = self.reg.e.read();
let h = self.reg.h.read();
let l = self.reg.l.read();
let sp = self.reg.sp.read();
match instr {
0x00 => ops::nop(), // NOP
0x01 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.b, &mut self.reg.c), // LD BC, nn
0x02 => ops::write_value_to_memory_at_address(self.mem, self.reg.a.read(), self.reg.b.read(), self.reg.c.read()), // LD (BC), A
0x03 => ops::increment_register_pair(&mut self.reg.b, &mut self.reg.c), // INC BC
0x04 => ops::increment_register(&mut self.reg.b, &mut self.reg.f), // INC B
0x05 => ops::decrement_register(&mut self.reg.b, &mut self.reg.f), // DEC B
0x06 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.b), // LD B, n
0x07 => ops::rotate_left_with_carry(&mut self.reg.a, &mut self.reg.f), // RLC A
0x08 => ops::write_sp_to_address_immediate(self.mem, &mut self.reg.pc, &self.reg.sp), // LD (nn), SP
0x09 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, b, c, &mut self.reg.f), // ADD HL, BC
0x0A => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.a, b, c), // LD A, (BC)
0x0B => ops::decrement_register_pair(&mut self.reg.b, &mut self.reg.c), // DEC BC
0x0C => ops::increment_register(&mut self.reg.c, &mut self.reg.f), // INC C
0x0D => ops::decrement_register(&mut self.reg.c, &mut self.reg.f), // DEC C
0x0E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.c), // LD C, n
0x0F => ops::rotate_right_with_carry(&mut self.reg.a, &mut self.reg.f), // RRC A
0x10 => error!("STOP Op Code not implemented and is being used"), // STOP
0x11 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.d, &mut self.reg.e), // LD DE, nn
0x12 => ops::write_value_to_memory_at_address(self.mem, a, d, e), // LD (DE), A
0x13 => ops::increment_register_pair(&mut self.reg.d, &mut self.reg.e), // INC DE
0x14 => ops::increment_register(&mut self.reg.d, &mut self.reg.f), // INC D
0x15 => ops::decrement_register(&mut self.reg.d, &mut self.reg.f), // DEC D
0x16 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.d), // LD D, n
0x17 => ops::rotate_left_with_carry(&mut self.reg.a, &mut self.reg.f), // RL A
0x18 => ops::jump_by_signed_immediate(self.mem, &mut self.reg.pc), // JR n
0x19 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, d, e, &mut self.reg.f), // Add HL, DE
0x1A => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.a, d, e), // LD A, (DE)
0x1B => ops::decrement_register_pair(&mut self.reg.d, &mut self.reg.e), // DEC DE
0x1C => ops::increment_register(&mut self.reg.e, &mut self.reg.f), // INC E
0x1E => ops::decrement_register(&mut self.reg.e, &mut self.reg.f), // DEC E
0x1F => ops::rotate_right_with_carry(&mut self.reg.a, &mut self.reg.f), // RR A
0x20 => ops::relative_jmp_by_signed_immediate_if_not_flag(self.mem, &mut self.reg.pc, &self.reg.f, ZeroFlag), // JR NZ, n
0x21 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.h, &mut self.reg.l), // LD HL, nn
0x22 => ops::write_value_to_memory_at_address_and_increment_register(self.mem, self.reg.a.read(), &mut self.reg.h, &mut self.reg.l), // LDI (HL), A
0x23 => ops::increment_register_pair(&mut self.reg.h, &mut self.reg.l), // INC HL
0x24 => ops::increment_register(&mut self.reg.h, &mut self.reg.f), // INC H
0x25 => ops::decrement_register(&mut self.reg.h, &mut self.reg.f), // DEC H
0x26 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.h), // LD H, n
0x27 => error!("DAA instruction not implemented and is being used"),
0x28 => ops::relative_jmp_by_signed_immediate_if_flag(self.mem, &mut self.reg.pc, &self.reg.f, ZeroFlag), // JR Z, n
0x29 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, h, l, &mut self.reg.f), // ADD HL, HL
0x2A => ops::ld_from_address_pointed_to_by_register_pair_and_increment_register_pair(self.mem, &mut self.reg.a, &mut self.reg.h, &mut self.reg.l), // LDI A, HL
0x2B => ops::decrement_register_pair(&mut self.reg.h, &mut self.reg.l), // DEC HL
0x2C => ops::increment_register(&mut self.reg.l, &mut self.reg.f), // INC L
0x2D => ops::decrement_register(&mut self.reg.l, &mut self.reg.f), // DEC L
0x2E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.l), // LD L, d8
0x2F => ops::complement(&mut self.reg.a, &mut self.reg.f), // CPL
0x30 => ops::relative_jmp_by_signed_immediate_if_not_flag(self.mem, &mut self.reg.pc, &self.reg.f, CarryFlag), // JR NC, n
0x31 => ops::ld_next_two_bytes_into_reg(self.mem, &mut self.reg.pc, &mut self.reg.sp), // LD SP, nn
0x32 => ops::write_value_to_memory_at_address_and_decrement_register(self.mem, self.reg.a.read(), &mut self.reg.h, &mut self.reg.l), // LDI (HL), A
0x33 => self.reg.sp.increment(), // INC SP
0x34 => ops::increment_value_at_address(self.mem, self.reg.h.read(), self.reg.l.read(), &mut self.reg.f),
0x35 => ops::decrement_value_at_address(self.mem, self.reg.h.read(), self.reg.l.read(), &mut self.reg.f),
0x36 => ops::ld_immediate_into_address(self.mem, &mut self.reg.pc, self.reg.h.read(), self.reg.l.read()),
0x37 => ops::set_flag(&mut self.reg.f, CarryFlag),
0x38 => ops::relative_jmp_by_signed_immediate_if_flag(self.mem, &mut self.reg.pc, &mut self.reg.f, CarryFlag),
0x39 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, high_byte(sp), low_byte(sp), &mut self.reg.f), // ADD HL, SP
0x3A => ops::ld_from_address_pointed_to_by_register_pair_and_decrement_register_pair(self.mem, &mut self.reg.a, &mut self.reg.h, &mut self.reg.l), // LDD A, HL
0x3B => self.reg.sp.decrement(), // INC SP
0x3C => ops::increment_register(&mut self.reg.a, &mut self.reg.f), // INC A
0x3D => ops::decrement_register(&mut self.reg.a, &mut self.reg.f), // DEC A
0x3E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.a), // LD A, d8
0x3F => ops::reset_flag(&mut self.reg.f, CarryFlag), // CCF
0x40 => ops::copy_value_into_register(&mut self.reg.b, b), // LD B, B
0x41 => ops::copy_value_into_register(&mut self.reg.b, c), // LD B, C
0x42 => ops::copy_value_into_register(&mut self.reg.b, d), // LD B, D
0x43 => ops::copy_value_into_register(&mut self.reg.b, e), // LD B, E
0x44 => ops::copy_value_into_register(&mut self.reg.b, h), // LD B, H
0x45 => ops::copy_value_into_register(&mut self.reg.b, l), // LD B, L
0x46 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD B, (HL)
0x47 => ops::copy_value_into_register(&mut self.reg.b, a), // LD B, A
0x48 => ops::copy_value_into_register(&mut self.reg.c, b), // LD C, B
0x49 => ops::copy_value_into_register(&mut self.reg.c, c), // LD C, C
0x4A => ops::copy_value_into_register(&mut self.reg.c, d), // LD C, D
0x4B => ops::copy_value_into_register(&mut self.reg.c, e), // LD C, E
0x4C => ops::copy_value_into_register(&mut self.reg.c, h), // LD C, H
0x4D => ops::copy_value_into_register(&mut self.reg.c, l), // LD C, L
0x4E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD C, (HL)
0x4F => ops::copy_value_into_register(&mut self.reg.c, a), // LD C, A
0x50 => ops::copy_value_into_register(&mut self.reg.d, b), // LD D, B
0x51 => ops::copy_value_into_register(&mut self.reg.d, c), // LD D, C
0x52 => ops::copy_value_into_register(&mut self.reg.d, d), // LD D, D
0x53 => ops::copy_value_into_register(&mut self.reg.d, e), // LD D, E
0x54 => ops::copy_value_into_register(&mut self.reg.d, h), // LD D, H
0x55 => ops::copy_value_into_register(&mut self.reg.d, l), // LD D, L
0x56 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.d, h, l), // LD D, (HL)
0x57 => ops::copy_value_into_register(&mut self.reg.d, a), // LD D, A
0x58 => ops::copy_value_into_register(&mut self.reg.e, b), // LD E, B
0x59 => ops::copy_value_into_register(&mut self.reg.e, c), // LD E, C
0x5A => ops::copy_value_into_register(&mut self.reg.e, d), // LD E, D
0x5B => ops::copy_value_into_register(&mut self.reg.e, e), // LD E, E
0x5C => ops::copy_value_into_register(&mut self.reg.e, h), // LD E, H
0x5D => ops::copy_value_into_register(&mut self.reg.e, l), // LD E, L
0x5E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD E, (HL)
0x5F => ops::copy_value_into_register(&mut self.reg.e, a), // LD E, A
0x60 => ops::copy_value_into_register(&mut self.reg.h, b), // LD H, B
0x61 => ops::copy_value_into_register(&mut self.reg.h, c), // LD H, C
0x62 => ops::copy_value_into_register(&mut self.reg.h, d), // LD H, D
0x63 => ops::copy_value_into_register(&mut self.reg.h, e), // LD H, E
0x64 => ops::copy_value_into_register(&mut self.reg.h, h), // LD H, H
0x65 => ops::copy_value_into_register(&mut self.reg.h, l), // LD H, L
0x66 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.h, h, l), // LD H, (HL)
0x67 => ops::copy_value_into_register(&mut self.reg.h, a), // LD H, A
0x68 => ops::copy_value_into_register(&mut self.reg.l, b), // LD L, B
0x69 => ops::copy_value_into_register(&mut self.reg.l, c), // LD L, C
0x6A => ops::copy_value_into_register(&mut self.reg.l, d), // LD L, D
0x6B => ops::copy_value_into_register(&mut self.reg.l, e), // LD L, E
0x6C => ops::copy_value_into_register(&mut self.reg.l, h), // LD L, H
0x6D => ops::copy_value_into_register(&mut self.reg.l, l), // LD L, L
0x6E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD L, (HL)
0x6F => ops::copy_value_into_register(&mut self.reg.l, a), // LD L, A
0x70 => ops::write_value_to_memory_at_address(self.mem, b, h, l), // LD (HL), B
0x71 => ops::write_value_to_memory_at_address(self.mem, c, h, l), // LD (HL), C
0x72 => ops::write_value_to_memory_at_address(self.mem, d, h, l), // LD (HL), D
0x73 => ops::write_value_to_memory_at_address(self.mem, e, h, l), // LD (HL), E
0x74 => ops::write_value_to_memory_at_address(self.mem, h, h, l), // LD (HL), H
0x75 => ops::write_value_to_memory_at_address(self.mem, l, h, l), // LD (HL), L
0x76 => error!("HALT instruction not implemented"),
0x77 => ops::write_value_to_memory_at_address(self.mem, a, h, l), // LD (HL), A
0x78 => ops::copy_value_into_register(&mut self.reg.a, b), // LD A, B
0x79 => ops::copy_value_into_register(&mut self.reg.a, c), // LD A, C
0x7A => ops::copy_value_into_register(&mut self.reg.a, d), // LD A, D
0x7B => ops::copy_value_into_register(&mut self.reg.a, e), // LD A, E
0x7C => ops::copy_value_into_register(&mut self.reg.a, h), // LD A, H
0x7D => ops::copy_value_into_register(&mut self.reg.a, l), // LD A, L
0x7E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD A, (HL)
0x7F => ops::copy_value_into_register(&mut self.reg.a, a), // LD A, A
0x80 => ops::add(&mut self.reg.a, b, &mut self.reg.f), // ADD A, B
0x81 => ops::add(&mut self.reg.a, c, &mut self.reg.f), // ADD A, C
0x82 => ops::add(&mut self.reg.a, d, &mut self.reg.f), // ADD A, D
0x83 => ops::add(&mut self.reg.a, e, &mut self.reg.f), // ADD A, E
0x84 => ops::add(&mut self.reg.a, h, &mut self.reg.f), // ADD A, H
0x85 => ops::add(&mut self.reg.a, l, &mut self.reg.f), // ADD A, L
0x86 => ops::add_value_at_address(self.mem, &mut self.reg.a, h, l, &mut self.reg.f),
0x87 => ops::add(&mut self.reg.a, a, &mut self.reg.f), // ADD A, A
0x88 => return,
_ => return
}
}
/// Fetches the instruction pointed to by the program counter
/// and increments the pc by 1
fn fetch_instruction(&mut self) -> u8 {
let instr = self.mem.read_byte(self.reg.pc.read());
self.reg.pc.increment();
return instr;
}
}
struct Registers {
a: Register<u8>, b: Register<u8>, c: Register<u8>,
d: Register<u8>, e: Register<u8>, f: Register<Flags>,
h: Register<u8>, l: Register<u8>, // 8-bit registers
pc: Register<u16>, sp: Register<u16>, // 16-bit registers
m: Register<u16>, t: Register<u16> // clock
}
impl Registers {
fn new() -> Registers {
return Registers{
a: Register::new(0),
b: Register::new(0),
c: Register::new(0),
d: Register::new(0),
e: Register::new(0),
f: Register::new(Flags::empty()),
h: Register::new(0),
l: Register::new(0),
pc: Register::new(0x100),
sp: Register::new(0xFFFE),
m: Register::new(0),
t: Register::new(0)
}
}
}
pub struct Register<T: Copy> {
val: T
}
impl<T: Copy> Register<T> {
pub fn new(i: T) -> Register<T> {
return Register { val: i };
}
pub fn read(&self) -> T {
return self.val;
}
pub fn write(&mut self, i: T) {
self.val = i;
}
}
impl<T: Copy + Unsigned> Register<T> {
pub fn increment(&mut self) {
let i = self.val;
self.write(i + One::one());
}
pub fn decrement(&mut self) {
let i = self.val;
self.write(i - One::one());
}
}
bitflags! {
flags Flags: u8 {
const ZeroFlag = 0b10000000,
const SubtractFlag = 0b01000000,
const HalfCarryFlag = 0b00100000,
const CarryFlag = 0b00010000,
}
}
#[test]
fn test_Register_new() {
let reg: Register<u8> = Register::new(10);
assert!(reg.val == 10);
}
#[test]
fn test_Register_read() {
let reg: Register<u32> = Register::new(5);
assert!(reg.read() == 5);
}
#[test]
fn test_Register_write() {
let mut reg: Register<u16> = Register::new(483);
reg.write(5);
assert!(reg.val == 5);
}
#[test]
fn test_Register_increment() {
let mut reg: Register<u16> = Register::new(483);
reg.increment();
assert!(reg.val == 484);
}
#[test]
fn test_Register_decrement() {
let mut reg: Register<u16> = Register::new(401);
reg.decrement();
assert!(reg.val == 400);
}
#[test]
fn test_Registers_new() {
let a = Registers::new();
assert!(a.pc.read() == 0x100);
assert!(a.sp.read() == 0xFFFE);
}
Add 0x88 - 0x8F
use memory::{Memory, low_nibble, high_nibble, low_byte, high_byte};
use extensions::Incrementor;
use ops::{mod};
use std::num::One;
pub struct Cpu<'a> {
reg: Registers,
mem: &'a mut Memory
}
impl<'a> Cpu<'a> {
pub fn new(memory: &'a mut Memory) -> Cpu<'a> {
return Cpu{reg: Registers::new(), mem: memory}
}
/// Execute a cycle on the cpu
pub fn tick(&mut self) {
let instr = self.fetch_instruction();
let a = self.reg.a.read();
let b = self.reg.b.read();
let c = self.reg.c.read();
let d = self.reg.d.read();
let e = self.reg.e.read();
let h = self.reg.h.read();
let l = self.reg.l.read();
let sp = self.reg.sp.read();
match instr {
0x00 => ops::nop(), // NOP
0x01 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.b, &mut self.reg.c), // LD BC, nn
0x02 => ops::write_value_to_memory_at_address(self.mem, self.reg.a.read(), self.reg.b.read(), self.reg.c.read()), // LD (BC), A
0x03 => ops::increment_register_pair(&mut self.reg.b, &mut self.reg.c), // INC BC
0x04 => ops::increment_register(&mut self.reg.b, &mut self.reg.f), // INC B
0x05 => ops::decrement_register(&mut self.reg.b, &mut self.reg.f), // DEC B
0x06 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.b), // LD B, n
0x07 => ops::rotate_left_with_carry(&mut self.reg.a, &mut self.reg.f), // RLC A
0x08 => ops::write_sp_to_address_immediate(self.mem, &mut self.reg.pc, &self.reg.sp), // LD (nn), SP
0x09 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, b, c, &mut self.reg.f), // ADD HL, BC
0x0A => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.a, b, c), // LD A, (BC)
0x0B => ops::decrement_register_pair(&mut self.reg.b, &mut self.reg.c), // DEC BC
0x0C => ops::increment_register(&mut self.reg.c, &mut self.reg.f), // INC C
0x0D => ops::decrement_register(&mut self.reg.c, &mut self.reg.f), // DEC C
0x0E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.c), // LD C, n
0x0F => ops::rotate_right_with_carry(&mut self.reg.a, &mut self.reg.f), // RRC A
0x10 => error!("STOP Op Code not implemented and is being used"), // STOP
0x11 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.d, &mut self.reg.e), // LD DE, nn
0x12 => ops::write_value_to_memory_at_address(self.mem, a, d, e), // LD (DE), A
0x13 => ops::increment_register_pair(&mut self.reg.d, &mut self.reg.e), // INC DE
0x14 => ops::increment_register(&mut self.reg.d, &mut self.reg.f), // INC D
0x15 => ops::decrement_register(&mut self.reg.d, &mut self.reg.f), // DEC D
0x16 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.d), // LD D, n
0x17 => ops::rotate_left_with_carry(&mut self.reg.a, &mut self.reg.f), // RL A
0x18 => ops::jump_by_signed_immediate(self.mem, &mut self.reg.pc), // JR n
0x19 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, d, e, &mut self.reg.f), // Add HL, DE
0x1A => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.a, d, e), // LD A, (DE)
0x1B => ops::decrement_register_pair(&mut self.reg.d, &mut self.reg.e), // DEC DE
0x1C => ops::increment_register(&mut self.reg.e, &mut self.reg.f), // INC E
0x1E => ops::decrement_register(&mut self.reg.e, &mut self.reg.f), // DEC E
0x1F => ops::rotate_right_with_carry(&mut self.reg.a, &mut self.reg.f), // RR A
0x20 => ops::relative_jmp_by_signed_immediate_if_not_flag(self.mem, &mut self.reg.pc, &self.reg.f, ZeroFlag), // JR NZ, n
0x21 => ops::ld_next_two_byte_into_reg_pair(self.mem, &mut self.reg.pc, &mut self.reg.h, &mut self.reg.l), // LD HL, nn
0x22 => ops::write_value_to_memory_at_address_and_increment_register(self.mem, self.reg.a.read(), &mut self.reg.h, &mut self.reg.l), // LDI (HL), A
0x23 => ops::increment_register_pair(&mut self.reg.h, &mut self.reg.l), // INC HL
0x24 => ops::increment_register(&mut self.reg.h, &mut self.reg.f), // INC H
0x25 => ops::decrement_register(&mut self.reg.h, &mut self.reg.f), // DEC H
0x26 => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.h), // LD H, n
0x27 => error!("DAA instruction not implemented and is being used"),
0x28 => ops::relative_jmp_by_signed_immediate_if_flag(self.mem, &mut self.reg.pc, &self.reg.f, ZeroFlag), // JR Z, n
0x29 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, h, l, &mut self.reg.f), // ADD HL, HL
0x2A => ops::ld_from_address_pointed_to_by_register_pair_and_increment_register_pair(self.mem, &mut self.reg.a, &mut self.reg.h, &mut self.reg.l), // LDI A, HL
0x2B => ops::decrement_register_pair(&mut self.reg.h, &mut self.reg.l), // DEC HL
0x2C => ops::increment_register(&mut self.reg.l, &mut self.reg.f), // INC L
0x2D => ops::decrement_register(&mut self.reg.l, &mut self.reg.f), // DEC L
0x2E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.l), // LD L, d8
0x2F => ops::complement(&mut self.reg.a, &mut self.reg.f), // CPL
0x30 => ops::relative_jmp_by_signed_immediate_if_not_flag(self.mem, &mut self.reg.pc, &self.reg.f, CarryFlag), // JR NC, n
0x31 => ops::ld_next_two_bytes_into_reg(self.mem, &mut self.reg.pc, &mut self.reg.sp), // LD SP, nn
0x32 => ops::write_value_to_memory_at_address_and_decrement_register(self.mem, self.reg.a.read(), &mut self.reg.h, &mut self.reg.l), // LDI (HL), A
0x33 => self.reg.sp.increment(), // INC SP
0x34 => ops::increment_value_at_address(self.mem, self.reg.h.read(), self.reg.l.read(), &mut self.reg.f),
0x35 => ops::decrement_value_at_address(self.mem, self.reg.h.read(), self.reg.l.read(), &mut self.reg.f),
0x36 => ops::ld_immediate_into_address(self.mem, &mut self.reg.pc, self.reg.h.read(), self.reg.l.read()),
0x37 => ops::set_flag(&mut self.reg.f, CarryFlag),
0x38 => ops::relative_jmp_by_signed_immediate_if_flag(self.mem, &mut self.reg.pc, &mut self.reg.f, CarryFlag),
0x39 => ops::add_register_pair_to_register_pair(&mut self.reg.h, &mut self.reg.l, high_byte(sp), low_byte(sp), &mut self.reg.f), // ADD HL, SP
0x3A => ops::ld_from_address_pointed_to_by_register_pair_and_decrement_register_pair(self.mem, &mut self.reg.a, &mut self.reg.h, &mut self.reg.l), // LDD A, HL
0x3B => self.reg.sp.decrement(), // INC SP
0x3C => ops::increment_register(&mut self.reg.a, &mut self.reg.f), // INC A
0x3D => ops::decrement_register(&mut self.reg.a, &mut self.reg.f), // DEC A
0x3E => ops::ld_immediate(self.mem, &mut self.reg.pc, &mut self.reg.a), // LD A, d8
0x3F => ops::reset_flag(&mut self.reg.f, CarryFlag), // CCF
0x40 => ops::copy_value_into_register(&mut self.reg.b, b), // LD B, B
0x41 => ops::copy_value_into_register(&mut self.reg.b, c), // LD B, C
0x42 => ops::copy_value_into_register(&mut self.reg.b, d), // LD B, D
0x43 => ops::copy_value_into_register(&mut self.reg.b, e), // LD B, E
0x44 => ops::copy_value_into_register(&mut self.reg.b, h), // LD B, H
0x45 => ops::copy_value_into_register(&mut self.reg.b, l), // LD B, L
0x46 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD B, (HL)
0x47 => ops::copy_value_into_register(&mut self.reg.b, a), // LD B, A
0x48 => ops::copy_value_into_register(&mut self.reg.c, b), // LD C, B
0x49 => ops::copy_value_into_register(&mut self.reg.c, c), // LD C, C
0x4A => ops::copy_value_into_register(&mut self.reg.c, d), // LD C, D
0x4B => ops::copy_value_into_register(&mut self.reg.c, e), // LD C, E
0x4C => ops::copy_value_into_register(&mut self.reg.c, h), // LD C, H
0x4D => ops::copy_value_into_register(&mut self.reg.c, l), // LD C, L
0x4E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD C, (HL)
0x4F => ops::copy_value_into_register(&mut self.reg.c, a), // LD C, A
0x50 => ops::copy_value_into_register(&mut self.reg.d, b), // LD D, B
0x51 => ops::copy_value_into_register(&mut self.reg.d, c), // LD D, C
0x52 => ops::copy_value_into_register(&mut self.reg.d, d), // LD D, D
0x53 => ops::copy_value_into_register(&mut self.reg.d, e), // LD D, E
0x54 => ops::copy_value_into_register(&mut self.reg.d, h), // LD D, H
0x55 => ops::copy_value_into_register(&mut self.reg.d, l), // LD D, L
0x56 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.d, h, l), // LD D, (HL)
0x57 => ops::copy_value_into_register(&mut self.reg.d, a), // LD D, A
0x58 => ops::copy_value_into_register(&mut self.reg.e, b), // LD E, B
0x59 => ops::copy_value_into_register(&mut self.reg.e, c), // LD E, C
0x5A => ops::copy_value_into_register(&mut self.reg.e, d), // LD E, D
0x5B => ops::copy_value_into_register(&mut self.reg.e, e), // LD E, E
0x5C => ops::copy_value_into_register(&mut self.reg.e, h), // LD E, H
0x5D => ops::copy_value_into_register(&mut self.reg.e, l), // LD E, L
0x5E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD E, (HL)
0x5F => ops::copy_value_into_register(&mut self.reg.e, a), // LD E, A
0x60 => ops::copy_value_into_register(&mut self.reg.h, b), // LD H, B
0x61 => ops::copy_value_into_register(&mut self.reg.h, c), // LD H, C
0x62 => ops::copy_value_into_register(&mut self.reg.h, d), // LD H, D
0x63 => ops::copy_value_into_register(&mut self.reg.h, e), // LD H, E
0x64 => ops::copy_value_into_register(&mut self.reg.h, h), // LD H, H
0x65 => ops::copy_value_into_register(&mut self.reg.h, l), // LD H, L
0x66 => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.h, h, l), // LD H, (HL)
0x67 => ops::copy_value_into_register(&mut self.reg.h, a), // LD H, A
0x68 => ops::copy_value_into_register(&mut self.reg.l, b), // LD L, B
0x69 => ops::copy_value_into_register(&mut self.reg.l, c), // LD L, C
0x6A => ops::copy_value_into_register(&mut self.reg.l, d), // LD L, D
0x6B => ops::copy_value_into_register(&mut self.reg.l, e), // LD L, E
0x6C => ops::copy_value_into_register(&mut self.reg.l, h), // LD L, H
0x6D => ops::copy_value_into_register(&mut self.reg.l, l), // LD L, L
0x6E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD L, (HL)
0x6F => ops::copy_value_into_register(&mut self.reg.l, a), // LD L, A
0x70 => ops::write_value_to_memory_at_address(self.mem, b, h, l), // LD (HL), B
0x71 => ops::write_value_to_memory_at_address(self.mem, c, h, l), // LD (HL), C
0x72 => ops::write_value_to_memory_at_address(self.mem, d, h, l), // LD (HL), D
0x73 => ops::write_value_to_memory_at_address(self.mem, e, h, l), // LD (HL), E
0x74 => ops::write_value_to_memory_at_address(self.mem, h, h, l), // LD (HL), H
0x75 => ops::write_value_to_memory_at_address(self.mem, l, h, l), // LD (HL), L
0x76 => error!("HALT instruction not implemented"),
0x77 => ops::write_value_to_memory_at_address(self.mem, a, h, l), // LD (HL), A
0x78 => ops::copy_value_into_register(&mut self.reg.a, b), // LD A, B
0x79 => ops::copy_value_into_register(&mut self.reg.a, c), // LD A, C
0x7A => ops::copy_value_into_register(&mut self.reg.a, d), // LD A, D
0x7B => ops::copy_value_into_register(&mut self.reg.a, e), // LD A, E
0x7C => ops::copy_value_into_register(&mut self.reg.a, h), // LD A, H
0x7D => ops::copy_value_into_register(&mut self.reg.a, l), // LD A, L
0x7E => ops::ld_from_reg_pair_as_address(self.mem, &mut self.reg.b, h, l), // LD A, (HL)
0x7F => ops::copy_value_into_register(&mut self.reg.a, a), // LD A, A
0x80 => ops::add(&mut self.reg.a, b, &mut self.reg.f), // ADD A, B
0x81 => ops::add(&mut self.reg.a, c, &mut self.reg.f), // ADD A, C
0x82 => ops::add(&mut self.reg.a, d, &mut self.reg.f), // ADD A, D
0x83 => ops::add(&mut self.reg.a, e, &mut self.reg.f), // ADD A, E
0x84 => ops::add(&mut self.reg.a, h, &mut self.reg.f), // ADD A, H
0x85 => ops::add(&mut self.reg.a, l, &mut self.reg.f), // ADD A, L
0x86 => ops::add_value_at_address(self.mem, &mut self.reg.a, h, l, &mut self.reg.f),
0x87 => ops::add(&mut self.reg.a, a, &mut self.reg.f), // ADD A, A
0x88 => ops::adc(&mut self.reg.a, b, &mut self.reg.f), // ADC A, B
0x89 => ops::adc(&mut self.reg.a, c, &mut self.reg.f), // ADC A, C
0x8A => ops::adc(&mut self.reg.a, d, &mut self.reg.f), // ADC A, D
0x8B => ops::adc(&mut self.reg.a, e, &mut self.reg.f), // ADC A, E
0x8C => ops::adc(&mut self.reg.a, h, &mut self.reg.f), // ADC A, H
0x8D => ops::adc(&mut self.reg.a, l, &mut self.reg.f), // ADC A, L
0x8E => return,
0x8F => ops::adc(&mut self.reg.a, a, &mut self.reg.f), // ADC A, A
_ => return
}
}
/// Fetches the instruction pointed to by the program counter
/// and increments the pc by 1
fn fetch_instruction(&mut self) -> u8 {
let instr = self.mem.read_byte(self.reg.pc.read());
self.reg.pc.increment();
return instr;
}
}
struct Registers {
a: Register<u8>, b: Register<u8>, c: Register<u8>,
d: Register<u8>, e: Register<u8>, f: Register<Flags>,
h: Register<u8>, l: Register<u8>, // 8-bit registers
pc: Register<u16>, sp: Register<u16>, // 16-bit registers
m: Register<u16>, t: Register<u16> // clock
}
impl Registers {
fn new() -> Registers {
return Registers{
a: Register::new(0),
b: Register::new(0),
c: Register::new(0),
d: Register::new(0),
e: Register::new(0),
f: Register::new(Flags::empty()),
h: Register::new(0),
l: Register::new(0),
pc: Register::new(0x100),
sp: Register::new(0xFFFE),
m: Register::new(0),
t: Register::new(0)
}
}
}
pub struct Register<T: Copy> {
val: T
}
impl<T: Copy> Register<T> {
pub fn new(i: T) -> Register<T> {
return Register { val: i };
}
pub fn read(&self) -> T {
return self.val;
}
pub fn write(&mut self, i: T) {
self.val = i;
}
}
impl<T: Copy + Unsigned> Register<T> {
pub fn increment(&mut self) {
let i = self.val;
self.write(i + One::one());
}
pub fn decrement(&mut self) {
let i = self.val;
self.write(i - One::one());
}
}
bitflags! {
flags Flags: u8 {
const ZeroFlag = 0b10000000,
const SubtractFlag = 0b01000000,
const HalfCarryFlag = 0b00100000,
const CarryFlag = 0b00010000,
}
}
#[test]
fn test_Register_new() {
let reg: Register<u8> = Register::new(10);
assert!(reg.val == 10);
}
#[test]
fn test_Register_read() {
let reg: Register<u32> = Register::new(5);
assert!(reg.read() == 5);
}
#[test]
fn test_Register_write() {
let mut reg: Register<u16> = Register::new(483);
reg.write(5);
assert!(reg.val == 5);
}
#[test]
fn test_Register_increment() {
let mut reg: Register<u16> = Register::new(483);
reg.increment();
assert!(reg.val == 484);
}
#[test]
fn test_Register_decrement() {
let mut reg: Register<u16> = Register::new(401);
reg.decrement();
assert!(reg.val == 400);
}
#[test]
fn test_Registers_new() {
let a = Registers::new();
assert!(a.pc.read() == 0x100);
assert!(a.sp.read() == 0xFFFE);
}
|
const INTERPRETER_START: u32 = 0x000;
const INTERPRETER_END: u32 = 0x1FF;
const INTERPRETER_LENGTH: u32 = INTERPRETER_END - INTERPRETER_START;
const FONT_SET_START: usize = 0x050;
const FONT_SET_END: usize = 0x0A0;
const FONT_SET_LENGTH: usize = FONT_SET_END - FONT_SET_START;
const DATA_START: usize = 0x200;
const DATA_END: usize = 0xFFF;
const DATA_LENGTH: usize = DATA_END - DATA_START;
const MEM_LENGTH: usize = 4096;
const STACK_LEVEL: usize = 16;
const REG_NUM: usize = 16;
const GFX_WIDTH: usize = 64;
const GFX_HEIGHT: usize = 32;
const FONTSET: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
];
pub fn init() -> Cpu {
let mut ret = Cpu {
pc: 0x200,
opcode: 0,
memory: vec![0; MEM_LENGTH],
reg: vec![0; REG_NUM],
index: 0,
sp: 0,
stack: vec![0; STACK_LEVEL],
// gfx: vec![vec![0; GFX_HEIGHT]; GFX_WIDTH],
gfx: vec![0; GFX_WIDTH * GFX_HEIGHT],
delay_timer: 0,
sound_timer: 0,
key: vec![0; STACK_LEVEL],
};
ret.load_fontset();
ret
}
#[derive(Debug)]
pub struct Cpu {
pc: usize,
opcode: u16,
memory: Vec<u8>,
reg: Vec<u8>,
index: u16,
// gfx: Vec<Vec<u8>>,
gfx: Vec<u8>,
delay_timer: u8,
sound_timer: u8,
stack: Vec<usize>,
sp: usize,
key: Vec<u8>,
}
impl Cpu {
fn load_fontset(&mut self) {
for i in 0..FONT_SET_LENGTH {
self.memory[FONT_SET_START + i] = FONTSET[i];
}
}
pub fn load_rom(&mut self, rom: Box<[u8]>) {
for i in 0..rom.len() {
self.memory[DATA_START + i] = rom[i];
}
}
pub fn emulate_cycle(&mut self) {
self.opcode = (self.memory[self.pc] as u16) << 8 | (self.memory[self.pc+1] as u16);
match self.opcode & 0xF000 {
0x2000 => { // 2NNN: Calls subroutine at NNN
let addr = self.opcode & 0x0FFF;
self.stack[self.sp] = self.pc;
self.sp += 1;
self.pc = addr as usize;
println!("pc: {:X}", self.pc);
},
0x6000 => { //6XNN: Sets VX to NN
let index = (self.opcode & 0x0F00) >> 8;
let val = self.opcode & 0x00FF;
self.reg[index as usize] = val as u8;
println!("set V{:X} to: {:X}", index, self.reg[index as usize]);
self.pc += 2;
},
0xA000 => { //ANNN: Sets I to the address NNN
let val = self.opcode & 0x0FFF;
self.index = val;
println!("Set I to: {:X}", self.index);
self.pc += 2;
},
0xD000 => { //DXYN: Draws sprite at cordinate VX, VY with height N
let x = (self.opcode & 0x0F00) >> 8;
let y = (self.opcode & 0x00F0) >> 4;
let n = self.opcode & 0x000F;
let mut pix: u8;
let tmp = self.index as usize;
let sprite = &self.memory[tmp..(tmp + (n as usize))];
self.reg[0xF] = 0;
for i in 0..n {
pix = (&sprite)[i as usize];
for j in 0..8 {
if (pix & (0x80 >> j)) != 0 {
if self.gfx[(x + j + ((y + i) * 64)) as usize] == 1 {
self.reg[0xF] = 1;
}
self.gfx[(x + j + ((y + i) * 64)) as usize] ^= 1;
}
}
}
println!("gfx: {:?}", self.gfx);
self.pc += 2;
}
_ => panic!("Unknown opcode or not implemented yet: {:X}", self.opcode)
}
}
}
Add opcode FX33
const INTERPRETER_START: u32 = 0x000;
const INTERPRETER_END: u32 = 0x1FF;
const INTERPRETER_LENGTH: u32 = INTERPRETER_END - INTERPRETER_START;
const FONT_SET_START: usize = 0x050;
const FONT_SET_END: usize = 0x0A0;
const FONT_SET_LENGTH: usize = FONT_SET_END - FONT_SET_START;
const DATA_START: usize = 0x200;
const DATA_END: usize = 0xFFF;
const DATA_LENGTH: usize = DATA_END - DATA_START;
const MEM_LENGTH: usize = 4096;
const STACK_LEVEL: usize = 16;
const REG_NUM: usize = 16;
const GFX_WIDTH: usize = 64;
const GFX_HEIGHT: usize = 32;
const FONTSET: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
];
pub fn init() -> Cpu {
let mut ret = Cpu {
pc: 0x200,
opcode: 0,
memory: vec![0; MEM_LENGTH],
reg: vec![0; REG_NUM],
index: 0,
sp: 0,
stack: vec![0; STACK_LEVEL],
// gfx: vec![vec![0; GFX_HEIGHT]; GFX_WIDTH],
gfx: vec![0; GFX_WIDTH * GFX_HEIGHT],
delay_timer: 0,
sound_timer: 0,
key: vec![0; STACK_LEVEL],
};
ret.load_fontset();
ret
}
#[derive(Debug)]
pub struct Cpu {
pc: usize,
opcode: u16,
memory: Vec<u8>,
reg: Vec<u8>,
index: usize,
// gfx: Vec<Vec<u8>>,
gfx: Vec<u8>,
delay_timer: u8,
sound_timer: u8,
stack: Vec<usize>,
sp: usize,
key: Vec<u8>,
}
impl Cpu {
fn load_fontset(&mut self) {
for i in 0..FONT_SET_LENGTH {
self.memory[FONT_SET_START + i] = FONTSET[i];
}
}
pub fn load_rom(&mut self, rom: Box<[u8]>) {
for i in 0..rom.len() {
self.memory[DATA_START + i] = rom[i];
}
}
pub fn emulate_cycle(&mut self) {
self.opcode = (self.memory[self.pc] as u16) << 8 | (self.memory[self.pc+1] as u16);
match self.opcode & 0xF000 {
0x2000 => { // 2NNN: Calls subroutine at NNN
let addr = self.opcode & 0x0FFF;
self.stack[self.sp] = self.pc;
self.sp += 1;
self.pc = addr as usize;
},
0x6000 => { // 6XNN: Sets VX to NN
let index = (self.opcode & 0x0F00) >> 8;
let val = self.opcode & 0x00FF;
self.reg[index as usize] = val as u8;
self.pc += 2;
},
0xA000 => { // ANNN: Sets I to the address NNN
let val = self.opcode & 0x0FFF;
self.index = val as usize;
self.pc += 2;
},
0xD000 => { // DXYN: Draws sprite at cordinate VX, VY with height N
let x = (self.opcode & 0x0F00) >> 8;
let y = (self.opcode & 0x00F0) >> 4;
let n = self.opcode & 0x000F;
let mut pix: u8;
let tmp = self.index as usize;
let sprite = &self.memory[tmp..(tmp + (n as usize))];
self.reg[0xF] = 0;
for i in 0..n {
pix = (&sprite)[i as usize];
for j in 0..8 {
if (pix & (0x80 >> j)) != 0 {
if self.gfx[(x + j + ((y + i) * 64)) as usize] == 1 {
self.reg[0xF] = 1;
}
self.gfx[(x + j + ((y + i) * 64)) as usize] ^= 1;
}
}
}
self.pc += 2;
},
0xF000 => {
match self.opcode & 0x00FF {
0x0033 => { // FX33 set memory at I:I+2 to VX
let x = self.opcode & 0x0F00 >> 8;
let val = self.reg[x as usize];
self.memory[self.index] = val / 100;
self.memory[self.index + 1] = (val / 10) % 10;
self.memory[self.index + 2] = val % 10;
self.pc += 2;
},
_ => panic!("Unknown opcode or not implemented yet: {:X}", self.opcode)
}
},
_ => panic!("Unknown opcode or not implemented yet: {:X}", self.opcode)
}
}
}
|
use super::mmu::Mmu;
use super::registers::Registers;
// The following are the four flags set by certain arithmetic operations
const Z: u8 = 0x80; // Zero: Set if the result is zero.
const N: u8 = 0x40; // Operation: Set if the last operation was a subtraction.
const H: u8 = 0x20; // Half-carry: Set if there was carry from the low nibble to the high. In the high byte for 16 bit operations.
const C: u8 = 0x10; // Carry: Set if last options overflowed or underflowed.
pub struct Cpu {
// Clock
m: u32,
t: u32,
r: Registers,
}
macro_rules! set_clock( ( $cpu: ident, $m: expr ) => ({
$cpu.m = $m;
$cpu.t = $m * 4;
}) );
macro_rules! set_r_clock( ( $cpu: ident, $m: expr ) => ({
$cpu.r.m = $m;
$cpu.r.t = $m * 4;
}) );
impl Cpu {
pub fn new() -> Cpu {
Cpu {
m: 0,
t: 0,
r: Registers::new(),
}
}
fn bump(&mut self) -> u16 {
let ret = self.r.pc;
self.r.pc += 1;
ret
}
pub fn reset(&mut self) {
self.m = 0; self.t = 0;
self.r.reset();
}
pub fn exec(&mut self, m: &mut Mmu) -> u32 {
let op = m.rb(self.bump());
let m_cycles = self.exec_instr(op, m);
self.m += self.r.m;
self.t += self.r.t;
m_cycles
}
fn exec_instr(&mut self, instr: u8, m: &mut Mmu) -> u32 {
macro_rules! ld_nn {
($reg1: ident, $reg2: ident) => ({
self.r.$reg1 = m.rb(self.bump());
self.r.$reg2 = m.rb(self.bump());
3
})
}
macro_rules! inc_ss {
($reg1: ident, $reg2: ident) => ({
self.r.$reg2 += 1;
if self.r.$reg2 == 0 {
self.r.$reg1 += 1;
}
2
})
}
macro_rules! inc {
($reg: ident) => ({
self.r.$reg += 1;
self.r.f &= C;
self.r.f |= if self.r.$reg == 0 { Z } else { 0 };
self.r.f |= if self.r.$reg & 0xf == 0 { H } else { 0 };
1
})
}
macro_rules! dec {
($reg: ident) => ({
self.r.$reg -= 1;
self.r.f &= C;
self.r.f |= N;
self.r.f |= if self.r.$reg == 0 { Z } else { 0 };
self.r.f |= if self.r.$reg & 0xf == 0xf { H } else { 0 };
1
})
}
macro_rules! ld_n {
($reg: ident) => ({
self.r.$reg = m.rb(self.bump());
2
})
}
macro_rules! rlc_r {
($reg: ident) => ({
let carry = if self.r.$reg & 0x80 == 0x80 { 0x1 } else { 0x0 };
self.r.$reg = (self.r.$reg << 1) | carry;
self.r.f = carry << 4;
2
})
}
macro_rules! add_hl_helper {
($val: expr) => ({
self.r.f &= Z;
// TODO: Cleanup
self.r.f |= if ((((self.r.h as u16) << 8) | self.r.l as u16) & 0xfff) + ($val & 0xfff) > 0xfff {
H
} else {
0
};
let result = ((self.r.h as u32) << 8 | self.r.l as u32)
+ $val as u32;
self.r.f |= if result > 0xffff { C } else { 0 };
self.r.h = (result >> 8) as u8;
self.r.l = result as u8;
2
})
}
macro_rules! add_hl {
($reg1: ident, $reg2: ident) => ({
add_hl_helper!(((self.r.$reg1 as u16) << 8) | self.r.$reg2 as u16)
})
}
macro_rules! ld_a {
($addr: expr) => ({
self.r.a = m.rb($addr);
2
})
}
macro_rules! dec_ss {
($reg1: ident, $reg2: ident) => ({
self.r.$reg2 -= 1;
if self.r.$reg2 == 0xff {
self.r.$reg1 -= 1;
}
2
})
}
macro_rules! add_r {
($reg: ident) => ({
self.r.f = 0;
if (self.r.a & 0xF) + (self.r.$reg & 0xF) > 0xF {
// Half carry
self.r.f |= H;
}
if (self.r.a as u32) + (self.r.$reg as u32) > 255 {
// Carry
self.r.f |= C;
}
self.r.a += self.r.$reg;
if self.r.a == 0 {
// Zero
self.r.f |= Z;
}
1
})
}
macro_rules! jr_e {
($cond: expr) => ({
let e = m.rb(self.bump()) as i8;
if $cond {
if e < 0 { self.r.pc -= (-e) as u16; } else { self.r.pc += e as u16; }
3
} else {
2
}
})
}
macro_rules! ld_r_r {
($dest: ident, $src: ident) => ({
self.r.$dest = self.r.$src;
1
})
}
macro_rules! ld_r_hl {
($r: ident) => ({
self.r.$r = m.rb(self.r.hl());
2
})
}
macro_rules! ld_hl_r {
($r: ident) => ({
m.wb(self.r.hl(), self.r.$r);
2
})
}
let m_cycle = match instr {
0x00 => 1, // NOP
0x01 => ld_nn!(b, c), // LD BC, nn
0x02 => { m.wb(self.r.bc(), self.r.a); 2 } // LD (BC), A
0x03 => inc_ss!(b, c), // INC BC
0x04 => inc!(b), // INC B
0x05 => dec!(b), // DEC B
0x06 => ld_n!(b), // LD B, n
0x07 => { // RLCA
let carry = if self.r.a & 0x80 == 0x80 { 0x1 } else { 0x0 };
self.r.a = (self.r.a << 1) | carry;
self.r.f = carry << 4;
1
}
0x08 => { let addr = m.rw(self.r.pc); m.ww(addr, self.r.sp); self.r.pc += 2; 5 }
0x09 => add_hl!(b, c), // ADD HL, BC
0x0a => ld_a!(self.r.bc()), // LD A, (BC)
0x0b => dec_ss!(b, c), // DEC BC
0x0c => inc!(c), // INC C
0x0d => dec!(c), // DEC C
0x0e => ld_n!(c), // LD C, n
0x0f => { // RRCA
let carry = if self.r.a & 0x1 == 0x1 { 0x1 } else { 0x0 };
self.r.a = (self.r.a >> 1) | (carry << 7);
self.r.f = carry << 4;
1
}
0x10 => { self.r.pc += 1; 1 }
0x11 => ld_nn!(d, e), // LD DE, nn
0x12 => { m.wb(self.r.de(), self.r.a); 2 } // LD (DE), A
0x13 => inc_ss!(d, e), // INC DE
0x14 => inc!(d), // INC D
0x15 => dec!(d), // DEC D
0x16 => ld_n!(d), // LD D, n
0x17 => { // RLA
self.r.f &= C;
let carry = if self.r.a & 0x80 == 0x80 { C } else { 0x0 };
self.r.a = (self.r.a << 1) | if self.r.f == C { 0x1 } else { 0x0 };
self.r.f = carry;
1
}
0x18 => jr_e!(true), // JR e
0x19 => add_hl!(d, e), // ADD HL, DE
0x1a => ld_a!(self.r.de()), // LD A, (DE)
0x1b => dec_ss!(d, e), // DEC DE
0x1c => inc!(e), // INC E
0x1d => dec!(e), // DEC E
0x1e => ld_n!(e), // LD E, n
0x1f => { // RRA
self.r.f &= C;
let carry = if self.r.a & 0x1 == 0x1 { C } else { 0x0 };
self.r.a = (self.r.a >> 1) | if self.r.f == C { 0x80 } else { 0x0 };
self.r.f = carry;
1
}
0x20 => jr_e!(self.r.f & Z != Z),
0x21 => ld_nn!(h, l), // LD HL, nn
0x22 => { // LDI (HL), A
m.wb(self.r.hl(), self.r.a);
inc_ss!(h, l)
}
0x23 => inc_ss!(h, l), // INC HL
0x24 => inc!(h), // INC H
0x25 => dec!(h), // DEC H
0x26 => ld_n!(h), // LD H
0x27 => { // DAA
// This beast is missing tests
let mut a = self.r.a as u16;
if self.r.f & N != N {
if self.r.f & H == H || (a & 0xf) > 0x9 {
a += 0x06;
}
if self.r.f & C == C || a > 0x9f {
a += 0x60;
}
} else {
if self.r.f & H == H {
a = (a - 6) & 0xff;
}
if self.r.f & C == C {
a -= 0x60;
}
}
self.r.f &= !(Z | H | C);
if (a & 0x100) == 0x100 {
self.r.f |= C;
}
if a == 0 {
self.r.f |= Z;
}
self.r.a = a as u8;
1
}
0x28 => jr_e!(self.r.f & Z == Z), // JR Z, e
0x29 => add_hl!(h, l), // ADD HL, HL
0x2a => { // LDI A, (HL)
self.r.a = m.rb(self.r.hl());
inc_ss!(h, l)
}
0x2b => dec_ss!(h, l), // DEC HL
0x2c => inc!(l), // INC L
0x2d => dec!(l), // DEC L
0x2e => ld_n!(l), // LD L, n
0x2f => { // CPL
self.r.a = !self.r.a;
self.r.f &= Z | C;
self.r.f |= N | H;
1
}
0x30 => jr_e!(self.r.f & C != C), // JR NC, e
0x31 => { // LD SP, nn
self.r.sp = m.rw(self.bump());
self.bump();
3
}
0x32 => { // LDD (HL), A
m.wb(self.r.hl(), self.r.a);
dec_ss!(h, l)
}
0x33 => { // INC SP
self.r.sp += 1;
2
}
0x34 => { // INC (HL)
let mut value = m.rb(self.r.hl());
value += 1;
self.r.f &= C;
self.r.f |= if value == 0 { Z } else { 0 };
self.r.f |= if value & 0xf == 0 { H } else { 0 };
m.wb(self.r.hl(), value);
3
}
0x35 => { // DEC (HL)
let mut value = m.rb(self.r.hl());
value -= 1;
self.r.f &= C;
self.r.f |= N;
self.r.f |= if value == 0 { Z } else { 0 };
self.r.f |= if value & 0xf == 0xf { H } else { 0 };
m.wb(self.r.hl(), value);
3
}
0x36 => { // LD (HL), n
let value = m.rb(self.bump());
m.wb(self.r.hl(), value);
3
}
0x37 => { self.r.f &= Z; self.r.f |= C; 1 },
0x38 => jr_e!(self.r.f & C == C), // JR C, e
0x39 => add_hl_helper!(self.r.sp), // ADD HL, SP
0x3a => { self.r.a = m.rb(self.r.hl()); dec_ss!(h, l) } // LDD A, (HL)
0x3b => { self.r.sp -= 1; 2 }, // DEC SP
0x3c => inc!(a), // INC A
0x3d => dec!(a), // DEC A
0x3e => ld_n!(a), // LD A, n
0x3f => { // CCF
self.r.f &= !(N | H);
if self.r.f & C == C {
self.r.f &= !C
} else {
self.r.f |= C
}
1
}
0x40 => ld_r_r!(b, b), // LD B, B
0x41 => ld_r_r!(b, c), // LD B, C
0x42 => ld_r_r!(b, d), // LD B, D
0x43 => ld_r_r!(b, e), // LD B, E
0x44 => ld_r_r!(b, h), // LD B, H
0x45 => ld_r_r!(b, l), // LD B, L
0x46 => ld_r_hl!(b), // LD B, (HL)
0x47 => ld_r_r!(b, a), // LD B, A
0x48 => ld_r_r!(c, b), // LD C, B
0x49 => ld_r_r!(c, c), // LD C, C
0x4a => ld_r_r!(c, d), // LD C, D
0x4b => ld_r_r!(c, e), // LD C, E
0x4c => ld_r_r!(c, h), // LD C, H
0x4d => ld_r_r!(c, l), // LD C, L
0x4e => ld_r_hl!(c), // LD C, (HL)
0x4f => ld_r_r!(c, a), // LD C, A
0x50 => ld_r_r!(d, b), // LD D, B
0x51 => ld_r_r!(d, c), // LD D, C
0x52 => ld_r_r!(d, d), // LD D, D
0x53 => ld_r_r!(d, e), // LD D, E
0x54 => ld_r_r!(d, h), // LD D, H
0x55 => ld_r_r!(d, l), // LD D, L
0x56 => ld_r_hl!(d), // LD D, (HL)
0x57 => ld_r_r!(d, a), // LD D, A
0x58 => ld_r_r!(e, b), // LD E, B
0x59 => ld_r_r!(e, c), // LD E, C
0x5a => ld_r_r!(e, d), // LD E, D
0x5b => ld_r_r!(e, e), // LD E, E
0x5c => ld_r_r!(e, h), // LD E, H
0x5d => ld_r_r!(e, l), // LD E, L
0x5e => ld_r_hl!(e), // LD E, (HL)
0x5f => ld_r_r!(e, a), // LD E, A
0x60 => ld_r_r!(h, b), // LD H, B
0x61 => ld_r_r!(h, c), // LD H, C
0x62 => ld_r_r!(h, d), // LD H, D
0x63 => ld_r_r!(h, e), // LD H, E
0x64 => ld_r_r!(h, h), // LD H, H
0x65 => ld_r_r!(h, l), // LD H, L
0x66 => ld_r_hl!(h), // LD H, (HL)
0x67 => ld_r_r!(h, a), // LD H, A
0x68 => ld_r_r!(l, b), // LD L, B
0x69 => ld_r_r!(l, c), // LD L, C
0x6a => ld_r_r!(l, d), // LD L, D
0x6b => ld_r_r!(l, e), // LD L, E
0x6c => ld_r_r!(l, h), // LD L, H
0x6d => ld_r_r!(l, l), // LD L, L
0x6e => ld_r_hl!(l), // LD L, (HL)
0x6f => ld_r_r!(l, a), // LD L, A
0x70 => ld_hl_r!(b), // LD (HL), B
0x71 => ld_hl_r!(c), // LD (HL), C
0x72 => ld_hl_r!(d), // LD (HL), D
0x73 => ld_hl_r!(e), // LD (HL), E
0x74 => ld_hl_r!(h), // LD (HL), H
0x75 => ld_hl_r!(l), // LD (HL), L
0x76 => { 1 } // TODO: HALT
0x80 => add_r!(b), // ADD A, B
_ => 0
};
set_r_clock!(self, m_cycle);
m_cycle
}
}
#[cfg(test)]
mod test {
use cpu::Cpu;
use cpu::{Z, N, H, C};
use mmu::Mmu;
fn init() -> (Cpu, Mmu) {
let (mut c, m) = (Cpu::new(), Mmu::new());
c.r.pc = 0xE000; // wram
(c, m)
}
#[test]
fn reset() {
let (mut c, _) = init();
c.r.a = 1;
c.r.b = 1;
c.r.c = 1;
c.r.d = 1;
c.r.e = 1;
c.r.h = 1;
c.r.l = 1;
c.r.f = 1;
c.r.pc = 1;
c.r.sp = 1;
c.m = 2;
c.t = 8;
// Sanity check
assert_eq!(c.m, 2);
assert_eq!(c.t, 8);
c.reset();
assert_eq!(c.r.a, 0);
assert_eq!(c.r.b, 0);
assert_eq!(c.r.c, 0);
assert_eq!(c.r.d, 0);
assert_eq!(c.r.e, 0);
assert_eq!(c.r.h, 0);
assert_eq!(c.r.l, 0);
assert_eq!(c.r.f, 0);
assert_eq!(c.r.pc, 0);
assert_eq!(c.r.sp, 0);
assert_eq!(c.m, 0);
assert_eq!(c.t, 0);
}
fn op(c: &mut Cpu, m: &mut Mmu, instr: u8, pc_diff: i16, m_cycles: u32) {
let pc = c.r.pc;
c.m = 4;
c.t = 16;
m.wb(pc, instr);
let m_cycle = c.exec(m);
assert_eq!(m_cycle, m_cycles);
if pc_diff >= 0 {
assert_eq!(c.r.pc, pc + (pc_diff as u16));
} else {
assert_eq!(c.r.pc, pc - ((-pc_diff) as u16));
}
assert_eq!(c.r.m, m_cycles);
assert_eq!(c.r.t, m_cycles * 4);
assert_eq!(c.m, 4 + m_cycles);
assert_eq!(c.t, 16 + m_cycles * 4);
}
macro_rules! op {
($reg: ident, $initial: expr, $op_code: expr, $pc: expr, $m: expr, $expect: expr, $f: expr) => ({
let (mut c, mut m) = init();
c.r.$reg = $initial;
op(&mut c, &mut m, $op_code, $pc, $m);
assert_eq!(c.r.$reg, $expect);
assert_eq!(c.r.f, $f);
})
}
macro_rules! inc_r_helper {
($reg: ident, $initial: expr, $op: expr, $expect: expr, $f: expr) => ({
op!($reg, $initial, $op, 1, 1, $expect, $f);
})
}
macro_rules! inc_r {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0x00, $op, 0x01, 0x00);
})
}
macro_rules! inc_r_zero {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0xff, $op, 0x00, Z | H);
})
}
macro_rules! inc_r_half_carry {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0x0f, $op, 0x10, H);
})
}
macro_rules! dec_r_helper {
($reg: ident, $initial: expr, $op: expr, $expect: expr, $f: expr) => ({
op!($reg, $initial, $op, 1, 1, $expect, $f);
})
}
macro_rules! dec_r {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x20, $op, 0x1f, N | H);
})
}
macro_rules! dec_r_zero {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x01, $op, 0x00, Z | N);
})
}
macro_rules! dec_r_half_carry {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x00, $op, 0xff, N | H);
})
}
macro_rules! ld_rr_nn {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0xe23f);
op(&mut c, &mut m, $op, 3, 3);
assert_eq!(c.r.$reg1, 0xe2);
assert_eq!(c.r.$reg2, 0x3f);
})
}
macro_rules! ld_rr_r {
($reg1: ident, $reg2: ident, $src: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$src = 0x34;
c.r.$reg1 = 0xD0;
c.r.$reg2 = 0xED;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(m.rb(0xD0ED), 0x34);
})
}
macro_rules! inc_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x20;
c.r.$reg2 = 0x43;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x20);
assert_eq!(c.r.$reg2, 0x44);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! inc_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x00;
c.r.$reg2 = 0xff;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x01);
assert_eq!(c.r.$reg2, 0x00);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! inc_rr_overflow {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0xff;
c.r.$reg2 = 0xff;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x00);
assert_eq!(c.r.$reg2, 0x00);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! ld_r_n {
($reg: ident, $op: expr) => ({
let (mut c, mut m) = init();
m.wb(c.r.pc + 1, 0x20);
op(&mut c, &mut m, $op, 2, 2);
assert_eq!(c.r.$reg, 0x20);
})
}
macro_rules! add_hl_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0x12;
c.r.l = 0x34;
c.r.$reg1 = 0x56;
c.r.$reg2 = 0x78;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x68);
assert_eq!(c.r.l, 0xac);
assert_eq!(c.r.f, 0x0);
})
}
macro_rules! add_hl_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0x1f;
c.r.l = 0xe0;
c.r.$reg1 = 0x21;
c.r.$reg2 = 0x01;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x40);
assert_eq!(c.r.l, 0xe1);
assert_eq!(c.r.f, H);
})
}
macro_rules! add_hl_rr_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xff;
c.r.l = 0xff;
c.r.$reg1 = 0x00;
c.r.$reg2 = 0x02;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x00);
assert_eq!(c.r.l, 0x01);
assert_eq!(c.r.f, H | C);
})
}
macro_rules! add_hl_rr_only_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xf0;
c.r.l = 0x12;
c.r.$reg1 = 0x11;
c.r.$reg2 = 0x02;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x01);
assert_eq!(c.r.l, 0x14);
assert_eq!(c.r.f, C);
})
}
macro_rules! ld_a_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0xd0;
c.r.$reg2 = 0x00;
m.wb(0xd000, 0x4e);
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.a, 0x4e);
})
}
macro_rules! dec_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x12;
c.r.$reg2 = 0x34;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x12);
assert_eq!(c.r.$reg2, 0x33);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! dec_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x12;
c.r.$reg2 = 0x00;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x11);
assert_eq!(c.r.$reg2, 0xff);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! dec_rr_underflow {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x00;
c.r.$reg2 = 0x00;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0xff);
assert_eq!(c.r.$reg2, 0xff);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! jr_e_helper {
($e: expr, $f: expr, $op: expr, $pc: expr, $t: expr) => ({
let (mut c, mut m) = init();
m.wb(c.r.pc + 1, $e);
c.r.f = $f;
op(&mut c, &mut m, $op, $pc, $t);
})
}
macro_rules! jr_e {
($f: expr, $op: expr) => ({
jr_e_helper!(0x02, $f, $op, 4, 3);
})
}
macro_rules! jr_e_back {
($f: expr, $op: expr) => ({
jr_e_helper!(0b11111100, $f, $op, -2, 3);
})
}
macro_rules! jr_e_no_jump {
($f: expr, $op: expr) => ({
jr_e_helper!(0x02, $f, $op, 2, 2);
})
}
#[test]
fn nop() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x00, 1, 1);
}
#[test]
fn ld_bc_nn() {
ld_rr_nn!(b, c, 0x01);
}
#[test]
fn ld_bc_a() {
ld_rr_r!(b, c, a, 0x02);
}
#[test]
fn inc_bc() {
inc_rr!(b, c, 0x03);
}
#[test]
fn inc_bc_half_carry() {
inc_rr_half_carry!(b, c, 0x03);
}
#[test]
fn inc_bc_overflow() {
inc_rr_overflow!(b, c, 0x03);
}
#[test]
fn inc_b() {
inc_r!(b, 0x04);
}
#[test]
fn inc_b_zero() {
inc_r_zero!(b, 0x04);
}
#[test]
fn inc_b_half_carry() {
inc_r_half_carry!(b, 0x04);
}
#[test]
fn dec_b() {
dec_r!(b, 0x05);
}
#[test]
fn dec_b_zero() {
dec_r_zero!(b, 0x05);
}
#[test]
fn dec_b_half_carry() {
dec_r_half_carry!(b, 0x05);
}
#[test]
fn ld_b_n() {
ld_r_n!(b, 0x06);
}
#[test]
fn rlc_a() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0xfc);
assert_eq!(c.r.f, 0);
}
#[test]
fn rlc_a_carry() {
let (mut c, mut m) = init();
c.r.a = 0x8e;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0x1d);
assert_eq!(c.r.f, C);
}
#[test]
fn rlc_a_flags() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0xfc);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn ld_nn_sp() {
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0xa2fe);
c.r.sp = 0xabcd;
op(&mut c, &mut m, 0x08, 3, 5);
assert_eq!(m.rw(0xa2fe), 0xabcd);
}
#[test]
fn add_hl_bc() {
add_hl_rr!(b, c, 0x09);
}
#[test]
fn add_hl_bc_half_carry() {
add_hl_rr_half_carry!(b, c, 0x09);
}
#[test]
fn add_hl_bc_carry() {
add_hl_rr_carry!(b, c, 0x09);
}
#[test]
fn add_hl_bc_only_carry() {
add_hl_rr_only_carry!(b, c, 0x09);
}
#[test]
fn ld_a_bc() {
ld_a_rr!(b, c, 0x0a);
}
#[test]
fn dec_bc() {
dec_rr!(b, c, 0x0b);
}
#[test]
fn dec_bc_half_carry() {
dec_rr_half_carry!(b, c, 0x0b);
}
#[test]
fn dec_bc_underflow() {
dec_rr_underflow!(b, c, 0x0b);
}
#[test]
fn inc_c() {
inc_r!(c, 0x0c);
}
#[test]
fn inc_c_zero() {
inc_r_zero!(c, 0x0c);
}
#[test]
fn inc_c_half_carry() {
inc_r_half_carry!(c, 0x0c);
}
#[test]
fn dec_c() {
dec_r!(c, 0x0d);
}
#[test]
fn dec_c_zero() {
dec_r_zero!(c, 0x0d);
}
#[test]
fn dec_c_half_carry() {
dec_r_half_carry!(c, 0x0d);
}
#[test]
fn ld_c_n() {
ld_r_n!(c, 0x0e);
}
#[test]
fn rrca() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0x3f);
}
#[test]
fn rrca_carry() {
let (mut c, mut m) = init();
c.r.a = 0xd1;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0xe8);
assert_eq!(c.r.f, C);
}
#[test]
fn rrca_flags() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0x3f);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn stop() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x10, 2, 1);
}
#[test]
fn ld_de_nn() {
ld_rr_nn!(d, e, 0x11);
}
#[test]
fn ld_de_a() {
ld_rr_r!(d, e, a, 0x12);
}
#[test]
fn inc_de() {
inc_rr!(d, e, 0x13);
}
#[test]
fn inc_de_half_carry() {
inc_rr_half_carry!(d, e, 0x13);
}
#[test]
fn inc_de_overflow() {
inc_rr_overflow!(d, e, 0x13);
}
#[test]
fn inc_d() {
inc_r!(d, 0x14);
}
#[test]
fn inc_d_zero() {
inc_r_zero!(d, 0x14);
}
#[test]
fn inc_d_half_carry() {
inc_r_half_carry!(d, 0x14);
}
#[test]
fn dec_d() {
dec_r!(d, 0x15);
}
#[test]
fn dec_d_zero() {
dec_r_zero!(d, 0x15);
}
#[test]
fn dec_d_half_carry() {
dec_r_half_carry!(d, 0x15);
}
#[test]
fn ld_d_n() {
ld_r_n!(d, 0x16);
}
#[test]
fn rla() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rla_into_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rla_from_carry() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
c.r.f = C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rla_through_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
c.r.f = C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, C);
}
#[test]
fn rla_flags() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn jr_e() {
jr_e!(0x00, 0x18);
}
#[test]
fn jr_e_back() {
jr_e_back!(0x00, 0x18);
}
#[test]
fn add_hl_de() {
add_hl_rr!(d, e, 0x19);
}
#[test]
fn add_hl_de_carry() {
add_hl_rr_carry!(d, e, 0x19);
}
#[test]
fn add_hl_de_half_carry() {
add_hl_rr_half_carry!(d, e, 0x19);
}
#[test]
fn add_hl_de_only_carry() {
add_hl_rr_only_carry!(d, e, 0x19);
}
#[test]
fn ld_a_de() {
ld_a_rr!(d, e, 0x1a);
}
#[test]
fn dec_de() {
dec_rr!(d, e, 0x1b);
}
#[test]
fn dec_de_half_carry() {
dec_rr_half_carry!(d, e, 0x1b);
}
#[test]
fn dec_de_underflow() {
dec_rr_underflow!(d, e, 0x1b);
}
#[test]
fn inc_e() {
inc_r!(e, 0x1c);
}
#[test]
fn inc_e_half_carry() {
inc_r_half_carry!(e, 0x1c);
}
#[test]
fn inc_e_zero() {
inc_r_zero!(e, 0x1c);
}
#[test]
fn dec_e() {
dec_r!(e, 0x1d);
}
#[test]
fn dec_e_half_carry() {
dec_r_half_carry!(e, 0x1d);
}
#[test]
fn dec_e_underflow() {
dec_r_half_carry!(e, 0x1d);
}
#[test]
fn ld_e_n() {
ld_r_n!(e, 0x1e);
}
#[test]
fn rra() {
let (mut c, mut m) = init();
c.r.a = 0b10101010;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b01010101);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rra_into_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b01101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rra_from_carry() {
let (mut c, mut m) = init();
c.r.a = 0b01010100;
c.r.f = C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rra_through_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
c.r.f = C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b11101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rra_flags() {
let (mut c, mut m) = init();
c.r.a = 0b01010100;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn jr_nz_e() {
jr_e!(0x00, 0x20);
}
#[test]
fn jr_nz_e_back() {
jr_e_back!(0x00, 0x20);
}
#[test]
fn jr_nz_e_no_jump() {
jr_e_no_jump!(Z, 0x20);
}
#[test]
fn ld_hl_nn() {
ld_rr_nn!(h, l, 0x21);
}
#[test]
fn ldi_hl_a() {
let (mut c, mut m) = init();
c.r.a = 0xab;
c.r.h = 0xd2;
c.r.l = 0xff;
op(&mut c, &mut m, 0x22, 1, 2);
assert_eq!(m.rb(0xd2ff), 0xab);
assert_eq!(c.r.h, 0xd3);
assert_eq!(c.r.l, 0x00);
}
#[test]
fn inc_hl() {
inc_rr!(h, l, 0x23);
}
#[test]
fn inc_hl_half_carry() {
inc_rr_half_carry!(h, l, 0x23);
}
#[test]
fn inc_hl_overflow() {
inc_rr_overflow!(h, l, 0x23);
}
#[test]
fn inc_h() {
inc_r!(h, 0x24);
}
#[test]
fn inc_h_half_carry() {
inc_r_half_carry!(h, 0x24);
}
#[test]
fn inc_h_zero() {
inc_r_zero!(h, 0x24);
}
#[test]
fn dec_h() {
dec_r!(h, 0x25);
}
#[test]
fn dec_h_half_carry() {
dec_r_half_carry!(h, 0x25);
}
#[test]
fn dec_h_zero() {
dec_r_zero!(h, 0x25);
}
#[test]
fn ld_h_n() {
ld_r_n!(h, 0x26);
}
#[test]
fn jr_z_e() {
jr_e!(Z, 0x28);
}
#[test]
fn jr_z_e_back() {
jr_e_back!(Z, 0x28);
}
#[test]
fn jr_z_e_no_jump() {
jr_e_no_jump!(0x00, 0x28);
}
fn add_hl_hl_helper(h: u8, l: u8, expected_h: u8, expected_l: u8, expected_f: u8) {
let (mut c, mut m) = init();
c.r.h = h;
c.r.l = l;
op(&mut c, &mut m, 0x29, 1, 2);
assert_eq!(c.r.h, expected_h);
assert_eq!(c.r.l, expected_l);
assert_eq!(c.r.f, expected_f);
}
#[test]
fn add_hl_hl() {
add_hl_hl_helper(0x12, 0x34, 0x24, 0x68, 0x0);
}
#[test]
fn add_hl_hl_carry() {
add_hl_hl_helper(0x88, 0x88, 0x11, 0x10, H | C);
}
#[test]
fn add_hl_hl_half_carry() {
add_hl_hl_helper(0x18, 0x00, 0x30, 0x00, H);
}
#[test]
fn add_hl_hl_only_carry() {
add_hl_hl_helper(0x82, 0x00, 0x04, 0x00, C);
}
#[test]
fn ldi_a_hl() {
let (mut c, mut m) = init();
c.r.h = 0xc0;
c.r.l = 0xff;
m.wb(0xc0ff, 0x12);
op(&mut c, &mut m, 0x2a, 1, 2);
assert_eq!(c.r.a, 0x12);
assert_eq!(c.r.h, 0xc1);
assert_eq!(c.r.l, 0x00);
}
#[test]
fn dec_hl() {
dec_rr!(h, l, 0x2b);
}
#[test]
fn dec_hl_half_carry() {
dec_rr_half_carry!(h, l, 0x2b);
}
#[test]
fn dec_hl_underflow() {
dec_rr_underflow!(h, l, 0x2b);
}
#[test]
fn inc_l() {
inc_r!(l, 0x2c);
}
#[test]
fn inc_l_half_carry() {
inc_r_half_carry!(l, 0x2c);
}
#[test]
fn inc_l_zero() {
inc_r_zero!(l, 0x2c);
}
#[test]
fn dec_l() {
dec_r!(l, 0x2d);
}
#[test]
fn dec_l_half_carry() {
dec_r_half_carry!(l, 0x2d);
}
#[test]
fn dec_l_underflow() {
dec_r_half_carry!(l, 0x2d);
}
#[test]
fn ld_l_n() {
ld_r_n!(l, 0x2e);
}
#[test]
fn cpl() {
let (mut c, mut m) = init();
c.r.a = 0b01101010;
c.r.f = Z | C;
op(&mut c, &mut m, 0x2f, 1, 1);
assert_eq!(c.r.a, 0b10010101);
assert_eq!(c.r.f, Z | N | H | C);
}
#[test]
fn ld_sp_nn() {
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0x1234);
op(&mut c, &mut m, 0x31, 3, 3);
assert_eq!(c.r.sp, 0x1234);
}
#[test]
fn ldd_hl_a() {
let (mut c, mut m) = init();
c.r.a = 0xab;
c.r.h = 0xd2;
c.r.l = 0xff;
op(&mut c, &mut m, 0x32, 1, 2);
assert_eq!(m.rb(0xd2ff), 0xab);
assert_eq!(c.r.h, 0xd2);
assert_eq!(c.r.l, 0xfe);
}
#[test]
fn inc_sp() {
let (mut c, mut m) = init();
c.r.sp = 0x1234;
op(&mut c, &mut m, 0x33, 1, 2);
assert_eq!(c.r.sp, 0x1235);
}
#[test]
fn inc_at_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x34, 1, 3);
assert_eq!(m.rb(0xd000), 0x13);
}
#[test]
fn dec_at_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x35, 1, 3);
assert_eq!(m.rb(0xd000), 0x11);
}
#[test]
fn ld_hl_n() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(c.r.pc + 1, 0x12);
op(&mut c, &mut m, 0x36, 2, 3);
assert_eq!(m.rb(0xd000), 0x12);
}
#[test]
fn scf() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x37, 1, 1);
assert_eq!(c.r.f, C);
}
#[test]
fn jr_c_e() {
jr_e!(C, 0x38);
}
#[test]
fn jr_c_e_back() {
jr_e_back!(C, 0x38);
}
#[test]
fn jr_c_e_no_jump() {
jr_e_no_jump!(0x00, 0x38);
}
fn add_hl_sp_helper(h: u8, l: u8, sp: u16, expected_h: u8, expected_l: u8, expected_f: u8) {
let (mut c, mut m) = init();
c.r.h = h;
c.r.l = l;
c.r.sp = sp;
op(&mut c, &mut m, 0x39, 1, 2);
assert_eq!(c.r.h, expected_h);
assert_eq!(c.r.l, expected_l);
assert_eq!(c.r.f, expected_f);
}
#[test]
fn add_hl_sp() {
add_hl_sp_helper(0x12, 0x34, 0x3451, 0x46, 0x85, 0x0);
}
#[test]
fn add_hl_sp_carry() {
add_hl_sp_helper(0xff, 0xff, 0x0002, 0x00, 0x01, H | C);
}
#[test]
fn add_hl_sp_half_carry() {
add_hl_sp_helper(0x18, 0x00, 0x0900, 0x21, 0x00, H);
}
#[test]
fn add_hl_sp_only_carry() {
add_hl_sp_helper(0x82, 0x00, 0x8000, 0x02, 0x00, C);
}
#[test]
fn ldd_a_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x3a, 1, 2);
assert_eq!(c.r.a, 0x12);
assert_eq!(c.r.h, 0xcf);
assert_eq!(c.r.l, 0xff);
}
#[test]
fn dec_sp() {
let (mut c, mut m) = init();
c.r.sp = 0x1234;
op(&mut c, &mut m, 0x3b, 1, 2);
assert_eq!(c.r.sp, 0x1233);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn inc_a() {
inc_r!(a, 0x3c);
}
#[test]
fn inc_a_half_carry() {
inc_r_half_carry!(a, 0x3c);
}
#[test]
fn inc_a_zero() {
inc_r_zero!(a, 0x3c);
}
#[test]
fn dec_a() {
dec_r!(a, 0x3d);
}
#[test]
fn dec_a_half_carry() {
dec_r_half_carry!(a, 0x3d);
}
#[test]
fn dec_a_underflow() {
dec_r_half_carry!(a, 0x3d);
}
#[test]
fn ld_a_n() {
ld_r_n!(a, 0x3e);
}
macro_rules! ccf {
($c: expr, $expected_c: expr) => ({
let (mut c, mut m) = init();
c.r.f = Z | N | H | $c;
op(&mut c, &mut m, 0x3f, 1, 1);
assert_eq!(c.r.f, Z | $expected_c);
})
}
#[test]
fn ccf() {
ccf!(0x00, C);
}
#[test]
fn ccf_reset() {
ccf!(C, 0x00);
}
macro_rules! ld_r_r {
($dest: ident, $src: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$src = 0x12;
op(&mut c, &mut m, $op, 1, 1);
assert_eq!(c.r.$dest, 0x12);
})
}
macro_rules! ld_r_hl {
($r: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$r, 0x12);
})
}
#[test]
fn ld_b_b() {
ld_r_r!(b, b, 0x40);
}
#[test]
fn ld_b_c() {
ld_r_r!(b, c, 0x41);
}
#[test]
fn ld_b_d() {
ld_r_r!(b, d, 0x42);
}
#[test]
fn ld_b_e() {
ld_r_r!(b, e, 0x43);
}
#[test]
fn ld_b_h() {
ld_r_r!(b, h, 0x44);
}
#[test]
fn ld_b_l() {
ld_r_r!(b, l, 0x45);
}
#[test]
fn ld_b_hl() {
ld_r_hl!(b, 0x46);
}
#[test]
fn ld_b_a() {
ld_r_r!(b, a, 0x47);
}
#[test]
fn ld_c_b() {
ld_r_r!(c, b, 0x48);
}
#[test]
fn ld_c_c() {
ld_r_r!(c, c, 0x49);
}
#[test]
fn ld_c_d() {
ld_r_r!(c, d, 0x4a);
}
#[test]
fn ld_c_e() {
ld_r_r!(c, e, 0x4b);
}
#[test]
fn ld_c_h() {
ld_r_r!(c, h, 0x4c);
}
#[test]
fn ld_c_l() {
ld_r_r!(c, l, 0x4d);
}
#[test]
fn ld_c_hl() {
ld_r_hl!(c, 0x4e);
}
#[test]
fn ld_c_a() {
ld_r_r!(c, a, 0x4f);
}
#[test]
fn ld_d_b() {
ld_r_r!(d, b, 0x50);
}
#[test]
fn ld_d_c() {
ld_r_r!(d, c, 0x51);
}
#[test]
fn ld_d_d() {
ld_r_r!(d, d, 0x52);
}
#[test]
fn ld_d_e() {
ld_r_r!(d, e, 0x53);
}
#[test]
fn ld_d_h() {
ld_r_r!(d, h, 0x54);
}
#[test]
fn ld_d_l() {
ld_r_r!(d, l, 0x55);
}
#[test]
fn ld_d_hl() {
ld_r_hl!(d, 0x56);
}
#[test]
fn ld_d_a() {
ld_r_r!(d, a, 0x57);
}
#[test]
fn ld_e_b() {
ld_r_r!(e, b, 0x58);
}
#[test]
fn ld_e_c() {
ld_r_r!(e, c, 0x59);
}
#[test]
fn ld_e_d() {
ld_r_r!(e, d, 0x5a);
}
#[test]
fn ld_e_e() {
ld_r_r!(e, e, 0x5b);
}
#[test]
fn ld_e_h() {
ld_r_r!(e, h, 0x5c);
}
#[test]
fn ld_e_l() {
ld_r_r!(e, l, 0x5d);
}
#[test]
fn ld_e_hl() {
ld_r_hl!(e, 0x5e);
}
#[test]
fn ld_e_a() {
ld_r_r!(e, a, 0x5f);
}
#[test]
fn ld_h_b() {
ld_r_r!(h, b, 0x60);
}
#[test]
fn ld_h_c() {
ld_r_r!(h, c, 0x61);
}
#[test]
fn ld_h_d() {
ld_r_r!(h, d, 0x62);
}
#[test]
fn ld_h_e() {
ld_r_r!(h, e, 0x63);
}
#[test]
fn ld_h_h() {
ld_r_r!(h, h, 0x64);
}
#[test]
fn ld_h_l() {
ld_r_r!(h, l, 0x65);
}
#[test]
fn ld_h_hl() {
ld_r_hl!(h, 0x66);
}
#[test]
fn ld_h_a() {
ld_r_r!(h, a, 0x67);
}
#[test]
fn ld_l_b() {
ld_r_r!(l, b, 0x68);
}
#[test]
fn ld_l_c() {
ld_r_r!(l, c, 0x69);
}
#[test]
fn ld_l_d() {
ld_r_r!(l, d, 0x6a);
}
#[test]
fn ld_l_e() {
ld_r_r!(l, e, 0x6b);
}
#[test]
fn ld_l_h() {
ld_r_r!(l, h, 0x6c);
}
#[test]
fn ld_l_l() {
ld_r_r!(l, l, 0x6d);
}
#[test]
fn ld_l_hl() {
ld_r_hl!(l, 0x6e);
}
#[test]
fn ld_l_a() {
ld_r_r!(l, a, 0x6f);
}
macro_rules! ld_hl_r {
($r: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
c.r.$r = 0x12;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(m.rb(0xd000), 0x12);
})
}
#[test]
fn ld_hl_b() {
ld_hl_r!(b, 0x70);
}
#[test]
fn ld_hl_c() {
ld_hl_r!(c, 0x71);
}
#[test]
fn ld_hl_d() {
ld_hl_r!(d, 0x72);
}
#[test]
fn ld_hl_e() {
ld_hl_r!(e, 0x73);
}
#[test]
fn ld_hl_h() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x12;
op(&mut c, &mut m, 0x74, 1, 2);
assert_eq!(m.rb(0xd012), 0xd0);
}
#[test]
fn ld_hl_l() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x12;
op(&mut c, &mut m, 0x75, 1, 2);
assert_eq!(m.rb(0xd012), 0x12);
}
#[test]
fn halt() {
// TODO
}
/*
#[test]
fn add_a_b() {
let (mut c, mut m) = init();
c.r.a = 0x02;
c.r.b = 0x01;
c.r.f = 0x80 | 0x40 | 0x20 | 0x10;
op(&mut c, &mut m, 0x80, 1, 1);
assert_eq!(c.r.a, 0x03);
assert_eq!(c.r.f, 0x00);
// TODO: Check all flags
}
*/
}
0x77-0x7f
use super::mmu::Mmu;
use super::registers::Registers;
// The following are the four flags set by certain arithmetic operations
const Z: u8 = 0x80; // Zero: Set if the result is zero.
const N: u8 = 0x40; // Operation: Set if the last operation was a subtraction.
const H: u8 = 0x20; // Half-carry: Set if there was carry from the low nibble to the high. In the high byte for 16 bit operations.
const C: u8 = 0x10; // Carry: Set if last options overflowed or underflowed.
pub struct Cpu {
// Clock
m: u32,
t: u32,
r: Registers,
}
macro_rules! set_clock( ( $cpu: ident, $m: expr ) => ({
$cpu.m = $m;
$cpu.t = $m * 4;
}) );
macro_rules! set_r_clock( ( $cpu: ident, $m: expr ) => ({
$cpu.r.m = $m;
$cpu.r.t = $m * 4;
}) );
impl Cpu {
pub fn new() -> Cpu {
Cpu {
m: 0,
t: 0,
r: Registers::new(),
}
}
fn bump(&mut self) -> u16 {
let ret = self.r.pc;
self.r.pc += 1;
ret
}
pub fn reset(&mut self) {
self.m = 0; self.t = 0;
self.r.reset();
}
pub fn exec(&mut self, m: &mut Mmu) -> u32 {
let op = m.rb(self.bump());
let m_cycles = self.exec_instr(op, m);
self.m += self.r.m;
self.t += self.r.t;
m_cycles
}
fn exec_instr(&mut self, instr: u8, m: &mut Mmu) -> u32 {
macro_rules! ld_nn {
($reg1: ident, $reg2: ident) => ({
self.r.$reg1 = m.rb(self.bump());
self.r.$reg2 = m.rb(self.bump());
3
})
}
macro_rules! inc_ss {
($reg1: ident, $reg2: ident) => ({
self.r.$reg2 += 1;
if self.r.$reg2 == 0 {
self.r.$reg1 += 1;
}
2
})
}
macro_rules! inc {
($reg: ident) => ({
self.r.$reg += 1;
self.r.f &= C;
self.r.f |= if self.r.$reg == 0 { Z } else { 0 };
self.r.f |= if self.r.$reg & 0xf == 0 { H } else { 0 };
1
})
}
macro_rules! dec {
($reg: ident) => ({
self.r.$reg -= 1;
self.r.f &= C;
self.r.f |= N;
self.r.f |= if self.r.$reg == 0 { Z } else { 0 };
self.r.f |= if self.r.$reg & 0xf == 0xf { H } else { 0 };
1
})
}
macro_rules! ld_n {
($reg: ident) => ({
self.r.$reg = m.rb(self.bump());
2
})
}
macro_rules! rlc_r {
($reg: ident) => ({
let carry = if self.r.$reg & 0x80 == 0x80 { 0x1 } else { 0x0 };
self.r.$reg = (self.r.$reg << 1) | carry;
self.r.f = carry << 4;
2
})
}
macro_rules! add_hl_helper {
($val: expr) => ({
self.r.f &= Z;
// TODO: Cleanup
self.r.f |= if ((((self.r.h as u16) << 8) | self.r.l as u16) & 0xfff) + ($val & 0xfff) > 0xfff {
H
} else {
0
};
let result = ((self.r.h as u32) << 8 | self.r.l as u32)
+ $val as u32;
self.r.f |= if result > 0xffff { C } else { 0 };
self.r.h = (result >> 8) as u8;
self.r.l = result as u8;
2
})
}
macro_rules! add_hl {
($reg1: ident, $reg2: ident) => ({
add_hl_helper!(((self.r.$reg1 as u16) << 8) | self.r.$reg2 as u16)
})
}
macro_rules! ld_a {
($addr: expr) => ({
self.r.a = m.rb($addr);
2
})
}
macro_rules! dec_ss {
($reg1: ident, $reg2: ident) => ({
self.r.$reg2 -= 1;
if self.r.$reg2 == 0xff {
self.r.$reg1 -= 1;
}
2
})
}
macro_rules! add_r {
($reg: ident) => ({
self.r.f = 0;
if (self.r.a & 0xF) + (self.r.$reg & 0xF) > 0xF {
// Half carry
self.r.f |= H;
}
if (self.r.a as u32) + (self.r.$reg as u32) > 255 {
// Carry
self.r.f |= C;
}
self.r.a += self.r.$reg;
if self.r.a == 0 {
// Zero
self.r.f |= Z;
}
1
})
}
macro_rules! jr_e {
($cond: expr) => ({
let e = m.rb(self.bump()) as i8;
if $cond {
if e < 0 { self.r.pc -= (-e) as u16; } else { self.r.pc += e as u16; }
3
} else {
2
}
})
}
macro_rules! ld_r_r {
($dest: ident, $src: ident) => ({
self.r.$dest = self.r.$src;
1
})
}
macro_rules! ld_r_hl {
($r: ident) => ({
self.r.$r = m.rb(self.r.hl());
2
})
}
macro_rules! ld_hl_r {
($r: ident) => ({
m.wb(self.r.hl(), self.r.$r);
2
})
}
let m_cycle = match instr {
0x00 => 1, // NOP
0x01 => ld_nn!(b, c), // LD BC, nn
0x02 => { m.wb(self.r.bc(), self.r.a); 2 } // LD (BC), A
0x03 => inc_ss!(b, c), // INC BC
0x04 => inc!(b), // INC B
0x05 => dec!(b), // DEC B
0x06 => ld_n!(b), // LD B, n
0x07 => { // RLCA
let carry = if self.r.a & 0x80 == 0x80 { 0x1 } else { 0x0 };
self.r.a = (self.r.a << 1) | carry;
self.r.f = carry << 4;
1
}
0x08 => { let addr = m.rw(self.r.pc); m.ww(addr, self.r.sp); self.r.pc += 2; 5 }
0x09 => add_hl!(b, c), // ADD HL, BC
0x0a => ld_a!(self.r.bc()), // LD A, (BC)
0x0b => dec_ss!(b, c), // DEC BC
0x0c => inc!(c), // INC C
0x0d => dec!(c), // DEC C
0x0e => ld_n!(c), // LD C, n
0x0f => { // RRCA
let carry = if self.r.a & 0x1 == 0x1 { 0x1 } else { 0x0 };
self.r.a = (self.r.a >> 1) | (carry << 7);
self.r.f = carry << 4;
1
}
0x10 => { self.r.pc += 1; 1 }
0x11 => ld_nn!(d, e), // LD DE, nn
0x12 => { m.wb(self.r.de(), self.r.a); 2 } // LD (DE), A
0x13 => inc_ss!(d, e), // INC DE
0x14 => inc!(d), // INC D
0x15 => dec!(d), // DEC D
0x16 => ld_n!(d), // LD D, n
0x17 => { // RLA
self.r.f &= C;
let carry = if self.r.a & 0x80 == 0x80 { C } else { 0x0 };
self.r.a = (self.r.a << 1) | if self.r.f == C { 0x1 } else { 0x0 };
self.r.f = carry;
1
}
0x18 => jr_e!(true), // JR e
0x19 => add_hl!(d, e), // ADD HL, DE
0x1a => ld_a!(self.r.de()), // LD A, (DE)
0x1b => dec_ss!(d, e), // DEC DE
0x1c => inc!(e), // INC E
0x1d => dec!(e), // DEC E
0x1e => ld_n!(e), // LD E, n
0x1f => { // RRA
self.r.f &= C;
let carry = if self.r.a & 0x1 == 0x1 { C } else { 0x0 };
self.r.a = (self.r.a >> 1) | if self.r.f == C { 0x80 } else { 0x0 };
self.r.f = carry;
1
}
0x20 => jr_e!(self.r.f & Z != Z),
0x21 => ld_nn!(h, l), // LD HL, nn
0x22 => { // LDI (HL), A
m.wb(self.r.hl(), self.r.a);
inc_ss!(h, l)
}
0x23 => inc_ss!(h, l), // INC HL
0x24 => inc!(h), // INC H
0x25 => dec!(h), // DEC H
0x26 => ld_n!(h), // LD H
0x27 => { // DAA
// This beast is missing tests
let mut a = self.r.a as u16;
if self.r.f & N != N {
if self.r.f & H == H || (a & 0xf) > 0x9 {
a += 0x06;
}
if self.r.f & C == C || a > 0x9f {
a += 0x60;
}
} else {
if self.r.f & H == H {
a = (a - 6) & 0xff;
}
if self.r.f & C == C {
a -= 0x60;
}
}
self.r.f &= !(Z | H | C);
if (a & 0x100) == 0x100 {
self.r.f |= C;
}
if a == 0 {
self.r.f |= Z;
}
self.r.a = a as u8;
1
}
0x28 => jr_e!(self.r.f & Z == Z), // JR Z, e
0x29 => add_hl!(h, l), // ADD HL, HL
0x2a => { // LDI A, (HL)
self.r.a = m.rb(self.r.hl());
inc_ss!(h, l)
}
0x2b => dec_ss!(h, l), // DEC HL
0x2c => inc!(l), // INC L
0x2d => dec!(l), // DEC L
0x2e => ld_n!(l), // LD L, n
0x2f => { // CPL
self.r.a = !self.r.a;
self.r.f &= Z | C;
self.r.f |= N | H;
1
}
0x30 => jr_e!(self.r.f & C != C), // JR NC, e
0x31 => { // LD SP, nn
self.r.sp = m.rw(self.bump());
self.bump();
3
}
0x32 => { // LDD (HL), A
m.wb(self.r.hl(), self.r.a);
dec_ss!(h, l)
}
0x33 => { // INC SP
self.r.sp += 1;
2
}
0x34 => { // INC (HL)
let mut value = m.rb(self.r.hl());
value += 1;
self.r.f &= C;
self.r.f |= if value == 0 { Z } else { 0 };
self.r.f |= if value & 0xf == 0 { H } else { 0 };
m.wb(self.r.hl(), value);
3
}
0x35 => { // DEC (HL)
let mut value = m.rb(self.r.hl());
value -= 1;
self.r.f &= C;
self.r.f |= N;
self.r.f |= if value == 0 { Z } else { 0 };
self.r.f |= if value & 0xf == 0xf { H } else { 0 };
m.wb(self.r.hl(), value);
3
}
0x36 => { // LD (HL), n
let value = m.rb(self.bump());
m.wb(self.r.hl(), value);
3
}
0x37 => { self.r.f &= Z; self.r.f |= C; 1 },
0x38 => jr_e!(self.r.f & C == C), // JR C, e
0x39 => add_hl_helper!(self.r.sp), // ADD HL, SP
0x3a => { self.r.a = m.rb(self.r.hl()); dec_ss!(h, l) } // LDD A, (HL)
0x3b => { self.r.sp -= 1; 2 }, // DEC SP
0x3c => inc!(a), // INC A
0x3d => dec!(a), // DEC A
0x3e => ld_n!(a), // LD A, n
0x3f => { // CCF
self.r.f &= !(N | H);
if self.r.f & C == C {
self.r.f &= !C
} else {
self.r.f |= C
}
1
}
0x40 => ld_r_r!(b, b), // LD B, B
0x41 => ld_r_r!(b, c), // LD B, C
0x42 => ld_r_r!(b, d), // LD B, D
0x43 => ld_r_r!(b, e), // LD B, E
0x44 => ld_r_r!(b, h), // LD B, H
0x45 => ld_r_r!(b, l), // LD B, L
0x46 => ld_r_hl!(b), // LD B, (HL)
0x47 => ld_r_r!(b, a), // LD B, A
0x48 => ld_r_r!(c, b), // LD C, B
0x49 => ld_r_r!(c, c), // LD C, C
0x4a => ld_r_r!(c, d), // LD C, D
0x4b => ld_r_r!(c, e), // LD C, E
0x4c => ld_r_r!(c, h), // LD C, H
0x4d => ld_r_r!(c, l), // LD C, L
0x4e => ld_r_hl!(c), // LD C, (HL)
0x4f => ld_r_r!(c, a), // LD C, A
0x50 => ld_r_r!(d, b), // LD D, B
0x51 => ld_r_r!(d, c), // LD D, C
0x52 => ld_r_r!(d, d), // LD D, D
0x53 => ld_r_r!(d, e), // LD D, E
0x54 => ld_r_r!(d, h), // LD D, H
0x55 => ld_r_r!(d, l), // LD D, L
0x56 => ld_r_hl!(d), // LD D, (HL)
0x57 => ld_r_r!(d, a), // LD D, A
0x58 => ld_r_r!(e, b), // LD E, B
0x59 => ld_r_r!(e, c), // LD E, C
0x5a => ld_r_r!(e, d), // LD E, D
0x5b => ld_r_r!(e, e), // LD E, E
0x5c => ld_r_r!(e, h), // LD E, H
0x5d => ld_r_r!(e, l), // LD E, L
0x5e => ld_r_hl!(e), // LD E, (HL)
0x5f => ld_r_r!(e, a), // LD E, A
0x60 => ld_r_r!(h, b), // LD H, B
0x61 => ld_r_r!(h, c), // LD H, C
0x62 => ld_r_r!(h, d), // LD H, D
0x63 => ld_r_r!(h, e), // LD H, E
0x64 => ld_r_r!(h, h), // LD H, H
0x65 => ld_r_r!(h, l), // LD H, L
0x66 => ld_r_hl!(h), // LD H, (HL)
0x67 => ld_r_r!(h, a), // LD H, A
0x68 => ld_r_r!(l, b), // LD L, B
0x69 => ld_r_r!(l, c), // LD L, C
0x6a => ld_r_r!(l, d), // LD L, D
0x6b => ld_r_r!(l, e), // LD L, E
0x6c => ld_r_r!(l, h), // LD L, H
0x6d => ld_r_r!(l, l), // LD L, L
0x6e => ld_r_hl!(l), // LD L, (HL)
0x6f => ld_r_r!(l, a), // LD L, A
0x70 => ld_hl_r!(b), // LD (HL), B
0x71 => ld_hl_r!(c), // LD (HL), C
0x72 => ld_hl_r!(d), // LD (HL), D
0x73 => ld_hl_r!(e), // LD (HL), E
0x74 => ld_hl_r!(h), // LD (HL), H
0x75 => ld_hl_r!(l), // LD (HL), L
0x76 => { 1 } // TODO: HALT
0x77 => ld_hl_r!(a), // LD (HL), A
0x78 => ld_r_r!(a, b), // LD A, B
0x79 => ld_r_r!(a, c), // LD A, C
0x7a => ld_r_r!(a, d), // LD A, D
0x7b => ld_r_r!(a, e), // LD A, E
0x7c => ld_r_r!(a, h), // LD A, H
0x7d => ld_r_r!(a, l), // LD A, L
0x7e => ld_r_hl!(a), // LD A, (HL)
0x7f => ld_r_r!(a, a), // LD A, A
0x80 => add_r!(b), // ADD A, B
_ => 0
};
set_r_clock!(self, m_cycle);
m_cycle
}
}
#[cfg(test)]
mod test {
use cpu::Cpu;
use cpu::{Z, N, H, C};
use mmu::Mmu;
fn init() -> (Cpu, Mmu) {
let (mut c, m) = (Cpu::new(), Mmu::new());
c.r.pc = 0xE000; // wram
(c, m)
}
#[test]
fn reset() {
let (mut c, _) = init();
c.r.a = 1;
c.r.b = 1;
c.r.c = 1;
c.r.d = 1;
c.r.e = 1;
c.r.h = 1;
c.r.l = 1;
c.r.f = 1;
c.r.pc = 1;
c.r.sp = 1;
c.m = 2;
c.t = 8;
// Sanity check
assert_eq!(c.m, 2);
assert_eq!(c.t, 8);
c.reset();
assert_eq!(c.r.a, 0);
assert_eq!(c.r.b, 0);
assert_eq!(c.r.c, 0);
assert_eq!(c.r.d, 0);
assert_eq!(c.r.e, 0);
assert_eq!(c.r.h, 0);
assert_eq!(c.r.l, 0);
assert_eq!(c.r.f, 0);
assert_eq!(c.r.pc, 0);
assert_eq!(c.r.sp, 0);
assert_eq!(c.m, 0);
assert_eq!(c.t, 0);
}
fn op(c: &mut Cpu, m: &mut Mmu, instr: u8, pc_diff: i16, m_cycles: u32) {
let pc = c.r.pc;
c.m = 4;
c.t = 16;
m.wb(pc, instr);
let m_cycle = c.exec(m);
assert_eq!(m_cycle, m_cycles);
if pc_diff >= 0 {
assert_eq!(c.r.pc, pc + (pc_diff as u16));
} else {
assert_eq!(c.r.pc, pc - ((-pc_diff) as u16));
}
assert_eq!(c.r.m, m_cycles);
assert_eq!(c.r.t, m_cycles * 4);
assert_eq!(c.m, 4 + m_cycles);
assert_eq!(c.t, 16 + m_cycles * 4);
}
macro_rules! op {
($reg: ident, $initial: expr, $op_code: expr, $pc: expr, $m: expr, $expect: expr, $f: expr) => ({
let (mut c, mut m) = init();
c.r.$reg = $initial;
op(&mut c, &mut m, $op_code, $pc, $m);
assert_eq!(c.r.$reg, $expect);
assert_eq!(c.r.f, $f);
})
}
macro_rules! inc_r_helper {
($reg: ident, $initial: expr, $op: expr, $expect: expr, $f: expr) => ({
op!($reg, $initial, $op, 1, 1, $expect, $f);
})
}
macro_rules! inc_r {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0x00, $op, 0x01, 0x00);
})
}
macro_rules! inc_r_zero {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0xff, $op, 0x00, Z | H);
})
}
macro_rules! inc_r_half_carry {
($reg: ident, $op: expr) => ({
inc_r_helper!($reg, 0x0f, $op, 0x10, H);
})
}
macro_rules! dec_r_helper {
($reg: ident, $initial: expr, $op: expr, $expect: expr, $f: expr) => ({
op!($reg, $initial, $op, 1, 1, $expect, $f);
})
}
macro_rules! dec_r {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x20, $op, 0x1f, N | H);
})
}
macro_rules! dec_r_zero {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x01, $op, 0x00, Z | N);
})
}
macro_rules! dec_r_half_carry {
($reg: ident, $op: expr) => ({
dec_r_helper!($reg, 0x00, $op, 0xff, N | H);
})
}
macro_rules! ld_rr_nn {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0xe23f);
op(&mut c, &mut m, $op, 3, 3);
assert_eq!(c.r.$reg1, 0xe2);
assert_eq!(c.r.$reg2, 0x3f);
})
}
macro_rules! ld_rr_r {
($reg1: ident, $reg2: ident, $src: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$src = 0x34;
c.r.$reg1 = 0xD0;
c.r.$reg2 = 0xED;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(m.rb(0xD0ED), 0x34);
})
}
macro_rules! inc_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x20;
c.r.$reg2 = 0x43;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x20);
assert_eq!(c.r.$reg2, 0x44);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! inc_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x00;
c.r.$reg2 = 0xff;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x01);
assert_eq!(c.r.$reg2, 0x00);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! inc_rr_overflow {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0xff;
c.r.$reg2 = 0xff;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x00);
assert_eq!(c.r.$reg2, 0x00);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! ld_r_n {
($reg: ident, $op: expr) => ({
let (mut c, mut m) = init();
m.wb(c.r.pc + 1, 0x20);
op(&mut c, &mut m, $op, 2, 2);
assert_eq!(c.r.$reg, 0x20);
})
}
macro_rules! add_hl_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0x12;
c.r.l = 0x34;
c.r.$reg1 = 0x56;
c.r.$reg2 = 0x78;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x68);
assert_eq!(c.r.l, 0xac);
assert_eq!(c.r.f, 0x0);
})
}
macro_rules! add_hl_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0x1f;
c.r.l = 0xe0;
c.r.$reg1 = 0x21;
c.r.$reg2 = 0x01;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x40);
assert_eq!(c.r.l, 0xe1);
assert_eq!(c.r.f, H);
})
}
macro_rules! add_hl_rr_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xff;
c.r.l = 0xff;
c.r.$reg1 = 0x00;
c.r.$reg2 = 0x02;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x00);
assert_eq!(c.r.l, 0x01);
assert_eq!(c.r.f, H | C);
})
}
macro_rules! add_hl_rr_only_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xf0;
c.r.l = 0x12;
c.r.$reg1 = 0x11;
c.r.$reg2 = 0x02;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.h, 0x01);
assert_eq!(c.r.l, 0x14);
assert_eq!(c.r.f, C);
})
}
macro_rules! ld_a_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0xd0;
c.r.$reg2 = 0x00;
m.wb(0xd000, 0x4e);
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.a, 0x4e);
})
}
macro_rules! dec_rr {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x12;
c.r.$reg2 = 0x34;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x12);
assert_eq!(c.r.$reg2, 0x33);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! dec_rr_half_carry {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x12;
c.r.$reg2 = 0x00;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0x11);
assert_eq!(c.r.$reg2, 0xff);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! dec_rr_underflow {
($reg1: ident, $reg2: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$reg1 = 0x00;
c.r.$reg2 = 0x00;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$reg1, 0xff);
assert_eq!(c.r.$reg2, 0xff);
assert_eq!(c.r.f, 0x00);
})
}
macro_rules! jr_e_helper {
($e: expr, $f: expr, $op: expr, $pc: expr, $t: expr) => ({
let (mut c, mut m) = init();
m.wb(c.r.pc + 1, $e);
c.r.f = $f;
op(&mut c, &mut m, $op, $pc, $t);
})
}
macro_rules! jr_e {
($f: expr, $op: expr) => ({
jr_e_helper!(0x02, $f, $op, 4, 3);
})
}
macro_rules! jr_e_back {
($f: expr, $op: expr) => ({
jr_e_helper!(0b11111100, $f, $op, -2, 3);
})
}
macro_rules! jr_e_no_jump {
($f: expr, $op: expr) => ({
jr_e_helper!(0x02, $f, $op, 2, 2);
})
}
#[test]
fn nop() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x00, 1, 1);
}
#[test]
fn ld_bc_nn() {
ld_rr_nn!(b, c, 0x01);
}
#[test]
fn ld_bc_a() {
ld_rr_r!(b, c, a, 0x02);
}
#[test]
fn inc_bc() {
inc_rr!(b, c, 0x03);
}
#[test]
fn inc_bc_half_carry() {
inc_rr_half_carry!(b, c, 0x03);
}
#[test]
fn inc_bc_overflow() {
inc_rr_overflow!(b, c, 0x03);
}
#[test]
fn inc_b() {
inc_r!(b, 0x04);
}
#[test]
fn inc_b_zero() {
inc_r_zero!(b, 0x04);
}
#[test]
fn inc_b_half_carry() {
inc_r_half_carry!(b, 0x04);
}
#[test]
fn dec_b() {
dec_r!(b, 0x05);
}
#[test]
fn dec_b_zero() {
dec_r_zero!(b, 0x05);
}
#[test]
fn dec_b_half_carry() {
dec_r_half_carry!(b, 0x05);
}
#[test]
fn ld_b_n() {
ld_r_n!(b, 0x06);
}
#[test]
fn rlc_a() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0xfc);
assert_eq!(c.r.f, 0);
}
#[test]
fn rlc_a_carry() {
let (mut c, mut m) = init();
c.r.a = 0x8e;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0x1d);
assert_eq!(c.r.f, C);
}
#[test]
fn rlc_a_flags() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x07, 1, 1);
assert_eq!(c.r.a, 0xfc);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn ld_nn_sp() {
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0xa2fe);
c.r.sp = 0xabcd;
op(&mut c, &mut m, 0x08, 3, 5);
assert_eq!(m.rw(0xa2fe), 0xabcd);
}
#[test]
fn add_hl_bc() {
add_hl_rr!(b, c, 0x09);
}
#[test]
fn add_hl_bc_half_carry() {
add_hl_rr_half_carry!(b, c, 0x09);
}
#[test]
fn add_hl_bc_carry() {
add_hl_rr_carry!(b, c, 0x09);
}
#[test]
fn add_hl_bc_only_carry() {
add_hl_rr_only_carry!(b, c, 0x09);
}
#[test]
fn ld_a_bc() {
ld_a_rr!(b, c, 0x0a);
}
#[test]
fn dec_bc() {
dec_rr!(b, c, 0x0b);
}
#[test]
fn dec_bc_half_carry() {
dec_rr_half_carry!(b, c, 0x0b);
}
#[test]
fn dec_bc_underflow() {
dec_rr_underflow!(b, c, 0x0b);
}
#[test]
fn inc_c() {
inc_r!(c, 0x0c);
}
#[test]
fn inc_c_zero() {
inc_r_zero!(c, 0x0c);
}
#[test]
fn inc_c_half_carry() {
inc_r_half_carry!(c, 0x0c);
}
#[test]
fn dec_c() {
dec_r!(c, 0x0d);
}
#[test]
fn dec_c_zero() {
dec_r_zero!(c, 0x0d);
}
#[test]
fn dec_c_half_carry() {
dec_r_half_carry!(c, 0x0d);
}
#[test]
fn ld_c_n() {
ld_r_n!(c, 0x0e);
}
#[test]
fn rrca() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0x3f);
}
#[test]
fn rrca_carry() {
let (mut c, mut m) = init();
c.r.a = 0xd1;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0xe8);
assert_eq!(c.r.f, C);
}
#[test]
fn rrca_flags() {
let (mut c, mut m) = init();
c.r.a = 0x7e;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x0f, 1, 1);
assert_eq!(c.r.a, 0x3f);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn stop() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x10, 2, 1);
}
#[test]
fn ld_de_nn() {
ld_rr_nn!(d, e, 0x11);
}
#[test]
fn ld_de_a() {
ld_rr_r!(d, e, a, 0x12);
}
#[test]
fn inc_de() {
inc_rr!(d, e, 0x13);
}
#[test]
fn inc_de_half_carry() {
inc_rr_half_carry!(d, e, 0x13);
}
#[test]
fn inc_de_overflow() {
inc_rr_overflow!(d, e, 0x13);
}
#[test]
fn inc_d() {
inc_r!(d, 0x14);
}
#[test]
fn inc_d_zero() {
inc_r_zero!(d, 0x14);
}
#[test]
fn inc_d_half_carry() {
inc_r_half_carry!(d, 0x14);
}
#[test]
fn dec_d() {
dec_r!(d, 0x15);
}
#[test]
fn dec_d_zero() {
dec_r_zero!(d, 0x15);
}
#[test]
fn dec_d_half_carry() {
dec_r_half_carry!(d, 0x15);
}
#[test]
fn ld_d_n() {
ld_r_n!(d, 0x16);
}
#[test]
fn rla() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rla_into_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rla_from_carry() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
c.r.f = C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rla_through_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
c.r.f = C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, C);
}
#[test]
fn rla_flags() {
let (mut c, mut m) = init();
c.r.a = 0b01010101;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x17, 1, 1);
assert_eq!(c.r.a, 0b10101011);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn jr_e() {
jr_e!(0x00, 0x18);
}
#[test]
fn jr_e_back() {
jr_e_back!(0x00, 0x18);
}
#[test]
fn add_hl_de() {
add_hl_rr!(d, e, 0x19);
}
#[test]
fn add_hl_de_carry() {
add_hl_rr_carry!(d, e, 0x19);
}
#[test]
fn add_hl_de_half_carry() {
add_hl_rr_half_carry!(d, e, 0x19);
}
#[test]
fn add_hl_de_only_carry() {
add_hl_rr_only_carry!(d, e, 0x19);
}
#[test]
fn ld_a_de() {
ld_a_rr!(d, e, 0x1a);
}
#[test]
fn dec_de() {
dec_rr!(d, e, 0x1b);
}
#[test]
fn dec_de_half_carry() {
dec_rr_half_carry!(d, e, 0x1b);
}
#[test]
fn dec_de_underflow() {
dec_rr_underflow!(d, e, 0x1b);
}
#[test]
fn inc_e() {
inc_r!(e, 0x1c);
}
#[test]
fn inc_e_half_carry() {
inc_r_half_carry!(e, 0x1c);
}
#[test]
fn inc_e_zero() {
inc_r_zero!(e, 0x1c);
}
#[test]
fn dec_e() {
dec_r!(e, 0x1d);
}
#[test]
fn dec_e_half_carry() {
dec_r_half_carry!(e, 0x1d);
}
#[test]
fn dec_e_underflow() {
dec_r_half_carry!(e, 0x1d);
}
#[test]
fn ld_e_n() {
ld_r_n!(e, 0x1e);
}
#[test]
fn rra() {
let (mut c, mut m) = init();
c.r.a = 0b10101010;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b01010101);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rra_into_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b01101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rra_from_carry() {
let (mut c, mut m) = init();
c.r.a = 0b01010100;
c.r.f = C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn rra_through_carry() {
let (mut c, mut m) = init();
c.r.a = 0b11010101;
c.r.f = C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b11101010);
assert_eq!(c.r.f, C);
}
#[test]
fn rra_flags() {
let (mut c, mut m) = init();
c.r.a = 0b01010100;
c.r.f = Z | N | H | C;
op(&mut c, &mut m, 0x1f, 1, 1);
assert_eq!(c.r.a, 0b10101010);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn jr_nz_e() {
jr_e!(0x00, 0x20);
}
#[test]
fn jr_nz_e_back() {
jr_e_back!(0x00, 0x20);
}
#[test]
fn jr_nz_e_no_jump() {
jr_e_no_jump!(Z, 0x20);
}
#[test]
fn ld_hl_nn() {
ld_rr_nn!(h, l, 0x21);
}
#[test]
fn ldi_hl_a() {
let (mut c, mut m) = init();
c.r.a = 0xab;
c.r.h = 0xd2;
c.r.l = 0xff;
op(&mut c, &mut m, 0x22, 1, 2);
assert_eq!(m.rb(0xd2ff), 0xab);
assert_eq!(c.r.h, 0xd3);
assert_eq!(c.r.l, 0x00);
}
#[test]
fn inc_hl() {
inc_rr!(h, l, 0x23);
}
#[test]
fn inc_hl_half_carry() {
inc_rr_half_carry!(h, l, 0x23);
}
#[test]
fn inc_hl_overflow() {
inc_rr_overflow!(h, l, 0x23);
}
#[test]
fn inc_h() {
inc_r!(h, 0x24);
}
#[test]
fn inc_h_half_carry() {
inc_r_half_carry!(h, 0x24);
}
#[test]
fn inc_h_zero() {
inc_r_zero!(h, 0x24);
}
#[test]
fn dec_h() {
dec_r!(h, 0x25);
}
#[test]
fn dec_h_half_carry() {
dec_r_half_carry!(h, 0x25);
}
#[test]
fn dec_h_zero() {
dec_r_zero!(h, 0x25);
}
#[test]
fn ld_h_n() {
ld_r_n!(h, 0x26);
}
#[test]
fn jr_z_e() {
jr_e!(Z, 0x28);
}
#[test]
fn jr_z_e_back() {
jr_e_back!(Z, 0x28);
}
#[test]
fn jr_z_e_no_jump() {
jr_e_no_jump!(0x00, 0x28);
}
fn add_hl_hl_helper(h: u8, l: u8, expected_h: u8, expected_l: u8, expected_f: u8) {
let (mut c, mut m) = init();
c.r.h = h;
c.r.l = l;
op(&mut c, &mut m, 0x29, 1, 2);
assert_eq!(c.r.h, expected_h);
assert_eq!(c.r.l, expected_l);
assert_eq!(c.r.f, expected_f);
}
#[test]
fn add_hl_hl() {
add_hl_hl_helper(0x12, 0x34, 0x24, 0x68, 0x0);
}
#[test]
fn add_hl_hl_carry() {
add_hl_hl_helper(0x88, 0x88, 0x11, 0x10, H | C);
}
#[test]
fn add_hl_hl_half_carry() {
add_hl_hl_helper(0x18, 0x00, 0x30, 0x00, H);
}
#[test]
fn add_hl_hl_only_carry() {
add_hl_hl_helper(0x82, 0x00, 0x04, 0x00, C);
}
#[test]
fn ldi_a_hl() {
let (mut c, mut m) = init();
c.r.h = 0xc0;
c.r.l = 0xff;
m.wb(0xc0ff, 0x12);
op(&mut c, &mut m, 0x2a, 1, 2);
assert_eq!(c.r.a, 0x12);
assert_eq!(c.r.h, 0xc1);
assert_eq!(c.r.l, 0x00);
}
#[test]
fn dec_hl() {
dec_rr!(h, l, 0x2b);
}
#[test]
fn dec_hl_half_carry() {
dec_rr_half_carry!(h, l, 0x2b);
}
#[test]
fn dec_hl_underflow() {
dec_rr_underflow!(h, l, 0x2b);
}
#[test]
fn inc_l() {
inc_r!(l, 0x2c);
}
#[test]
fn inc_l_half_carry() {
inc_r_half_carry!(l, 0x2c);
}
#[test]
fn inc_l_zero() {
inc_r_zero!(l, 0x2c);
}
#[test]
fn dec_l() {
dec_r!(l, 0x2d);
}
#[test]
fn dec_l_half_carry() {
dec_r_half_carry!(l, 0x2d);
}
#[test]
fn dec_l_underflow() {
dec_r_half_carry!(l, 0x2d);
}
#[test]
fn ld_l_n() {
ld_r_n!(l, 0x2e);
}
#[test]
fn cpl() {
let (mut c, mut m) = init();
c.r.a = 0b01101010;
c.r.f = Z | C;
op(&mut c, &mut m, 0x2f, 1, 1);
assert_eq!(c.r.a, 0b10010101);
assert_eq!(c.r.f, Z | N | H | C);
}
#[test]
fn ld_sp_nn() {
let (mut c, mut m) = init();
m.ww(c.r.pc + 1, 0x1234);
op(&mut c, &mut m, 0x31, 3, 3);
assert_eq!(c.r.sp, 0x1234);
}
#[test]
fn ldd_hl_a() {
let (mut c, mut m) = init();
c.r.a = 0xab;
c.r.h = 0xd2;
c.r.l = 0xff;
op(&mut c, &mut m, 0x32, 1, 2);
assert_eq!(m.rb(0xd2ff), 0xab);
assert_eq!(c.r.h, 0xd2);
assert_eq!(c.r.l, 0xfe);
}
#[test]
fn inc_sp() {
let (mut c, mut m) = init();
c.r.sp = 0x1234;
op(&mut c, &mut m, 0x33, 1, 2);
assert_eq!(c.r.sp, 0x1235);
}
#[test]
fn inc_at_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x34, 1, 3);
assert_eq!(m.rb(0xd000), 0x13);
}
#[test]
fn dec_at_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x35, 1, 3);
assert_eq!(m.rb(0xd000), 0x11);
}
#[test]
fn ld_hl_n() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(c.r.pc + 1, 0x12);
op(&mut c, &mut m, 0x36, 2, 3);
assert_eq!(m.rb(0xd000), 0x12);
}
#[test]
fn scf() {
let (mut c, mut m) = init();
op(&mut c, &mut m, 0x37, 1, 1);
assert_eq!(c.r.f, C);
}
#[test]
fn jr_c_e() {
jr_e!(C, 0x38);
}
#[test]
fn jr_c_e_back() {
jr_e_back!(C, 0x38);
}
#[test]
fn jr_c_e_no_jump() {
jr_e_no_jump!(0x00, 0x38);
}
fn add_hl_sp_helper(h: u8, l: u8, sp: u16, expected_h: u8, expected_l: u8, expected_f: u8) {
let (mut c, mut m) = init();
c.r.h = h;
c.r.l = l;
c.r.sp = sp;
op(&mut c, &mut m, 0x39, 1, 2);
assert_eq!(c.r.h, expected_h);
assert_eq!(c.r.l, expected_l);
assert_eq!(c.r.f, expected_f);
}
#[test]
fn add_hl_sp() {
add_hl_sp_helper(0x12, 0x34, 0x3451, 0x46, 0x85, 0x0);
}
#[test]
fn add_hl_sp_carry() {
add_hl_sp_helper(0xff, 0xff, 0x0002, 0x00, 0x01, H | C);
}
#[test]
fn add_hl_sp_half_carry() {
add_hl_sp_helper(0x18, 0x00, 0x0900, 0x21, 0x00, H);
}
#[test]
fn add_hl_sp_only_carry() {
add_hl_sp_helper(0x82, 0x00, 0x8000, 0x02, 0x00, C);
}
#[test]
fn ldd_a_hl() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, 0x3a, 1, 2);
assert_eq!(c.r.a, 0x12);
assert_eq!(c.r.h, 0xcf);
assert_eq!(c.r.l, 0xff);
}
#[test]
fn dec_sp() {
let (mut c, mut m) = init();
c.r.sp = 0x1234;
op(&mut c, &mut m, 0x3b, 1, 2);
assert_eq!(c.r.sp, 0x1233);
assert_eq!(c.r.f, 0x00);
}
#[test]
fn inc_a() {
inc_r!(a, 0x3c);
}
#[test]
fn inc_a_half_carry() {
inc_r_half_carry!(a, 0x3c);
}
#[test]
fn inc_a_zero() {
inc_r_zero!(a, 0x3c);
}
#[test]
fn dec_a() {
dec_r!(a, 0x3d);
}
#[test]
fn dec_a_half_carry() {
dec_r_half_carry!(a, 0x3d);
}
#[test]
fn dec_a_underflow() {
dec_r_half_carry!(a, 0x3d);
}
#[test]
fn ld_a_n() {
ld_r_n!(a, 0x3e);
}
macro_rules! ccf {
($c: expr, $expected_c: expr) => ({
let (mut c, mut m) = init();
c.r.f = Z | N | H | $c;
op(&mut c, &mut m, 0x3f, 1, 1);
assert_eq!(c.r.f, Z | $expected_c);
})
}
#[test]
fn ccf() {
ccf!(0x00, C);
}
#[test]
fn ccf_reset() {
ccf!(C, 0x00);
}
macro_rules! ld_r_r {
($dest: ident, $src: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.$src = 0x12;
op(&mut c, &mut m, $op, 1, 1);
assert_eq!(c.r.$dest, 0x12);
})
}
macro_rules! ld_r_hl {
($r: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
m.wb(0xd000, 0x12);
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(c.r.$r, 0x12);
})
}
#[test]
fn ld_b_b() {
ld_r_r!(b, b, 0x40);
}
#[test]
fn ld_b_c() {
ld_r_r!(b, c, 0x41);
}
#[test]
fn ld_b_d() {
ld_r_r!(b, d, 0x42);
}
#[test]
fn ld_b_e() {
ld_r_r!(b, e, 0x43);
}
#[test]
fn ld_b_h() {
ld_r_r!(b, h, 0x44);
}
#[test]
fn ld_b_l() {
ld_r_r!(b, l, 0x45);
}
#[test]
fn ld_b_hl() {
ld_r_hl!(b, 0x46);
}
#[test]
fn ld_b_a() {
ld_r_r!(b, a, 0x47);
}
#[test]
fn ld_c_b() {
ld_r_r!(c, b, 0x48);
}
#[test]
fn ld_c_c() {
ld_r_r!(c, c, 0x49);
}
#[test]
fn ld_c_d() {
ld_r_r!(c, d, 0x4a);
}
#[test]
fn ld_c_e() {
ld_r_r!(c, e, 0x4b);
}
#[test]
fn ld_c_h() {
ld_r_r!(c, h, 0x4c);
}
#[test]
fn ld_c_l() {
ld_r_r!(c, l, 0x4d);
}
#[test]
fn ld_c_hl() {
ld_r_hl!(c, 0x4e);
}
#[test]
fn ld_c_a() {
ld_r_r!(c, a, 0x4f);
}
#[test]
fn ld_d_b() {
ld_r_r!(d, b, 0x50);
}
#[test]
fn ld_d_c() {
ld_r_r!(d, c, 0x51);
}
#[test]
fn ld_d_d() {
ld_r_r!(d, d, 0x52);
}
#[test]
fn ld_d_e() {
ld_r_r!(d, e, 0x53);
}
#[test]
fn ld_d_h() {
ld_r_r!(d, h, 0x54);
}
#[test]
fn ld_d_l() {
ld_r_r!(d, l, 0x55);
}
#[test]
fn ld_d_hl() {
ld_r_hl!(d, 0x56);
}
#[test]
fn ld_d_a() {
ld_r_r!(d, a, 0x57);
}
#[test]
fn ld_e_b() {
ld_r_r!(e, b, 0x58);
}
#[test]
fn ld_e_c() {
ld_r_r!(e, c, 0x59);
}
#[test]
fn ld_e_d() {
ld_r_r!(e, d, 0x5a);
}
#[test]
fn ld_e_e() {
ld_r_r!(e, e, 0x5b);
}
#[test]
fn ld_e_h() {
ld_r_r!(e, h, 0x5c);
}
#[test]
fn ld_e_l() {
ld_r_r!(e, l, 0x5d);
}
#[test]
fn ld_e_hl() {
ld_r_hl!(e, 0x5e);
}
#[test]
fn ld_e_a() {
ld_r_r!(e, a, 0x5f);
}
#[test]
fn ld_h_b() {
ld_r_r!(h, b, 0x60);
}
#[test]
fn ld_h_c() {
ld_r_r!(h, c, 0x61);
}
#[test]
fn ld_h_d() {
ld_r_r!(h, d, 0x62);
}
#[test]
fn ld_h_e() {
ld_r_r!(h, e, 0x63);
}
#[test]
fn ld_h_h() {
ld_r_r!(h, h, 0x64);
}
#[test]
fn ld_h_l() {
ld_r_r!(h, l, 0x65);
}
#[test]
fn ld_h_hl() {
ld_r_hl!(h, 0x66);
}
#[test]
fn ld_h_a() {
ld_r_r!(h, a, 0x67);
}
#[test]
fn ld_l_b() {
ld_r_r!(l, b, 0x68);
}
#[test]
fn ld_l_c() {
ld_r_r!(l, c, 0x69);
}
#[test]
fn ld_l_d() {
ld_r_r!(l, d, 0x6a);
}
#[test]
fn ld_l_e() {
ld_r_r!(l, e, 0x6b);
}
#[test]
fn ld_l_h() {
ld_r_r!(l, h, 0x6c);
}
#[test]
fn ld_l_l() {
ld_r_r!(l, l, 0x6d);
}
#[test]
fn ld_l_hl() {
ld_r_hl!(l, 0x6e);
}
#[test]
fn ld_l_a() {
ld_r_r!(l, a, 0x6f);
}
macro_rules! ld_hl_r {
($r: ident, $op: expr) => ({
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
c.r.$r = 0x12;
op(&mut c, &mut m, $op, 1, 2);
assert_eq!(m.rb(0xd000), 0x12);
})
}
#[test]
fn ld_hl_b() {
ld_hl_r!(b, 0x70);
}
#[test]
fn ld_hl_c() {
ld_hl_r!(c, 0x71);
}
#[test]
fn ld_hl_d() {
ld_hl_r!(d, 0x72);
}
#[test]
fn ld_hl_e() {
ld_hl_r!(e, 0x73);
}
#[test]
fn ld_hl_h() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x00;
op(&mut c, &mut m, 0x74, 1, 2);
assert_eq!(m.rb(0xd000), 0xd0);
}
#[test]
fn ld_hl_l() {
let (mut c, mut m) = init();
c.r.h = 0xd0;
c.r.l = 0x12;
op(&mut c, &mut m, 0x75, 1, 2);
assert_eq!(m.rb(0xd012), 0x12);
}
#[test]
fn halt() {
// TODO
}
#[test]
fn ld_hl_a() {
ld_hl_r!(a, 0x77);
}
#[test]
fn ld_a_b() {
ld_r_r!(a, b, 0x78);
}
#[test]
fn ld_a_c() {
ld_r_r!(a, c, 0x79);
}
#[test]
fn ld_a_d() {
ld_r_r!(a, d, 0x7a);
}
#[test]
fn ld_a_e() {
ld_r_r!(a, e, 0x7b);
}
#[test]
fn ld_a_h() {
ld_r_r!(a, h, 0x7c);
}
#[test]
fn ld_a_l() {
ld_r_r!(a, l, 0x7d);
}
#[test]
fn ld_a_hl() {
ld_r_hl!(a, 0x7e);
}
#[test]
fn ld_a_a() {
ld_r_r!(a, a, 0x7f);
}
macro_rules! add_r_r_helper {
($r1: ident, $r2: ident, $r1_val: expr, $r2_val: expr, $op: expr, $expected_f: expr) => ({
let (mut c, mut m) = init();
c.r.$r1 = $r1_val;
c.r.$r2 = $r2_val;
op(&mut c, &mut m, $op, 1, 1);
assert_eq!(c.r.$r1, $r1_val + $r2_val);
assert_eq!(c.r.f, $expected_f);
})
}
macro_rules! add_r_r {
($r1: ident, $r2: ident) => ({
add_r_r_helper!($r1, $r2, 0x12, 0x34, 0x80, 0x00);
})
}
/*
macro_rules! add_r_r_zero {
}
*/
/*
#[test]
fn add_a_b() {
let (mut c, mut m) = init();
c.r.a = 0x02;
c.r.b = 0x01;
c.r.f = 0x80 | 0x40 | 0x20 | 0x10;
op(&mut c, &mut m, 0x80, 1, 1);
assert_eq!(c.r.a, 0x03);
assert_eq!(c.r.f, 0x00);
// TODO: Check all flags
}
*/
}
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `version` module gives you tools to create and compare SemVer-compliant versions.
use std::cmp;
use std::fmt::Show;
use std::fmt;
use std::hash;
use self::Identifier::{Numeric, AlphaNumeric};
use self::ParseError::{GenericFailure, IncorrectParse, NonAsciiIdentifier};
/// An identifier in the pre-release or build metadata.
///
/// See sections 9 and 10 of the spec for more about pre-release identifers and build metadata.
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Identifier {
/// An identifier that's solely numbers.
Numeric(u64),
/// An identifier with letters and numbers.
AlphaNumeric(String)
}
impl fmt::Show for Identifier {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Numeric(ref n) => n.fmt(f),
AlphaNumeric(ref s) => s.fmt(f)
}
}
}
/// Represents a version number conforming to the semantic versioning scheme.
#[deriving(Clone, Eq)]
pub struct Version {
/// The major version, to be incremented on incompatible changes.
pub major: uint,
/// The minor version, to be incremented when functionality is added in a
/// backwards-compatible manner.
pub minor: uint,
/// The patch version, to be incremented when backwards-compatible bug
/// fixes are made.
pub patch: uint,
/// The pre-release version identifier, if one exists.
pub pre: Vec<Identifier>,
/// The build metadata, ignored when determining version precedence.
pub build: Vec<Identifier>,
}
/// A `ParseError` is returned as the `Err` side of a `Result` when a version is attempted
/// to be parsed.
#[deriving(Clone,PartialEq,Show,PartialOrd)]
pub enum ParseError {
/// All identifiers must be ASCII.
NonAsciiIdentifier,
/// The version was mis-parsed.
IncorrectParse(Version, String),
/// Any other failure.
GenericFailure,
}
impl Version {
/// Parse a string into a semver object.
pub fn parse(s: &str) -> Result<Version, ParseError> {
if !s.is_ascii() {
return Err(NonAsciiIdentifier)
}
let s = s.trim();
let v = parse_iter(&mut s.chars());
match v {
Some(v) => {
if v.to_string() == s {
Ok(v)
} else {
Err(IncorrectParse(v, s.to_string()))
}
}
None => Err(GenericFailure)
}
}
}
impl fmt::Show for Version {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch))
if !self.pre.is_empty() {
try!(write!(f, "-"));
for (i, x) in self.pre.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
if !self.build.is_empty() {
try!(write!(f, "+"));
for (i, x) in self.build.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
Ok(())
}
}
impl cmp::PartialEq for Version {
#[inline]
fn eq(&self, other: &Version) -> bool {
// We should ignore build metadata here, otherwise versions v1 and v2
// can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which
// violate strict total ordering rules.
self.major == other.major &&
self.minor == other.minor &&
self.patch == other.patch &&
self.pre == other.pre
}
}
impl cmp::PartialOrd for Version {
fn partial_cmp(&self, other: &Version) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl cmp::Ord for Version {
fn cmp(&self, other: &Version) -> Ordering {
match self.major.cmp(&other.major) {
Equal => {}
r => return r,
}
match self.minor.cmp(&other.minor) {
Equal => {}
r => return r,
}
match self.patch.cmp(&other.patch) {
Equal => {}
r => return r,
}
// NB: semver spec says 0.0.0-pre < 0.0.0
// but the version of ord defined for vec
// says that [] < [pre] so we alter it here
match (self.pre.len(), other.pre.len()) {
(0, 0) => Equal,
(0, _) => Greater,
(_, 0) => Less,
(_, _) => self.pre.cmp(&other.pre)
}
}
}
impl<S: hash::Writer> hash::Hash<S> for Version {
fn hash(&self, into: &mut S) {
self.major.hash(into);
self.minor.hash(into);
self.patch.hash(into);
self.pre.hash(into);
}
}
fn take_nonempty_prefix<T:Iterator<char>>(rdr: &mut T, pred: |char| -> bool)
-> (String, Option<char>) {
let mut buf = String::new();
let mut ch = rdr.next();
loop {
match ch {
None => break,
Some(c) if !pred(c) => break,
Some(c) => {
buf.push(c);
ch = rdr.next();
}
}
}
(buf, ch)
}
fn take_num<T: Iterator<char>>(rdr: &mut T) -> Option<(uint, Option<char>)> {
let (s, ch) = take_nonempty_prefix(rdr, |c| c.is_digit(10));
match from_str::<uint>(s[]) {
None => None,
Some(i) => Some((i, ch))
}
}
fn take_ident<T: Iterator<char>>(rdr: &mut T) -> Option<(Identifier, Option<char>)> {
let (s,ch) = take_nonempty_prefix(rdr, |c| c.is_alphanumeric());
if s.len() == 0 {
None
} else if s[].chars().all(|c| c.is_digit(10)) && s[].char_at(0) != '0' {
match from_str::<u64>(s.as_slice()) {
None => None,
Some(i) => Some((Numeric(i), ch))
}
} else {
Some((AlphaNumeric(s), ch))
}
}
fn expect(ch: Option<char>, c: char) -> Option<()> {
if ch != Some(c) {
None
} else {
Some(())
}
}
fn parse_iter<T: Iterator<char>>(rdr: &mut T) -> Option<Version> {
let maybe_vers = take_num(rdr).and_then(|(major, ch)| {
expect(ch, '.').and_then(|_| Some(major))
}).and_then(|major| {
take_num(rdr).and_then(|(minor, ch)| {
expect(ch, '.').and_then(|_| Some((major, minor)))
})
}).and_then(|(major, minor)| {
take_num(rdr).and_then(|(patch, ch)| {
Some((major, minor, patch, ch))
})
});
let (major, minor, patch, ch) = match maybe_vers {
Some((a, b, c, d)) => (a, b, c, d),
None => return None
};
let mut pre = vec!();
let mut build = vec!();
let mut ch = ch;
if ch == Some('-') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
pre.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
if ch == Some('+') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
build.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
Some(Version {
major: major,
minor: minor,
patch: patch,
pre: pre,
build: build,
})
}
#[cfg(test)]
mod test {
use super::{Version};
use super::ParseError::{IncorrectParse, GenericFailure};
use super::Identifier::{AlphaNumeric, Numeric};
#[test]
fn test_parse() {
assert_eq!(Version::parse(""), Err(GenericFailure));
assert_eq!(Version::parse(" "), Err(GenericFailure));
assert_eq!(Version::parse("1"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1.2.3-"), Err(GenericFailure));
assert_eq!(Version::parse("a.b.c"), Err(GenericFailure));
let version = Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
};
let error = Err(IncorrectParse(version, "1.2.3 abc".to_string()));
assert_eq!(Version::parse("1.2.3 abc"), error);
assert!(Version::parse("1.2.3") == Ok(Version {
major: 1,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(Version::parse(" 1.2.3 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(Version::parse("1.2.3-alpha1") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(),
}));
assert!(Version::parse(" 1.2.3-alpha1 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!()
}));
assert!(Version::parse("1.2.3+build5") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse(" 1.2.3+build5 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse("1.2.3-alpha1+build5") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse(" 1.2.3-alpha1+build5 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_string()),Numeric(9)),
build: vec!(AlphaNumeric("build5".to_string()),
Numeric(7),
AlphaNumeric("3aedf".to_string()))
}));
assert_eq!(Version::parse("0.4.0-beta.1+0851523"), Ok(Version {
major: 0,
minor: 4,
patch: 0,
pre: vec![AlphaNumeric("beta".to_string()), Numeric(1)],
build: vec![AlphaNumeric("0851523".to_string())],
}));
}
#[test]
fn test_eq() {
assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3"));
assert_eq!(Version::parse("1.2.3-alpha1"), Version::parse("1.2.3-alpha1"));
assert_eq!(Version::parse("1.2.3+build.42"), Version::parse("1.2.3+build.42"));
assert_eq!(Version::parse("1.2.3-alpha1+42"), Version::parse("1.2.3-alpha1+42"));
assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42"));
}
#[test]
fn test_ne() {
assert!(Version::parse("0.0.0") != Version::parse("0.0.1"));
assert!(Version::parse("0.0.0") != Version::parse("0.1.0"));
assert!(Version::parse("0.0.0") != Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta"));
}
#[test]
fn test_show() {
assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()),
"1.2.3".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()),
"1.2.3-alpha1".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()),
"1.2.3+build.42".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()),
"1.2.3-alpha1+42".to_string());
}
#[test]
fn test_to_string() {
assert_eq!(Version::parse("1.2.3").unwrap().to_string(), "1.2.3".to_string());
assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), "1.2.3-alpha1".to_string());
assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), "1.2.3+build.42".to_string());
assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), "1.2.3-alpha1+42".to_string());
}
#[test]
fn test_lt() {
assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3"));
assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2"));
assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2")));
assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42")));
}
#[test]
fn test_le() {
assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42"));
}
#[test]
fn test_gt() {
assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1"));
assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2"));
assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2")));
assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42")));
}
#[test]
fn test_ge() {
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42"));
}
#[test]
fn test_spec_order() {
let vs = ["1.0.0-alpha",
"1.0.0-alpha.1",
"1.0.0-alpha.beta",
"1.0.0-beta",
"1.0.0-beta.2",
"1.0.0-beta.11",
"1.0.0-rc.1",
"1.0.0"];
let mut i = 1;
while i < vs.len() {
let a = Version::parse(vs[i-1]).unwrap();
let b = Version::parse(vs[i]).unwrap();
assert!(a < b);
i += 1;
}
}
}
added `;` to calm nightly rustc down
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The `version` module gives you tools to create and compare SemVer-compliant versions.
use std::cmp;
use std::fmt::Show;
use std::fmt;
use std::hash;
use self::Identifier::{Numeric, AlphaNumeric};
use self::ParseError::{GenericFailure, IncorrectParse, NonAsciiIdentifier};
/// An identifier in the pre-release or build metadata.
///
/// See sections 9 and 10 of the spec for more about pre-release identifers and build metadata.
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Identifier {
/// An identifier that's solely numbers.
Numeric(u64),
/// An identifier with letters and numbers.
AlphaNumeric(String)
}
impl fmt::Show for Identifier {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Numeric(ref n) => n.fmt(f),
AlphaNumeric(ref s) => s.fmt(f)
}
}
}
/// Represents a version number conforming to the semantic versioning scheme.
#[deriving(Clone, Eq)]
pub struct Version {
/// The major version, to be incremented on incompatible changes.
pub major: uint,
/// The minor version, to be incremented when functionality is added in a
/// backwards-compatible manner.
pub minor: uint,
/// The patch version, to be incremented when backwards-compatible bug
/// fixes are made.
pub patch: uint,
/// The pre-release version identifier, if one exists.
pub pre: Vec<Identifier>,
/// The build metadata, ignored when determining version precedence.
pub build: Vec<Identifier>,
}
/// A `ParseError` is returned as the `Err` side of a `Result` when a version is attempted
/// to be parsed.
#[deriving(Clone,PartialEq,Show,PartialOrd)]
pub enum ParseError {
/// All identifiers must be ASCII.
NonAsciiIdentifier,
/// The version was mis-parsed.
IncorrectParse(Version, String),
/// Any other failure.
GenericFailure,
}
impl Version {
/// Parse a string into a semver object.
pub fn parse(s: &str) -> Result<Version, ParseError> {
if !s.is_ascii() {
return Err(NonAsciiIdentifier)
}
let s = s.trim();
let v = parse_iter(&mut s.chars());
match v {
Some(v) => {
if v.to_string() == s {
Ok(v)
} else {
Err(IncorrectParse(v, s.to_string()))
}
}
None => Err(GenericFailure)
}
}
}
impl fmt::Show for Version {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch));
if !self.pre.is_empty() {
try!(write!(f, "-"));
for (i, x) in self.pre.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
if !self.build.is_empty() {
try!(write!(f, "+"));
for (i, x) in self.build.iter().enumerate() {
if i != 0 { try!(write!(f, ".")) };
try!(x.fmt(f));
}
}
Ok(())
}
}
impl cmp::PartialEq for Version {
#[inline]
fn eq(&self, other: &Version) -> bool {
// We should ignore build metadata here, otherwise versions v1 and v2
// can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which
// violate strict total ordering rules.
self.major == other.major &&
self.minor == other.minor &&
self.patch == other.patch &&
self.pre == other.pre
}
}
impl cmp::PartialOrd for Version {
fn partial_cmp(&self, other: &Version) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl cmp::Ord for Version {
fn cmp(&self, other: &Version) -> Ordering {
match self.major.cmp(&other.major) {
Equal => {}
r => return r,
}
match self.minor.cmp(&other.minor) {
Equal => {}
r => return r,
}
match self.patch.cmp(&other.patch) {
Equal => {}
r => return r,
}
// NB: semver spec says 0.0.0-pre < 0.0.0
// but the version of ord defined for vec
// says that [] < [pre] so we alter it here
match (self.pre.len(), other.pre.len()) {
(0, 0) => Equal,
(0, _) => Greater,
(_, 0) => Less,
(_, _) => self.pre.cmp(&other.pre)
}
}
}
impl<S: hash::Writer> hash::Hash<S> for Version {
fn hash(&self, into: &mut S) {
self.major.hash(into);
self.minor.hash(into);
self.patch.hash(into);
self.pre.hash(into);
}
}
fn take_nonempty_prefix<T:Iterator<char>>(rdr: &mut T, pred: |char| -> bool)
-> (String, Option<char>) {
let mut buf = String::new();
let mut ch = rdr.next();
loop {
match ch {
None => break,
Some(c) if !pred(c) => break,
Some(c) => {
buf.push(c);
ch = rdr.next();
}
}
}
(buf, ch)
}
fn take_num<T: Iterator<char>>(rdr: &mut T) -> Option<(uint, Option<char>)> {
let (s, ch) = take_nonempty_prefix(rdr, |c| c.is_digit(10));
match from_str::<uint>(s[]) {
None => None,
Some(i) => Some((i, ch))
}
}
fn take_ident<T: Iterator<char>>(rdr: &mut T) -> Option<(Identifier, Option<char>)> {
let (s,ch) = take_nonempty_prefix(rdr, |c| c.is_alphanumeric());
if s.len() == 0 {
None
} else if s[].chars().all(|c| c.is_digit(10)) && s[].char_at(0) != '0' {
match from_str::<u64>(s.as_slice()) {
None => None,
Some(i) => Some((Numeric(i), ch))
}
} else {
Some((AlphaNumeric(s), ch))
}
}
fn expect(ch: Option<char>, c: char) -> Option<()> {
if ch != Some(c) {
None
} else {
Some(())
}
}
fn parse_iter<T: Iterator<char>>(rdr: &mut T) -> Option<Version> {
let maybe_vers = take_num(rdr).and_then(|(major, ch)| {
expect(ch, '.').and_then(|_| Some(major))
}).and_then(|major| {
take_num(rdr).and_then(|(minor, ch)| {
expect(ch, '.').and_then(|_| Some((major, minor)))
})
}).and_then(|(major, minor)| {
take_num(rdr).and_then(|(patch, ch)| {
Some((major, minor, patch, ch))
})
});
let (major, minor, patch, ch) = match maybe_vers {
Some((a, b, c, d)) => (a, b, c, d),
None => return None
};
let mut pre = vec!();
let mut build = vec!();
let mut ch = ch;
if ch == Some('-') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
pre.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
if ch == Some('+') {
loop {
let (id, c) = match take_ident(rdr) {
Some((id, c)) => (id, c),
None => return None
};
build.push(id);
ch = c;
if ch != Some('.') { break; }
}
}
Some(Version {
major: major,
minor: minor,
patch: patch,
pre: pre,
build: build,
})
}
#[cfg(test)]
mod test {
use super::{Version};
use super::ParseError::{IncorrectParse, GenericFailure};
use super::Identifier::{AlphaNumeric, Numeric};
#[test]
fn test_parse() {
assert_eq!(Version::parse(""), Err(GenericFailure));
assert_eq!(Version::parse(" "), Err(GenericFailure));
assert_eq!(Version::parse("1"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1"), Err(GenericFailure));
assert_eq!(Version::parse("1.2"), Err(GenericFailure));
assert_eq!(Version::parse("1.2.3-"), Err(GenericFailure));
assert_eq!(Version::parse("a.b.c"), Err(GenericFailure));
let version = Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
};
let error = Err(IncorrectParse(version, "1.2.3 abc".to_string()));
assert_eq!(Version::parse("1.2.3 abc"), error);
assert!(Version::parse("1.2.3") == Ok(Version {
major: 1,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(Version::parse(" 1.2.3 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(),
}));
assert!(Version::parse("1.2.3-alpha1") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(),
}));
assert!(Version::parse(" 1.2.3-alpha1 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!()
}));
assert!(Version::parse("1.2.3+build5") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse(" 1.2.3+build5 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse("1.2.3-alpha1+build5") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse(" 1.2.3-alpha1+build5 ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(AlphaNumeric("alpha1".to_string())),
build: vec!(AlphaNumeric("build5".to_string()))
}));
assert!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Ok(Version {
major: 1u,
minor: 2u,
patch: 3u,
pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_string()),Numeric(9)),
build: vec!(AlphaNumeric("build5".to_string()),
Numeric(7),
AlphaNumeric("3aedf".to_string()))
}));
assert_eq!(Version::parse("0.4.0-beta.1+0851523"), Ok(Version {
major: 0,
minor: 4,
patch: 0,
pre: vec![AlphaNumeric("beta".to_string()), Numeric(1)],
build: vec![AlphaNumeric("0851523".to_string())],
}));
}
#[test]
fn test_eq() {
assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3"));
assert_eq!(Version::parse("1.2.3-alpha1"), Version::parse("1.2.3-alpha1"));
assert_eq!(Version::parse("1.2.3+build.42"), Version::parse("1.2.3+build.42"));
assert_eq!(Version::parse("1.2.3-alpha1+42"), Version::parse("1.2.3-alpha1+42"));
assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42"));
}
#[test]
fn test_ne() {
assert!(Version::parse("0.0.0") != Version::parse("0.0.1"));
assert!(Version::parse("0.0.0") != Version::parse("0.1.0"));
assert!(Version::parse("0.0.0") != Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta"));
}
#[test]
fn test_show() {
assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()),
"1.2.3".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()),
"1.2.3-alpha1".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()),
"1.2.3+build.42".to_string());
assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()),
"1.2.3-alpha1+42".to_string());
}
#[test]
fn test_to_string() {
assert_eq!(Version::parse("1.2.3").unwrap().to_string(), "1.2.3".to_string());
assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), "1.2.3-alpha1".to_string());
assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), "1.2.3+build.42".to_string());
assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), "1.2.3-alpha1+42".to_string());
}
#[test]
fn test_lt() {
assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3"));
assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2"));
assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2")));
assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42")));
}
#[test]
fn test_le() {
assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42"));
}
#[test]
fn test_gt() {
assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0"));
assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1"));
assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2"));
assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2")));
assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42")));
}
#[test]
fn test_ge() {
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1"));
assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2"));
assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42"));
}
#[test]
fn test_spec_order() {
let vs = ["1.0.0-alpha",
"1.0.0-alpha.1",
"1.0.0-alpha.beta",
"1.0.0-beta",
"1.0.0-beta.2",
"1.0.0-beta.11",
"1.0.0-rc.1",
"1.0.0"];
let mut i = 1;
while i < vs.len() {
let a = Version::parse(vs[i-1]).unwrap();
let b = Version::parse(vs[i]).unwrap();
assert!(a < b);
i += 1;
}
}
}
|
use std::rc::Rc;
use std::collections::hash_map::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::borrow::Borrow;
use std::cmp::{Ordering, min};
use regex::Regex;
use db::*;
use types::*;
use web::data::*;
use web::config::*;
use web::vec_set::*;
fn make_organism(rc_organism: &Rc<Organism>) -> ConfigOrganism {
ConfigOrganism {
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
}
}
#[derive(Clone)]
pub struct AlleleAndExpression {
allele_uniquename: String,
expression: Option<String>,
}
pub struct WebDataBuild<'a> {
raw: &'a Raw,
config: &'a Config,
genes: UniquenameGeneMap,
transcripts: UniquenameTranscriptMap,
genotypes: UniquenameGenotypeMap,
alleles: UniquenameAlleleMap,
terms: TermIdDetailsMap,
references: IdReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
all_not_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
genes_of_transcripts: HashMap<String, String>,
transcripts_of_polypeptides: HashMap<String, String>,
genes_of_alleles: HashMap<String, String>,
alleles_of_genotypes: HashMap<String, Vec<AlleleAndExpression>>,
// gene_uniquename vs transcript_type_name:
transcript_type_of_genes: HashMap<String, String>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
children_by_termid: HashMap<TermId, HashSet<TermId>>,
dbxrefs_of_features: HashMap<String, HashSet<String>>,
possible_interesting_parents: HashSet<InterestingParent>,
}
fn get_maps() ->
(HashMap<String, ReferenceShortMap>,
HashMap<String, GeneShortMap>,
HashMap<String, GenotypeShortMap>,
HashMap<String, AlleleShortMap>,
HashMap<GeneUniquename, TermShortMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature: &Feature,
feature_relationship: &FeatureRelationship) -> Option<String> {
for feature_prop in feature.featureprops.borrow().iter() {
if feature_prop.prop_type.name == "allele_type" {
if let Some(ref value) = feature_prop.value {
if value == "deletion" {
return Some("Null".into());
}
}
}
}
for rel_prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if rel_prop.prop_type.name == "expression" {
return rel_prop.value.clone();
}
}
None
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
pub fn remove_first<T, P>(vec: &mut Vec<T>, predicate: P) -> Option<T>
where P: FnMut(&T) -> bool {
if let Some(pos) = vec.iter().position(predicate) {
return Some(vec.remove(pos));
}
None
}
// merge two ExtPart objects into one by merging gene ranges
pub fn merge_gene_ext_parts(ext_part1: &ExtPart, ext_part2: &ExtPart) -> ExtPart {
if ext_part1.rel_type_name == ext_part2.rel_type_name {
if let ExtRange::SummaryGenes(ref part1_summ_genes) = ext_part1.ext_range {
if let ExtRange::SummaryGenes(ref part2_summ_genes) = ext_part2.ext_range {
let mut ret_ext_part = ext_part1.clone();
let mut new_genes = [part1_summ_genes.clone(), part2_summ_genes.clone()].concat();
new_genes.sort();
new_genes.dedup();
ret_ext_part.ext_range = ExtRange::SummaryGenes(new_genes);
return ret_ext_part
}
}
panic!("passed ExtPart objects that have non-gene ranges to merge_gene_ext_parts():
{:?} {:?}", ext_part1, ext_part2);
} else {
panic!("passed ExtPart objects with mismatched relations to merge_gene_ext_parts():
{} {}\n", ext_part1.rel_type_name, ext_part2.rel_type_name);
}
}
// turn "has_substrate(gene1),has_substrate(gene2)" into "has_substrate(gene1,gene2)"
pub fn collect_ext_summary_genes(cv_config: &CvConfig, rows: &mut Vec<TermSummaryRow>) {
let conf_gene_rels = &cv_config.summary_gene_relations_to_collect;
let gene_range_rel_p =
|ext_part: &ExtPart| {
if let ExtRange::SummaryGenes(_) = ext_part.ext_range {
conf_gene_rels.contains(&ext_part.rel_type_name)
} else {
false
}
};
let mut ret_rows = vec![];
{
let mut row_iter = rows.iter().cloned();
if let Some(mut prev_row) = row_iter.next() {
for current_row in row_iter {
if prev_row.gene_uniquenames != current_row.gene_uniquenames ||
prev_row.genotype_uniquenames != current_row.genotype_uniquenames {
ret_rows.push(prev_row);
prev_row = current_row;
continue;
}
let mut prev_row_extension = prev_row.extension.clone();
let prev_matching_gene_ext_part =
remove_first(&mut prev_row_extension, &gene_range_rel_p);
let mut current_row_extension = current_row.extension.clone();
let current_matching_gene_ext_part =
remove_first(&mut current_row_extension, &gene_range_rel_p);
if let (Some(prev_gene_ext_part), Some(current_gene_ext_part)) =
(prev_matching_gene_ext_part, current_matching_gene_ext_part) {
if current_row_extension == prev_row_extension &&
prev_gene_ext_part.rel_type_name == current_gene_ext_part.rel_type_name {
let merged_gene_ext_parts =
merge_gene_ext_parts(&prev_gene_ext_part,
¤t_gene_ext_part);
let mut new_ext = vec![merged_gene_ext_parts];
new_ext.extend_from_slice(&prev_row_extension);
prev_row.extension = new_ext;
} else {
ret_rows.push(prev_row);
prev_row = current_row;
}
} else {
ret_rows.push(prev_row);
prev_row = current_row
}
}
ret_rows.push(prev_row);
}
}
*rows = ret_rows;
}
// combine rows that have a gene or genotype but no extension into one row
pub fn collect_summary_rows(rows: &mut Vec<TermSummaryRow>) {
let mut no_ext_rows = vec![];
let mut other_rows = vec![];
for row in rows.drain(0..) {
if (row.gene_uniquenames.len() > 0 || row.genotype_uniquenames.len() > 0)
&& row.extension.len() == 0 {
if row.gene_uniquenames.len() > 1 {
panic!("row has more than one gene\n");
}
if row.genotype_uniquenames.len() > 1 {
panic!("row has more than one genotype\n");
}
no_ext_rows.push(row);
} else {
other_rows.push(row);
}
}
let gene_uniquenames: Vec<String> =
no_ext_rows.iter().filter(|row| row.gene_uniquenames.len() > 0)
.map(|row| row.gene_uniquenames.get(0).unwrap().clone())
.collect();
let genotype_uniquenames: Vec<String> =
no_ext_rows.iter().filter(|row| row.genotype_uniquenames.len() > 0)
.map(|row| row.genotype_uniquenames.get(0).unwrap().clone())
.collect();
rows.clear();
if gene_uniquenames.len() > 0 || genotype_uniquenames.len() > 0 {
let genes_row = TermSummaryRow {
gene_uniquenames: gene_uniquenames,
genotype_uniquenames: genotype_uniquenames,
extension: vec![],
};
rows.push(genes_row);
}
rows.append(&mut other_rows);
}
// Remove annotations from the summary where there is another more
// specific annotation. ie. the same annotation but with extra part(s) in the
// extension.
// See: https://github.com/pombase/website/issues/185
pub fn remove_redundant_summary_rows(rows: &mut Vec<TermSummaryRow>) {
let mut results = vec![];
if rows.len() <= 1 {
return;
}
rows.reverse();
let mut vec_set = VecSet::new();
let mut prev = rows.remove(0);
results.push(prev.clone());
if prev.gene_uniquenames.len() > 1 {
panic!("remove_redundant_summary_rows() failed: num genes > 1\n");
}
vec_set.insert(&prev.extension);
for current in rows.drain(0..) {
if current.gene_uniquenames.len() > 1 {
panic!("remove_redundant_summary_rows() failed: num genes > 1\n");
}
if (&prev.gene_uniquenames, &prev.genotype_uniquenames) ==
(¤t.gene_uniquenames, ¤t.genotype_uniquenames) {
if !vec_set.contains_superset(¤t.extension) {
results.push(current.clone());
vec_set.insert(¤t.extension);
}
} else {
vec_set = VecSet::new();
vec_set.insert(¤t.extension);
results.push(current.clone());
}
prev = current;
}
results.reverse();
*rows = results;
}
fn remove_redundant_summaries(children_by_termid: &HashMap<TermId, HashSet<TermId>>,
term_annotations: &mut Vec<OntTermAnnotations>) {
let mut term_annotations_by_termid = HashMap::new();
for term_annotation in &*term_annotations {
term_annotations_by_termid.insert(term_annotation.term.termid.clone(),
term_annotation.clone());
}
for mut term_annotation in term_annotations.iter_mut() {
if let Some(child_termids) = children_by_termid.get(&term_annotation.term.termid) {
if term_annotation.summary.clone().unwrap().len() == 0 {
let mut found_child_match = false;
for child_termid in child_termids {
if term_annotations_by_termid.get(child_termid).is_some() {
found_child_match = true;
}
}
if found_child_match {
term_annotation.summary = None;
}
} else {
let mut filtered_rows: Vec<TermSummaryRow> = vec![];
for row in &mut term_annotation.summary.clone().unwrap() {
let mut found_child_match = false;
for child_termid in child_termids {
if let Some(ref mut child_term_annotation) =
term_annotations_by_termid.get(child_termid) {
for child_row in &child_term_annotation.summary.clone().unwrap() {
if *row == *child_row {
found_child_match = true;
break;
}
}
}
}
if !found_child_match {
filtered_rows.push(row.clone());
}
}
if filtered_rows.len() == 0 {
term_annotation.summary = None;
}
}
}
}
}
fn make_cv_summaries(config: &Config,
children_by_termid: &HashMap<TermId, HashSet<TermId>>,
include_gene: bool, include_genotype: bool,
term_and_annotations_vec: &mut Vec<OntTermAnnotations>) {
for term_and_annotations in term_and_annotations_vec.iter_mut() {
let term = &term_and_annotations.term;
let cv_config = config.cv_config_by_name(&term.cv_name);
let mut rows = vec![];
for annotation in &term_and_annotations.annotations {
let gene_uniquenames =
if include_gene && cv_config.feature_type == "gene" {
annotation.genes.clone()
} else {
vec![]
};
let genotype_uniquenames =
if include_genotype && cv_config.feature_type == "genotype" {
if let Some(ref genotype_uniquename) = annotation.genotype {
vec![genotype_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
};
let summary_relations_to_hide = &cv_config.summary_relations_to_hide;
let mut summary_extension = annotation.extension.iter().cloned()
.filter(|ext_part| {
!summary_relations_to_hide.contains(&ext_part.rel_type_name) &&
*summary_relations_to_hide != vec!["ALL"]
})
.map(move |mut ext_part| {
if let ExtRange::Gene(gene_uniquename) = ext_part.ext_range.clone() {
let summ_genes = vec![gene_uniquename];
ext_part.ext_range = ExtRange::SummaryGenes(vec![summ_genes]);
}
ext_part })
.collect::<Vec<ExtPart>>();
if gene_uniquenames.len() == 0 &&
genotype_uniquenames.len() == 0 &&
summary_extension.len() == 0 {
continue;
}
collect_duplicated_relations(&mut summary_extension);
let row = TermSummaryRow {
gene_uniquenames: gene_uniquenames,
genotype_uniquenames: genotype_uniquenames,
extension: summary_extension,
};
rows.push(row);
}
remove_redundant_summary_rows(&mut rows);
term_and_annotations.summary = Some(rows);
}
remove_redundant_summaries(children_by_termid, term_and_annotations_vec);
for ref mut term_and_annotations in term_and_annotations_vec.iter_mut() {
if let Some(ref mut summary) = term_and_annotations.summary {
collect_summary_rows(summary);
let cv_config = config.cv_config_by_name(&term_and_annotations.term.cv_name);
collect_ext_summary_genes(&cv_config, summary);
}
}
}
// turns binds([[gene1]]),binds([[gene2]]),other_rel(...) into:
// binds([[gene1, gene2]]),other_rel(...)
pub fn collect_duplicated_relations(ext: &mut Vec<ExtPart>) {
let mut result: Vec<ExtPart> = vec![];
{
let mut iter = ext.iter().cloned();
if let Some(mut prev) = iter.next() {
for current in iter {
if prev.rel_type_name != current.rel_type_name {
result.push(prev);
prev = current;
continue;
}
if let ExtRange::SummaryGenes(ref current_summ_genes) = current.ext_range {
if let ExtRange::SummaryGenes(ref mut prev_summ_genes) = prev.ext_range {
let mut current_genes = current_summ_genes.get(0).unwrap().clone();
prev_summ_genes.get_mut(0).unwrap().append(& mut current_genes);
continue;
}
}
result.push(prev);
prev = current;
}
result.push(prev);
}
}
ext.clear();
ext.append(&mut result);
}
fn compare_ext_part_with_config(config: &Config, ep1: &ExtPart, ep2: &ExtPart) -> Ordering {
let rel_order_conf = &config.extension_relation_order;
let order_conf = &rel_order_conf.relation_order;
let always_last_conf = &rel_order_conf.always_last;
let maybe_ep1_index = order_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_index = order_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_index) = maybe_ep1_index {
if let Some(ep2_index) = maybe_ep2_index {
ep1_index.cmp(&ep2_index)
} else {
Ordering::Less
}
} else {
if let Some(_) = maybe_ep2_index {
Ordering::Greater
} else {
let maybe_ep1_last_index = always_last_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_last_index = always_last_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_last_index) = maybe_ep1_last_index {
if let Some(ep2_last_index) = maybe_ep2_last_index {
ep1_last_index.cmp(&ep2_last_index)
} else {
Ordering::Greater
}
} else {
if let Some(_) = maybe_ep2_last_index {
Ordering::Less
} else {
ep1.rel_type_name.cmp(&ep2.rel_type_name)
}
}
}
}
}
fn string_from_ext_range(ext_range: &ExtRange,
genes: &UniquenameGeneMap, terms: &TermIdDetailsMap) -> String {
match ext_range {
&ExtRange::Gene(ref gene_uniquename) => {
let gene = genes.get(gene_uniquename).unwrap();
gene_display_name(&gene)
},
&ExtRange::SummaryGenes(_) => panic!("can't handle SummaryGenes\n"),
&ExtRange::Term(ref termid) => terms.get(termid).unwrap().name.clone(),
&ExtRange::Misc(ref misc) => misc.clone(),
&ExtRange::Domain(ref domain) => domain.clone(),
&ExtRange::GeneProduct(ref gene_product) => gene_product.clone(),
}
}
fn cmp_ext_part(ext_part1: &ExtPart, ext_part2: &ExtPart,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let ord = ext_part1.rel_type_display_name.cmp(&ext_part2.rel_type_display_name);
if ord == Ordering::Equal {
let ext_part1_str = string_from_ext_range(&ext_part1.ext_range, genes, terms);
let ext_part2_str = string_from_ext_range(&ext_part2.ext_range, genes, terms);
ext_part1_str.to_lowercase().cmp(&ext_part2_str.to_lowercase())
} else {
ord
}
}
// compare the extension up to the last common index
fn cmp_extension_prefix(ext1: &Vec<ExtPart>, ext2: &Vec<ExtPart>,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> (usize, Ordering) {
let iter = ext1.iter().zip(ext2).enumerate();
for (index, (ext1_part, ext2_part)) in iter {
let ord = cmp_ext_part(&ext1_part, &ext2_part, genes, terms);
if ord != Ordering::Equal {
return (index, ord)
}
}
(min(ext1.len(), ext2.len()), Ordering::Equal)
}
fn cmp_extension(ext1: &Vec<ExtPart>, ext2: &Vec<ExtPart>,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let (_, cmp) = cmp_extension_prefix(ext1, ext2, genes, terms);
if cmp == Ordering::Equal {
ext1.len().cmp(&ext2.len())
} else {
cmp
}
}
fn cmp_genotypes(genotype1: &GenotypeDetails, genotype2: &GenotypeDetails,
alleles: &UniquenameAlleleMap) -> Ordering {
let name1 = genotype_display_name(genotype1, alleles);
let name2 = genotype_display_name(genotype2, alleles);
name1.to_lowercase().cmp(&name2.to_lowercase())
}
fn allele_display_name(allele: &AlleleShort) -> String {
let name = allele.name.clone().unwrap_or("unnamed".into());
let allele_type = allele.allele_type.clone();
let mut description = allele.description.clone().unwrap_or(allele_type.clone());
if allele_type == "deletion" && name.ends_with("delta") ||
allele_type.starts_with("wild_type") && name.ends_with("+") {
let normalised_description = description.replace("[\\s_]+", "");
let normalised_allele_type = allele_type.replace("[\\s_]+", "");
if normalised_description != normalised_allele_type {
return name + "(" + description.as_str() + ")";
} else {
return name;
}
}
if allele_type.starts_with("mutation") {
let re = Regex::new(r"(?P<m>^|,\\s*)").unwrap();
if allele_type.contains("amino acid") {
description = re.replace_all(&description, "$maa");
} else {
if allele_type.contains("nucleotide") {
description = re.replace_all(&description, "$nt");
}
}
}
name + "(" + description.as_str() + ")"
}
fn gene_display_name(gene: &GeneDetails) -> String {
if let Some(name) = gene.name.clone() {
name
} else {
gene.uniquename.clone()
}
}
pub fn genotype_display_name(genotype: &GenotypeDetails,
alleles: &UniquenameAlleleMap) -> String {
if let Some(ref name) = genotype.name {
name.clone()
} else {
let allele_display_names: Vec<String> =
genotype.expressed_alleles.iter().map(|ref expressed_allele| {
let allele_short = alleles.get(&expressed_allele.allele_uniquename).unwrap();
allele_display_name(allele_short)
}).collect();
allele_display_names.join(" ")
}
}
fn make_gene_short<'b>(gene_map: &'b UniquenameGeneMap,
gene_uniquename: &'b str) -> GeneShort {
if let Some(gene_details) = gene_map.get(gene_uniquename) {
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
// compare two gene vectors which must be ordered vecs
fn cmp_gene_vec(genes: &UniquenameGeneMap,
gene_vec1: &Vec<GeneUniquename>,
gene_vec2: &Vec<GeneUniquename>) -> Ordering {
let gene_short_vec1: Vec<GeneShort> =
gene_vec1.iter().map(|gene_uniquename: &String| {
make_gene_short(genes, &gene_uniquename)
}).collect();
let gene_short_vec2: Vec<GeneShort> =
gene_vec2.iter().map(|gene_uniquename: &String| {
make_gene_short(genes, &gene_uniquename)
}).collect();
return gene_short_vec1.cmp(&gene_short_vec2)
}
fn cmp_ont_annotation_detail(detail1: &Rc<OntAnnotationDetail>,
detail2: &Rc<OntAnnotationDetail>,
genes: &UniquenameGeneMap,
genotypes: &UniquenameGenotypeMap,
alleles: &UniquenameAlleleMap,
terms: &TermIdDetailsMap) -> Ordering {
if let Some(ref detail1_genotype_uniquename) = detail1.genotype {
if let Some(ref detail2_genotype_uniquename) = detail2.genotype {
let genotype1 = genotypes.get(detail1_genotype_uniquename).unwrap();
let genotype2 = genotypes.get(detail2_genotype_uniquename).unwrap();
let ord = cmp_genotypes(&genotype1, &genotype2, alleles);
if ord == Ordering::Equal {
cmp_extension(&detail1.extension, &detail2.extension, genes, terms)
} else {
ord
}
} else {
panic!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n");
}
} else {
if detail2.genotype.is_some() {
panic!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n");
} else {
let ord = cmp_gene_vec(genes, &detail1.genes, &detail2.genes);
if ord == Ordering::Equal {
cmp_extension(&detail1.extension, &detail2.extension, genes, terms)
} else {
ord
}
}
}
}
// Some ancestor terms are useful in the web code. This function uses the Config and returns
// the terms that might be useful.
fn get_possible_interesting_parents(config: &Config) -> HashSet<InterestingParent> {
let mut ret = HashSet::new();
for parent_conf in config.interesting_parents.iter() {
ret.insert(parent_conf.clone());
}
for ext_conf in &config.extension_display_names {
if let Some(ref conf_termid) = ext_conf.if_descendent_of {
ret.insert(InterestingParent {
termid: conf_termid.clone(),
rel_name: "is_a".into(),
});
}
}
for (cv_name, conf) in &config.cv_config {
for filter in &conf.filters {
for category in &filter.term_categories {
for ancestor in &category.ancestors {
for config_rel_name in DESCENDANT_REL_NAMES.iter() {
if *config_rel_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&cv_name.as_str()) {
continue;
}
ret.insert(InterestingParent {
termid: ancestor.clone(),
rel_name: String::from(*config_rel_name),
});
}
}
}
}
}
ret
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, config: &'a Config) -> WebDataBuild<'a> {
WebDataBuild {
raw: raw,
config: config,
genes: HashMap::new(),
transcripts: HashMap::new(),
genotypes: HashMap::new(),
alleles: HashMap::new(),
terms: HashMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
transcript_type_of_genes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
children_by_termid: HashMap::new(),
dbxrefs_of_features: HashMap::new(),
possible_interesting_parents: get_possible_interesting_parents(config),
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<String, ReferenceShortMap>,
identifier: String,
maybe_reference_uniquename: Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if let Some(reference_short) = self.make_reference_short(&reference_uniquename) {
seen_references
.entry(identifier.clone())
.or_insert(HashMap::new())
.insert(reference_uniquename.clone(),
reference_short);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
other_gene_uniquename: GeneUniquename) {
seen_genes
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_gene_uniquename.clone(),
self.make_gene_short(&other_gene_uniquename));
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
genotype_uniquename: &GenotypeUniquename) {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
self.add_allele_to_hash(seen_alleles, seen_genes, identifier.clone(),
expressed_allele.allele_uniquename.clone());
}
seen_genotypes
.entry(identifier)
.or_insert(HashMap::new())
.insert(genotype_uniquename.clone(),
self.make_genotype_short(genotype_uniquename));
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
allele_uniquename: AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(seen_genes, identifier.clone(), allele_gene_uniquename);
seen_alleles
.entry(identifier)
.or_insert(HashMap::new())
.insert(allele_uniquename, allele_short.clone());
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortMap>,
identifier: String,
other_termid: TermId) {
seen_terms
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(&gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(&gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<String>>();
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
synonyms: synonyms,
feature_type: gene_details.feature_type.clone(),
organism: gene_details.organism.clone(),
location: gene_details.location.clone(),
}
}
fn make_reference_short(&self, reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = self.references.get(reference_uniquename).unwrap();
let reference_short =
ReferenceShort {
uniquename: String::from(reference_uniquename),
title: reference_details.title.clone(),
citation: reference_details.citation.clone(),
publication_year: reference_details.publication_year.clone(),
authors: reference_details.authors.clone(),
authors_abbrev: reference_details.authors_abbrev.clone(),
gene_count: reference_details.genes_by_uniquename.keys().len(),
genotype_count: reference_details.genotypes_by_uniquename.keys().len(),
};
Some(reference_short)
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: term_details.is_obsolete,
gene_count: term_details.genes_by_uniquename.keys().len(),
genotype_count: term_details.genotypes_by_uniquename.keys().len(),
}
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &String, cvterm_name: &String) {
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &String, product: &String) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = {
let mut new_ext = extension_parts.clone();
let compare_ext_part_func =
|e1: &ExtPart, e2: &ExtPart| compare_ext_part_with_config(&self.config, e1, e2);
new_ext.sort_by(compare_ext_part_func);
new_ext
};
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert(
vec![]
).push(Rc::new(ont_annotation_detail));
}
fn process_dbxrefs(&mut self) {
let mut map = HashMap::new();
for feature_dbxref in self.raw.feature_dbxrefs.iter() {
let feature = &feature_dbxref.feature;
let dbxref = &feature_dbxref.dbxref;
map.entry(feature.uniquename.clone())
.or_insert(HashSet::new())
.insert(dbxref.identifier());
}
self.dbxrefs_of_features = map;
}
fn process_references(&mut self) {
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
let mut pubmed_authors: Option<String> = None;
let mut pubmed_publication_date: Option<String> = None;
let mut pubmed_abstract: Option<String> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(",") {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
authors_abbrev = Some(author_re.replace_all(&authors, "$f et al."));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(date_re.replace_all(&publication_date, "$y"));
}
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev: authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
publication_year: publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
fn make_feature_rel_maps(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
self.transcript_type_of_genes.insert(object_uniquename.clone(),
subject_type_name.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let expression = get_feat_rel_expression(&feature_rel.subject, feature_rel);
let allele_and_expression =
AlleleAndExpression {
allele_uniquename: subject_uniquename.clone(),
expression: expression,
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert(Vec::new()).push(allele_and_expression);
continue;
}
}
}
}
fn make_location(&self, feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
Some(ChromosomeLocation {
chromosome_name: feature_loc.srcfeature.uniquename.clone(),
start_pos: start_pos,
end_pos: end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
})
},
None => None,
}
}
fn get_feature_dbxrefs(&self, feature: &Feature) -> HashSet<String> {
if let Some(dbxrefs) = self.dbxrefs_of_features.get(&feature.uniquename) {
dbxrefs.clone()
} else {
HashSet::new()
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let location = self.make_location(&feat);
let organism = make_organism(&feat.organism);
let dbxrefs = self.get_feature_dbxrefs(feat);
let mut orfeome_identifier = None;
for dbxref in dbxrefs.iter() {
if dbxref.starts_with("SPD:") {
orfeome_identifier = Some(String::from(&dbxref[4..]));
}
}
let mut uniprot_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "uniprot_identifier" {
uniprot_identifier = prop.value.clone();
break;
}
}
let feature_type =
if let Some(transcript_type) =
self.transcript_type_of_genes.get(&feat.uniquename) {
transcript_type.clone() + " " + &feat.feat_type.name
} else {
feat.feat_type.name.clone()
};
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
organism: organism,
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier: uniprot_identifier,
orfeome_identifier: orfeome_identifier,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs: dbxrefs,
feature_type: feature_type,
characterisation_status: None,
location: location,
gene_neighbourhood: vec![],
cds_location: None,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut background = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
background = prop.value.clone()
}
}
self.genotypes.insert(feat.uniquename.clone(),
GenotypeDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
background: background,
expressed_alleles: vec![],
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles.get(&feat.uniquename).unwrap();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename: gene_uniquename.clone(),
allele_type: allele_type.unwrap(),
description: description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_feature(&mut self, feat: &Feature) {
match &feat.feat_type.name as &str {
"gene" | "pseudogene" =>
self.store_gene_details(feat),
_ => {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.transcripts.insert(feat.uniquename.clone(),
TranscriptDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
});
}
}
}
}
fn process_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name != "genotype" && feat.feat_type.name != "allele" {
self.process_feature(&feat);
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<String, HashSet<String>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert(HashSet::new())
.insert(object_termid.into());
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let mut term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(&feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(&feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: String,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let mut this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
fn add_alleles_to_genotypes(&mut self) {
let mut alleles_to_add: HashMap<String, Vec<ExpressedAllele>> = HashMap::new();
for genotype_uniquename in self.genotypes.keys() {
let allele_uniquenames: Vec<AlleleAndExpression> =
self.alleles_of_genotypes.get(genotype_uniquename).unwrap().clone();
let expressed_allele_vec: Vec<ExpressedAllele> =
allele_uniquenames.iter()
.map(|ref allele_and_expression| {
ExpressedAllele {
allele_uniquename: allele_and_expression.allele_uniquename.clone(),
expression: allele_and_expression.expression.clone(),
}
})
.collect();
alleles_to_add.insert(genotype_uniquename.clone(), expressed_allele_vec);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
genotype_details.expressed_alleles =
alleles_to_add.remove(genotype_uniquename).unwrap();
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in FEATURE_REL_CONFIGS.iter() {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let mut is_inferred_interaction: bool = false;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0).clone();
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) => Some(publication.uniquename.clone()),
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
}
}
if prop.prop_type.name == "is_inferred" {
if let Some(is_inferred_value) = prop.value.clone() {
if is_inferred_value == "yes" {
is_inferred_interaction = true;
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism = {
self.genes.get(subject_uniquename).unwrap().organism.clone()
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism = {
self.genes.get(object_uniquename).unwrap().organism.clone()
};
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction =>
if !is_inferred_interaction {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
{
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
{
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
if rel_name == "interacts_physically" {
other_gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
other_gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_organism: other_gene_organism,
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == gene_details.organism {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == gene_details.organism {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
// for orthologs and paralogs, store the reverse annotation too
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_organism: gene_organism,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == other_gene_details.organism {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == other_gene_details.organism {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
},
}
}
}
}
for (_, ref_details) in &mut self.references {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for (_, gene_details) in &mut self.genes {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionDisplayNames> {
let ext_configs = &self.config.extension_display_names;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendent_of) = ext_config.if_descendent_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendent_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &String,
genes: &Vec<String>,
maybe_genotype_uniquename: &Option<String>,
reference_uniquename: &Option<String>,
annotation_termid: &String,
extension: &Vec<ExtPart>) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
let (annotation_gene_uniquenames, annotation_genotype_uniquename) =
if maybe_genotype_uniquename.is_some() {
(genes.clone(), maybe_genotype_uniquename.clone())
} else {
(genes.clone(), None)
};
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.clone(),
ext_rel_display_name: reciprocal_display_name,
genes: annotation_gene_uniquenames,
genotype_uniquename: annotation_genotype_uniquename,
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for (_, term_details) in &self.terms {
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
'ANNOTATION: for annotation in &term_annotation.annotations {
if let Some(ref genotype_uniquename) = annotation.genotype {
let genotype = self.genotypes.get(genotype_uniquename).unwrap();
if genotype.expressed_alleles.len() > 1 {
break 'ANNOTATION;
}
}
let new_annotations =
self.make_target_of_for_ext(&term_details.cv_name,
&annotation.genes,
&annotation.genotype,
&annotation.reference,
&term_details.termid,
&annotation.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert(HashSet::new())
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let mut gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn set_deletion_viability(&mut self) {
let mut gene_statuses = HashMap::new();
let viable_termid = &self.config.viability_terms.viable;
let inviable_termid = &self.config.viability_terms.inviable;
for (gene_uniquename, gene_details) in &mut self.genes {
let mut new_status = DeletionViability::Unknown;
if let Some(single_allele_term_annotations) =
gene_details.cv_annotations.get("single_allele_phenotype") {
let mut maybe_viable_conditions: Option<HashSet<TermId>> = None;
let mut maybe_inviable_conditions: Option<HashSet<TermId>> = None;
for term_annotation in single_allele_term_annotations {
'ANNOTATION: for annotation in &term_annotation.annotations {
let genotype_uniquename = annotation.genotype.clone().unwrap();
let genotype = self.genotypes.get(&genotype_uniquename).unwrap();
let allele_uniquename =
genotype.expressed_alleles[0].allele_uniquename.clone();
let allele = self.alleles.get(&allele_uniquename).unwrap();
if allele.allele_type != "deletion" {
break 'ANNOTATION;
}
let interesting_parents = &term_annotation.term.interesting_parents;
if interesting_parents.contains(viable_termid) {
if let Some(ref mut viable_conditions) =
maybe_viable_conditions {
viable_conditions.extend(annotation.conditions.clone());
} else {
maybe_viable_conditions = Some(annotation.conditions.clone());
}
}
if interesting_parents.contains(inviable_termid) {
if let Some(ref mut inviable_conditions) =
maybe_inviable_conditions {
inviable_conditions.extend(annotation.conditions.clone());
} else {
maybe_inviable_conditions = Some(annotation.conditions.clone());
}
}
}
}
if maybe_viable_conditions.is_none() {
if maybe_inviable_conditions.is_some() {
new_status = DeletionViability::Inviable;
}
} else {
if maybe_inviable_conditions.is_none() {
new_status = DeletionViability::Viable;
} else {
if maybe_viable_conditions == maybe_inviable_conditions {
println!("{} is viable and inviable with conditions: {:?}",
gene_uniquename, maybe_viable_conditions);
} else {
new_status = DeletionViability::DependsOnConditions;
}
}
}
}
gene_statuses.insert(gene_uniquename.clone(), new_status);
}
for (gene_uniquename, status) in &gene_statuses {
if let Some(ref mut gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details.deletion_viability = status.clone();
}
}
}
fn make_all_cv_summaries(&mut self) {
for (_, term_details) in &mut self.terms {
for (_, mut term_annotations) in &mut term_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
true, true, &mut term_annotations);
}
}
for (_, gene_details) in &mut self.genes {
for (_, mut term_annotations) in &mut gene_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
false, true, &mut term_annotations);
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, mut term_annotations) in &mut genotype_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
false, false, &mut term_annotations);
}
}
for (_, reference_details) in &mut self.references {
for (_, mut term_annotations) in &mut reference_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
true, true, &mut term_annotations);
}
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
let cv_config =
self.config.cv_config_by_name(&cvterm.cv.name);
let annotation_feature_type =
cv_config.feature_type.clone();
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
annotation_feature_type: annotation_feature_type,
interesting_parents: HashSet::new(),
termid: cvterm.termid(),
definition: cvterm.definition.clone(),
direct_ancestors: vec![],
is_obsolete: cvterm.is_obsolete,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &String,
ext_rel_name: &String) -> String {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
let re = Regex::new("_").unwrap();
re.replace_all(&ext_rel_name, " ")
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = String::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
ExtRange::Gene(ext_range)
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: String::from(ext_rel_name),
rel_type_display_name: rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
} else {
let object_term_short =
self.make_term_short(&object_term.termid());
if let Some(ref mut subject_term_details) = self.terms.get_mut(&subject_term.termid()) {
subject_term_details.direct_ancestors.push(TermAndRelation {
termid: object_term_short.termid.clone(),
term_name: object_term_short.name.clone(),
relation_name: rel_type.name.clone(),
});
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
self.parts_of_extensions.entry(subject_termid)
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name: rel_type_display_name,
ext_range: ExtRange::Term(object_term.termid().clone()),
});
} else {
panic!("can't find details for {}\n", object_term.termid());
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in self.raw.feature_synonyms.iter() {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn make_genotype_short(&self, genotype_uniquename: &str) -> GenotypeShort {
let details = self.genotypes.get(genotype_uniquename).unwrap().clone();
GenotypeShort {
uniquename: details.uniquename,
name: details.name,
background: details.background,
expressed_alleles: details.expressed_alleles,
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles.get(allele_uniquename).unwrap().clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if cvterm.cv.name == "PomBase gene products" {
if feature.feat_type.name == "polypeptide" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: &String) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value.clone())
} else {
ExtRange::Misc(prod_value.clone())
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range: ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &String) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
String::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range: ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: String) -> WithFromValue {
let db_prefix_patt = String::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = re.replace_all(&with_or_from_value, "");
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(&with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(&with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value)
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &String, evidence_code: Option<String>,
extension: &mut Vec<ExtPart>,
with_value: String) -> WithFromValue {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if evidence_code.is_some() &&
evidence_code.unwrap() == "IPI" &&
(base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents
.contains("GO:0005515")) {
extension.push(self.get_with_extension(&with_value));
} else {
return self.make_with_or_from_value(with_value);
}
WithFromValue::None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<String, String> = HashMap::new();
let mut conditions: HashSet<TermId> = HashSet::new();
let mut with: WithFromValue = WithFromValue::None;
let mut from: WithFromValue = WithFromValue::None;
let mut qualifiers: Vec<Qualifier> = vec![];
let mut evidence: Option<String> = None;
let mut raw_with_value: Option<String> = None;
for ref prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"evidence" =>
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.insert(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"with" => {
raw_with_value = prop.value.clone();
},
"from" => {
if let Some(value) = prop.value.clone() {
from = self.make_with_or_from_value(value);
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(&value));
}
},
_ => ()
}
}
if let Some(value) = raw_with_value {
let with_gene_short =
self.make_with_extension(&cvterm.termid(), evidence.clone(),
&mut extension, value);
if with_gene_short.is_some() {
with = with_gene_short;
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let genotype_short = self.make_genotype_short(&feature.uniquename);
maybe_genotype_uniquename = Some(genotype_short.uniquename.clone());
genotype_short.expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
gene_uniquenames_vec =
gene_uniquenames_vec.iter().map(|gene_uniquename: &String| {
self.make_gene_short(&gene_uniquename).uniquename
}).collect();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell: copies_per_cell,
avg_copies_per_cell: avg_copies_per_cell,
scale: scale,
})
} else {
None
};
let annotation = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
genes: gene_uniquenames_vec,
reference: reference_uniquename.clone(),
genotype: maybe_genotype_uniquename.clone(),
with: with.clone(),
from: from.clone(),
residue: extra_props_clone.remove("residue"),
gene_ex_props: gene_ex_props,
qualifiers: qualifiers.clone(),
evidence: evidence.clone(),
conditions: conditions.clone(),
extension: extension.clone(),
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation);
}
}
fn make_term_annotations(&self, termid: &str, details: &Vec<Rc<OntAnnotationDetail>>,
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_short = self.make_term_short(termid);
let cv_name = term_short.cv_name.clone();
match cv_name.as_ref() {
"gene_ex" => {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut quant_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for detail in details {
if detail.gene_ex_props.is_some() {
quant_annotations.annotations.push(detail.clone())
} else {
qual_annotations.annotations.push(detail.clone())
}
}
let mut return_vec = vec![];
if qual_annotations.annotations.len() > 0 {
return_vec.push((String::from("qualitative_gene_expression"),
qual_annotations));
}
if quant_annotations.annotations.len() > 0 {
return_vec.push((String::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
},
"fission_yeast_phenotype" => {
let mut single_allele =
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut multi_allele =
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for detail in details {
let genotype_uniquename = detail.genotype.clone().unwrap();
if let Some(genotype_details) = self.genotypes.get(&genotype_uniquename) {
if genotype_details.expressed_alleles.len() == 1 {
single_allele.annotations.push(detail.clone())
} else {
multi_allele.annotations.push(detail.clone())
}
} else {
panic!("can't find genotype details for {}\n", genotype_uniquename);
}
}
let mut return_vec = vec![];
if single_allele.annotations.len() > 0 {
return_vec.push((String::from("single_allele_phenotype"),
single_allele));
}
if multi_allele.annotations.len() > 0 {
return_vec.push((String::from("multi_allele_phenotype"),
multi_allele));
}
return_vec
},
_ => {
vec![(cv_name,
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: details.clone(),
summary: None,
})]
}
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotations = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<String, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
for (termid, annotations) in ont_annotations {
let mut sorted_annotations = annotations.clone();
{
let cmp_detail_with_maps =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &self.genes,
&self.genotypes, &self.alleles,
&self.terms)
};
sorted_annotations.sort_by(cmp_detail_with_maps);
}
// genotype annotations are stored in all_ont_annotations
// once for each gene mentioned in the genotype - this set is
// used to avoid adding an annotation multiple times to a
// GenotypeDetails
let mut seen_annotations_for_term = HashSet::new();
let annotations_for_term: Vec<Rc<OntAnnotationDetail>> =
sorted_annotations.iter().cloned()
.filter(|annotation|
if seen_annotations_for_term.contains(&annotation.id) {
false
} else {
seen_annotations_for_term.insert(annotation.id);
true
}).collect();
let new_annotations =
self.make_term_annotations(&termid, &annotations_for_term, is_not);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
for (cv_name, new_annotation) in new_annotations {
term_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
for detail in sorted_annotations {
for gene_uniquename in &detail.genes {
gene_annotation_by_term.entry(gene_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
if let Some(ref genotype_uniquename) = detail.genotype {
let mut existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![]);
if !existing.contains(&detail) {
existing.push(detail.clone());
}
}
if let Some(reference_uniquename) = detail.reference.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
for condition_termid in &detail.conditions {
let condition_term_short = {
self.make_term_short(&condition_termid)
};
let cv_name = condition_term_short.cv_name.clone();
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
condition_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: condition_term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
condition_term_details.cv_annotations.get_mut(&cv_name)
.unwrap()[0]
.annotations.push(detail.clone());
}
}
}
}
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (_, mut cv_annotations) in &mut gene_details.cv_annotations {
cv_annotations.sort()
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (_, mut cv_annotations) in &mut details.cv_annotations {
cv_annotations.sort()
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert(Vec::new())
.push(new_annotation.clone());
}
}
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (_, mut term_annotations) in &mut ref_details.cv_annotations {
term_annotations.sort()
}
}
}
// return true if the term could or should appear in the interesting_parents
// field of the TermDetails and TermShort structs
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
return self.possible_interesting_parents.contains(&InterestingParent {
termid: termid.into(),
rel_name: rel_name.into(),
});
}
fn process_cvtermpath(&mut self) {
let mut annotation_by_id: HashMap<i32, Rc<OntAnnotationDetail>> = HashMap::new();
let mut new_annotations: HashMap<TermId, HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
let mut children_by_termid: HashMap<TermId, HashSet<TermId>> = HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if rel_term_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) {
continue;
}
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) {
continue;
}
if subject_term_details.cv_annotations.keys().len() > 0 {
if let Some(object_term_details) = self.terms.get(&object_termid) {
if object_term_details.cv_annotations.keys().len() > 0 {
children_by_termid
.entry(object_termid.clone())
.or_insert(HashSet::new())
.insert(subject_termid.clone());
}
}
}
for (_, term_annotations) in &subject_term_details.cv_annotations {
for term_annotation in term_annotations {
for detail in &term_annotation.annotations {
if !annotation_by_id.contains_key(&detail.id) {
annotation_by_id.insert(detail.id, detail.clone());
}
let dest_termid = object_termid.clone();
let source_termid = subject_termid.clone();
if !term_annotation.is_not {
new_annotations.entry(dest_termid)
.or_insert(HashMap::new())
.entry(source_termid)
.or_insert(HashMap::new())
.entry(detail.id)
.or_insert(HashSet::new())
.insert(rel_term_name.clone());
}
}
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for (dest_termid, dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_details: Vec<Rc<OntAnnotationDetail>> = vec![];
let mut all_rel_names: HashSet<String> = HashSet::new();
for (id, rel_names) in source_annotations_map {
let detail = annotation_by_id.get(&id).unwrap().clone();
new_details.push(detail);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
{
let cmp_detail_with_genotypes =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &self.genes,
&self.genotypes, &self.alleles, &self.terms)
};
new_details.sort_by(cmp_detail_with_genotypes);
}
let new_annotations =
self.make_term_annotations(&source_termid, &new_details, false);
let mut dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
for (cv_name, new_annotation) in new_annotations {
let mut new_annotation_clone = new_annotation.clone();
new_annotation_clone.rel_names.extend(all_rel_names.clone());
dest_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation_clone);
}
}
}
self.children_by_termid = children_by_termid;
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
const PKG_NAME: &'static str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: String::from(PKG_NAME),
export_prog_version: String::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
}
}
pub fn make_search_api_maps(&self) -> SearchAPIMaps {
let mut gene_summaries: Vec<GeneSummary> = vec![];
let load_org_full_name = self.config.load_organism.full_name();
for (gene_uniquename, gene_details) in &self.genes {
let gene_genus_species = String::new() +
&gene_details.organism.genus + "_" + &gene_details.organism.species;
if gene_genus_species == load_org_full_name {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
}
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_name_genes: HashMap<TermName, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
term_summaries.insert(self.make_term_short(&termid));
for gene_uniquename in term_details.genes_by_uniquename.keys() {
termid_genes.entry(termid.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
term_name_genes.entry(term_details.name.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
}
}
SearchAPIMaps {
gene_summaries: gene_summaries,
termid_genes: termid_genes,
term_name_genes: term_name_genes,
term_summaries: term_summaries,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &String,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<String, ReferenceShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_terms: &mut HashMap<String, TermShortMap>) {
for (_, feat_annotations) in cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
self.add_ref_to_hash(seen_references,
identifier.clone(), detail.reference.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(seen_terms,
identifier.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
self.add_genotype_to_hash(seen_genotypes, seen_alleles, seen_genes,
identifier.clone(),
&genotype_uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (termid, term_details) in &self.terms {
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
for detail in &term_annotation.annotations {
for gene_uniquename in &detail.genes {
self.add_gene_to_hash(&mut seen_genes, termid.clone(), gene_uniquename.clone());
}
self.add_ref_to_hash(&mut seen_references, termid.clone(), detail.reference.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles,
&mut seen_genes, termid.clone(),
&genotype_uniquename);
}
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), interaction.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), ortholog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), paralog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
for target_of_annotation in &gene_details.target_of_annotations {
for annotation_gene_uniquename in &target_of_annotation.genes {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(),
annotation_gene_uniquename.clone());
}
if let Some(ref annotation_genotype_uniquename) = target_of_annotation.genotype_uniquename {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
gene_uniquename.clone(),
&annotation_genotype_uniquename.clone())
}
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(),
target_of_annotation.reference_uniquename.clone());
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
type GeneShortMap = HashMap<GeneUniquename, GeneShort>;
let mut seen_genes: HashMap<String, GeneShortMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
type TermShortMap = HashMap<TermId, TermShort>;
let mut seen_terms: HashMap<GeneUniquename, TermShortMap> = HashMap::new();
{
for (reference_uniquename, reference_details) in &self.references {
for (_, feat_annotations) in &reference_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
for gene_uniquename in &detail.genes {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(),
gene_uniquename.clone())
}
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, reference_uniquename.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, reference_uniquename.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
let genotype = self.make_genotype_short(genotype_uniquename);
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
reference_uniquename.clone(),
&genotype.uniquename);
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &reference_details.paralog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut term_seen_single_allele_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
let mut seen_single_allele_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
for annotation in &term_annotation.annotations {
for gene_uniquename in &annotation.genes {
seen_genes.insert(gene_uniquename.clone());
}
if let Some(ref genotype_uniquename) = annotation.genotype {
seen_genotypes.insert(genotype_uniquename.clone());
let genotype = self.genotypes.get(genotype_uniquename).unwrap();
if genotype.expressed_alleles.len() == 1 {
seen_single_allele_genotypes.insert(genotype_uniquename.clone());
}
}
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
term_seen_single_allele_genotypes.insert(termid.clone(), seen_single_allele_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for (_, rel_annotations) in &reference_details.cv_annotations {
for rel_annotation in rel_annotations {
for annotation in &rel_annotation.annotations {
if !rel_annotation.is_not {
for gene_uniquename in &annotation.genes {
seen_genes.insert(gene_uniquename.clone());
}
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for (_, gene_details) in &mut self.genes {
for (_, feat_annotations) in &mut gene_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.gene_count =
term_seen_genes.get(&feat_annotation.term.termid).unwrap().len();
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut gene_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, feat_annotations) in &mut genotype_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
}
for (_, ref_details) in &mut self.references {
for (_, ref_annotations) in &mut ref_details.cv_annotations {
for ref_annotation in ref_annotations {
ref_annotation.term.gene_count =
term_seen_genes.get(&ref_annotation.term.termid).unwrap().len();
ref_annotation.term.genotype_count =
term_seen_genotypes.get(&ref_annotation.term.termid).unwrap().len();
}
}
}
for (_, term_details) in &mut self.terms {
for (_, term_annotations) in &mut term_details.cv_annotations {
for term_annotation in term_annotations {
term_annotation.term.gene_count =
term_seen_genes.get(&term_annotation.term.termid).unwrap().len();
term_annotation.term.genotype_count =
term_seen_genotypes.get(&term_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut term_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
term_details.single_allele_genotype_uniquenames =
term_seen_single_allele_genotypes.remove(&term_details.termid).unwrap();
}
}
pub fn get_web_data(&mut self) -> WebData {
self.process_dbxrefs();
self.process_references();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.add_alleles_to_genotypes();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_deletion_viability();
self.make_all_cv_summaries();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
let mut web_data_terms: IdRcTermDetailsMap = HashMap::new();
let search_api_maps = self.make_search_api_maps();
for (termid, term_details) in self.terms.drain() {
web_data_terms.insert(termid.clone(), Rc::new(term_details));
}
self.terms = HashMap::new();
let mut used_terms: IdRcTermDetailsMap = HashMap::new();
// remove terms with no annotation
for (termid, term_details) in &web_data_terms {
if term_details.cv_annotations.keys().len() > 0 {
used_terms.insert(termid.clone(), term_details.clone());
}
}
let metadata = self.make_metadata();
WebData {
genes: self.genes.clone(),
genotypes: self.genotypes.clone(),
terms: web_data_terms,
used_terms: used_terms,
metadata: metadata,
references: self.references.clone(),
search_api_maps: search_api_maps,
}
}
}
#[allow(dead_code)]
fn get_test_config() -> Config {
let mut config = Config {
load_organism: ConfigOrganism {
genus: String::from("Schizosaccharomyces"),
species: String::from("pombe"),
},
extension_display_names: vec![],
extension_relation_order: RelationOrder {
relation_order: vec![
String::from("directly_positively_regulates"),
String::from("has_direct_input"),
String::from("involved_in"),
String::from("occurs_at"),
String::from("occurs_in"),
String::from("added_by"),
String::from("added_during"),
String::from("has_penetrance"),
],
always_last: vec![String::from("happens_during"),
String::from("exists_during")],
},
evidence_types: HashMap::new(),
cv_config: HashMap::new(),
interesting_parents: vec![],
viability_terms: ViabilityTerms {
viable: "FYPO:0002058".into(),
inviable: "FYPO:0002059".into(),
},
};
config.cv_config.insert(String::from("molecular_function"),
CvConfig {
feature_type: String::from("Gene"),
filters: vec![],
summary_relations_to_hide: vec![],
summary_gene_relations_to_collect: vec![String::from("has_substrate")],
});
config
}
#[test]
fn test_compare_ext_part_with_config() {
let config = get_test_config();
let mut ext_part1 = ExtPart {
rel_type_name: String::from("has_direct_input"),
rel_type_display_name: String::from("NA"),
ext_range: ExtRange::Misc(String::from("misc_ext_part_1")),
};
let mut ext_part2 = ExtPart {
rel_type_name: String::from("has_direct_input"),
rel_type_display_name: String::from("NA"),
ext_range: ExtRange::Misc(String::from("misc_ext_part_2")),
};
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
ext_part1.rel_type_name = "directly_positively_regulates".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "has_direct_input".into();
ext_part2.rel_type_name = "directly_positively_regulates".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part2.rel_type_name = "absent_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part2.rel_type_name = "misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "other_misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "other_misc_rel".into();
ext_part2.rel_type_name = "other_misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "has_direct_input".into();
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "has_direct_input".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "exists_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
}
#[allow(dead_code)]
fn make_test_ext_part(rel_type_name: &str, rel_type_display_name: &str,
ext_range: ExtRange) -> ExtPart {
ExtPart {
rel_type_name: rel_type_name.into(),
rel_type_display_name: rel_type_display_name.into(),
ext_range: ext_range,
}
}
#[allow(dead_code)]
fn get_test_annotations() -> Vec<OntTermAnnotations> {
let annotations1 =
vec![
make_one_detail(188448, "SPBC11B10.09", "PMID:3322810", None,
"IDA", vec![], HashSet::new()),
make_one_detail(202017,"SPBC11B10.09", "PMID:2665944", None,
"IDA", vec![], HashSet::new()),
];
let ont_term1 = OntTermAnnotations {
term: TermShort {
name: "cyclin-dependent protein kinase activity".into(),
cv_name: "molecular_function".into(),
interesting_parents: HashSet::from_iter(vec!["GO:0003824".into()]),
termid: "GO:0097472".into(),
is_obsolete: false,
gene_count: 6,
genotype_count: 0
},
is_not: false,
rel_names: HashSet::new(),
annotations: annotations1,
summary: None,
};
let annotations2 =
vec![
make_one_detail(41717, "SPBC11B10.09", "PMID:9242669", None,
"IDA",vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC646.13".into())), // sds23
], HashSet::new()),
make_one_detail(41718, "SPBC11B10.09", "PMID:9490630", None,
"IDA", vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPAC25G10.07c".into())), // cut7
], HashSet::new()),
make_one_detail(41718, "SPBC11B10.09", "PMID:11937031", None,
"IDA", vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC32F12.09".into())), // no name
], HashSet::new()),
make_one_detail(187893, "SPBC11B10.09", "PMID:19523829", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC6B1.04".into())), // mde4
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1902845".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
make_one_detail(187907, "SPBC11B10.09", "PMID:19523829", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC6B1.04".into())), // mde4
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:0098783".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
make_one_detail(193221, "SPBC11B10.09", "PMID:10921876", None, "IMP",
vec![
make_test_ext_part("directly_negatively_regulates", "directly inhibits",
ExtRange::Gene("SPAC144.13c".into())), // srw1
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1903693".into())),
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1905785".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000080".into())),
],
HashSet::new()),
make_one_detail(194213, "SPBC11B10.09", "PMID:7957097", None, "IDA",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC776.02c".into())), // dis2
],
HashSet::new()),
make_one_detail(194661, "SPBC11B10.09", "PMID:10485849", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC146.03c".into())), // cut3
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1903380".into())),
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:0042307".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
];
let ont_term2 = OntTermAnnotations {
term: TermShort {
name: "cyclin-dependent protein serine/threonine kinase activity".into(),
cv_name: "molecular_function".into(),
gene_count: 5,
genotype_count: 0,
interesting_parents: HashSet::from_iter(vec!{"GO:0003824".into()}),
is_obsolete: false,
termid: "GO:0004693".into(),
},
is_not: false,
rel_names: HashSet::new(),
annotations: annotations2,
summary: None,
};
vec![ont_term1, ont_term2]
}
#[allow(dead_code)]
fn make_one_detail(id: i32, gene_uniquename: &str, reference_uniquename: &str,
maybe_genotype_uniquename: Option<&str>, evidence: &str,
extension: Vec<ExtPart>,
conditions: HashSet<TermId>) -> Rc<OntAnnotationDetail> {
Rc::new(OntAnnotationDetail {
id: id,
genes: vec![gene_uniquename.into()],
genotype: maybe_genotype_uniquename.map(str::to_string),
reference: Some(reference_uniquename.into()),
evidence: Some(evidence.into()),
with: WithFromValue::None,
from: WithFromValue::None,
residue: None,
qualifiers: vec![],
extension: extension,
gene_ex_props: None,
conditions: conditions,
})
}
#[allow(dead_code)]
fn get_test_fypo_term_details() -> Vec<Rc<OntAnnotationDetail>> {
let mut test_conditions = HashSet::new();
test_conditions.insert("PECO:0000103".into());
test_conditions.insert("PECO:0000137".into());
vec![
make_one_detail(223656,
"SPBC16A3.11",
"PMID:23050226",
Some("e674fe7ceba478aa-genotype-2"),
"Cell growth assay",
vec![],
test_conditions.clone()),
make_one_detail(201099,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-4"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(201095,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-3"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(204063,
"SPAC25A8.01c",
"PMID:25798942",
Some("fd4f3f52f1d38106-genotype-4"),
"Cell growth assay",
vec![],
test_conditions.clone()),
make_one_detail(227452,
"SPAC3G6.02",
"PMID:25306921",
Some("a6d8f45c20c2227d-genotype-9"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(201094,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-2"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(186589,
"SPAC24H6.05",
"PMID:1464319",
Some("65c76fa511461156-genotype-3"),
"Cell growth assay",
vec![],
test_conditions)]
}
#[allow(dead_code)]
fn make_one_genotype(uniquename: &str, name: Option<&str>,
expressed_alleles: Vec<ExpressedAllele>) -> GenotypeDetails {
GenotypeDetails {
uniquename: uniquename.into(),
name: name.map(str::to_string),
background: None,
expressed_alleles: expressed_alleles,
cv_annotations: HashMap::new(),
references_by_uniquename: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn make_test_gene(uniquename: &str, name: Option<&str>) -> GeneDetails {
GeneDetails {
uniquename: uniquename.into(),
name: name.map(str::to_string),
organism: ConfigOrganism {
genus: "Schizosaccharomyces".into(),
species: "pombe".into(),
},
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier: None,
orfeome_identifier: None,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs: HashSet::new(),
feature_type: "gene".into(),
characterisation_status: None,
location: None,
cds_location: None,
gene_neighbourhood: vec![],
transcripts: vec![],
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
references_by_uniquename: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn get_test_genes_map() -> UniquenameGeneMap {
let mut ret = HashMap::new();
let gene_data =
vec![("SPBC11B10.09", Some("cdc2")),
("SPAC144.13c", Some("srw1")),
("SPAC25G10.07c", Some("cut7")),
("SPBC146.03c", Some("cut3")),
("SPBC32F12.09", None),
("SPBC646.13", Some("sds23")),
("SPBC6B1.04", Some("mde4")),
("SPBC776.02c", Some("dis2"))];
for (uniquename, name) in gene_data {
ret.insert(uniquename.into(), make_test_gene(uniquename, name));
}
ret
}
#[allow(dead_code)]
fn get_test_genotypes_map() -> UniquenameGenotypeMap {
let mut ret = HashMap::new();
ret.insert(String::from("e674fe7ceba478aa-genotype-2"),
make_one_genotype(
"e674fe7ceba478aa-genotype-2",
Some("test genotype name"),
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPBC16A3.11:allele-7".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-4"),
make_one_genotype(
"d6c914796c35e3b5-genotype-4",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-5".into(),
}
]
));
ret.insert(String::from("65c76fa511461156-genotype-3"),
make_one_genotype(
"65c76fa511461156-genotype-3",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPAC24H6.05:allele-3".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-2"),
make_one_genotype(
"d6c914796c35e3b5-genotype-2",
Some("ZZ-name"),
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-4".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-3"),
make_one_genotype(
"d6c914796c35e3b5-genotype-3",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-6".into(),
}
]
));
ret.insert(String::from("fd4f3f52f1d38106-genotype-4"),
make_one_genotype(
"fd4f3f52f1d38106-genotype-4",
None,
vec![
ExpressedAllele {
expression: Some("Wild type product level".into()),
allele_uniquename: "SPAC25A8.01c:allele-5".into(),
}
]
));
ret.insert(String::from("a6d8f45c20c2227d-genotype-9"),
make_one_genotype(
"a6d8f45c20c2227d-genotype-9",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPAC3G6.02:allele-7".into(),
}
]
));
ret
}
#[allow(dead_code)]
fn make_one_allele_short(uniquename: &str, name: &str, allele_type: &str,
description: Option<&str>, gene_uniquename: &str) -> AlleleShort {
AlleleShort {
uniquename: uniquename.into(),
description: description.map(str::to_string),
name: Some(name.into()),
allele_type: allele_type.into(),
gene_uniquename: gene_uniquename.into(),
}
}
#[allow(dead_code)]
fn get_test_alleles_map() -> UniquenameAlleleMap {
let mut ret = HashMap::new();
ret.insert(String::from("SPCC1919.10c:allele-4"),
make_one_allele_short("SPCC1919.10c:allele-4", "ATPase dead mutant", "unknown", None, "SPCC1919.10c"));
ret.insert(String::from("SPCC1919.10c:allele-5"),
make_one_allele_short("SPCC1919.10c:allele-5", "C-terminal truncation 940-1516", "partial_amino_acid_deletion",
Some("940-1516"), "SPCC1919.10c"));
ret.insert(String::from("SPCC1919.10c:allele-6"),
make_one_allele_short("SPCC1919.10c:allele-6", "C-terminal truncation", "partial_amino_acid_deletion", Some("1320-1516"),
"SPCC1919.10c"));
ret.insert(String::from("SPBC16A3.11:allele-7"),
make_one_allele_short("SPBC16A3.11:allele-7", "G799D", "amino_acid_mutation", Some("G799D"), "SPBC16A3.11"));
ret.insert(String::from("SPAC25A8.01c:allele-5"),
make_one_allele_short("SPAC25A8.01c:allele-5", "K418R", "amino_acid_mutation", Some("K418R"), "SPAC25A8.01c"));
ret.insert(String::from("SPAC3G6.02:allele-7"),
make_one_allele_short("SPAC3G6.02:allele-7", "UBS-I&II", "amino_acid_mutation", Some("F18A,F21A,W26A,L40A,W41A,W45A"), "SPAC3G6.02"));
ret.insert(String::from("SPAC24H6.05:allele-3"),
make_one_allele_short("SPAC24H6.05:allele-3", "cdc25-22", "amino_acid_mutation", Some("C532Y"), "SPAC24H6.05"));
ret
}
#[allow(dead_code)]
fn make_test_term_details(id: &str, name: &str, cv_name: &str) -> TermDetails {
TermDetails {
termid: id.into(),
name: name.into(),
cv_name: cv_name.into(),
annotation_feature_type: "gene".into(),
interesting_parents: HashSet::new(),
definition: None,
direct_ancestors: vec![],
is_obsolete: false,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn get_test_terms_map() -> TermIdDetailsMap {
let mut ret = HashMap::new();
let term_data = vec![
("GO:0022403", "cell cycle phase", "biological_process"),
("GO:0051318", "G1 phase", "biological_process"),
("GO:0000080", "mitotic G1 phase", "biological_process"),
("GO:0088888", "fake child of mitotic G1 phase", "biological_process"),
("GO:0000089", "mitotic metaphase", "biological_process"),
("GO:0099999", "fake child of mitotic metaphase term", "biological_process"),
("GO:0042307", "positive regulation of protein import into nucleus", "biological_process"),
("GO:0098783", "correction of merotelic kinetochore attachment, mitotic", "biological_process"),
("GO:1902845", "negative regulation of mitotic spindle elongation", "biological_process"),
("GO:1903380", "positive regulation of mitotic chromosome condensation", "biological_process"),
("GO:1903693", "regulation of mitotic G1 cell cycle arrest in response to nitrogen starvation", "biological_process"),
("GO:1905785", "negative regulation of anaphase-promoting complex-dependent catabolic process", "biological_process"),
];
for (id, name, cv_name) in term_data {
ret.insert(id.into(), make_test_term_details(id, name, cv_name));
}
ret
}
#[test]
fn test_cmp_ont_annotation_detail() {
let mut details_vec = get_test_fypo_term_details();
let genes = get_test_genes_map();
let genotypes = get_test_genotypes_map();
let alleles = get_test_alleles_map();
let terms = get_test_terms_map();
let cmp_detail_with_genotypes =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &genes,
&genotypes, &alleles, &terms)
};
details_vec.sort_by(&cmp_detail_with_genotypes);
let expected: Vec<String> =
vec!["C-terminal truncation 940-1516(940-1516)",
"C-terminal truncation(1320-1516)",
"cdc25-22(C532Y)",
"K418R(K418R)",
"test genotype name",
"UBS-I&II(F18A,F21A,W26A,L40A,W41A,W45A)",
"ZZ-name"]
.iter().map(|s| str::to_string(s)).collect();
assert_eq!(details_vec.drain(0..)
.map(|detail| {
let genotype_uniquename: String =
(*detail).clone().genotype.unwrap();
let genotype = genotypes.get(&genotype_uniquename).unwrap();
genotype_display_name(&genotype, &alleles)
}).collect::<Vec<String>>(),
expected);
let test_term_annotations = get_test_annotations();
let mut extension_details_vec = test_term_annotations[1].annotations.clone();
extension_details_vec.sort_by(&cmp_detail_with_genotypes);
let annotation_sort_results: Vec<(String, String)> =
extension_details_vec.iter().map(|detail| {
((*detail).genes[0].clone(),
(*detail).reference.clone().unwrap())
}).collect();
let expected_annotation_sort: Vec<(String, String)> =
vec![("SPBC11B10.09", "PMID:10921876"),
("SPBC11B10.09", "PMID:10485849" /* has_direct_input(cut3) */),
("SPBC11B10.09", "PMID:9490630" /* has_direct_input(cut7) */),
("SPBC11B10.09", "PMID:7957097" /* has_direct_input(dis2) */),
("SPBC11B10.09", "PMID:19523829" /* has_direct_input(mde4), part_of(...), happens_during(...) */),
("SPBC11B10.09", "PMID:19523829" /* has_direct_input(mde4), part_of(...), happens_during(...) */),
("SPBC11B10.09", "PMID:9242669" /* has_direct_input(sds23) */),
("SPBC11B10.09", "PMID:11937031" /* has_direct_input(SPBC32F12.09) */),
]
.iter()
.map(|&(gene, reference)|
(gene.into(), reference.into())).collect();
assert_eq![annotation_sort_results, expected_annotation_sort];
}
#[allow(dead_code)]
fn make_term_short_from_details(term_details: &TermDetails) -> TermShort {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: false,
gene_count: 0,
genotype_count: 0
}
}
#[allow(dead_code)]
fn make_test_summary(termid: &str, rows: Vec<TermSummaryRow>) -> OntTermAnnotations {
let terms = get_test_terms_map();
OntTermAnnotations {
term: make_term_short_from_details(&terms.get(termid).unwrap().clone()),
is_not: false,
annotations: vec![],
rel_names: HashSet::new(),
summary: Some(rows),
}
}
#[allow(dead_code)]
fn get_test_summaries() -> Vec<OntTermAnnotations> {
let mut summaries = vec![];
let ext = make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1905785".into()));
let ext2 = make_test_ext_part("some_rel", "some_rel_display_name",
ExtRange::Term("GO:1234567".into()));
summaries.push(make_test_summary("GO:0022403", vec![]));
summaries.push(make_test_summary("GO:0051318",
vec![TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone()],
}]));
summaries.push(make_test_summary("GO:0000080", vec![]));
summaries.push(make_test_summary("GO:0000089",
vec![
TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone()],
}
]));
summaries.push(make_test_summary("GO:0099999",
vec![
TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone(), ext2],
}
]));
summaries
}
#[allow(dead_code)]
fn get_test_children_by_termid() -> HashMap<TermId, HashSet<TermId>> {
let mut children_by_termid = HashMap::new();
let mut children_of_0022403 = HashSet::new();
children_of_0022403.insert("GO:0051318".into());
children_of_0022403.insert("GO:0000080".into());
children_of_0022403.insert("GO:0088888".into());
children_of_0022403.insert("GO:0000089".into());
children_of_0022403.insert("GO:0099999".into());
let mut children_of_0051318 = HashSet::new();
children_of_0051318.insert("GO:0000080".into());
children_of_0051318.insert("GO:0088888".into());
children_of_0051318.insert("GO:0000089".into());
children_of_0051318.insert("GO:0099999".into());
let mut children_of_0000080 = HashSet::new();
children_of_0000080.insert("GO:0088888".into());
let mut children_of_0000089 = HashSet::new();
children_of_0000089.insert("GO:0099999".into());
children_by_termid.insert("GO:0022403".into(), children_of_0022403);
children_by_termid.insert("GO:0051318".into(), children_of_0051318);
children_by_termid.insert("GO:0000080".into(), children_of_0000080);
children_by_termid.insert("GO:0000089".into(), children_of_0000089);
children_by_termid
}
#[test]
fn test_remove_redundant_summaries() {
let mut term_annotations: Vec<OntTermAnnotations> = get_test_summaries();
let children_by_termid = get_test_children_by_termid();
assert_eq!(term_annotations.len(), 5);
remove_redundant_summaries(&children_by_termid, &mut term_annotations);
assert_eq!(term_annotations.iter().filter(|term_annotation| {
term_annotation.summary.is_some()
}).collect::<Vec<&OntTermAnnotations>>().len(), 3);
}
#[test]
fn test_summary_row_equals() {
let r1 = TermSummaryRow {
gene_uniquenames: vec!["SPAPB1A10.09".into()],
genotype_uniquenames: vec![],
extension: vec![],
};
let r2 = TermSummaryRow {
gene_uniquenames: vec!["SPAPB1A10.09".into()],
genotype_uniquenames: vec![],
extension: vec![],
};
assert!(r1 == r2);
}
Fix viability logic, too many "unknowns"
Refs pombase/website#233
use std::rc::Rc;
use std::collections::hash_map::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::borrow::Borrow;
use std::cmp::{Ordering, min};
use regex::Regex;
use db::*;
use types::*;
use web::data::*;
use web::config::*;
use web::vec_set::*;
fn make_organism(rc_organism: &Rc<Organism>) -> ConfigOrganism {
ConfigOrganism {
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
}
}
#[derive(Clone)]
pub struct AlleleAndExpression {
allele_uniquename: String,
expression: Option<String>,
}
pub struct WebDataBuild<'a> {
raw: &'a Raw,
config: &'a Config,
genes: UniquenameGeneMap,
transcripts: UniquenameTranscriptMap,
genotypes: UniquenameGenotypeMap,
alleles: UniquenameAlleleMap,
terms: TermIdDetailsMap,
references: IdReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
all_not_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
genes_of_transcripts: HashMap<String, String>,
transcripts_of_polypeptides: HashMap<String, String>,
genes_of_alleles: HashMap<String, String>,
alleles_of_genotypes: HashMap<String, Vec<AlleleAndExpression>>,
// gene_uniquename vs transcript_type_name:
transcript_type_of_genes: HashMap<String, String>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
children_by_termid: HashMap<TermId, HashSet<TermId>>,
dbxrefs_of_features: HashMap<String, HashSet<String>>,
possible_interesting_parents: HashSet<InterestingParent>,
}
fn get_maps() ->
(HashMap<String, ReferenceShortMap>,
HashMap<String, GeneShortMap>,
HashMap<String, GenotypeShortMap>,
HashMap<String, AlleleShortMap>,
HashMap<GeneUniquename, TermShortMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature: &Feature,
feature_relationship: &FeatureRelationship) -> Option<String> {
for feature_prop in feature.featureprops.borrow().iter() {
if feature_prop.prop_type.name == "allele_type" {
if let Some(ref value) = feature_prop.value {
if value == "deletion" {
return Some("Null".into());
}
}
}
}
for rel_prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if rel_prop.prop_type.name == "expression" {
return rel_prop.value.clone();
}
}
None
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
pub fn remove_first<T, P>(vec: &mut Vec<T>, predicate: P) -> Option<T>
where P: FnMut(&T) -> bool {
if let Some(pos) = vec.iter().position(predicate) {
return Some(vec.remove(pos));
}
None
}
// merge two ExtPart objects into one by merging gene ranges
pub fn merge_gene_ext_parts(ext_part1: &ExtPart, ext_part2: &ExtPart) -> ExtPart {
if ext_part1.rel_type_name == ext_part2.rel_type_name {
if let ExtRange::SummaryGenes(ref part1_summ_genes) = ext_part1.ext_range {
if let ExtRange::SummaryGenes(ref part2_summ_genes) = ext_part2.ext_range {
let mut ret_ext_part = ext_part1.clone();
let mut new_genes = [part1_summ_genes.clone(), part2_summ_genes.clone()].concat();
new_genes.sort();
new_genes.dedup();
ret_ext_part.ext_range = ExtRange::SummaryGenes(new_genes);
return ret_ext_part
}
}
panic!("passed ExtPart objects that have non-gene ranges to merge_gene_ext_parts():
{:?} {:?}", ext_part1, ext_part2);
} else {
panic!("passed ExtPart objects with mismatched relations to merge_gene_ext_parts():
{} {}\n", ext_part1.rel_type_name, ext_part2.rel_type_name);
}
}
// turn "has_substrate(gene1),has_substrate(gene2)" into "has_substrate(gene1,gene2)"
pub fn collect_ext_summary_genes(cv_config: &CvConfig, rows: &mut Vec<TermSummaryRow>) {
let conf_gene_rels = &cv_config.summary_gene_relations_to_collect;
let gene_range_rel_p =
|ext_part: &ExtPart| {
if let ExtRange::SummaryGenes(_) = ext_part.ext_range {
conf_gene_rels.contains(&ext_part.rel_type_name)
} else {
false
}
};
let mut ret_rows = vec![];
{
let mut row_iter = rows.iter().cloned();
if let Some(mut prev_row) = row_iter.next() {
for current_row in row_iter {
if prev_row.gene_uniquenames != current_row.gene_uniquenames ||
prev_row.genotype_uniquenames != current_row.genotype_uniquenames {
ret_rows.push(prev_row);
prev_row = current_row;
continue;
}
let mut prev_row_extension = prev_row.extension.clone();
let prev_matching_gene_ext_part =
remove_first(&mut prev_row_extension, &gene_range_rel_p);
let mut current_row_extension = current_row.extension.clone();
let current_matching_gene_ext_part =
remove_first(&mut current_row_extension, &gene_range_rel_p);
if let (Some(prev_gene_ext_part), Some(current_gene_ext_part)) =
(prev_matching_gene_ext_part, current_matching_gene_ext_part) {
if current_row_extension == prev_row_extension &&
prev_gene_ext_part.rel_type_name == current_gene_ext_part.rel_type_name {
let merged_gene_ext_parts =
merge_gene_ext_parts(&prev_gene_ext_part,
¤t_gene_ext_part);
let mut new_ext = vec![merged_gene_ext_parts];
new_ext.extend_from_slice(&prev_row_extension);
prev_row.extension = new_ext;
} else {
ret_rows.push(prev_row);
prev_row = current_row;
}
} else {
ret_rows.push(prev_row);
prev_row = current_row
}
}
ret_rows.push(prev_row);
}
}
*rows = ret_rows;
}
// combine rows that have a gene or genotype but no extension into one row
pub fn collect_summary_rows(rows: &mut Vec<TermSummaryRow>) {
let mut no_ext_rows = vec![];
let mut other_rows = vec![];
for row in rows.drain(0..) {
if (row.gene_uniquenames.len() > 0 || row.genotype_uniquenames.len() > 0)
&& row.extension.len() == 0 {
if row.gene_uniquenames.len() > 1 {
panic!("row has more than one gene\n");
}
if row.genotype_uniquenames.len() > 1 {
panic!("row has more than one genotype\n");
}
no_ext_rows.push(row);
} else {
other_rows.push(row);
}
}
let gene_uniquenames: Vec<String> =
no_ext_rows.iter().filter(|row| row.gene_uniquenames.len() > 0)
.map(|row| row.gene_uniquenames.get(0).unwrap().clone())
.collect();
let genotype_uniquenames: Vec<String> =
no_ext_rows.iter().filter(|row| row.genotype_uniquenames.len() > 0)
.map(|row| row.genotype_uniquenames.get(0).unwrap().clone())
.collect();
rows.clear();
if gene_uniquenames.len() > 0 || genotype_uniquenames.len() > 0 {
let genes_row = TermSummaryRow {
gene_uniquenames: gene_uniquenames,
genotype_uniquenames: genotype_uniquenames,
extension: vec![],
};
rows.push(genes_row);
}
rows.append(&mut other_rows);
}
// Remove annotations from the summary where there is another more
// specific annotation. ie. the same annotation but with extra part(s) in the
// extension.
// See: https://github.com/pombase/website/issues/185
pub fn remove_redundant_summary_rows(rows: &mut Vec<TermSummaryRow>) {
let mut results = vec![];
if rows.len() <= 1 {
return;
}
rows.reverse();
let mut vec_set = VecSet::new();
let mut prev = rows.remove(0);
results.push(prev.clone());
if prev.gene_uniquenames.len() > 1 {
panic!("remove_redundant_summary_rows() failed: num genes > 1\n");
}
vec_set.insert(&prev.extension);
for current in rows.drain(0..) {
if current.gene_uniquenames.len() > 1 {
panic!("remove_redundant_summary_rows() failed: num genes > 1\n");
}
if (&prev.gene_uniquenames, &prev.genotype_uniquenames) ==
(¤t.gene_uniquenames, ¤t.genotype_uniquenames) {
if !vec_set.contains_superset(¤t.extension) {
results.push(current.clone());
vec_set.insert(¤t.extension);
}
} else {
vec_set = VecSet::new();
vec_set.insert(¤t.extension);
results.push(current.clone());
}
prev = current;
}
results.reverse();
*rows = results;
}
fn remove_redundant_summaries(children_by_termid: &HashMap<TermId, HashSet<TermId>>,
term_annotations: &mut Vec<OntTermAnnotations>) {
let mut term_annotations_by_termid = HashMap::new();
for term_annotation in &*term_annotations {
term_annotations_by_termid.insert(term_annotation.term.termid.clone(),
term_annotation.clone());
}
for mut term_annotation in term_annotations.iter_mut() {
if let Some(child_termids) = children_by_termid.get(&term_annotation.term.termid) {
if term_annotation.summary.clone().unwrap().len() == 0 {
let mut found_child_match = false;
for child_termid in child_termids {
if term_annotations_by_termid.get(child_termid).is_some() {
found_child_match = true;
}
}
if found_child_match {
term_annotation.summary = None;
}
} else {
let mut filtered_rows: Vec<TermSummaryRow> = vec![];
for row in &mut term_annotation.summary.clone().unwrap() {
let mut found_child_match = false;
for child_termid in child_termids {
if let Some(ref mut child_term_annotation) =
term_annotations_by_termid.get(child_termid) {
for child_row in &child_term_annotation.summary.clone().unwrap() {
if *row == *child_row {
found_child_match = true;
break;
}
}
}
}
if !found_child_match {
filtered_rows.push(row.clone());
}
}
if filtered_rows.len() == 0 {
term_annotation.summary = None;
}
}
}
}
}
fn make_cv_summaries(config: &Config,
children_by_termid: &HashMap<TermId, HashSet<TermId>>,
include_gene: bool, include_genotype: bool,
term_and_annotations_vec: &mut Vec<OntTermAnnotations>) {
for term_and_annotations in term_and_annotations_vec.iter_mut() {
let term = &term_and_annotations.term;
let cv_config = config.cv_config_by_name(&term.cv_name);
let mut rows = vec![];
for annotation in &term_and_annotations.annotations {
let gene_uniquenames =
if include_gene && cv_config.feature_type == "gene" {
annotation.genes.clone()
} else {
vec![]
};
let genotype_uniquenames =
if include_genotype && cv_config.feature_type == "genotype" {
if let Some(ref genotype_uniquename) = annotation.genotype {
vec![genotype_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
};
let summary_relations_to_hide = &cv_config.summary_relations_to_hide;
let mut summary_extension = annotation.extension.iter().cloned()
.filter(|ext_part| {
!summary_relations_to_hide.contains(&ext_part.rel_type_name) &&
*summary_relations_to_hide != vec!["ALL"]
})
.map(move |mut ext_part| {
if let ExtRange::Gene(gene_uniquename) = ext_part.ext_range.clone() {
let summ_genes = vec![gene_uniquename];
ext_part.ext_range = ExtRange::SummaryGenes(vec![summ_genes]);
}
ext_part })
.collect::<Vec<ExtPart>>();
if gene_uniquenames.len() == 0 &&
genotype_uniquenames.len() == 0 &&
summary_extension.len() == 0 {
continue;
}
collect_duplicated_relations(&mut summary_extension);
let row = TermSummaryRow {
gene_uniquenames: gene_uniquenames,
genotype_uniquenames: genotype_uniquenames,
extension: summary_extension,
};
rows.push(row);
}
remove_redundant_summary_rows(&mut rows);
term_and_annotations.summary = Some(rows);
}
remove_redundant_summaries(children_by_termid, term_and_annotations_vec);
for ref mut term_and_annotations in term_and_annotations_vec.iter_mut() {
if let Some(ref mut summary) = term_and_annotations.summary {
collect_summary_rows(summary);
let cv_config = config.cv_config_by_name(&term_and_annotations.term.cv_name);
collect_ext_summary_genes(&cv_config, summary);
}
}
}
// turns binds([[gene1]]),binds([[gene2]]),other_rel(...) into:
// binds([[gene1, gene2]]),other_rel(...)
pub fn collect_duplicated_relations(ext: &mut Vec<ExtPart>) {
let mut result: Vec<ExtPart> = vec![];
{
let mut iter = ext.iter().cloned();
if let Some(mut prev) = iter.next() {
for current in iter {
if prev.rel_type_name != current.rel_type_name {
result.push(prev);
prev = current;
continue;
}
if let ExtRange::SummaryGenes(ref current_summ_genes) = current.ext_range {
if let ExtRange::SummaryGenes(ref mut prev_summ_genes) = prev.ext_range {
let mut current_genes = current_summ_genes.get(0).unwrap().clone();
prev_summ_genes.get_mut(0).unwrap().append(& mut current_genes);
continue;
}
}
result.push(prev);
prev = current;
}
result.push(prev);
}
}
ext.clear();
ext.append(&mut result);
}
fn compare_ext_part_with_config(config: &Config, ep1: &ExtPart, ep2: &ExtPart) -> Ordering {
let rel_order_conf = &config.extension_relation_order;
let order_conf = &rel_order_conf.relation_order;
let always_last_conf = &rel_order_conf.always_last;
let maybe_ep1_index = order_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_index = order_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_index) = maybe_ep1_index {
if let Some(ep2_index) = maybe_ep2_index {
ep1_index.cmp(&ep2_index)
} else {
Ordering::Less
}
} else {
if let Some(_) = maybe_ep2_index {
Ordering::Greater
} else {
let maybe_ep1_last_index = always_last_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_last_index = always_last_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_last_index) = maybe_ep1_last_index {
if let Some(ep2_last_index) = maybe_ep2_last_index {
ep1_last_index.cmp(&ep2_last_index)
} else {
Ordering::Greater
}
} else {
if let Some(_) = maybe_ep2_last_index {
Ordering::Less
} else {
ep1.rel_type_name.cmp(&ep2.rel_type_name)
}
}
}
}
}
fn string_from_ext_range(ext_range: &ExtRange,
genes: &UniquenameGeneMap, terms: &TermIdDetailsMap) -> String {
match ext_range {
&ExtRange::Gene(ref gene_uniquename) => {
let gene = genes.get(gene_uniquename).unwrap();
gene_display_name(&gene)
},
&ExtRange::SummaryGenes(_) => panic!("can't handle SummaryGenes\n"),
&ExtRange::Term(ref termid) => terms.get(termid).unwrap().name.clone(),
&ExtRange::Misc(ref misc) => misc.clone(),
&ExtRange::Domain(ref domain) => domain.clone(),
&ExtRange::GeneProduct(ref gene_product) => gene_product.clone(),
}
}
fn cmp_ext_part(ext_part1: &ExtPart, ext_part2: &ExtPart,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let ord = ext_part1.rel_type_display_name.cmp(&ext_part2.rel_type_display_name);
if ord == Ordering::Equal {
let ext_part1_str = string_from_ext_range(&ext_part1.ext_range, genes, terms);
let ext_part2_str = string_from_ext_range(&ext_part2.ext_range, genes, terms);
ext_part1_str.to_lowercase().cmp(&ext_part2_str.to_lowercase())
} else {
ord
}
}
// compare the extension up to the last common index
fn cmp_extension_prefix(ext1: &Vec<ExtPart>, ext2: &Vec<ExtPart>,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> (usize, Ordering) {
let iter = ext1.iter().zip(ext2).enumerate();
for (index, (ext1_part, ext2_part)) in iter {
let ord = cmp_ext_part(&ext1_part, &ext2_part, genes, terms);
if ord != Ordering::Equal {
return (index, ord)
}
}
(min(ext1.len(), ext2.len()), Ordering::Equal)
}
fn cmp_extension(ext1: &Vec<ExtPart>, ext2: &Vec<ExtPart>,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let (_, cmp) = cmp_extension_prefix(ext1, ext2, genes, terms);
if cmp == Ordering::Equal {
ext1.len().cmp(&ext2.len())
} else {
cmp
}
}
fn cmp_genotypes(genotype1: &GenotypeDetails, genotype2: &GenotypeDetails,
alleles: &UniquenameAlleleMap) -> Ordering {
let name1 = genotype_display_name(genotype1, alleles);
let name2 = genotype_display_name(genotype2, alleles);
name1.to_lowercase().cmp(&name2.to_lowercase())
}
fn allele_display_name(allele: &AlleleShort) -> String {
let name = allele.name.clone().unwrap_or("unnamed".into());
let allele_type = allele.allele_type.clone();
let mut description = allele.description.clone().unwrap_or(allele_type.clone());
if allele_type == "deletion" && name.ends_with("delta") ||
allele_type.starts_with("wild_type") && name.ends_with("+") {
let normalised_description = description.replace("[\\s_]+", "");
let normalised_allele_type = allele_type.replace("[\\s_]+", "");
if normalised_description != normalised_allele_type {
return name + "(" + description.as_str() + ")";
} else {
return name;
}
}
if allele_type.starts_with("mutation") {
let re = Regex::new(r"(?P<m>^|,\\s*)").unwrap();
if allele_type.contains("amino acid") {
description = re.replace_all(&description, "$maa");
} else {
if allele_type.contains("nucleotide") {
description = re.replace_all(&description, "$nt");
}
}
}
name + "(" + description.as_str() + ")"
}
fn gene_display_name(gene: &GeneDetails) -> String {
if let Some(name) = gene.name.clone() {
name
} else {
gene.uniquename.clone()
}
}
pub fn genotype_display_name(genotype: &GenotypeDetails,
alleles: &UniquenameAlleleMap) -> String {
if let Some(ref name) = genotype.name {
name.clone()
} else {
let allele_display_names: Vec<String> =
genotype.expressed_alleles.iter().map(|ref expressed_allele| {
let allele_short = alleles.get(&expressed_allele.allele_uniquename).unwrap();
allele_display_name(allele_short)
}).collect();
allele_display_names.join(" ")
}
}
fn make_gene_short<'b>(gene_map: &'b UniquenameGeneMap,
gene_uniquename: &'b str) -> GeneShort {
if let Some(gene_details) = gene_map.get(gene_uniquename) {
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
// compare two gene vectors which must be ordered vecs
fn cmp_gene_vec(genes: &UniquenameGeneMap,
gene_vec1: &Vec<GeneUniquename>,
gene_vec2: &Vec<GeneUniquename>) -> Ordering {
let gene_short_vec1: Vec<GeneShort> =
gene_vec1.iter().map(|gene_uniquename: &String| {
make_gene_short(genes, &gene_uniquename)
}).collect();
let gene_short_vec2: Vec<GeneShort> =
gene_vec2.iter().map(|gene_uniquename: &String| {
make_gene_short(genes, &gene_uniquename)
}).collect();
return gene_short_vec1.cmp(&gene_short_vec2)
}
fn cmp_ont_annotation_detail(detail1: &Rc<OntAnnotationDetail>,
detail2: &Rc<OntAnnotationDetail>,
genes: &UniquenameGeneMap,
genotypes: &UniquenameGenotypeMap,
alleles: &UniquenameAlleleMap,
terms: &TermIdDetailsMap) -> Ordering {
if let Some(ref detail1_genotype_uniquename) = detail1.genotype {
if let Some(ref detail2_genotype_uniquename) = detail2.genotype {
let genotype1 = genotypes.get(detail1_genotype_uniquename).unwrap();
let genotype2 = genotypes.get(detail2_genotype_uniquename).unwrap();
let ord = cmp_genotypes(&genotype1, &genotype2, alleles);
if ord == Ordering::Equal {
cmp_extension(&detail1.extension, &detail2.extension, genes, terms)
} else {
ord
}
} else {
panic!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n");
}
} else {
if detail2.genotype.is_some() {
panic!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n");
} else {
let ord = cmp_gene_vec(genes, &detail1.genes, &detail2.genes);
if ord == Ordering::Equal {
cmp_extension(&detail1.extension, &detail2.extension, genes, terms)
} else {
ord
}
}
}
}
// Some ancestor terms are useful in the web code. This function uses the Config and returns
// the terms that might be useful.
fn get_possible_interesting_parents(config: &Config) -> HashSet<InterestingParent> {
let mut ret = HashSet::new();
for parent_conf in config.interesting_parents.iter() {
ret.insert(parent_conf.clone());
}
for ext_conf in &config.extension_display_names {
if let Some(ref conf_termid) = ext_conf.if_descendent_of {
ret.insert(InterestingParent {
termid: conf_termid.clone(),
rel_name: "is_a".into(),
});
}
}
for (cv_name, conf) in &config.cv_config {
for filter in &conf.filters {
for category in &filter.term_categories {
for ancestor in &category.ancestors {
for config_rel_name in DESCENDANT_REL_NAMES.iter() {
if *config_rel_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&cv_name.as_str()) {
continue;
}
ret.insert(InterestingParent {
termid: ancestor.clone(),
rel_name: String::from(*config_rel_name),
});
}
}
}
}
}
ret
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, config: &'a Config) -> WebDataBuild<'a> {
WebDataBuild {
raw: raw,
config: config,
genes: HashMap::new(),
transcripts: HashMap::new(),
genotypes: HashMap::new(),
alleles: HashMap::new(),
terms: HashMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
transcript_type_of_genes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
children_by_termid: HashMap::new(),
dbxrefs_of_features: HashMap::new(),
possible_interesting_parents: get_possible_interesting_parents(config),
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<String, ReferenceShortMap>,
identifier: String,
maybe_reference_uniquename: Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if let Some(reference_short) = self.make_reference_short(&reference_uniquename) {
seen_references
.entry(identifier.clone())
.or_insert(HashMap::new())
.insert(reference_uniquename.clone(),
reference_short);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
other_gene_uniquename: GeneUniquename) {
seen_genes
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_gene_uniquename.clone(),
self.make_gene_short(&other_gene_uniquename));
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
genotype_uniquename: &GenotypeUniquename) {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
self.add_allele_to_hash(seen_alleles, seen_genes, identifier.clone(),
expressed_allele.allele_uniquename.clone());
}
seen_genotypes
.entry(identifier)
.or_insert(HashMap::new())
.insert(genotype_uniquename.clone(),
self.make_genotype_short(genotype_uniquename));
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
allele_uniquename: AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(seen_genes, identifier.clone(), allele_gene_uniquename);
seen_alleles
.entry(identifier)
.or_insert(HashMap::new())
.insert(allele_uniquename, allele_short.clone());
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortMap>,
identifier: String,
other_termid: TermId) {
seen_terms
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(&gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(&gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<String>>();
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
synonyms: synonyms,
feature_type: gene_details.feature_type.clone(),
organism: gene_details.organism.clone(),
location: gene_details.location.clone(),
}
}
fn make_reference_short(&self, reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = self.references.get(reference_uniquename).unwrap();
let reference_short =
ReferenceShort {
uniquename: String::from(reference_uniquename),
title: reference_details.title.clone(),
citation: reference_details.citation.clone(),
publication_year: reference_details.publication_year.clone(),
authors: reference_details.authors.clone(),
authors_abbrev: reference_details.authors_abbrev.clone(),
gene_count: reference_details.genes_by_uniquename.keys().len(),
genotype_count: reference_details.genotypes_by_uniquename.keys().len(),
};
Some(reference_short)
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: term_details.is_obsolete,
gene_count: term_details.genes_by_uniquename.keys().len(),
genotype_count: term_details.genotypes_by_uniquename.keys().len(),
}
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &String, cvterm_name: &String) {
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &String, product: &String) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = {
let mut new_ext = extension_parts.clone();
let compare_ext_part_func =
|e1: &ExtPart, e2: &ExtPart| compare_ext_part_with_config(&self.config, e1, e2);
new_ext.sort_by(compare_ext_part_func);
new_ext
};
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert(
vec![]
).push(Rc::new(ont_annotation_detail));
}
fn process_dbxrefs(&mut self) {
let mut map = HashMap::new();
for feature_dbxref in self.raw.feature_dbxrefs.iter() {
let feature = &feature_dbxref.feature;
let dbxref = &feature_dbxref.dbxref;
map.entry(feature.uniquename.clone())
.or_insert(HashSet::new())
.insert(dbxref.identifier());
}
self.dbxrefs_of_features = map;
}
fn process_references(&mut self) {
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
let mut pubmed_authors: Option<String> = None;
let mut pubmed_publication_date: Option<String> = None;
let mut pubmed_abstract: Option<String> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(",") {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
authors_abbrev = Some(author_re.replace_all(&authors, "$f et al."));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(date_re.replace_all(&publication_date, "$y"));
}
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev: authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
publication_year: publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
fn make_feature_rel_maps(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
self.transcript_type_of_genes.insert(object_uniquename.clone(),
subject_type_name.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let expression = get_feat_rel_expression(&feature_rel.subject, feature_rel);
let allele_and_expression =
AlleleAndExpression {
allele_uniquename: subject_uniquename.clone(),
expression: expression,
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert(Vec::new()).push(allele_and_expression);
continue;
}
}
}
}
fn make_location(&self, feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
Some(ChromosomeLocation {
chromosome_name: feature_loc.srcfeature.uniquename.clone(),
start_pos: start_pos,
end_pos: end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
})
},
None => None,
}
}
fn get_feature_dbxrefs(&self, feature: &Feature) -> HashSet<String> {
if let Some(dbxrefs) = self.dbxrefs_of_features.get(&feature.uniquename) {
dbxrefs.clone()
} else {
HashSet::new()
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let location = self.make_location(&feat);
let organism = make_organism(&feat.organism);
let dbxrefs = self.get_feature_dbxrefs(feat);
let mut orfeome_identifier = None;
for dbxref in dbxrefs.iter() {
if dbxref.starts_with("SPD:") {
orfeome_identifier = Some(String::from(&dbxref[4..]));
}
}
let mut uniprot_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "uniprot_identifier" {
uniprot_identifier = prop.value.clone();
break;
}
}
let feature_type =
if let Some(transcript_type) =
self.transcript_type_of_genes.get(&feat.uniquename) {
transcript_type.clone() + " " + &feat.feat_type.name
} else {
feat.feat_type.name.clone()
};
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
organism: organism,
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier: uniprot_identifier,
orfeome_identifier: orfeome_identifier,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs: dbxrefs,
feature_type: feature_type,
characterisation_status: None,
location: location,
gene_neighbourhood: vec![],
cds_location: None,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut background = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
background = prop.value.clone()
}
}
self.genotypes.insert(feat.uniquename.clone(),
GenotypeDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
background: background,
expressed_alleles: vec![],
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles.get(&feat.uniquename).unwrap();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename: gene_uniquename.clone(),
allele_type: allele_type.unwrap(),
description: description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_feature(&mut self, feat: &Feature) {
match &feat.feat_type.name as &str {
"gene" | "pseudogene" =>
self.store_gene_details(feat),
_ => {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.transcripts.insert(feat.uniquename.clone(),
TranscriptDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
});
}
}
}
}
fn process_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name != "genotype" && feat.feat_type.name != "allele" {
self.process_feature(&feat);
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<String, HashSet<String>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert(HashSet::new())
.insert(object_termid.into());
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let mut term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(&feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(&feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: String,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let mut this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
fn add_alleles_to_genotypes(&mut self) {
let mut alleles_to_add: HashMap<String, Vec<ExpressedAllele>> = HashMap::new();
for genotype_uniquename in self.genotypes.keys() {
let allele_uniquenames: Vec<AlleleAndExpression> =
self.alleles_of_genotypes.get(genotype_uniquename).unwrap().clone();
let expressed_allele_vec: Vec<ExpressedAllele> =
allele_uniquenames.iter()
.map(|ref allele_and_expression| {
ExpressedAllele {
allele_uniquename: allele_and_expression.allele_uniquename.clone(),
expression: allele_and_expression.expression.clone(),
}
})
.collect();
alleles_to_add.insert(genotype_uniquename.clone(), expressed_allele_vec);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
genotype_details.expressed_alleles =
alleles_to_add.remove(genotype_uniquename).unwrap();
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in FEATURE_REL_CONFIGS.iter() {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let mut is_inferred_interaction: bool = false;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0).clone();
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) => Some(publication.uniquename.clone()),
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
}
}
if prop.prop_type.name == "is_inferred" {
if let Some(is_inferred_value) = prop.value.clone() {
if is_inferred_value == "yes" {
is_inferred_interaction = true;
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism = {
self.genes.get(subject_uniquename).unwrap().organism.clone()
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism = {
self.genes.get(object_uniquename).unwrap().organism.clone()
};
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction =>
if !is_inferred_interaction {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
{
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
{
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
if rel_name == "interacts_physically" {
other_gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
other_gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_organism: other_gene_organism,
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == gene_details.organism {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == gene_details.organism {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
// for orthologs and paralogs, store the reverse annotation too
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_organism: gene_organism,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == other_gene_details.organism {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism == other_gene_details.organism {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
},
}
}
}
}
for (_, ref_details) in &mut self.references {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for (_, gene_details) in &mut self.genes {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionDisplayNames> {
let ext_configs = &self.config.extension_display_names;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendent_of) = ext_config.if_descendent_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendent_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &String,
genes: &Vec<String>,
maybe_genotype_uniquename: &Option<String>,
reference_uniquename: &Option<String>,
annotation_termid: &String,
extension: &Vec<ExtPart>) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
let (annotation_gene_uniquenames, annotation_genotype_uniquename) =
if maybe_genotype_uniquename.is_some() {
(genes.clone(), maybe_genotype_uniquename.clone())
} else {
(genes.clone(), None)
};
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.clone(),
ext_rel_display_name: reciprocal_display_name,
genes: annotation_gene_uniquenames,
genotype_uniquename: annotation_genotype_uniquename,
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for (_, term_details) in &self.terms {
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
'ANNOTATION: for annotation in &term_annotation.annotations {
if let Some(ref genotype_uniquename) = annotation.genotype {
let genotype = self.genotypes.get(genotype_uniquename).unwrap();
if genotype.expressed_alleles.len() > 1 {
break 'ANNOTATION;
}
}
let new_annotations =
self.make_target_of_for_ext(&term_details.cv_name,
&annotation.genes,
&annotation.genotype,
&annotation.reference,
&term_details.termid,
&annotation.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert(HashSet::new())
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let mut gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn set_deletion_viability(&mut self) {
let mut gene_statuses = HashMap::new();
let viable_termid = &self.config.viability_terms.viable;
let inviable_termid = &self.config.viability_terms.inviable;
for (gene_uniquename, gene_details) in &mut self.genes {
let mut new_status = DeletionViability::Unknown;
if let Some(single_allele_term_annotations) =
gene_details.cv_annotations.get("single_allele_phenotype") {
let mut maybe_viable_conditions: Option<HashSet<TermId>> = None;
let mut maybe_inviable_conditions: Option<HashSet<TermId>> = None;
for term_annotation in single_allele_term_annotations {
'ANNOTATION: for annotation in &term_annotation.annotations {
let genotype_uniquename = annotation.genotype.clone().unwrap();
let genotype = self.genotypes.get(&genotype_uniquename).unwrap();
let allele_uniquename =
genotype.expressed_alleles[0].allele_uniquename.clone();
let allele = self.alleles.get(&allele_uniquename).unwrap();
if allele.allele_type != "deletion" {
continue 'ANNOTATION;
}
let interesting_parents = &term_annotation.term.interesting_parents;
if interesting_parents.contains(viable_termid) {
if let Some(ref mut viable_conditions) =
maybe_viable_conditions {
viable_conditions.extend(annotation.conditions.clone());
} else {
maybe_viable_conditions = Some(annotation.conditions.clone());
}
}
if interesting_parents.contains(inviable_termid) {
if let Some(ref mut inviable_conditions) =
maybe_inviable_conditions {
inviable_conditions.extend(annotation.conditions.clone());
} else {
maybe_inviable_conditions = Some(annotation.conditions.clone());
}
}
}
}
if maybe_viable_conditions.is_none() {
if maybe_inviable_conditions.is_some() {
new_status = DeletionViability::Inviable;
}
} else {
if maybe_inviable_conditions.is_none() {
new_status = DeletionViability::Viable;
} else {
if maybe_viable_conditions == maybe_inviable_conditions {
println!("{} is viable and inviable with conditions: {:?}",
gene_uniquename, maybe_viable_conditions);
} else {
new_status = DeletionViability::DependsOnConditions;
}
}
}
}
gene_statuses.insert(gene_uniquename.clone(), new_status);
}
for (gene_uniquename, status) in &gene_statuses {
if let Some(ref mut gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details.deletion_viability = status.clone();
}
}
}
fn make_all_cv_summaries(&mut self) {
for (_, term_details) in &mut self.terms {
for (_, mut term_annotations) in &mut term_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
true, true, &mut term_annotations);
}
}
for (_, gene_details) in &mut self.genes {
for (_, mut term_annotations) in &mut gene_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
false, true, &mut term_annotations);
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, mut term_annotations) in &mut genotype_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
false, false, &mut term_annotations);
}
}
for (_, reference_details) in &mut self.references {
for (_, mut term_annotations) in &mut reference_details.cv_annotations {
make_cv_summaries(&self.config, &self.children_by_termid,
true, true, &mut term_annotations);
}
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
let cv_config =
self.config.cv_config_by_name(&cvterm.cv.name);
let annotation_feature_type =
cv_config.feature_type.clone();
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
annotation_feature_type: annotation_feature_type,
interesting_parents: HashSet::new(),
termid: cvterm.termid(),
definition: cvterm.definition.clone(),
direct_ancestors: vec![],
is_obsolete: cvterm.is_obsolete,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &String,
ext_rel_name: &String) -> String {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
let re = Regex::new("_").unwrap();
re.replace_all(&ext_rel_name, " ")
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = String::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
ExtRange::Gene(ext_range)
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: String::from(ext_rel_name),
rel_type_display_name: rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
} else {
let object_term_short =
self.make_term_short(&object_term.termid());
if let Some(ref mut subject_term_details) = self.terms.get_mut(&subject_term.termid()) {
subject_term_details.direct_ancestors.push(TermAndRelation {
termid: object_term_short.termid.clone(),
term_name: object_term_short.name.clone(),
relation_name: rel_type.name.clone(),
});
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
self.parts_of_extensions.entry(subject_termid)
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name: rel_type_display_name,
ext_range: ExtRange::Term(object_term.termid().clone()),
});
} else {
panic!("can't find details for {}\n", object_term.termid());
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in self.raw.feature_synonyms.iter() {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn make_genotype_short(&self, genotype_uniquename: &str) -> GenotypeShort {
let details = self.genotypes.get(genotype_uniquename).unwrap().clone();
GenotypeShort {
uniquename: details.uniquename,
name: details.name,
background: details.background,
expressed_alleles: details.expressed_alleles,
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles.get(allele_uniquename).unwrap().clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if cvterm.cv.name == "PomBase gene products" {
if feature.feat_type.name == "polypeptide" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: &String) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value.clone())
} else {
ExtRange::Misc(prod_value.clone())
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range: ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &String) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
String::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range: ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: String) -> WithFromValue {
let db_prefix_patt = String::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = re.replace_all(&with_or_from_value, "");
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(&with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(&with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value)
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &String, evidence_code: Option<String>,
extension: &mut Vec<ExtPart>,
with_value: String) -> WithFromValue {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if evidence_code.is_some() &&
evidence_code.unwrap() == "IPI" &&
(base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents
.contains("GO:0005515")) {
extension.push(self.get_with_extension(&with_value));
} else {
return self.make_with_or_from_value(with_value);
}
WithFromValue::None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<String, String> = HashMap::new();
let mut conditions: HashSet<TermId> = HashSet::new();
let mut with: WithFromValue = WithFromValue::None;
let mut from: WithFromValue = WithFromValue::None;
let mut qualifiers: Vec<Qualifier> = vec![];
let mut evidence: Option<String> = None;
let mut raw_with_value: Option<String> = None;
for ref prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"evidence" =>
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.insert(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"with" => {
raw_with_value = prop.value.clone();
},
"from" => {
if let Some(value) = prop.value.clone() {
from = self.make_with_or_from_value(value);
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(&value));
}
},
_ => ()
}
}
if let Some(value) = raw_with_value {
let with_gene_short =
self.make_with_extension(&cvterm.termid(), evidence.clone(),
&mut extension, value);
if with_gene_short.is_some() {
with = with_gene_short;
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let genotype_short = self.make_genotype_short(&feature.uniquename);
maybe_genotype_uniquename = Some(genotype_short.uniquename.clone());
genotype_short.expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
gene_uniquenames_vec =
gene_uniquenames_vec.iter().map(|gene_uniquename: &String| {
self.make_gene_short(&gene_uniquename).uniquename
}).collect();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell: copies_per_cell,
avg_copies_per_cell: avg_copies_per_cell,
scale: scale,
})
} else {
None
};
let annotation = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
genes: gene_uniquenames_vec,
reference: reference_uniquename.clone(),
genotype: maybe_genotype_uniquename.clone(),
with: with.clone(),
from: from.clone(),
residue: extra_props_clone.remove("residue"),
gene_ex_props: gene_ex_props,
qualifiers: qualifiers.clone(),
evidence: evidence.clone(),
conditions: conditions.clone(),
extension: extension.clone(),
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation);
}
}
fn make_term_annotations(&self, termid: &str, details: &Vec<Rc<OntAnnotationDetail>>,
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_short = self.make_term_short(termid);
let cv_name = term_short.cv_name.clone();
match cv_name.as_ref() {
"gene_ex" => {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut quant_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for detail in details {
if detail.gene_ex_props.is_some() {
quant_annotations.annotations.push(detail.clone())
} else {
qual_annotations.annotations.push(detail.clone())
}
}
let mut return_vec = vec![];
if qual_annotations.annotations.len() > 0 {
return_vec.push((String::from("qualitative_gene_expression"),
qual_annotations));
}
if quant_annotations.annotations.len() > 0 {
return_vec.push((String::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
},
"fission_yeast_phenotype" => {
let mut single_allele =
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut multi_allele =
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for detail in details {
let genotype_uniquename = detail.genotype.clone().unwrap();
if let Some(genotype_details) = self.genotypes.get(&genotype_uniquename) {
if genotype_details.expressed_alleles.len() == 1 {
single_allele.annotations.push(detail.clone())
} else {
multi_allele.annotations.push(detail.clone())
}
} else {
panic!("can't find genotype details for {}\n", genotype_uniquename);
}
}
let mut return_vec = vec![];
if single_allele.annotations.len() > 0 {
return_vec.push((String::from("single_allele_phenotype"),
single_allele));
}
if multi_allele.annotations.len() > 0 {
return_vec.push((String::from("multi_allele_phenotype"),
multi_allele));
}
return_vec
},
_ => {
vec![(cv_name,
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: details.clone(),
summary: None,
})]
}
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotations = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<String, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
for (termid, annotations) in ont_annotations {
let mut sorted_annotations = annotations.clone();
{
let cmp_detail_with_maps =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &self.genes,
&self.genotypes, &self.alleles,
&self.terms)
};
sorted_annotations.sort_by(cmp_detail_with_maps);
}
// genotype annotations are stored in all_ont_annotations
// once for each gene mentioned in the genotype - this set is
// used to avoid adding an annotation multiple times to a
// GenotypeDetails
let mut seen_annotations_for_term = HashSet::new();
let annotations_for_term: Vec<Rc<OntAnnotationDetail>> =
sorted_annotations.iter().cloned()
.filter(|annotation|
if seen_annotations_for_term.contains(&annotation.id) {
false
} else {
seen_annotations_for_term.insert(annotation.id);
true
}).collect();
let new_annotations =
self.make_term_annotations(&termid, &annotations_for_term, is_not);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
for (cv_name, new_annotation) in new_annotations {
term_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
for detail in sorted_annotations {
for gene_uniquename in &detail.genes {
gene_annotation_by_term.entry(gene_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
if let Some(ref genotype_uniquename) = detail.genotype {
let mut existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![]);
if !existing.contains(&detail) {
existing.push(detail.clone());
}
}
if let Some(reference_uniquename) = detail.reference.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
for condition_termid in &detail.conditions {
let condition_term_short = {
self.make_term_short(&condition_termid)
};
let cv_name = condition_term_short.cv_name.clone();
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
condition_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: condition_term_short.clone(),
is_not: is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
condition_term_details.cv_annotations.get_mut(&cv_name)
.unwrap()[0]
.annotations.push(detail.clone());
}
}
}
}
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (_, mut cv_annotations) in &mut gene_details.cv_annotations {
cv_annotations.sort()
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (_, mut cv_annotations) in &mut details.cv_annotations {
cv_annotations.sort()
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert(Vec::new())
.push(new_annotation.clone());
}
}
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (_, mut term_annotations) in &mut ref_details.cv_annotations {
term_annotations.sort()
}
}
}
// return true if the term could or should appear in the interesting_parents
// field of the TermDetails and TermShort structs
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
return self.possible_interesting_parents.contains(&InterestingParent {
termid: termid.into(),
rel_name: rel_name.into(),
});
}
fn process_cvtermpath(&mut self) {
let mut annotation_by_id: HashMap<i32, Rc<OntAnnotationDetail>> = HashMap::new();
let mut new_annotations: HashMap<TermId, HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
let mut children_by_termid: HashMap<TermId, HashSet<TermId>> = HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if rel_term_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) {
continue;
}
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) {
continue;
}
if subject_term_details.cv_annotations.keys().len() > 0 {
if let Some(object_term_details) = self.terms.get(&object_termid) {
if object_term_details.cv_annotations.keys().len() > 0 {
children_by_termid
.entry(object_termid.clone())
.or_insert(HashSet::new())
.insert(subject_termid.clone());
}
}
}
for (_, term_annotations) in &subject_term_details.cv_annotations {
for term_annotation in term_annotations {
for detail in &term_annotation.annotations {
if !annotation_by_id.contains_key(&detail.id) {
annotation_by_id.insert(detail.id, detail.clone());
}
let dest_termid = object_termid.clone();
let source_termid = subject_termid.clone();
if !term_annotation.is_not {
new_annotations.entry(dest_termid)
.or_insert(HashMap::new())
.entry(source_termid)
.or_insert(HashMap::new())
.entry(detail.id)
.or_insert(HashSet::new())
.insert(rel_term_name.clone());
}
}
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for (dest_termid, dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_details: Vec<Rc<OntAnnotationDetail>> = vec![];
let mut all_rel_names: HashSet<String> = HashSet::new();
for (id, rel_names) in source_annotations_map {
let detail = annotation_by_id.get(&id).unwrap().clone();
new_details.push(detail);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
{
let cmp_detail_with_genotypes =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &self.genes,
&self.genotypes, &self.alleles, &self.terms)
};
new_details.sort_by(cmp_detail_with_genotypes);
}
let new_annotations =
self.make_term_annotations(&source_termid, &new_details, false);
let mut dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
for (cv_name, new_annotation) in new_annotations {
let mut new_annotation_clone = new_annotation.clone();
new_annotation_clone.rel_names.extend(all_rel_names.clone());
dest_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation_clone);
}
}
}
self.children_by_termid = children_by_termid;
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
const PKG_NAME: &'static str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: String::from(PKG_NAME),
export_prog_version: String::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
}
}
pub fn make_search_api_maps(&self) -> SearchAPIMaps {
let mut gene_summaries: Vec<GeneSummary> = vec![];
let load_org_full_name = self.config.load_organism.full_name();
for (gene_uniquename, gene_details) in &self.genes {
let gene_genus_species = String::new() +
&gene_details.organism.genus + "_" + &gene_details.organism.species;
if gene_genus_species == load_org_full_name {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
}
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_name_genes: HashMap<TermName, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
term_summaries.insert(self.make_term_short(&termid));
for gene_uniquename in term_details.genes_by_uniquename.keys() {
termid_genes.entry(termid.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
term_name_genes.entry(term_details.name.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
}
}
SearchAPIMaps {
gene_summaries: gene_summaries,
termid_genes: termid_genes,
term_name_genes: term_name_genes,
term_summaries: term_summaries,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &String,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<String, ReferenceShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_terms: &mut HashMap<String, TermShortMap>) {
for (_, feat_annotations) in cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
self.add_ref_to_hash(seen_references,
identifier.clone(), detail.reference.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(seen_terms,
identifier.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
self.add_genotype_to_hash(seen_genotypes, seen_alleles, seen_genes,
identifier.clone(),
&genotype_uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (termid, term_details) in &self.terms {
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
for detail in &term_annotation.annotations {
for gene_uniquename in &detail.genes {
self.add_gene_to_hash(&mut seen_genes, termid.clone(), gene_uniquename.clone());
}
self.add_ref_to_hash(&mut seen_references, termid.clone(), detail.reference.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles,
&mut seen_genes, termid.clone(),
&genotype_uniquename);
}
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), interaction.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), ortholog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), paralog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
for target_of_annotation in &gene_details.target_of_annotations {
for annotation_gene_uniquename in &target_of_annotation.genes {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(),
annotation_gene_uniquename.clone());
}
if let Some(ref annotation_genotype_uniquename) = target_of_annotation.genotype_uniquename {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
gene_uniquename.clone(),
&annotation_genotype_uniquename.clone())
}
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(),
target_of_annotation.reference_uniquename.clone());
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
type GeneShortMap = HashMap<GeneUniquename, GeneShort>;
let mut seen_genes: HashMap<String, GeneShortMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
type TermShortMap = HashMap<TermId, TermShort>;
let mut seen_terms: HashMap<GeneUniquename, TermShortMap> = HashMap::new();
{
for (reference_uniquename, reference_details) in &self.references {
for (_, feat_annotations) in &reference_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
for gene_uniquename in &detail.genes {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(),
gene_uniquename.clone())
}
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, reference_uniquename.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, reference_uniquename.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype {
let genotype = self.make_genotype_short(genotype_uniquename);
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
reference_uniquename.clone(),
&genotype.uniquename);
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &reference_details.paralog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, reference_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut term_seen_single_allele_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
let mut seen_single_allele_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for (_, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
for annotation in &term_annotation.annotations {
for gene_uniquename in &annotation.genes {
seen_genes.insert(gene_uniquename.clone());
}
if let Some(ref genotype_uniquename) = annotation.genotype {
seen_genotypes.insert(genotype_uniquename.clone());
let genotype = self.genotypes.get(genotype_uniquename).unwrap();
if genotype.expressed_alleles.len() == 1 {
seen_single_allele_genotypes.insert(genotype_uniquename.clone());
}
}
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
term_seen_single_allele_genotypes.insert(termid.clone(), seen_single_allele_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for (_, rel_annotations) in &reference_details.cv_annotations {
for rel_annotation in rel_annotations {
for annotation in &rel_annotation.annotations {
if !rel_annotation.is_not {
for gene_uniquename in &annotation.genes {
seen_genes.insert(gene_uniquename.clone());
}
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for (_, gene_details) in &mut self.genes {
for (_, feat_annotations) in &mut gene_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.gene_count =
term_seen_genes.get(&feat_annotation.term.termid).unwrap().len();
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut gene_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, feat_annotations) in &mut genotype_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
}
for (_, ref_details) in &mut self.references {
for (_, ref_annotations) in &mut ref_details.cv_annotations {
for ref_annotation in ref_annotations {
ref_annotation.term.gene_count =
term_seen_genes.get(&ref_annotation.term.termid).unwrap().len();
ref_annotation.term.genotype_count =
term_seen_genotypes.get(&ref_annotation.term.termid).unwrap().len();
}
}
}
for (_, term_details) in &mut self.terms {
for (_, term_annotations) in &mut term_details.cv_annotations {
for term_annotation in term_annotations {
term_annotation.term.gene_count =
term_seen_genes.get(&term_annotation.term.termid).unwrap().len();
term_annotation.term.genotype_count =
term_seen_genotypes.get(&term_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut term_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
term_details.single_allele_genotype_uniquenames =
term_seen_single_allele_genotypes.remove(&term_details.termid).unwrap();
}
}
pub fn get_web_data(&mut self) -> WebData {
self.process_dbxrefs();
self.process_references();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.add_alleles_to_genotypes();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_deletion_viability();
self.make_all_cv_summaries();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
let mut web_data_terms: IdRcTermDetailsMap = HashMap::new();
let search_api_maps = self.make_search_api_maps();
for (termid, term_details) in self.terms.drain() {
web_data_terms.insert(termid.clone(), Rc::new(term_details));
}
self.terms = HashMap::new();
let mut used_terms: IdRcTermDetailsMap = HashMap::new();
// remove terms with no annotation
for (termid, term_details) in &web_data_terms {
if term_details.cv_annotations.keys().len() > 0 {
used_terms.insert(termid.clone(), term_details.clone());
}
}
let metadata = self.make_metadata();
WebData {
genes: self.genes.clone(),
genotypes: self.genotypes.clone(),
terms: web_data_terms,
used_terms: used_terms,
metadata: metadata,
references: self.references.clone(),
search_api_maps: search_api_maps,
}
}
}
#[allow(dead_code)]
fn get_test_config() -> Config {
let mut config = Config {
load_organism: ConfigOrganism {
genus: String::from("Schizosaccharomyces"),
species: String::from("pombe"),
},
extension_display_names: vec![],
extension_relation_order: RelationOrder {
relation_order: vec![
String::from("directly_positively_regulates"),
String::from("has_direct_input"),
String::from("involved_in"),
String::from("occurs_at"),
String::from("occurs_in"),
String::from("added_by"),
String::from("added_during"),
String::from("has_penetrance"),
],
always_last: vec![String::from("happens_during"),
String::from("exists_during")],
},
evidence_types: HashMap::new(),
cv_config: HashMap::new(),
interesting_parents: vec![],
viability_terms: ViabilityTerms {
viable: "FYPO:0002058".into(),
inviable: "FYPO:0002059".into(),
},
};
config.cv_config.insert(String::from("molecular_function"),
CvConfig {
feature_type: String::from("Gene"),
filters: vec![],
summary_relations_to_hide: vec![],
summary_gene_relations_to_collect: vec![String::from("has_substrate")],
});
config
}
#[test]
fn test_compare_ext_part_with_config() {
let config = get_test_config();
let mut ext_part1 = ExtPart {
rel_type_name: String::from("has_direct_input"),
rel_type_display_name: String::from("NA"),
ext_range: ExtRange::Misc(String::from("misc_ext_part_1")),
};
let mut ext_part2 = ExtPart {
rel_type_name: String::from("has_direct_input"),
rel_type_display_name: String::from("NA"),
ext_range: ExtRange::Misc(String::from("misc_ext_part_2")),
};
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
ext_part1.rel_type_name = "directly_positively_regulates".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "has_direct_input".into();
ext_part2.rel_type_name = "directly_positively_regulates".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part2.rel_type_name = "absent_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part2.rel_type_name = "misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "other_misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "other_misc_rel".into();
ext_part2.rel_type_name = "other_misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "misc_rel".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "has_direct_input".into();
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "has_direct_input".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Greater);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "exists_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Less);
ext_part1.rel_type_name = "happens_during".into();
ext_part2.rel_type_name = "happens_during".into();
assert_eq!(compare_ext_part_with_config(&config, &ext_part1, &ext_part2),
Ordering::Equal);
}
#[allow(dead_code)]
fn make_test_ext_part(rel_type_name: &str, rel_type_display_name: &str,
ext_range: ExtRange) -> ExtPart {
ExtPart {
rel_type_name: rel_type_name.into(),
rel_type_display_name: rel_type_display_name.into(),
ext_range: ext_range,
}
}
#[allow(dead_code)]
fn get_test_annotations() -> Vec<OntTermAnnotations> {
let annotations1 =
vec![
make_one_detail(188448, "SPBC11B10.09", "PMID:3322810", None,
"IDA", vec![], HashSet::new()),
make_one_detail(202017,"SPBC11B10.09", "PMID:2665944", None,
"IDA", vec![], HashSet::new()),
];
let ont_term1 = OntTermAnnotations {
term: TermShort {
name: "cyclin-dependent protein kinase activity".into(),
cv_name: "molecular_function".into(),
interesting_parents: HashSet::from_iter(vec!["GO:0003824".into()]),
termid: "GO:0097472".into(),
is_obsolete: false,
gene_count: 6,
genotype_count: 0
},
is_not: false,
rel_names: HashSet::new(),
annotations: annotations1,
summary: None,
};
let annotations2 =
vec![
make_one_detail(41717, "SPBC11B10.09", "PMID:9242669", None,
"IDA",vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC646.13".into())), // sds23
], HashSet::new()),
make_one_detail(41718, "SPBC11B10.09", "PMID:9490630", None,
"IDA", vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPAC25G10.07c".into())), // cut7
], HashSet::new()),
make_one_detail(41718, "SPBC11B10.09", "PMID:11937031", None,
"IDA", vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC32F12.09".into())), // no name
], HashSet::new()),
make_one_detail(187893, "SPBC11B10.09", "PMID:19523829", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC6B1.04".into())), // mde4
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1902845".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
make_one_detail(187907, "SPBC11B10.09", "PMID:19523829", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC6B1.04".into())), // mde4
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:0098783".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
make_one_detail(193221, "SPBC11B10.09", "PMID:10921876", None, "IMP",
vec![
make_test_ext_part("directly_negatively_regulates", "directly inhibits",
ExtRange::Gene("SPAC144.13c".into())), // srw1
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1903693".into())),
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1905785".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000080".into())),
],
HashSet::new()),
make_one_detail(194213, "SPBC11B10.09", "PMID:7957097", None, "IDA",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC776.02c".into())), // dis2
],
HashSet::new()),
make_one_detail(194661, "SPBC11B10.09", "PMID:10485849", None, "IMP",
vec![
make_test_ext_part("has_direct_input", "has substrate",
ExtRange::Gene("SPBC146.03c".into())), // cut3
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1903380".into())),
make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:0042307".into())),
make_test_ext_part("happens_during", "during",
ExtRange::Term("GO:0000089".into())),
],
HashSet::new()),
];
let ont_term2 = OntTermAnnotations {
term: TermShort {
name: "cyclin-dependent protein serine/threonine kinase activity".into(),
cv_name: "molecular_function".into(),
gene_count: 5,
genotype_count: 0,
interesting_parents: HashSet::from_iter(vec!{"GO:0003824".into()}),
is_obsolete: false,
termid: "GO:0004693".into(),
},
is_not: false,
rel_names: HashSet::new(),
annotations: annotations2,
summary: None,
};
vec![ont_term1, ont_term2]
}
#[allow(dead_code)]
fn make_one_detail(id: i32, gene_uniquename: &str, reference_uniquename: &str,
maybe_genotype_uniquename: Option<&str>, evidence: &str,
extension: Vec<ExtPart>,
conditions: HashSet<TermId>) -> Rc<OntAnnotationDetail> {
Rc::new(OntAnnotationDetail {
id: id,
genes: vec![gene_uniquename.into()],
genotype: maybe_genotype_uniquename.map(str::to_string),
reference: Some(reference_uniquename.into()),
evidence: Some(evidence.into()),
with: WithFromValue::None,
from: WithFromValue::None,
residue: None,
qualifiers: vec![],
extension: extension,
gene_ex_props: None,
conditions: conditions,
})
}
#[allow(dead_code)]
fn get_test_fypo_term_details() -> Vec<Rc<OntAnnotationDetail>> {
let mut test_conditions = HashSet::new();
test_conditions.insert("PECO:0000103".into());
test_conditions.insert("PECO:0000137".into());
vec![
make_one_detail(223656,
"SPBC16A3.11",
"PMID:23050226",
Some("e674fe7ceba478aa-genotype-2"),
"Cell growth assay",
vec![],
test_conditions.clone()),
make_one_detail(201099,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-4"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(201095,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-3"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(204063,
"SPAC25A8.01c",
"PMID:25798942",
Some("fd4f3f52f1d38106-genotype-4"),
"Cell growth assay",
vec![],
test_conditions.clone()),
make_one_detail(227452,
"SPAC3G6.02",
"PMID:25306921",
Some("a6d8f45c20c2227d-genotype-9"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(201094,
"SPCC1919.10c",
"PMID:16421926",
Some("d6c914796c35e3b5-genotype-2"),
"Cell growth assay",
vec![],
HashSet::new()),
make_one_detail(186589,
"SPAC24H6.05",
"PMID:1464319",
Some("65c76fa511461156-genotype-3"),
"Cell growth assay",
vec![],
test_conditions)]
}
#[allow(dead_code)]
fn make_one_genotype(uniquename: &str, name: Option<&str>,
expressed_alleles: Vec<ExpressedAllele>) -> GenotypeDetails {
GenotypeDetails {
uniquename: uniquename.into(),
name: name.map(str::to_string),
background: None,
expressed_alleles: expressed_alleles,
cv_annotations: HashMap::new(),
references_by_uniquename: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn make_test_gene(uniquename: &str, name: Option<&str>) -> GeneDetails {
GeneDetails {
uniquename: uniquename.into(),
name: name.map(str::to_string),
organism: ConfigOrganism {
genus: "Schizosaccharomyces".into(),
species: "pombe".into(),
},
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier: None,
orfeome_identifier: None,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs: HashSet::new(),
feature_type: "gene".into(),
characterisation_status: None,
location: None,
cds_location: None,
gene_neighbourhood: vec![],
transcripts: vec![],
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
references_by_uniquename: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn get_test_genes_map() -> UniquenameGeneMap {
let mut ret = HashMap::new();
let gene_data =
vec![("SPBC11B10.09", Some("cdc2")),
("SPAC144.13c", Some("srw1")),
("SPAC25G10.07c", Some("cut7")),
("SPBC146.03c", Some("cut3")),
("SPBC32F12.09", None),
("SPBC646.13", Some("sds23")),
("SPBC6B1.04", Some("mde4")),
("SPBC776.02c", Some("dis2"))];
for (uniquename, name) in gene_data {
ret.insert(uniquename.into(), make_test_gene(uniquename, name));
}
ret
}
#[allow(dead_code)]
fn get_test_genotypes_map() -> UniquenameGenotypeMap {
let mut ret = HashMap::new();
ret.insert(String::from("e674fe7ceba478aa-genotype-2"),
make_one_genotype(
"e674fe7ceba478aa-genotype-2",
Some("test genotype name"),
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPBC16A3.11:allele-7".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-4"),
make_one_genotype(
"d6c914796c35e3b5-genotype-4",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-5".into(),
}
]
));
ret.insert(String::from("65c76fa511461156-genotype-3"),
make_one_genotype(
"65c76fa511461156-genotype-3",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPAC24H6.05:allele-3".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-2"),
make_one_genotype(
"d6c914796c35e3b5-genotype-2",
Some("ZZ-name"),
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-4".into(),
}
]
));
ret.insert(String::from("d6c914796c35e3b5-genotype-3"),
make_one_genotype(
"d6c914796c35e3b5-genotype-3",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPCC1919.10c:allele-6".into(),
}
]
));
ret.insert(String::from("fd4f3f52f1d38106-genotype-4"),
make_one_genotype(
"fd4f3f52f1d38106-genotype-4",
None,
vec![
ExpressedAllele {
expression: Some("Wild type product level".into()),
allele_uniquename: "SPAC25A8.01c:allele-5".into(),
}
]
));
ret.insert(String::from("a6d8f45c20c2227d-genotype-9"),
make_one_genotype(
"a6d8f45c20c2227d-genotype-9",
None,
vec![
ExpressedAllele {
expression: Some("Not assayed".into()),
allele_uniquename: "SPAC3G6.02:allele-7".into(),
}
]
));
ret
}
#[allow(dead_code)]
fn make_one_allele_short(uniquename: &str, name: &str, allele_type: &str,
description: Option<&str>, gene_uniquename: &str) -> AlleleShort {
AlleleShort {
uniquename: uniquename.into(),
description: description.map(str::to_string),
name: Some(name.into()),
allele_type: allele_type.into(),
gene_uniquename: gene_uniquename.into(),
}
}
#[allow(dead_code)]
fn get_test_alleles_map() -> UniquenameAlleleMap {
let mut ret = HashMap::new();
ret.insert(String::from("SPCC1919.10c:allele-4"),
make_one_allele_short("SPCC1919.10c:allele-4", "ATPase dead mutant", "unknown", None, "SPCC1919.10c"));
ret.insert(String::from("SPCC1919.10c:allele-5"),
make_one_allele_short("SPCC1919.10c:allele-5", "C-terminal truncation 940-1516", "partial_amino_acid_deletion",
Some("940-1516"), "SPCC1919.10c"));
ret.insert(String::from("SPCC1919.10c:allele-6"),
make_one_allele_short("SPCC1919.10c:allele-6", "C-terminal truncation", "partial_amino_acid_deletion", Some("1320-1516"),
"SPCC1919.10c"));
ret.insert(String::from("SPBC16A3.11:allele-7"),
make_one_allele_short("SPBC16A3.11:allele-7", "G799D", "amino_acid_mutation", Some("G799D"), "SPBC16A3.11"));
ret.insert(String::from("SPAC25A8.01c:allele-5"),
make_one_allele_short("SPAC25A8.01c:allele-5", "K418R", "amino_acid_mutation", Some("K418R"), "SPAC25A8.01c"));
ret.insert(String::from("SPAC3G6.02:allele-7"),
make_one_allele_short("SPAC3G6.02:allele-7", "UBS-I&II", "amino_acid_mutation", Some("F18A,F21A,W26A,L40A,W41A,W45A"), "SPAC3G6.02"));
ret.insert(String::from("SPAC24H6.05:allele-3"),
make_one_allele_short("SPAC24H6.05:allele-3", "cdc25-22", "amino_acid_mutation", Some("C532Y"), "SPAC24H6.05"));
ret
}
#[allow(dead_code)]
fn make_test_term_details(id: &str, name: &str, cv_name: &str) -> TermDetails {
TermDetails {
termid: id.into(),
name: name.into(),
cv_name: cv_name.into(),
annotation_feature_type: "gene".into(),
interesting_parents: HashSet::new(),
definition: None,
direct_ancestors: vec![],
is_obsolete: false,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
}
}
#[allow(dead_code)]
fn get_test_terms_map() -> TermIdDetailsMap {
let mut ret = HashMap::new();
let term_data = vec![
("GO:0022403", "cell cycle phase", "biological_process"),
("GO:0051318", "G1 phase", "biological_process"),
("GO:0000080", "mitotic G1 phase", "biological_process"),
("GO:0088888", "fake child of mitotic G1 phase", "biological_process"),
("GO:0000089", "mitotic metaphase", "biological_process"),
("GO:0099999", "fake child of mitotic metaphase term", "biological_process"),
("GO:0042307", "positive regulation of protein import into nucleus", "biological_process"),
("GO:0098783", "correction of merotelic kinetochore attachment, mitotic", "biological_process"),
("GO:1902845", "negative regulation of mitotic spindle elongation", "biological_process"),
("GO:1903380", "positive regulation of mitotic chromosome condensation", "biological_process"),
("GO:1903693", "regulation of mitotic G1 cell cycle arrest in response to nitrogen starvation", "biological_process"),
("GO:1905785", "negative regulation of anaphase-promoting complex-dependent catabolic process", "biological_process"),
];
for (id, name, cv_name) in term_data {
ret.insert(id.into(), make_test_term_details(id, name, cv_name));
}
ret
}
#[test]
fn test_cmp_ont_annotation_detail() {
let mut details_vec = get_test_fypo_term_details();
let genes = get_test_genes_map();
let genotypes = get_test_genotypes_map();
let alleles = get_test_alleles_map();
let terms = get_test_terms_map();
let cmp_detail_with_genotypes =
|annotation1: &Rc<OntAnnotationDetail>, annotation2: &Rc<OntAnnotationDetail>| {
cmp_ont_annotation_detail(annotation1, annotation2, &genes,
&genotypes, &alleles, &terms)
};
details_vec.sort_by(&cmp_detail_with_genotypes);
let expected: Vec<String> =
vec!["C-terminal truncation 940-1516(940-1516)",
"C-terminal truncation(1320-1516)",
"cdc25-22(C532Y)",
"K418R(K418R)",
"test genotype name",
"UBS-I&II(F18A,F21A,W26A,L40A,W41A,W45A)",
"ZZ-name"]
.iter().map(|s| str::to_string(s)).collect();
assert_eq!(details_vec.drain(0..)
.map(|detail| {
let genotype_uniquename: String =
(*detail).clone().genotype.unwrap();
let genotype = genotypes.get(&genotype_uniquename).unwrap();
genotype_display_name(&genotype, &alleles)
}).collect::<Vec<String>>(),
expected);
let test_term_annotations = get_test_annotations();
let mut extension_details_vec = test_term_annotations[1].annotations.clone();
extension_details_vec.sort_by(&cmp_detail_with_genotypes);
let annotation_sort_results: Vec<(String, String)> =
extension_details_vec.iter().map(|detail| {
((*detail).genes[0].clone(),
(*detail).reference.clone().unwrap())
}).collect();
let expected_annotation_sort: Vec<(String, String)> =
vec![("SPBC11B10.09", "PMID:10921876"),
("SPBC11B10.09", "PMID:10485849" /* has_direct_input(cut3) */),
("SPBC11B10.09", "PMID:9490630" /* has_direct_input(cut7) */),
("SPBC11B10.09", "PMID:7957097" /* has_direct_input(dis2) */),
("SPBC11B10.09", "PMID:19523829" /* has_direct_input(mde4), part_of(...), happens_during(...) */),
("SPBC11B10.09", "PMID:19523829" /* has_direct_input(mde4), part_of(...), happens_during(...) */),
("SPBC11B10.09", "PMID:9242669" /* has_direct_input(sds23) */),
("SPBC11B10.09", "PMID:11937031" /* has_direct_input(SPBC32F12.09) */),
]
.iter()
.map(|&(gene, reference)|
(gene.into(), reference.into())).collect();
assert_eq![annotation_sort_results, expected_annotation_sort];
}
#[allow(dead_code)]
fn make_term_short_from_details(term_details: &TermDetails) -> TermShort {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: false,
gene_count: 0,
genotype_count: 0
}
}
#[allow(dead_code)]
fn make_test_summary(termid: &str, rows: Vec<TermSummaryRow>) -> OntTermAnnotations {
let terms = get_test_terms_map();
OntTermAnnotations {
term: make_term_short_from_details(&terms.get(termid).unwrap().clone()),
is_not: false,
annotations: vec![],
rel_names: HashSet::new(),
summary: Some(rows),
}
}
#[allow(dead_code)]
fn get_test_summaries() -> Vec<OntTermAnnotations> {
let mut summaries = vec![];
let ext = make_test_ext_part("part_of", "involved in",
ExtRange::Term("GO:1905785".into()));
let ext2 = make_test_ext_part("some_rel", "some_rel_display_name",
ExtRange::Term("GO:1234567".into()));
summaries.push(make_test_summary("GO:0022403", vec![]));
summaries.push(make_test_summary("GO:0051318",
vec![TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone()],
}]));
summaries.push(make_test_summary("GO:0000080", vec![]));
summaries.push(make_test_summary("GO:0000089",
vec![
TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone()],
}
]));
summaries.push(make_test_summary("GO:0099999",
vec![
TermSummaryRow {
gene_uniquenames: vec![],
genotype_uniquenames: vec![],
extension: vec![ext.clone(), ext2],
}
]));
summaries
}
#[allow(dead_code)]
fn get_test_children_by_termid() -> HashMap<TermId, HashSet<TermId>> {
let mut children_by_termid = HashMap::new();
let mut children_of_0022403 = HashSet::new();
children_of_0022403.insert("GO:0051318".into());
children_of_0022403.insert("GO:0000080".into());
children_of_0022403.insert("GO:0088888".into());
children_of_0022403.insert("GO:0000089".into());
children_of_0022403.insert("GO:0099999".into());
let mut children_of_0051318 = HashSet::new();
children_of_0051318.insert("GO:0000080".into());
children_of_0051318.insert("GO:0088888".into());
children_of_0051318.insert("GO:0000089".into());
children_of_0051318.insert("GO:0099999".into());
let mut children_of_0000080 = HashSet::new();
children_of_0000080.insert("GO:0088888".into());
let mut children_of_0000089 = HashSet::new();
children_of_0000089.insert("GO:0099999".into());
children_by_termid.insert("GO:0022403".into(), children_of_0022403);
children_by_termid.insert("GO:0051318".into(), children_of_0051318);
children_by_termid.insert("GO:0000080".into(), children_of_0000080);
children_by_termid.insert("GO:0000089".into(), children_of_0000089);
children_by_termid
}
#[test]
fn test_remove_redundant_summaries() {
let mut term_annotations: Vec<OntTermAnnotations> = get_test_summaries();
let children_by_termid = get_test_children_by_termid();
assert_eq!(term_annotations.len(), 5);
remove_redundant_summaries(&children_by_termid, &mut term_annotations);
assert_eq!(term_annotations.iter().filter(|term_annotation| {
term_annotation.summary.is_some()
}).collect::<Vec<&OntTermAnnotations>>().len(), 3);
}
#[test]
fn test_summary_row_equals() {
let r1 = TermSummaryRow {
gene_uniquenames: vec!["SPAPB1A10.09".into()],
genotype_uniquenames: vec![],
extension: vec![],
};
let r2 = TermSummaryRow {
gene_uniquenames: vec!["SPAPB1A10.09".into()],
genotype_uniquenames: vec![],
extension: vec![],
};
assert!(r1 == r2);
}
|
use std::rc::Rc;
use std::collections::hash_map::HashMap;
use std::collections::HashSet;
use std::borrow::Borrow;
use std::cmp::Ordering;
use regex::Regex;
use db::*;
use web::data::*;
use web::config::*;
include!(concat!(env!("OUT_DIR"), "/config_serde.rs"));
fn make_organism_short(rc_organism: &Rc<Organism>) -> OrganismShort {
OrganismShort {
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
}
}
#[derive(Clone)]
pub struct AlleleAndExpression {
allele_uniquename: String,
expression: Option<String>,
}
pub struct WebDataBuild<'a> {
raw: &'a Raw,
config: &'a Config,
genes: UniquenameGeneMap,
transcripts: UniquenameTranscriptMap,
genotypes: UniquenameGenotypeMap,
alleles: UniquenameAlleleMap,
terms: HashMap<TermId, TermDetails>,
references: IdReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
all_not_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
genes_of_transcripts: HashMap<String, String>,
transcripts_of_polypeptides: HashMap<String, String>,
genes_of_alleles: HashMap<String, String>,
alleles_of_genotypes: HashMap<String, Vec<AlleleAndExpression>>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
}
fn get_maps() ->
(HashMap<String, ReferenceShortMap>,
HashMap<String, GeneShortMap>,
HashMap<String, GenotypeShortMap>,
HashMap<String, AlleleShortMap>,
HashMap<GeneUniquename, TermShortMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature_relationship: &FeatureRelationship) -> Option<String> {
for prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "expression" {
return prop.value.clone();
}
}
None
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, config: &'a Config) -> WebDataBuild<'a> {
WebDataBuild {
raw: raw,
config: config,
genes: HashMap::new(),
transcripts: HashMap::new(),
genotypes: HashMap::new(),
alleles: HashMap::new(),
terms: HashMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<String, ReferenceShortMap>,
identifier: String,
maybe_reference_uniquename: Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if let Some(reference_short) = self.make_reference_short(&reference_uniquename) {
seen_references
.entry(identifier.clone())
.or_insert(HashMap::new())
.insert(reference_uniquename.clone(),
reference_short);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
other_gene_uniquename: GeneUniquename) {
seen_genes
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_gene_uniquename.clone(),
self.make_gene_short(&other_gene_uniquename));
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
identifier: String,
genotype_uniquename: &GenotypeUniquename) {
seen_genotypes
.entry(identifier)
.or_insert(HashMap::new())
.insert(genotype_uniquename.clone(),
self.make_genotype_short(genotype_uniquename));
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
identifier: String,
allele_uniquename: AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
seen_alleles
.entry(identifier)
.or_insert(HashMap::new())
.insert(allele_uniquename, allele_short.clone());
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortMap>,
identifier: String,
other_termid: TermId) {
seen_terms
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(&gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(&gene_uniquename);
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
synonyms: gene_details.synonyms.clone(),
feature_type: gene_details.feature_type.clone(),
organism: gene_details.organism.clone(),
location: gene_details.location.clone(),
}
}
fn make_reference_short(&self, reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = self.references.get(reference_uniquename).unwrap();
let reference_short =
ReferenceShort {
uniquename: String::from(reference_uniquename),
title: reference_details.title.clone(),
citation: reference_details.citation.clone(),
publication_year: reference_details.publication_year.clone(),
authors: reference_details.authors.clone(),
authors_abbrev: reference_details.authors_abbrev.clone(),
gene_count: reference_details.genes_by_uniquename.keys().len(),
genotype_count: reference_details.genotypes_by_uniquename.keys().len(),
};
Some(reference_short)
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: term_details.is_obsolete,
gene_count: term_details.genes_by_uniquename.keys().len(),
genotype_count: term_details.genotypes_by_uniquename.keys().len(),
}
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &String, cvterm_name: &String) {
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &String, product: &String) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = extension_parts.clone();
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert(
vec![]
).push(Rc::new(ont_annotation_detail));
}
fn process_references(&mut self) {
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
let mut pubmed_authors: Option<String> = None;
let mut pubmed_publication_date: Option<String> = None;
let mut pubmed_abstract: Option<String> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(",") {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
authors_abbrev = Some(author_re.replace_all(&authors, "$f et al."));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(date_re.replace_all(&publication_date, "$y"));
}
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev: authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
publication_year: publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
fn make_feature_rel_maps(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let allele_and_expression =
AlleleAndExpression {
allele_uniquename: subject_uniquename.clone(),
expression: get_feat_rel_expression(feature_rel),
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert(Vec::new()).push(allele_and_expression);
continue;
}
}
}
}
fn make_location(&self, feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
Some(ChromosomeLocation {
chromosome_name: feature_loc.srcfeature.uniquename.clone(),
start_pos: start_pos,
end_pos: end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
})
},
None => None,
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let location = self.make_location(&feat);
let organism = make_organism_short(&feat.organism);
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
organism: organism,
product: None,
name_descriptions: vec![],
synonyms: vec![],
feature_type: feat.feat_type.name.clone(),
characterisation_status: None,
location: location,
gene_neighbourhood: vec![],
cds_location: None,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut background = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
background = prop.value.clone()
}
}
self.genotypes.insert(feat.uniquename.clone(),
GenotypeDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
background: background,
expressed_alleles: vec![],
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles.get(&feat.uniquename).unwrap();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename: gene_uniquename.clone(),
allele_type: allele_type.unwrap(),
description: description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_feature(&mut self, feat: &Feature) {
match &feat.feat_type.name as &str {
"gene" | "pseudogene" =>
self.store_gene_details(feat),
_ => {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.transcripts.insert(feat.uniquename.clone(),
TranscriptDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
});
}
}
}
}
fn process_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name != "genotype" && feat.feat_type.name != "allele" {
self.process_feature(&feat);
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<String, HashSet<String>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert(HashSet::new())
.insert(object_termid.into());
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let mut term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(&feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(&feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: String,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let mut this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
fn add_alleles_to_genotypes(&mut self) {
let mut alleles_to_add: HashMap<String, Vec<ExpressedAllele>> = HashMap::new();
for genotype_uniquename in self.genotypes.keys() {
let allele_uniquenames: Vec<AlleleAndExpression> =
self.alleles_of_genotypes.get(genotype_uniquename).unwrap().clone();
let expressed_allele_vec: Vec<ExpressedAllele> =
allele_uniquenames.iter()
.map(|ref allele_and_expression| {
ExpressedAllele {
allele_uniquename: allele_and_expression.allele_uniquename.clone(),
expression: allele_and_expression.expression.clone(),
}
})
.collect();
alleles_to_add.insert(genotype_uniquename.clone(), expressed_allele_vec);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
genotype_details.expressed_alleles =
alleles_to_add.remove(genotype_uniquename).unwrap();
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in FEATURE_REL_CONFIGS.iter() {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0).clone();
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) => Some(publication.uniquename.clone()),
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism_short = {
self.genes.get(subject_uniquename).unwrap().organism.clone()
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism_short = {
self.genes.get(object_uniquename).unwrap().organism.clone()
};
{
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_organism: other_gene_organism_short,
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
ref_details.ortholog_annotations.push(ortholog_annotation);
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
{
// for orthologs and paralogs, store the reverses annotation too
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog =>
other_gene_details.ortholog_annotations.push(
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_organism: gene_organism_short,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
}),
FeatureRelAnnotationType::Paralog =>
other_gene_details.paralog_annotations.push(
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename
}),
}
}
}
}
}
for (_, ref_details) in &mut self.references {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for (_, gene_details) in &mut self.genes {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionConfig> {
let ext_configs = &self.config.extensions;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendent_of) = ext_config.if_descendent_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendent_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &String,
gene_uniquename: &String,
reference_uniquename: &Option<String>,
annotation_termid: &String,
extension: &Vec<ExtPart>) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.clone(),
ext_rel_display_name: reciprocal_display_name,
gene_uniquename: gene_uniquename.clone(),
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for (gene_uniquename, gene_details) in &self.genes {
for (cv_name, feat_annotations) in &gene_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
let new_annotations =
self.make_target_of_for_ext(&cv_name, &gene_uniquename,
&detail.reference_uniquename,
&feat_annotation.term.termid, &detail.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert(HashSet::new())
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let mut gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
interesting_parents: HashSet::new(),
termid: cvterm.termid(),
definition: cvterm.definition.clone(),
is_obsolete: cvterm.is_obsolete,
rel_annotations: vec![],
not_rel_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &String,
ext_rel_name: &String) -> String {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
let re = Regex::new("_").unwrap();
re.replace_all(&ext_rel_name, " ")
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = String::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
ExtRange::Gene(ext_range)
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: String::from(ext_rel_name),
rel_type_display_name: rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
self.parts_of_extensions.entry(subject_termid)
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name: rel_type_display_name,
ext_range: ExtRange::Term(object_term.termid().clone()),
});
} else {
panic!("can't find details for {}\n", object_term.termid());
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in self.raw.feature_synonyms.iter() {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn make_genotype_short(&self, genotype_uniquename: &str) -> GenotypeShort {
let details = self.genotypes.get(genotype_uniquename).unwrap().clone();
GenotypeShort {
uniquename: details.uniquename,
name: details.name,
background: details.background,
expressed_alleles: details.expressed_alleles,
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles.get(allele_uniquename).unwrap().clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if feature.feat_type.name == "polypeptide" && cvterm.cv.name == "PomBase gene products" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: &String) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value.clone())
} else {
ExtRange::Misc(prod_value.clone())
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range: ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &String) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
String::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range: ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: String) -> WithFromValue {
let db_prefix_patt = String::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = re.replace_all(&with_or_from_value, "");
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(&with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(&with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value)
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &String, extension: &mut Vec<ExtPart>,
with_value: String) -> WithFromValue {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents
.contains("GO:0005515") {
extension.push(self.get_with_extension(&with_value));
} else {
return self.make_with_or_from_value(with_value);
}
WithFromValue::None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<String, String> = HashMap::new();
let mut conditions: Vec<TermId> = vec![];
let mut with: WithFromValue = WithFromValue::None;
let mut from: WithFromValue = WithFromValue::None;
let mut qualifiers: Vec<Qualifier> = vec![];
let mut evidence: Option<String> = None;
for ref prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"evidence" =>
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.push(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"with" => {
if let Some(value) = prop.value.clone() {
let with_gene_short =
self.make_with_extension(&cvterm.termid(),
&mut extension, value);
if with_gene_short.is_some() {
with = with_gene_short;
}
}
},
"from" => {
if let Some(value) = prop.value.clone() {
from = self.make_with_or_from_value(value);
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(&value));
}
},
_ => ()
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let genotype_short = self.make_genotype_short(&feature.uniquename);
maybe_genotype_uniquename = Some(genotype_short.uniquename.clone());
genotype_short.expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
for gene_uniquename in &gene_uniquenames_vec {
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell: copies_per_cell,
avg_copies_per_cell: avg_copies_per_cell,
scale: scale,
})
} else {
None
};
let annotation = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
gene_uniquename: gene_uniquename.clone(),
reference_uniquename: reference_uniquename.clone(),
genotype_uniquename: maybe_genotype_uniquename.clone(),
with: with.clone(),
from: from.clone(),
residue: extra_props_clone.remove("residue"),
gene_ex_props: gene_ex_props,
qualifiers: qualifiers.clone(),
evidence: evidence.clone(),
conditions: conditions.clone(),
extension: extension.clone(),
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation);
}
}
}
fn make_term_annotations(&self, termid: &str, details: &Vec<Rc<OntAnnotationDetail>>,
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_short = self.make_term_short(termid);
let cv_name = term_short.cv_name.clone();
if cv_name == "gene_ex" {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
annotations: vec![],
};
let mut quant_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
annotations: vec![],
};
for detail in details {
if detail.gene_ex_props.is_some() {
quant_annotations.annotations.push(detail.clone())
} else {
qual_annotations.annotations.push(detail.clone())
}
}
let mut return_vec = vec![];
if qual_annotations.annotations.len() > 0 {
return_vec.push((String::from("qualitative_gene_expression"),
qual_annotations));
}
if quant_annotations.annotations.len() > 0 {
return_vec.push((String::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
} else {
vec![(cv_name,
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
annotations: details.clone(),
})]
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotations = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<String, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
for (termid, annotations) in ont_annotations {
let term_short = self.make_term_short(termid);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
let new_rel_ont_annotation = RelOntAnnotation {
rel_names: HashSet::new(),
term: term_short.clone(),
annotations: annotations.clone(),
};
if is_not {
term_details.not_rel_annotations.push(new_rel_ont_annotation);
} else {
term_details.rel_annotations.push(new_rel_ont_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
for detail in annotations {
gene_annotation_by_term.entry(detail.gene_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let mut existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![]);
if !existing.contains(detail) {
existing.push(detail.clone());
}
}
if let Some(reference_uniquename) = detail.reference_uniquename.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
for condition_termid in &detail.conditions {
let condition_term_short = {
self.make_term_short(&condition_termid)
};
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
if condition_term_details.rel_annotations.len() == 0 {
condition_term_details.rel_annotations.push(
RelOntAnnotation {
term: condition_term_short,
rel_names: HashSet::new(),
annotations: vec![],
});
}
if let Some(rel_annotation) = condition_term_details.rel_annotations.get_mut(0) {
rel_annotation.annotations.push(detail.clone())
}
}
}
}
}
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (_, mut cv_annotations) in &mut gene_details.cv_annotations {
cv_annotations.sort()
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (_, mut cv_annotations) in &mut details.cv_annotations {
cv_annotations.sort()
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert(Vec::new())
.push(new_annotation.clone());
}
}
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (_, mut term_annotations) in &mut ref_details.cv_annotations {
term_annotations.sort()
}
}
}
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
for parent_conf in INTERESTING_PARENTS.iter() {
if parent_conf.termid == termid &&
parent_conf.rel_name == rel_name {
return true;
}
}
for ext_conf in &self.config.extensions {
if let Some(ref conf_termid) = ext_conf.if_descendent_of {
if conf_termid == termid && rel_name == "is_a" {
return true;
}
}
}
false
}
fn process_cvtermpath(&mut self) {
let mut annotation_by_id: HashMap<i32, Rc<OntAnnotationDetail>> = HashMap::new();
let mut new_annotations: HashMap<TermId, HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
let is_inverse =
INVERSE_REL_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) &&
INVERSE_REL_NAMES.contains(&rel_term_name.as_str());
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) &&
!is_inverse {
continue;
}
let annotations = &subject_term_details.rel_annotations;
for rel_annotation in annotations {
let RelOntAnnotation {
rel_names: _,
term: _,
annotations: existing_details
} = rel_annotation.clone();
for detail in &existing_details {
if !annotation_by_id.contains_key(&detail.id) {
annotation_by_id.insert(detail.id, detail.clone());
}
let (dest_termid, source_termid) =
if is_inverse {
(subject_termid.clone(), object_termid.clone())
} else {
(object_termid.clone(), subject_termid.clone())
};
new_annotations.entry(dest_termid)
.or_insert(HashMap::new())
.entry(source_termid)
.or_insert(HashMap::new())
.entry(detail.id)
.or_insert(HashSet::new())
.insert(rel_term_name.clone());
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for (dest_termid, dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_details: Vec<Rc<OntAnnotationDetail>> = vec![];
let mut all_rel_names: HashSet<String> = HashSet::new();
for (id, rel_names) in source_annotations_map {
let detail = annotation_by_id.get(&id).unwrap().clone();
new_details.push(detail);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
let source_term_short = self.make_term_short(&source_termid);
let mut dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
dest_term_details.rel_annotations.push(RelOntAnnotation {
rel_names: all_rel_names,
term: source_term_short.clone(),
annotations: new_details,
});
}
}
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
const PKG_NAME: &'static str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: String::from(PKG_NAME),
export_prog_version: String::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
}
}
pub fn make_search_api_maps(&self) -> SearchAPIMaps {
let mut gene_summaries: Vec<GeneSummary> = vec![];
let gene_uniquenames: Vec<String> =
self.genes.keys().map(|uniquename| uniquename.clone()).collect();
for gene_uniquename in gene_uniquenames {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_name_genes: HashMap<TermName, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
term_summaries.insert(self.make_term_short(&termid));
for gene_uniquename in term_details.genes_by_uniquename.keys() {
termid_genes.entry(termid.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
term_name_genes.entry(term_details.name.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
}
}
SearchAPIMaps {
gene_summaries: gene_summaries,
termid_genes: termid_genes,
term_name_genes: term_name_genes,
term_summaries: term_summaries,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &String,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<String, ReferenceShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_terms: &mut HashMap<String, TermShortMap>) {
for (_, feat_annotations) in cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
self.add_ref_to_hash(seen_references,
identifier.clone(), detail.reference_uniquename.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(seen_terms,
identifier.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
self.add_allele_to_hash(seen_alleles, identifier.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(seen_genes, identifier.clone(), allele_gene_uniquename);
}
self.add_genotype_to_hash(seen_genotypes, identifier.clone(),
&genotype.uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (termid, term_details) in &self.terms {
for rel_annotation in &term_details.rel_annotations {
for detail in &rel_annotation.annotations {
let gene_uniquename = detail.gene_uniquename.clone();
self.add_gene_to_hash(&mut seen_genes, termid.clone(), gene_uniquename.clone());
self.add_ref_to_hash(&mut seen_references, termid.clone(), detail.reference_uniquename.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
self.add_allele_to_hash(&mut seen_alleles, termid.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(&mut seen_genes, termid.clone(), allele_gene_uniquename);
}
self.add_genotype_to_hash(&mut seen_genotypes, termid.clone(),
&genotype.uniquename);
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), interaction.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), ortholog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), paralog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
for target_of_annotation in &gene_details.target_of_annotations {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(),
target_of_annotation.gene_uniquename.clone());
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(),
target_of_annotation.reference_uniquename.clone());
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
type GeneShortMap = HashMap<GeneUniquename, GeneShort>;
let mut seen_genes: HashMap<String, GeneShortMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
type TermShortMap = HashMap<TermId, TermShort>;
let mut seen_terms: HashMap<GeneUniquename, TermShortMap> = HashMap::new();
{
let mut add_gene_to_hash =
|reference_uniquename: ReferenceUniquename, gene_uniquename: GeneUniquename| {
seen_genes
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(gene_uniquename.clone(),
self.make_gene_short(&gene_uniquename));
};
let mut add_allele_to_hash =
|reference_uniquename: ReferenceUniquename, allele_uniquename: AlleleUniquename| {
let allele_short = self.make_allele_short(&allele_uniquename);
seen_alleles
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(allele_uniquename.clone(), allele_short.clone());
allele_short
};
let mut add_term_to_hash =
|reference_uniquename: ReferenceUniquename, other_termid: TermId| {
seen_terms
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
};
for (reference_uniquename, reference_details) in &self.references {
for (_, feat_annotations) in &reference_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
add_gene_to_hash(reference_uniquename.clone(),
detail.gene_uniquename.clone());
for condition_termid in &detail.conditions {
add_term_to_hash(reference_uniquename.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
add_term_to_hash(reference_uniquename.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
add_gene_to_hash(reference_uniquename.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
add_allele_to_hash(reference_uniquename.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
add_gene_to_hash(reference_uniquename.clone(), allele_gene_uniquename);
}
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
add_gene_to_hash(reference_uniquename.clone(), interaction.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
add_gene_to_hash(reference_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &reference_details.paralog_annotations {
add_gene_to_hash(reference_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for rel_annotation in &term_details.rel_annotations {
for annotation in &rel_annotation.annotations {
seen_genes.insert(annotation.gene_uniquename.clone());
if let Some(ref genotype_uniquename) = annotation.genotype_uniquename {
seen_genotypes.insert(genotype_uniquename.clone());
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for (_, rel_annotations) in &reference_details.cv_annotations {
for rel_annotation in rel_annotations {
for annotation in &rel_annotation.annotations {
if !rel_annotation.is_not {
seen_genes.insert(annotation.gene_uniquename.clone());
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for (_, gene_details) in &mut self.genes {
for (_, feat_annotations) in &mut gene_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.gene_count =
term_seen_genes.get(&feat_annotation.term.termid).unwrap().len();
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut gene_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, feat_annotations) in &mut genotype_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
}
for (_, ref_details) in &mut self.references {
for (_, ref_annotations) in &mut ref_details.cv_annotations {
for ref_annotation in ref_annotations {
ref_annotation.term.gene_count =
term_seen_genes.get(&ref_annotation.term.termid).unwrap().len();
ref_annotation.term.genotype_count =
term_seen_genotypes.get(&ref_annotation.term.termid).unwrap().len();
}
}
}
for (_, term_details) in &mut self.terms {
for rel_annotation in &mut term_details.rel_annotations {
rel_annotation.term.gene_count =
term_seen_genes.get(&rel_annotation.term.termid).unwrap().len();
rel_annotation.term.genotype_count =
term_seen_genotypes.get(&rel_annotation.term.termid).unwrap().len();
}
for (reference_uniquename, reference_short) in
&mut term_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
}
pub fn get_web_data(&mut self) -> WebData {
self.process_references();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.add_alleles_to_genotypes();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
let mut web_data_terms: IdTermDetailsMap = HashMap::new();
let search_api_maps = self.make_search_api_maps();
for (termid, term_details) in self.terms.drain() {
web_data_terms.insert(termid.clone(), Rc::new(term_details));
}
self.terms = HashMap::new();
let mut used_terms: IdTermDetailsMap = HashMap::new();
// remove terms with no annotation
for (termid, term_details) in &web_data_terms {
if term_details.rel_annotations.len() > 0 {
used_terms.insert(termid.clone(), term_details.clone());
}
}
let metadata = self.make_metadata();
WebData {
genes: self.genes.clone(),
genotypes: self.genotypes.clone(),
terms: web_data_terms,
used_terms: used_terms,
metadata: metadata,
references: self.references.clone(),
search_api_maps: search_api_maps,
}
}
}
Add genotypes_by_uniquename map to ref JSON
use std::rc::Rc;
use std::collections::hash_map::HashMap;
use std::collections::HashSet;
use std::borrow::Borrow;
use std::cmp::Ordering;
use regex::Regex;
use db::*;
use web::data::*;
use web::config::*;
include!(concat!(env!("OUT_DIR"), "/config_serde.rs"));
fn make_organism_short(rc_organism: &Rc<Organism>) -> OrganismShort {
OrganismShort {
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
}
}
#[derive(Clone)]
pub struct AlleleAndExpression {
allele_uniquename: String,
expression: Option<String>,
}
pub struct WebDataBuild<'a> {
raw: &'a Raw,
config: &'a Config,
genes: UniquenameGeneMap,
transcripts: UniquenameTranscriptMap,
genotypes: UniquenameGenotypeMap,
alleles: UniquenameAlleleMap,
terms: HashMap<TermId, TermDetails>,
references: IdReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
all_not_ont_annotations: HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>,
genes_of_transcripts: HashMap<String, String>,
transcripts_of_polypeptides: HashMap<String, String>,
genes_of_alleles: HashMap<String, String>,
alleles_of_genotypes: HashMap<String, Vec<AlleleAndExpression>>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
}
fn get_maps() ->
(HashMap<String, ReferenceShortMap>,
HashMap<String, GeneShortMap>,
HashMap<String, GenotypeShortMap>,
HashMap<String, AlleleShortMap>,
HashMap<GeneUniquename, TermShortMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature_relationship: &FeatureRelationship) -> Option<String> {
for prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "expression" {
return prop.value.clone();
}
}
None
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, config: &'a Config) -> WebDataBuild<'a> {
WebDataBuild {
raw: raw,
config: config,
genes: HashMap::new(),
transcripts: HashMap::new(),
genotypes: HashMap::new(),
alleles: HashMap::new(),
terms: HashMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<String, ReferenceShortMap>,
identifier: String,
maybe_reference_uniquename: Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if let Some(reference_short) = self.make_reference_short(&reference_uniquename) {
seen_references
.entry(identifier.clone())
.or_insert(HashMap::new())
.insert(reference_uniquename.clone(),
reference_short);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<String, GeneShortMap>,
identifier: String,
other_gene_uniquename: GeneUniquename) {
seen_genes
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_gene_uniquename.clone(),
self.make_gene_short(&other_gene_uniquename));
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
identifier: String,
genotype_uniquename: &GenotypeUniquename) {
seen_genotypes
.entry(identifier)
.or_insert(HashMap::new())
.insert(genotype_uniquename.clone(),
self.make_genotype_short(genotype_uniquename));
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
identifier: String,
allele_uniquename: AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
seen_alleles
.entry(identifier)
.or_insert(HashMap::new())
.insert(allele_uniquename, allele_short.clone());
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortMap>,
identifier: String,
other_termid: TermId) {
seen_terms
.entry(identifier)
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(&gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(&gene_uniquename);
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
synonyms: gene_details.synonyms.clone(),
feature_type: gene_details.feature_type.clone(),
organism: gene_details.organism.clone(),
location: gene_details.location.clone(),
}
}
fn make_reference_short(&self, reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = self.references.get(reference_uniquename).unwrap();
let reference_short =
ReferenceShort {
uniquename: String::from(reference_uniquename),
title: reference_details.title.clone(),
citation: reference_details.citation.clone(),
publication_year: reference_details.publication_year.clone(),
authors: reference_details.authors.clone(),
authors_abbrev: reference_details.authors_abbrev.clone(),
gene_count: reference_details.genes_by_uniquename.keys().len(),
genotype_count: reference_details.genotypes_by_uniquename.keys().len(),
};
Some(reference_short)
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort {
name: term_details.name.clone(),
cv_name: term_details.cv_name.clone(),
interesting_parents: term_details.interesting_parents.clone(),
termid: term_details.termid.clone(),
is_obsolete: term_details.is_obsolete,
gene_count: term_details.genes_by_uniquename.keys().len(),
genotype_count: term_details.genotypes_by_uniquename.keys().len(),
}
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &String, cvterm_name: &String) {
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &String, product: &String) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let mut gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = extension_parts.clone();
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert(
vec![]
).push(Rc::new(ont_annotation_detail));
}
fn process_references(&mut self) {
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
let mut pubmed_authors: Option<String> = None;
let mut pubmed_publication_date: Option<String> = None;
let mut pubmed_abstract: Option<String> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(",") {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
authors_abbrev = Some(author_re.replace_all(&authors, "$f et al."));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(date_re.replace_all(&publication_date, "$y"));
}
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev: authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
publication_year: publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
fn make_feature_rel_maps(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let allele_and_expression =
AlleleAndExpression {
allele_uniquename: subject_uniquename.clone(),
expression: get_feat_rel_expression(feature_rel),
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert(Vec::new()).push(allele_and_expression);
continue;
}
}
}
}
fn make_location(&self, feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
Some(ChromosomeLocation {
chromosome_name: feature_loc.srcfeature.uniquename.clone(),
start_pos: start_pos,
end_pos: end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
})
},
None => None,
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let location = self.make_location(&feat);
let organism = make_organism_short(&feat.organism);
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
organism: organism,
product: None,
name_descriptions: vec![],
synonyms: vec![],
feature_type: feat.feat_type.name.clone(),
characterisation_status: None,
location: location,
gene_neighbourhood: vec![],
cds_location: None,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut background = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
background = prop.value.clone()
}
}
self.genotypes.insert(feat.uniquename.clone(),
GenotypeDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
background: background,
expressed_alleles: vec![],
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles.get(&feat.uniquename).unwrap();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename: gene_uniquename.clone(),
allele_type: allele_type.unwrap(),
description: description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_feature(&mut self, feat: &Feature) {
match &feat.feat_type.name as &str {
"gene" | "pseudogene" =>
self.store_gene_details(feat),
_ => {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.transcripts.insert(feat.uniquename.clone(),
TranscriptDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
});
}
}
}
}
fn process_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name != "genotype" && feat.feat_type.name != "allele" {
self.process_feature(&feat);
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<String, HashSet<String>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert(HashSet::new())
.insert(object_termid.into());
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let mut term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(&feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(&feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: String,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let mut this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
fn add_alleles_to_genotypes(&mut self) {
let mut alleles_to_add: HashMap<String, Vec<ExpressedAllele>> = HashMap::new();
for genotype_uniquename in self.genotypes.keys() {
let allele_uniquenames: Vec<AlleleAndExpression> =
self.alleles_of_genotypes.get(genotype_uniquename).unwrap().clone();
let expressed_allele_vec: Vec<ExpressedAllele> =
allele_uniquenames.iter()
.map(|ref allele_and_expression| {
ExpressedAllele {
allele_uniquename: allele_and_expression.allele_uniquename.clone(),
expression: allele_and_expression.expression.clone(),
}
})
.collect();
alleles_to_add.insert(genotype_uniquename.clone(), expressed_allele_vec);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
genotype_details.expressed_alleles =
alleles_to_add.remove(genotype_uniquename).unwrap();
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in self.raw.feature_relationships.iter() {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in FEATURE_REL_CONFIGS.iter() {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0).clone();
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) => Some(publication.uniquename.clone()),
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism_short = {
self.genes.get(subject_uniquename).unwrap().organism.clone()
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism_short = {
self.genes.get(object_uniquename).unwrap().organism.clone()
};
{
let mut gene_details = self.genes.get_mut(subject_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_organism: other_gene_organism_short,
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
ref_details.ortholog_annotations.push(ortholog_annotation);
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence: evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
{
// for orthologs and paralogs, store the reverses annotation too
let mut other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog =>
other_gene_details.ortholog_annotations.push(
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_organism: gene_organism_short,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
}),
FeatureRelAnnotationType::Paralog =>
other_gene_details.paralog_annotations.push(
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename
}),
}
}
}
}
}
for (_, ref_details) in &mut self.references {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for (_, gene_details) in &mut self.genes {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionConfig> {
let ext_configs = &self.config.extensions;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendent_of) = ext_config.if_descendent_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendent_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &String,
gene_uniquename: &String,
reference_uniquename: &Option<String>,
annotation_termid: &String,
extension: &Vec<ExtPart>) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.clone(),
ext_rel_display_name: reciprocal_display_name,
gene_uniquename: gene_uniquename.clone(),
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for (gene_uniquename, gene_details) in &self.genes {
for (cv_name, feat_annotations) in &gene_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
let new_annotations =
self.make_target_of_for_ext(&cv_name, &gene_uniquename,
&detail.reference_uniquename,
&feat_annotation.term.termid, &detail.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert(HashSet::new())
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let mut gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
interesting_parents: HashSet::new(),
termid: cvterm.termid(),
definition: cvterm.definition.clone(),
is_obsolete: cvterm.is_obsolete,
rel_annotations: vec![],
not_rel_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &String,
ext_rel_name: &String) -> String {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
let re = Regex::new("_").unwrap();
re.replace_all(&ext_rel_name, " ")
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = String::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
ExtRange::Gene(ext_range)
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: String::from(ext_rel_name),
rel_type_display_name: rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
self.parts_of_extensions.entry(subject_termid)
.or_insert(Vec::new()).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name: rel_type_display_name,
ext_range: ExtRange::Term(object_term.termid().clone()),
});
} else {
panic!("can't find details for {}\n", object_term.termid());
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in self.raw.feature_synonyms.iter() {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn make_genotype_short(&self, genotype_uniquename: &str) -> GenotypeShort {
let details = self.genotypes.get(genotype_uniquename).unwrap().clone();
GenotypeShort {
uniquename: details.uniquename,
name: details.name,
background: details.background,
expressed_alleles: details.expressed_alleles,
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles.get(allele_uniquename).unwrap().clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if feature.feat_type.name == "polypeptide" && cvterm.cv.name == "PomBase gene products" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: &String) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value.clone())
} else {
ExtRange::Misc(prod_value.clone())
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range: ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &String) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
String::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range: ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: String) -> WithFromValue {
let db_prefix_patt = String::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = re.replace_all(&with_or_from_value, "");
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(&with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(&with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value)
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &String, extension: &mut Vec<ExtPart>,
with_value: String) -> WithFromValue {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents
.contains("GO:0005515") {
extension.push(self.get_with_extension(&with_value));
} else {
return self.make_with_or_from_value(with_value);
}
WithFromValue::None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in self.raw.feature_cvterms.iter() {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<String, String> = HashMap::new();
let mut conditions: Vec<TermId> = vec![];
let mut with: WithFromValue = WithFromValue::None;
let mut from: WithFromValue = WithFromValue::None;
let mut qualifiers: Vec<Qualifier> = vec![];
let mut evidence: Option<String> = None;
for ref prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"evidence" =>
if let Some(evidence_long) = prop.value.clone() {
if let Some(code) = self.config.evidence_types.get(&evidence_long) {
evidence = Some(code.clone());
} else {
evidence = Some(evidence_long);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.push(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"with" => {
if let Some(value) = prop.value.clone() {
let with_gene_short =
self.make_with_extension(&cvterm.termid(),
&mut extension, value);
if with_gene_short.is_some() {
with = with_gene_short;
}
}
},
"from" => {
if let Some(value) = prop.value.clone() {
from = self.make_with_or_from_value(value);
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(&value));
}
},
_ => ()
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let genotype_short = self.make_genotype_short(&feature.uniquename);
maybe_genotype_uniquename = Some(genotype_short.uniquename.clone());
genotype_short.expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
for gene_uniquename in &gene_uniquenames_vec {
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell: copies_per_cell,
avg_copies_per_cell: avg_copies_per_cell,
scale: scale,
})
} else {
None
};
let annotation = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
gene_uniquename: gene_uniquename.clone(),
reference_uniquename: reference_uniquename.clone(),
genotype_uniquename: maybe_genotype_uniquename.clone(),
with: with.clone(),
from: from.clone(),
residue: extra_props_clone.remove("residue"),
gene_ex_props: gene_ex_props,
qualifiers: qualifiers.clone(),
evidence: evidence.clone(),
conditions: conditions.clone(),
extension: extension.clone(),
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation);
}
}
}
fn make_term_annotations(&self, termid: &str, details: &Vec<Rc<OntAnnotationDetail>>,
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_short = self.make_term_short(termid);
let cv_name = term_short.cv_name.clone();
if cv_name == "gene_ex" {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
annotations: vec![],
};
let mut quant_annotations =
OntTermAnnotations {
term: term_short.clone(),
is_not: false,
annotations: vec![],
};
for detail in details {
if detail.gene_ex_props.is_some() {
quant_annotations.annotations.push(detail.clone())
} else {
qual_annotations.annotations.push(detail.clone())
}
}
let mut return_vec = vec![];
if qual_annotations.annotations.len() > 0 {
return_vec.push((String::from("qualitative_gene_expression"),
qual_annotations));
}
if quant_annotations.annotations.len() > 0 {
return_vec.push((String::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
} else {
vec![(cv_name,
OntTermAnnotations {
term: term_short.clone(),
is_not: is_not,
annotations: details.clone(),
})]
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotations = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<String, HashMap<TermId, Vec<Rc<OntAnnotationDetail>>>> =
HashMap::new();
for (termid, annotations) in ont_annotations {
let term_short = self.make_term_short(termid);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
let new_rel_ont_annotation = RelOntAnnotation {
rel_names: HashSet::new(),
term: term_short.clone(),
annotations: annotations.clone(),
};
if is_not {
term_details.not_rel_annotations.push(new_rel_ont_annotation);
} else {
term_details.rel_annotations.push(new_rel_ont_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
for detail in annotations {
gene_annotation_by_term.entry(detail.gene_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let mut existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![]);
if !existing.contains(detail) {
existing.push(detail.clone());
}
}
if let Some(reference_uniquename) = detail.reference_uniquename.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert(HashMap::new())
.entry(termid.clone())
.or_insert(vec![])
.push(detail.clone());
}
for condition_termid in &detail.conditions {
let condition_term_short = {
self.make_term_short(&condition_termid)
};
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
if condition_term_details.rel_annotations.len() == 0 {
condition_term_details.rel_annotations.push(
RelOntAnnotation {
term: condition_term_short,
rel_names: HashSet::new(),
annotations: vec![],
});
}
if let Some(rel_annotation) = condition_term_details.rel_annotations.get_mut(0) {
rel_annotation.annotations.push(detail.clone())
}
}
}
}
}
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (_, mut cv_annotations) in &mut gene_details.cv_annotations {
cv_annotations.sort()
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert(Vec::new())
.push(new_annotation);
}
}
let mut details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (_, mut cv_annotations) in &mut details.cv_annotations {
cv_annotations.sort()
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert(Vec::new())
.push(new_annotation.clone());
}
}
let mut ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (_, mut term_annotations) in &mut ref_details.cv_annotations {
term_annotations.sort()
}
}
}
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
for parent_conf in INTERESTING_PARENTS.iter() {
if parent_conf.termid == termid &&
parent_conf.rel_name == rel_name {
return true;
}
}
for ext_conf in &self.config.extensions {
if let Some(ref conf_termid) = ext_conf.if_descendent_of {
if conf_termid == termid && rel_name == "is_a" {
return true;
}
}
}
false
}
fn process_cvtermpath(&mut self) {
let mut annotation_by_id: HashMap<i32, Rc<OntAnnotationDetail>> = HashMap::new();
let mut new_annotations: HashMap<TermId, HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
let is_inverse =
INVERSE_REL_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) &&
INVERSE_REL_NAMES.contains(&rel_term_name.as_str());
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) &&
!is_inverse {
continue;
}
let annotations = &subject_term_details.rel_annotations;
for rel_annotation in annotations {
let RelOntAnnotation {
rel_names: _,
term: _,
annotations: existing_details
} = rel_annotation.clone();
for detail in &existing_details {
if !annotation_by_id.contains_key(&detail.id) {
annotation_by_id.insert(detail.id, detail.clone());
}
let (dest_termid, source_termid) =
if is_inverse {
(subject_termid.clone(), object_termid.clone())
} else {
(object_termid.clone(), subject_termid.clone())
};
new_annotations.entry(dest_termid)
.or_insert(HashMap::new())
.entry(source_termid)
.or_insert(HashMap::new())
.entry(detail.id)
.or_insert(HashSet::new())
.insert(rel_term_name.clone());
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for (dest_termid, dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_details: Vec<Rc<OntAnnotationDetail>> = vec![];
let mut all_rel_names: HashSet<String> = HashSet::new();
for (id, rel_names) in source_annotations_map {
let detail = annotation_by_id.get(&id).unwrap().clone();
new_details.push(detail);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
let source_term_short = self.make_term_short(&source_termid);
let mut dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
dest_term_details.rel_annotations.push(RelOntAnnotation {
rel_names: all_rel_names,
term: source_term_short.clone(),
annotations: new_details,
});
}
}
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
const PKG_NAME: &'static str = env!("CARGO_PKG_NAME");
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: String::from(PKG_NAME),
export_prog_version: String::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
}
}
pub fn make_search_api_maps(&self) -> SearchAPIMaps {
let mut gene_summaries: Vec<GeneSummary> = vec![];
let gene_uniquenames: Vec<String> =
self.genes.keys().map(|uniquename| uniquename.clone()).collect();
for gene_uniquename in gene_uniquenames {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_name_genes: HashMap<TermName, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
term_summaries.insert(self.make_term_short(&termid));
for gene_uniquename in term_details.genes_by_uniquename.keys() {
termid_genes.entry(termid.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
term_name_genes.entry(term_details.name.clone())
.or_insert(HashSet::new())
.insert(gene_uniquename.clone());
}
}
SearchAPIMaps {
gene_summaries: gene_summaries,
termid_genes: termid_genes,
term_name_genes: term_name_genes,
term_summaries: term_summaries,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &String,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<String, ReferenceShortMap>,
seen_genes: &mut HashMap<String, GeneShortMap>,
seen_genotypes: &mut HashMap<String, GenotypeShortMap>,
seen_alleles: &mut HashMap<String, AlleleShortMap>,
seen_terms: &mut HashMap<String, TermShortMap>) {
for (_, feat_annotations) in cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
self.add_ref_to_hash(seen_references,
identifier.clone(), detail.reference_uniquename.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(seen_terms,
identifier.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
self.add_allele_to_hash(seen_alleles, identifier.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(seen_genes, identifier.clone(), allele_gene_uniquename);
}
self.add_genotype_to_hash(seen_genotypes, identifier.clone(),
&genotype.uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (termid, term_details) in &self.terms {
for rel_annotation in &term_details.rel_annotations {
for detail in &rel_annotation.annotations {
let gene_uniquename = detail.gene_uniquename.clone();
self.add_gene_to_hash(&mut seen_genes, termid.clone(), gene_uniquename.clone());
self.add_ref_to_hash(&mut seen_references, termid.clone(), detail.reference_uniquename.clone());
for condition_termid in &detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
self.add_allele_to_hash(&mut seen_alleles, termid.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
self.add_gene_to_hash(&mut seen_genes, termid.clone(), allele_gene_uniquename);
}
self.add_genotype_to_hash(&mut seen_genotypes, termid.clone(),
&genotype.uniquename);
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), interaction.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), ortholog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(), paralog_annotation.reference_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
for target_of_annotation in &gene_details.target_of_annotations {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename.clone(),
target_of_annotation.gene_uniquename.clone());
self.add_ref_to_hash(&mut seen_references, gene_uniquename.clone(),
target_of_annotation.reference_uniquename.clone());
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
type GeneShortMap = HashMap<GeneUniquename, GeneShort>;
let mut seen_genes: HashMap<String, GeneShortMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
type TermShortMap = HashMap<TermId, TermShort>;
let mut seen_terms: HashMap<GeneUniquename, TermShortMap> = HashMap::new();
{
let mut add_gene_to_hash =
|reference_uniquename: ReferenceUniquename, gene_uniquename: GeneUniquename| {
seen_genes
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(gene_uniquename.clone(),
self.make_gene_short(&gene_uniquename));
};
let mut add_allele_to_hash =
|reference_uniquename: ReferenceUniquename, allele_uniquename: AlleleUniquename| {
let allele_short = self.make_allele_short(&allele_uniquename);
seen_alleles
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(allele_uniquename.clone(), allele_short.clone());
allele_short
};
let mut add_term_to_hash =
|reference_uniquename: ReferenceUniquename, other_termid: TermId| {
seen_terms
.entry(reference_uniquename.clone())
.or_insert(HashMap::new())
.insert(other_termid.clone(),
self.make_term_short(&other_termid));
};
for (reference_uniquename, reference_details) in &self.references {
for (_, feat_annotations) in &reference_details.cv_annotations {
for feat_annotation in feat_annotations.iter() {
for detail in &feat_annotation.annotations {
add_gene_to_hash(reference_uniquename.clone(),
detail.gene_uniquename.clone());
for condition_termid in &detail.conditions {
add_term_to_hash(reference_uniquename.clone(), condition_termid.clone());
}
for ext_part in &detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) =>
add_term_to_hash(reference_uniquename.clone(), range_termid.clone()),
ExtRange::Gene(ref allele_gene_uniquename) =>
add_gene_to_hash(reference_uniquename.clone(),
allele_gene_uniquename.clone()),
_ => {},
}
}
if let Some(ref genotype_uniquename) = detail.genotype_uniquename {
let genotype = self.make_genotype_short(genotype_uniquename);
for expressed_allele in &genotype.expressed_alleles {
let allele_short =
add_allele_to_hash(reference_uniquename.clone(),
expressed_allele.allele_uniquename.clone());
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
add_gene_to_hash(reference_uniquename.clone(), allele_gene_uniquename);
}
self.add_genotype_to_hash(&mut seen_genotypes, reference_uniquename.clone(),
&genotype.uniquename);
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
add_gene_to_hash(reference_uniquename.clone(), interaction.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
add_gene_to_hash(reference_uniquename.clone(), ortholog_annotation.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), ortholog_annotation.ortholog_uniquename.clone());
}
for paralog_annotation in &reference_details.paralog_annotations {
add_gene_to_hash(reference_uniquename.clone(), paralog_annotation.gene_uniquename.clone());
add_gene_to_hash(reference_uniquename.clone(), paralog_annotation.paralog_uniquename.clone());
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for rel_annotation in &term_details.rel_annotations {
for annotation in &rel_annotation.annotations {
seen_genes.insert(annotation.gene_uniquename.clone());
if let Some(ref genotype_uniquename) = annotation.genotype_uniquename {
seen_genotypes.insert(genotype_uniquename.clone());
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for (_, rel_annotations) in &reference_details.cv_annotations {
for rel_annotation in rel_annotations {
for annotation in &rel_annotation.annotations {
if !rel_annotation.is_not {
seen_genes.insert(annotation.gene_uniquename.clone());
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for (_, gene_details) in &mut self.genes {
for (_, feat_annotations) in &mut gene_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.gene_count =
term_seen_genes.get(&feat_annotation.term.termid).unwrap().len();
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
for (reference_uniquename, reference_short) in
&mut gene_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
for (_, genotype_details) in &mut self.genotypes {
for (_, feat_annotations) in &mut genotype_details.cv_annotations {
for mut feat_annotation in feat_annotations.iter_mut() {
feat_annotation.term.genotype_count =
term_seen_genotypes.get(&feat_annotation.term.termid).unwrap().len();
}
}
}
for (_, ref_details) in &mut self.references {
for (_, ref_annotations) in &mut ref_details.cv_annotations {
for ref_annotation in ref_annotations {
ref_annotation.term.gene_count =
term_seen_genes.get(&ref_annotation.term.termid).unwrap().len();
ref_annotation.term.genotype_count =
term_seen_genotypes.get(&ref_annotation.term.termid).unwrap().len();
}
}
}
for (_, term_details) in &mut self.terms {
for rel_annotation in &mut term_details.rel_annotations {
rel_annotation.term.gene_count =
term_seen_genes.get(&rel_annotation.term.termid).unwrap().len();
rel_annotation.term.genotype_count =
term_seen_genotypes.get(&rel_annotation.term.termid).unwrap().len();
}
for (reference_uniquename, reference_short) in
&mut term_details.references_by_uniquename {
reference_short.gene_count =
ref_seen_genes.get(reference_uniquename).unwrap().len();
}
}
}
pub fn get_web_data(&mut self) -> WebData {
self.process_references();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.add_alleles_to_genotypes();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
let mut web_data_terms: IdTermDetailsMap = HashMap::new();
let search_api_maps = self.make_search_api_maps();
for (termid, term_details) in self.terms.drain() {
web_data_terms.insert(termid.clone(), Rc::new(term_details));
}
self.terms = HashMap::new();
let mut used_terms: IdTermDetailsMap = HashMap::new();
// remove terms with no annotation
for (termid, term_details) in &web_data_terms {
if term_details.rel_annotations.len() > 0 {
used_terms.insert(termid.clone(), term_details.clone());
}
}
let metadata = self.make_metadata();
WebData {
genes: self.genes.clone(),
genotypes: self.genotypes.clone(),
terms: web_data_terms,
used_terms: used_terms,
metadata: metadata,
references: self.references.clone(),
search_api_maps: search_api_maps,
}
}
}
|
use std::rc::Rc;
use std::collections::{BTreeMap, HashMap};
use std::collections::HashSet;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::u32;
use regex::Regex;
use db::*;
use types::*;
use web::data::*;
use web::config::*;
use web::cv_summary::make_cv_summaries;
use web::util::cmp_str_dates;
use pombase_rc_string::RcString;
use interpro::UniprotResult;
fn make_organism(rc_organism: &Rc<Organism>) -> ConfigOrganism {
let mut maybe_taxonid: Option<u32> = None;
for prop in rc_organism.organismprops.borrow().iter() {
if prop.prop_type.name == "taxon_id" {
maybe_taxonid = Some(prop.value.parse().unwrap());
}
}
ConfigOrganism {
taxonid: maybe_taxonid.unwrap(),
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
assembly_version: None,
}
}
type TermShortOptionMap = HashMap<TermId, Option<TermShort>>;
type UniprotIdentifier = RcString;
pub struct WebDataBuild<'a> {
raw: &'a Raw,
domain_data: &'a HashMap<UniprotIdentifier, UniprotResult>,
config: &'a Config,
genes: UniquenameGeneMap,
genotypes: UniquenameGenotypeMap,
genotype_backgrounds: HashMap<GenotypeUniquename, RcString>,
alleles: UniquenameAlleleMap,
other_features: UniquenameFeatureShortMap,
terms: TermIdDetailsMap,
chromosomes: ChrNameDetailsMap,
references: UniquenameReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<OntAnnotationId>>,
all_not_ont_annotations: HashMap<TermId, Vec<OntAnnotationId>>,
genes_of_transcripts: HashMap<RcString, RcString>,
transcripts_of_polypeptides: HashMap<RcString, RcString>,
parts_of_transcripts: HashMap<RcString, Vec<FeatureShort>>,
genes_of_alleles: HashMap<RcString, RcString>,
alleles_of_genotypes: HashMap<RcString, Vec<ExpressedAllele>>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
children_by_termid: HashMap<TermId, HashSet<TermId>>,
dbxrefs_of_features: HashMap<RcString, HashSet<RcString>>,
possible_interesting_parents: HashSet<InterestingParent>,
recent_references: RecentReferences,
all_community_curated: Vec<ReferenceShort>,
term_subsets: IdTermSubsetMap,
gene_subsets: IdGeneSubsetMap,
annotation_details: IdOntAnnotationDetailMap,
ont_annotations: Vec<OntAnnotation>,
}
fn get_maps() ->
(HashMap<RcString, ReferenceShortOptionMap>,
HashMap<RcString, GeneShortOptionMap>,
HashMap<RcString, GenotypeShortMap>,
HashMap<RcString, AlleleShortMap>,
HashMap<GeneUniquename, TermShortOptionMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature: &Feature,
feature_relationship: &FeatureRelationship) -> Option<RcString> {
for feature_prop in feature.featureprops.borrow().iter() {
if feature_prop.prop_type.name == "allele_type" {
if let Some(ref value) = feature_prop.value {
if value == "deletion" {
return Some("Null".into());
}
}
}
}
for rel_prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if rel_prop.prop_type.name == "expression" {
return rel_prop.value.clone();
}
}
None
}
fn reference_has_annotation(reference_details: &ReferenceDetails) -> bool {
!reference_details.cv_annotations.is_empty() ||
!reference_details.physical_interactions.is_empty() ||
!reference_details.genetic_interactions.is_empty() ||
!reference_details.ortholog_annotations.is_empty() ||
!reference_details.paralog_annotations.is_empty()
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
pub fn compare_ext_part_with_config(config: &Config, ep1: &ExtPart, ep2: &ExtPart) -> Ordering {
let rel_order_conf = &config.extension_relation_order;
let order_conf = &rel_order_conf.relation_order;
let always_last_conf = &rel_order_conf.always_last;
let maybe_ep1_index = order_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_index = order_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_index) = maybe_ep1_index {
if let Some(ep2_index) = maybe_ep2_index {
ep1_index.cmp(&ep2_index)
} else {
Ordering::Less
}
} else {
if maybe_ep2_index.is_some() {
Ordering::Greater
} else {
let maybe_ep1_last_index = always_last_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_last_index = always_last_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_last_index) = maybe_ep1_last_index {
if let Some(ep2_last_index) = maybe_ep2_last_index {
ep1_last_index.cmp(&ep2_last_index)
} else {
Ordering::Greater
}
} else {
if maybe_ep2_last_index.is_some() {
Ordering::Less
} else {
let name_cmp = ep1.rel_type_name.cmp(&ep2.rel_type_name);
if name_cmp == Ordering::Equal {
if ep1.ext_range.is_gene() && !ep2.ext_range.is_gene() {
Ordering::Less
} else {
if !ep1.ext_range.is_gene() && ep2.ext_range.is_gene() {
Ordering::Greater
} else {
Ordering::Equal
}
}
} else {
name_cmp
}
}
}
}
}
}
fn string_from_ext_range(ext_range: &ExtRange,
genes: &UniquenameGeneMap, terms: &TermIdDetailsMap) -> RcString {
match *ext_range {
ExtRange::Gene(ref gene_uniquename) | ExtRange::Promoter(ref gene_uniquename) => {
let gene = genes.get(gene_uniquename)
.unwrap_or_else(|| panic!("can't find gene: {}", gene_uniquename));
gene_display_name(gene)
},
ExtRange::SummaryGenes(_) => panic!("can't handle SummaryGenes\n"),
ExtRange::Term(ref termid) => RcString::from(&terms.get(termid).unwrap().name),
ExtRange::SummaryModifiedResidues(_) => panic!("can't handle ModifiedResidues\n"),
ExtRange::SummaryTerms(_) => panic!("can't handle SummaryGenes\n"),
ExtRange::Misc(ref misc) => misc.clone(),
ExtRange::Domain(ref domain) => domain.clone(),
ExtRange::GeneProduct(ref gene_product) => gene_product.clone(),
}
}
fn cmp_ext_part(ext_part1: &ExtPart, ext_part2: &ExtPart,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let ord = ext_part1.rel_type_display_name.cmp(&ext_part2.rel_type_display_name);
if ord == Ordering::Equal {
let ext_part1_str = string_from_ext_range(&ext_part1.ext_range, genes, terms);
let ext_part2_str = string_from_ext_range(&ext_part2.ext_range, genes, terms);
ext_part1_str.to_lowercase().cmp(&ext_part2_str.to_lowercase())
} else {
ord
}
}
// compare the extension up to the last common index
fn cmp_extension_prefix(cv_config: &CvConfig, ext1: &[ExtPart], ext2: &[ExtPart],
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let conf_rel_ranges = &cv_config.summary_relation_ranges_to_collect;
let is_grouping_rel_name =
|ext: &ExtPart| !conf_rel_ranges.contains(&ext.rel_type_name);
// put the extension that will be grouped in the summary at the end
// See: https://github.com/pombase/pombase-chado/issues/636
let (mut ext1_for_cmp, ext1_rest): (Vec<ExtPart>, Vec<ExtPart>) =
ext1.to_vec().into_iter().partition(&is_grouping_rel_name);
ext1_for_cmp.extend(ext1_rest.into_iter());
let (mut ext2_for_cmp, ext2_rest): (Vec<ExtPart>, Vec<ExtPart>) =
ext2.to_vec().into_iter().partition(&is_grouping_rel_name);
ext2_for_cmp.extend(ext2_rest.into_iter());
let iter = ext1_for_cmp.iter().zip(&ext2_for_cmp).enumerate();
for (_, (ext1_part, ext2_part)) in iter {
let ord = cmp_ext_part(ext1_part, ext2_part, genes, terms);
if ord != Ordering::Equal {
return ord
}
}
Ordering::Equal
}
fn cmp_extension(cv_config: &CvConfig, ext1: &[ExtPart], ext2: &[ExtPart],
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let cmp = cmp_extension_prefix(cv_config, ext1, ext2, genes, terms);
if cmp == Ordering::Equal {
ext1.len().cmp(&ext2.len())
} else {
cmp
}
}
fn cmp_genotypes(genotype1: &GenotypeDetails, genotype2: &GenotypeDetails) -> Ordering {
genotype1.display_uniquename.to_lowercase().cmp(&genotype2.display_uniquename.to_lowercase())
}
fn allele_display_name(allele: &AlleleShort) -> RcString {
let name = allele.name.clone().unwrap_or_else(|| RcString::from("unnamed"));
let allele_type = allele.allele_type.clone();
let description = allele.description.clone().unwrap_or_else(|| allele_type.clone());
if allele_type == "deletion" && name.ends_with("delta") ||
allele_type.starts_with("wild_type") && name.ends_with('+') {
let normalised_description = description.replace("[\\s_]+", "");
let normalised_allele_type = allele_type.replace("[\\s_]+", "");
if normalised_description != normalised_allele_type {
return RcString::from(&(name + "(" + description.as_str() + ")"));
} else {
return name;
}
}
let display_name =
if allele_type == "deletion" {
name + "-" + description.as_str()
} else {
name + "-" + description.as_str() + "-" + &allele.allele_type
};
RcString::from(&display_name)
}
fn gene_display_name(gene: &GeneDetails) -> RcString {
if let Some(ref name) = gene.name {
name.clone()
} else {
gene.uniquename.clone()
}
}
pub fn make_genotype_display_name(genotype_expressed_alleles: &[ExpressedAllele],
allele_map: &UniquenameAlleleMap) -> RcString {
let mut allele_display_names: Vec<String> =
genotype_expressed_alleles.iter().map(|expressed_allele| {
let allele_short = allele_map.get(&expressed_allele.allele_uniquename).unwrap();
let mut display_name = allele_display_name(allele_short).to_string();
if allele_short.allele_type != "deletion" {
if display_name == "unnamed-unrecorded-unrecorded" {
display_name = format!("{}-{}", allele_short.gene_uniquename,
display_name);
}
if let Some(ref expression) = expressed_allele.expression {
display_name += &format!("-expression-{}", expression.to_lowercase());
}
}
display_name
}).collect();
allele_display_names.sort();
let joined_alleles = allele_display_names.join(" ");
RcString::from(&str::replace(&joined_alleles, " ", "_"))
}
fn make_phase(feature_loc: &Featureloc) -> Option<Phase> {
if let Some(phase) = feature_loc.phase {
match phase {
0 => Some(Phase::Zero),
1 => Some(Phase::One),
2 => Some(Phase::Two),
_ => panic!(),
}
} else {
None
}
}
fn make_location(chromosome_map: &ChrNameDetailsMap,
feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
let feature_uniquename = &feature_loc.srcfeature.uniquename;
let chr_short = make_chromosome_short(chromosome_map, feature_uniquename);
Some(ChromosomeLocation {
chromosome_name: chr_short.name,
start_pos,
end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
phase: make_phase(&feature_loc),
})
},
None => None,
}
}
fn complement_char(base: char) -> char {
match base {
'a' => 't',
'A' => 'T',
't' => 'a',
'T' => 'A',
'g' => 'c',
'G' => 'C',
'c' => 'g',
'C' => 'G',
_ => 'n',
}
}
fn rev_comp(residues: &str) -> Residues {
let residues: String = residues.chars()
.rev().map(complement_char)
.collect();
RcString::from(&residues)
}
fn get_loc_residues(chr: &ChromosomeDetails,
loc: &ChromosomeLocation) -> Residues {
let start = (loc.start_pos - 1) as usize;
let end = loc.end_pos as usize;
let residues: Residues = chr.residues[start..end].into();
if loc.strand == Strand::Forward {
residues
} else {
rev_comp(&residues)
}
}
fn make_feature_short(chromosome_map: &ChrNameDetailsMap, feat: &Feature) -> FeatureShort {
let maybe_loc = make_location(chromosome_map, feat);
if let Some(loc) = maybe_loc {
if let Some(chr) = chromosome_map.get(&loc.chromosome_name) {
let residues = get_loc_residues(chr, &loc);
let feature_type = match &feat.feat_type.name as &str {
"five_prime_UTR" => FeatureType::FivePrimeUtr,
"pseudogenic_exon" | "exon" => FeatureType::Exon,
"three_prime_UTR" => FeatureType::ThreePrimeUtr,
"dg_repeat" => FeatureType::DGRepeat,
"dh_repeat" => FeatureType::DHRepeat,
"gap" => FeatureType::Gap,
"gene_group" => FeatureType::GeneGroup,
"long_terminal_repeat" => FeatureType::LongTerminalRepeat,
"low_complexity_region" => FeatureType::LowComplexityRegion,
"LTR_retrotransposon" => FeatureType::LTRRetrotransposon,
"mating_type_region" => FeatureType::MatingTypeRegion,
"nuclear_mt_pseudogene" => FeatureType::NuclearMtPseudogene,
"origin_of_replication" => FeatureType::OriginOfReplication,
"polyA_signal_sequence" => FeatureType::PolyASignalSequence,
"polyA_site" => FeatureType::PolyASite,
"promoter" => FeatureType::Promoter,
"region" => FeatureType::Region,
"regional_centromere" => FeatureType::RegionalCentromere,
"regional_centromere_central_core" => FeatureType::RegionalCentromereCentralCore,
"regional_centromere_inner_repeat_region" => FeatureType::RegionalCentromereInnerRepeatRegion,
"repeat_region" => FeatureType::RepeatRegion,
"TR_box" => FeatureType::TRBox,
"SNP" => FeatureType::SNP,
_ => panic!("can't handle feature type: {}", feat.feat_type.name),
};
FeatureShort {
feature_type,
uniquename: feat.uniquename.clone(),
location: loc,
residues,
}
} else {
panic!("can't find chromosome {}", loc.chromosome_name);
}
} else {
panic!("{} has no featureloc", feat.uniquename);
}
}
pub fn make_chromosome_short<'a>(chromosome_map: &'a ChrNameDetailsMap,
chromosome_name: &'a str) -> ChromosomeShort {
if let Some(chr) = chromosome_map.get(chromosome_name) {
chr.make_chromosome_short()
} else {
panic!("can't find chromosome: {}", chromosome_name);
}
}
fn make_gene_short<'b>(gene_map: &'b UniquenameGeneMap,
gene_uniquename: &'b str) -> GeneShort {
if let Some(gene_details) = gene_map.get(gene_uniquename) {
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_reference_short<'a>(reference_map: &'a UniquenameReferenceMap,
reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = reference_map.get(reference_uniquename)
.unwrap_or_else(|| panic!("missing reference in make_reference_short(): {}",
reference_uniquename));
let reference_short = ReferenceShort::from_reference_details(reference_details);
Some(reference_short)
}
}
// compare two gene vectors which must be ordered vecs
fn cmp_gene_vec(genes: &UniquenameGeneMap,
gene_vec1: &[GeneUniquename],
gene_vec2: &[GeneUniquename]) -> Ordering {
let gene_short_vec1: Vec<GeneShort> =
gene_vec1.iter().map(|gene_uniquename: &RcString| {
make_gene_short(genes, gene_uniquename)
}).collect();
let gene_short_vec2: Vec<GeneShort> =
gene_vec2.iter().map(|gene_uniquename: &RcString| {
make_gene_short(genes, gene_uniquename)
}).collect();
gene_short_vec1.cmp(&gene_short_vec2)
}
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
static ref PROMOTER_RE: Regex = Regex::new(r"^(?P<gene>.*)-promoter$").unwrap();
}
fn cmp_residues(residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering {
if let Some(ref res1) = *residue1 {
if let Some(ref res2) = *residue2 {
if let (Some(res1_captures), Some(res2_captures)) =
(MODIFICATION_RE.captures(res1), MODIFICATION_RE.captures(res2))
{
let res1_aa = res1_captures.name("aa").unwrap().as_str();
let res2_aa = res2_captures.name("aa").unwrap().as_str();
let aa_order = res1_aa.cmp(&res2_aa);
if aa_order == Ordering::Equal {
let res1_pos =
res1_captures.name("pos").unwrap().as_str().parse::<i32>().unwrap();
let res2_pos =
res2_captures.name("pos").unwrap().as_str().parse::<i32>().unwrap();
res1_pos.cmp(&res2_pos)
} else {
aa_order
}
} else {
res1.cmp(&res2)
}
} else {
Ordering::Less
}
} else {
if residue2.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
pub fn cmp_ont_annotation_detail(cv_config: &CvConfig,
detail1: &OntAnnotationDetail,
detail2: &OntAnnotationDetail,
genes: &UniquenameGeneMap,
genotypes: &UniquenameGenotypeMap,
terms: &TermIdDetailsMap) -> Result<Ordering, String> {
if let Some(ref detail1_genotype_uniquename) = detail1.genotype {
if let Some(ref detail2_genotype_uniquename) = detail2.genotype {
let genotype1 = genotypes.get(detail1_genotype_uniquename).unwrap();
let genotype2 = genotypes.get(detail2_genotype_uniquename).unwrap();
let ord = cmp_genotypes(genotype1, genotype2);
if ord == Ordering::Equal {
Ok(cmp_extension(cv_config, &detail1.extension, &detail2.extension,
genes, terms))
} else {
Ok(ord)
}
} else {
Err(format!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n", detail1, detail2))
}
} else {
if detail2.genotype.is_some() {
Err(format!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n", detail1, detail2))
} else {
let ord = cmp_gene_vec(genes, &detail1.genes, &detail2.genes);
if ord == Ordering::Equal {
if let Some(ref sort_details_by) = cv_config.sort_details_by {
for sort_type in sort_details_by {
if sort_type == "modification" {
let res = cmp_residues(&detail1.residue, &detail2.residue);
if res != Ordering::Equal {
return Ok(res);
}
} else {
let res = cmp_extension(cv_config, &detail1.extension,
&detail2.extension, genes, terms);
if res != Ordering::Equal {
return Ok(res);
}
}
}
Ok(Ordering::Equal)
} else {
Ok(cmp_extension(cv_config, &detail1.extension, &detail2.extension,
genes, terms))
}
} else {
Ok(ord)
}
}
}
}
// Some ancestor terms are useful in the web code. This function uses the Config and returns
// the terms that might be useful.
fn get_possible_interesting_parents(config: &Config) -> HashSet<InterestingParent> {
let mut ret = HashSet::new();
for parent_conf in &config.interesting_parents {
ret.insert(parent_conf.clone());
}
for ext_conf in &config.extension_display_names {
if let Some(ref conf_termid) = ext_conf.if_descendant_of {
ret.insert(InterestingParent {
termid: conf_termid.clone(),
rel_name: RcString::from("is_a"),
});
}
}
let add_to_set = |set: &mut HashSet<_>, termid: RcString| {
for rel_name in &DESCENDANT_REL_NAMES {
set.insert(InterestingParent {
termid: termid.to_owned(),
rel_name: RcString::from(rel_name),
});
}
};
for go_slim_conf in &config.go_slim_terms {
add_to_set(&mut ret, go_slim_conf.termid.clone());
}
for go_termid in &config.query_data_config.go_components {
add_to_set(&mut ret, go_termid.clone());
}
for go_termid in &config.query_data_config.go_process_superslim {
add_to_set(&mut ret, go_termid.clone());
}
for go_termid in &config.query_data_config.go_function {
add_to_set(&mut ret, go_termid.clone());
}
ret.insert(InterestingParent {
termid: config.viability_terms.viable.clone(),
rel_name: RcString::from("is_a"),
});
ret.insert(InterestingParent {
termid: config.viability_terms.inviable.clone(),
rel_name: RcString::from("is_a"),
});
let add_filter_ancestor =
|set: &mut HashSet<_>, category: &AncestorFilterCategory, cv_name: &str| {
for ancestor in &category.ancestors {
for config_rel_name in &DESCENDANT_REL_NAMES {
if *config_rel_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&cv_name) {
continue;
}
set.insert(InterestingParent {
termid: ancestor.clone(),
rel_name: RcString::from(*config_rel_name),
});
}
}
};
for (cv_name, conf) in &config.cv_config {
for filter in &conf.filters {
for category in &filter.term_categories {
add_filter_ancestor(&mut ret, category, cv_name);
}
for category in &filter.extension_categories {
add_filter_ancestor(&mut ret, category, cv_name);
}
}
for split_by_parent_config in &conf.split_by_parents {
for ancestor in &split_by_parent_config.termids {
let ancestor_termid =
if ancestor.starts_with("NOT ") {
RcString::from(&ancestor[4..])
} else {
ancestor.clone()
};
ret.insert(InterestingParent {
termid: ancestor_termid,
rel_name: "is_a".into(),
});
}
}
}
ret
}
const MAX_RECENT_REFS: usize = 20;
fn make_recently_added(references_map: &UniquenameReferenceMap,
all_ref_uniquenames: &[RcString]) -> Vec<ReferenceShort> {
let mut date_sorted_pub_uniquenames = all_ref_uniquenames.to_owned();
{
let ref_added_date_cmp =
|ref_uniquename1: &ReferenceUniquename, ref_uniquename2: &ReferenceUniquename| {
let ref1 = references_map.get(ref_uniquename1).unwrap();
let ref2 = references_map.get(ref_uniquename2).unwrap();
if let Some(ref ref1_added_date) = ref1.canto_added_date {
if let Some(ref ref2_added_date) = ref2.canto_added_date {
cmp_str_dates(ref1_added_date, ref2_added_date).reverse()
} else {
Ordering::Less
}
} else {
if ref2.canto_added_date.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
};
date_sorted_pub_uniquenames.sort_by(ref_added_date_cmp);
}
let recently_added_iter =
date_sorted_pub_uniquenames.iter().take(MAX_RECENT_REFS);
let mut recently_added: Vec<ReferenceShort> = vec![];
for ref_uniquename in recently_added_iter {
let ref_short_maybe = make_reference_short(references_map, ref_uniquename);
if let Some(ref_short) = ref_short_maybe {
recently_added.push(ref_short);
}
}
recently_added
}
fn make_canto_curated(references_map: &UniquenameReferenceMap,
all_ref_uniquenames: &[RcString])
-> (Vec<ReferenceShort>, Vec<ReferenceShort>, Vec<ReferenceShort>) {
let mut sorted_pub_uniquenames: Vec<ReferenceUniquename> =
all_ref_uniquenames.iter()
.filter(|ref_uniquename| {
let reference = references_map.get(*ref_uniquename).unwrap();
(reference.canto_first_approved_date.is_some() ||
reference.canto_session_submitted_date.is_some()) &&
reference.canto_curator_role.is_some()
})
.cloned()
.collect();
{
let pub_date_cmp =
|ref_uniquename1: &ReferenceUniquename, ref_uniquename2: &ReferenceUniquename| {
let ref1 = references_map.get(ref_uniquename1).unwrap();
let ref2 = references_map.get(ref_uniquename2).unwrap();
// use first approval date, but fall back to the most recent approval date
let ref1_date =
ref1.canto_first_approved_date.as_ref()
.unwrap_or_else(|| ref1.canto_approved_date.as_ref()
.unwrap_or_else(|| ref1.canto_session_submitted_date.
as_ref().unwrap()));
let ref2_date =
ref2.canto_first_approved_date.as_ref()
.unwrap_or_else(|| ref2.canto_approved_date.as_ref()
.unwrap_or_else(|| ref2.canto_session_submitted_date.
as_ref().unwrap()));
cmp_str_dates(ref2_date, ref1_date)
};
sorted_pub_uniquenames.sort_by(pub_date_cmp);
}
let mut recent_admin_curated = vec![];
let mut recent_community_curated = vec![];
let mut all_community_curated = vec![];
let ref_uniquename_iter = sorted_pub_uniquenames.iter();
for ref_uniquename in ref_uniquename_iter {
let reference = references_map.get(ref_uniquename).unwrap();
if reference.canto_curator_role == Some("community".into()) {
let ref_short = make_reference_short(references_map, ref_uniquename).unwrap();
all_community_curated.push(ref_short.clone());
if recent_community_curated.len() <= MAX_RECENT_REFS {
recent_community_curated.push(ref_short);
}
} else {
if recent_admin_curated.len() <= MAX_RECENT_REFS {
let ref_short = make_reference_short(references_map, ref_uniquename).unwrap();
recent_admin_curated.push(ref_short);
}
}
}
(recent_admin_curated, recent_community_curated, all_community_curated)
}
fn add_introns_to_transcript(chromosome: &ChromosomeDetails,
transcript_uniquename: &str, parts: &mut Vec<FeatureShort>) {
let mut new_parts: Vec<FeatureShort> = vec![];
let mut intron_count = 0;
for part in parts.drain(0..) {
let mut maybe_new_intron = None;
if let Some(prev_part) = new_parts.last() {
let intron_start = prev_part.location.end_pos + 1;
let intron_end = part.location.start_pos - 1;
if intron_start > intron_end {
if intron_start > intron_end + 1 {
println!("no gap between exons at {}..{} in {}", intron_start, intron_end,
transcript_uniquename);
}
// if intron_start == intron_end-1 then it is a one base overlap that
// represents a frameshift in the reference See:
// https://github.com/pombase/curation/issues/1453#issuecomment-303214177
} else {
intron_count += 1;
let new_intron_loc = ChromosomeLocation {
chromosome_name: prev_part.location.chromosome_name.clone(),
start_pos: intron_start,
end_pos: intron_end,
strand: prev_part.location.strand.clone(),
phase: None,
};
let intron_uniquename =
format!("{}:intron:{}", transcript_uniquename, intron_count);
let intron_residues = get_loc_residues(chromosome, &new_intron_loc);
let intron_type =
if prev_part.feature_type == FeatureType::Exon &&
part.feature_type == FeatureType::Exon {
FeatureType::CdsIntron
} else {
if prev_part.feature_type == FeatureType::FivePrimeUtr {
FeatureType::FivePrimeUtrIntron
} else {
FeatureType::ThreePrimeUtrIntron
}
};
maybe_new_intron = Some(FeatureShort {
feature_type: intron_type,
uniquename: RcString::from(&intron_uniquename),
location: new_intron_loc,
residues: intron_residues,
});
}
}
if let Some(new_intron) = maybe_new_intron {
new_parts.push(new_intron);
}
new_parts.push(part);
}
*parts = new_parts;
}
fn validate_transcript_parts(transcript_uniquename: &str, parts: &[FeatureShort]) {
let mut seen_exon = false;
for part in parts {
if part.feature_type == FeatureType::Exon {
seen_exon = true;
break;
}
}
if !seen_exon {
panic!("transcript has no exons: {}", transcript_uniquename);
}
if parts[0].feature_type != FeatureType::Exon {
for i in 1..parts.len() {
let part = &parts[i];
if part.feature_type == FeatureType::Exon {
let last_utr_before_exons = &parts[i-1];
let first_exon = &parts[i];
if last_utr_before_exons.location.end_pos + 1 != first_exon.location.start_pos {
println!("{} and exon don't meet up: {} at pos {}",
last_utr_before_exons.feature_type, transcript_uniquename,
last_utr_before_exons.location.end_pos);
}
break;
} else {
if part.location.strand == Strand::Forward {
if part.feature_type != FeatureType::FivePrimeUtr {
println!("{:?}", parts);
panic!("wrong feature type '{}' before exons in {}",
part.feature_type, transcript_uniquename);
}
} else {
if part.feature_type != FeatureType::ThreePrimeUtr {
println!("{:?}", parts);
panic!("wrong feature type '{}' after exons in {}",
part.feature_type, transcript_uniquename);
}
}
}
}
}
let last_part = parts.last().unwrap();
if last_part.feature_type != FeatureType::Exon {
for i in (0..parts.len()-1).rev() {
let part = &parts[i];
if part.feature_type == FeatureType::Exon {
let first_utr_after_exons = &parts[i+1];
let last_exon = &parts[i];
if last_exon.location.end_pos + 1 != first_utr_after_exons.location.start_pos {
println!("{} and exon don't meet up: {} at pos {}",
first_utr_after_exons.feature_type, transcript_uniquename,
first_utr_after_exons.location.end_pos);
}
break;
} else {
if part.location.strand == Strand::Forward {
if part.feature_type != FeatureType::ThreePrimeUtr {
panic!("wrong feature type '{}' before exons in {}",
part.feature_type, transcript_uniquename);
}
} else {
if part.feature_type != FeatureType::FivePrimeUtr {
panic!("wrong feature type '{}' after exons in {}",
part.feature_type, transcript_uniquename);
}
}
}
}
}
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, domain_data: &'a HashMap<UniprotIdentifier, UniprotResult>,
config: &'a Config) -> WebDataBuild<'a>
{
WebDataBuild {
raw,
domain_data,
config,
genes: BTreeMap::new(),
genotypes: HashMap::new(),
genotype_backgrounds: HashMap::new(),
alleles: HashMap::new(),
other_features: HashMap::new(),
terms: HashMap::new(),
chromosomes: BTreeMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
recent_references: RecentReferences {
admin_curated: vec![],
community_curated: vec![],
pubmed: vec![],
},
all_community_curated: vec![],
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
parts_of_transcripts: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
children_by_termid: HashMap::new(),
dbxrefs_of_features: HashMap::new(),
possible_interesting_parents: get_possible_interesting_parents(config),
term_subsets: HashMap::new(),
gene_subsets: HashMap::new(),
annotation_details: HashMap::new(),
ont_annotations: vec![],
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<RcString, ReferenceShortOptionMap>,
identifier: &str,
maybe_reference_uniquename: &Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if reference_uniquename != "null" {
seen_references
.entry(identifier.into())
.or_insert_with(HashMap::new)
.insert(reference_uniquename.clone(), None);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
other_gene_uniquename: &GeneUniquename) {
seen_genes
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(other_gene_uniquename.clone(), None);
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<RcString, GenotypeShortMap>,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
genotype_uniquename: &RcString) {
let genotype_short = self.make_genotype_short(&genotype_uniquename);
for expressed_allele in &genotype_short.expressed_alleles {
self.add_allele_to_hash(seen_alleles, seen_genes, identifier,
&expressed_allele.allele_uniquename);
}
seen_genotypes
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(genotype_uniquename.clone(), genotype_short);
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
allele_uniquename: &AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
{
let allele_gene_uniquename = &allele_short.gene_uniquename;
self.add_gene_to_hash(seen_genes, identifier, allele_gene_uniquename);
seen_alleles
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(allele_uniquename.clone(), allele_short.clone());
}
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortOptionMap>,
identifier: &RcString,
other_termid: &TermId) {
seen_terms
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(other_termid.clone(), None);
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<RcString>>();
let mut ortholog_ids =
gene_details.ortholog_annotations.iter()
.map(|ortholog_annotation| {
IdAndOrganism {
identifier: ortholog_annotation.ortholog_uniquename.clone(),
taxonid: ortholog_annotation.ortholog_taxonid,
}
})
.collect::<Vec<IdAndOrganism>>();
for ortholog_annotation in &gene_details.ortholog_annotations {
let orth_uniquename = &ortholog_annotation.ortholog_uniquename;
if let Some(orth_gene) =
self.genes.get(orth_uniquename) {
if let Some(ref orth_name) = orth_gene.name {
let id_and_org = IdAndOrganism {
identifier: RcString::from(&orth_name),
taxonid: ortholog_annotation.ortholog_taxonid,
};
ortholog_ids.push(id_and_org);
}
} else {
panic!("missing GeneShort for: {:?}", orth_uniquename);
}
}
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
uniprot_identifier: gene_details.uniprot_identifier.clone(),
synonyms,
orthologs: ortholog_ids,
feature_type: gene_details.feature_type.clone(),
taxonid: gene_details.taxonid,
location: gene_details.location.clone(),
}
}
fn make_api_gene_summary(&self, gene_uniquename: &str) -> APIGeneSummary {
let gene_details = self.get_gene(gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<RcString>>();
let exon_count =
if let Some(transcript) = gene_details.transcripts.get(0) {
let mut count = 0;
for part in &transcript.parts {
if part.feature_type == FeatureType::Exon {
count += 1;
}
}
count
} else {
0
};
APIGeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
uniprot_identifier: gene_details.uniprot_identifier.clone(),
exact_synonyms: synonyms,
dbxrefs: gene_details.dbxrefs.clone(),
location: gene_details.location.clone(),
transcripts: gene_details.transcripts.clone(),
tm_domain_count: gene_details.tm_domain_coords.len(),
exon_count,
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort::from_term_details(&term_details)
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &str,
cvterm_name: &RcString) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &str, product: &RcString) {
let gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = extension_parts.clone();
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
{
let compare_ext_part_func =
|e1: &ExtPart, e2: &ExtPart| compare_ext_part_with_config(self.config, e1, e2);
new_extension.sort_by(compare_ext_part_func);
};
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert_with(Vec::new).push(ont_annotation_detail.id);
self.annotation_details.insert(ont_annotation_detail.id,
ont_annotation_detail);
}
fn process_dbxrefs(&mut self) {
let mut map = HashMap::new();
for feature_dbxref in &self.raw.feature_dbxrefs {
let feature = &feature_dbxref.feature;
let dbxref = &feature_dbxref.dbxref;
map.entry(feature.uniquename.clone())
.or_insert_with(HashSet::new)
.insert(dbxref.identifier());
}
self.dbxrefs_of_features = map;
}
fn process_references(&mut self) {
let mut all_uniquenames = vec![];
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
if reference_uniquename.to_lowercase() == "null" {
continue;
}
let mut pubmed_authors: Option<RcString> = None;
let mut pubmed_publication_date: Option<RcString> = None;
let mut pubmed_abstract: Option<RcString> = None;
let mut canto_triage_status: Option<RcString> = None;
let mut canto_curator_role: Option<RcString> = None;
let mut canto_curator_name: Option<RcString> = None;
let mut canto_first_approved_date: Option<RcString> = None;
let mut canto_approved_date: Option<RcString> = None;
let mut canto_added_date: Option<RcString> = None;
let mut canto_session_submitted_date: Option<RcString> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
"canto_triage_status" =>
canto_triage_status = Some(prop.value.clone()),
"canto_curator_role" =>
canto_curator_role = Some(prop.value.clone()),
"canto_curator_name" =>
canto_curator_name = Some(prop.value.clone()),
"canto_first_approved_date" =>
canto_first_approved_date = Some(prop.value.clone()),
"canto_approved_date" =>
canto_approved_date = Some(prop.value.clone()),
"canto_added_date" =>
canto_added_date = Some(prop.value.clone()),
"canto_session_submitted_date" =>
canto_session_submitted_date = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(',') {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
let replaced: String =
author_re.replace_all(&authors, "$f et al.").into();
authors_abbrev = Some(RcString::from(&replaced));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(RcString::from(&date_re.replace_all(&publication_date, "$y")));
}
let mut approved_date = canto_first_approved_date.clone();
if approved_date.is_none() {
approved_date = canto_approved_date.clone();
}
if approved_date.is_none() {
approved_date = canto_session_submitted_date.clone();
}
approved_date =
if let Some(date) = approved_date {
let re = Regex::new(r"^(?P<date>\d\d\d\d-\d\d-\d\d).*").unwrap();
Some(RcString::from(&re.replace_all(&date, "$date")))
} else {
None
};
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
canto_triage_status,
canto_curator_role,
canto_curator_name,
canto_first_approved_date,
canto_approved_date,
canto_session_submitted_date,
canto_added_date,
approved_date,
publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
});
if pubmed_publication_date.is_some() {
all_uniquenames.push(reference_uniquename.clone());
}
}
let (recent_admin_curated, recent_community_curated,
all_community_curated) =
make_canto_curated(&self.references, &all_uniquenames);
let recent_references = RecentReferences {
pubmed: make_recently_added(&self.references, &all_uniquenames),
admin_curated: recent_admin_curated,
community_curated: recent_community_curated,
};
self.recent_references = recent_references;
self.all_community_curated = all_community_curated;
}
// make maps from genes to transcript, transcripts to polypeptide,
// exon, intron, UTRs
fn make_feature_rel_maps(&mut self) {
for feature_rel in &self.raw.feature_relationships {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" && is_gene_type(object_type_name) {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let expression = get_feat_rel_expression(&feature_rel.subject, feature_rel);
let allele_and_expression =
ExpressedAllele {
allele_uniquename: subject_uniquename.clone(),
expression,
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert_with(Vec::new).push(allele_and_expression);
continue;
}
}
if TRANSCRIPT_PART_TYPES.contains(&subject_type_name.as_str()) {
let entry = self.parts_of_transcripts.entry(object_uniquename.clone());
let part = make_feature_short(&self.chromosomes, &feature_rel.subject);
entry.or_insert_with(Vec::new).push(part);
}
}
}
fn get_feature_dbxrefs(&self, feature: &Feature) -> HashSet<RcString> {
if let Some(dbxrefs) = self.dbxrefs_of_features.get(&feature.uniquename) {
dbxrefs.clone()
} else {
HashSet::new()
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let maybe_location = make_location(&self.chromosomes, feat);
if let Some(ref location) = maybe_location {
if let Some(ref mut chr) = self.chromosomes.get_mut(&location.chromosome_name) {
chr.gene_uniquenames.push(feat.uniquename.clone());
}
}
let organism = make_organism(&feat.organism);
let dbxrefs = self.get_feature_dbxrefs(feat);
let mut orfeome_identifier = None;
for dbxref in &dbxrefs {
if dbxref.starts_with("SPD:") {
orfeome_identifier = Some(RcString::from(&dbxref[4..]));
}
}
let mut uniprot_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "uniprot_identifier" {
uniprot_identifier = prop.value.clone();
break;
}
}
let (interpro_matches, tm_domain_coords) =
if let Some(ref uniprot_identifier) = uniprot_identifier {
if let Some(result) = self.domain_data.get(uniprot_identifier as &str) {
let tm_domain_matches = result.tmhmm_matches.iter()
.map(|tm_match| (tm_match.start, tm_match.end))
.collect::<Vec<_>>();
(result.interpro_matches.clone(), tm_domain_matches)
} else {
(vec![], vec![])
}
} else {
(vec![], vec![])
};
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
taxonid: organism.taxonid,
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier,
interpro_matches,
tm_domain_coords,
orfeome_identifier,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs,
feature_type: feat.feat_type.name.clone(),
transcript_so_termid: feat.feat_type.termid(),
characterisation_status: None,
location: maybe_location,
gene_neighbourhood: vec![],
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
feature_publications: HashSet::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn get_transcript_parts(&mut self, transcript_uniquename: &str) -> Vec<FeatureShort> {
let mut parts = self.parts_of_transcripts.remove(transcript_uniquename)
.expect("can't find transcript");
if parts.is_empty() {
panic!("transcript has no parts: {}", transcript_uniquename);
}
let part_cmp = |a: &FeatureShort, b: &FeatureShort| {
a.location.start_pos.cmp(&b.location.start_pos)
};
parts.sort_by(&part_cmp);
validate_transcript_parts(transcript_uniquename, &parts);
let chr_name = &parts[0].location.chromosome_name.clone();
if let Some(chromosome) = self.chromosomes.get(chr_name) {
add_introns_to_transcript(chromosome, transcript_uniquename, &mut parts);
} else {
panic!("can't find chromosome details for: {}", chr_name);
}
if parts[0].location.strand == Strand::Reverse {
parts.reverse();
}
parts
}
fn store_transcript_details(&mut self, feat: &Feature) {
let transcript_uniquename = feat.uniquename.clone();
let parts = self.get_transcript_parts(&transcript_uniquename);
if parts.is_empty() {
panic!("transcript has no parts");
}
let mut transcript_start = u32::MAX;
let mut transcript_end = 0;
for part in &parts {
if part.location.start_pos < transcript_start {
transcript_start = part.location.start_pos;
}
if part.location.end_pos > transcript_end {
transcript_end = part.location.end_pos;
}
}
// use the first part as a template to get the chromosome details
let transcript_location =
ChromosomeLocation {
start_pos: transcript_start,
end_pos: transcript_end,
phase: None,
.. parts[0].location.clone()
};
let maybe_cds_location =
if feat.feat_type.name == "mRNA" {
let mut cds_start = u32::MAX;
let mut cds_end = 0;
for part in &parts {
if part.feature_type == FeatureType::Exon {
if part.location.start_pos < cds_start {
cds_start = part.location.start_pos;
}
if part.location.end_pos > cds_end {
cds_end = part.location.end_pos;
}
}
}
if cds_end == 0 {
None
} else {
if let Some(mrna_location) = feat.featurelocs.borrow().get(0) {
let first_part_loc = &parts[0].location;
Some(ChromosomeLocation {
chromosome_name: first_part_loc.chromosome_name.clone(),
start_pos: cds_start,
end_pos: cds_end,
strand: first_part_loc.strand.clone(),
phase: make_phase(&mrna_location),
})
} else {
None
}
}
} else {
None
};
let transcript = TranscriptDetails {
uniquename: transcript_uniquename.clone(),
location: transcript_location,
transcript_type: feat.feat_type.name.clone(),
parts,
protein: None,
cds_location: maybe_cds_location,
};
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&transcript_uniquename) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
if gene_details.feature_type != "pseudogene" {
let feature_type =
transcript.transcript_type.clone() + " " + &gene_details.feature_type;
gene_details.feature_type = RcString::from(&feature_type);
}
gene_details.transcripts.push(transcript);
gene_details.transcript_so_termid = feat.feat_type.termid();
} else {
panic!("can't find gene for transcript: {}", transcript_uniquename);
}
}
fn store_protein_details(&mut self, feat: &Feature) {
if let Some(residues) = feat.residues.clone() {
let protein_uniquename = feat.uniquename.clone();
let mut molecular_weight = None;
let mut average_residue_weight = None;
let mut charge_at_ph7 = None;
let mut isoelectric_point = None;
let mut codon_adaptation_index = None;
let parse_prop_as_f32 = |p: &Option<RcString>| {
if let Some(ref prop_value) = p {
let maybe_value = prop_value.parse();
if let Ok(parsed_prop) = maybe_value {
Some(parsed_prop)
} else {
println!("{}: couldn't parse {} as f32",
feat.uniquename, &prop_value);
None
}
} else {
None
}
};
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "molecular_weight" {
if let Some(value) = parse_prop_as_f32(&prop.value) {
molecular_weight = Some(value / 1000.0);
}
}
if prop.prop_type.name == "average_residue_weight" {
if let Some(value) = parse_prop_as_f32(&prop.value) {
average_residue_weight = Some(value / 1000.0);
}
}
if prop.prop_type.name == "charge_at_ph7" {
charge_at_ph7 = parse_prop_as_f32(&prop.value);
}
if prop.prop_type.name == "isoelectric_point" {
isoelectric_point = parse_prop_as_f32(&prop.value);
}
if prop.prop_type.name == "codon_adaptation_index" {
codon_adaptation_index = parse_prop_as_f32(&prop.value);
}
}
if molecular_weight.is_none() {
panic!("{} has no molecular_weight", feat.uniquename)
}
let protein = ProteinDetails {
uniquename: feat.uniquename.clone(),
sequence: RcString::from(&residues),
molecular_weight: molecular_weight.unwrap(),
average_residue_weight: average_residue_weight.unwrap(),
charge_at_ph7: charge_at_ph7.unwrap(),
isoelectric_point: isoelectric_point.unwrap(),
codon_adaptation_index: codon_adaptation_index.unwrap(),
};
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&protein_uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
if gene_details.transcripts.len() > 1 {
panic!("unimplemented - can't handle multiple transcripts for: {}",
gene_uniquename);
} else {
if gene_details.transcripts.is_empty() {
panic!("gene has no transcript: {}", gene_uniquename);
} else {
gene_details.transcripts[0].protein = Some(protein);
}
}
} else {
panic!("can't find gene for transcript: {}", transcript_uniquename);
}
} else {
panic!("can't find transcript of polypeptide: {}", protein_uniquename)
}
} else {
panic!("no residues for protein: {}", feat.uniquename);
}
}
fn store_chromosome_details(&mut self, feat: &Feature) {
let mut ena_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "ena_id" {
ena_identifier = prop.value.clone()
}
}
if feat.residues.is_none() {
panic!("{:?}", feat.uniquename);
}
let org = make_organism(&feat.organism);
let residues = feat.residues.clone().unwrap();
let chr = ChromosomeDetails {
name: feat.uniquename.clone(),
residues: RcString::from(&residues),
ena_identifier: RcString::from(&ena_identifier.unwrap()),
gene_uniquenames: vec![],
taxonid: org.taxonid,
};
self.chromosomes.insert(feat.uniquename.clone(), chr);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut expressed_alleles =
self.alleles_of_genotypes[&feat.uniquename].clone();
let genotype_display_uniquename =
make_genotype_display_name(&expressed_alleles, &self.alleles);
{
let allele_cmp = |allele1: &ExpressedAllele, allele2: &ExpressedAllele| {
let allele1_display_name =
allele_display_name(&self.alleles[&allele1.allele_uniquename]);
let allele2_display_name =
allele_display_name(&self.alleles[&allele2.allele_uniquename]);
allele1_display_name.cmp(&allele2_display_name)
};
expressed_alleles.sort_by(&allele_cmp);
}
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
if let Some(ref background) = prop.value {
self.genotype_backgrounds.insert(feat.uniquename.clone(),
background.clone());
}
}
}
let rc_display_name = RcString::from(&genotype_display_uniquename);
self.genotypes.insert(rc_display_name.clone(),
GenotypeDetails {
display_uniquename: rc_display_name,
name: feat.name.as_ref().map(|s| RcString::from(s)),
expressed_alleles,
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles[&feat.uniquename].clone();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename,
allele_type: allele_type.unwrap(),
description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_chromosome_features(&mut self) {
// we need to process all chromosomes before other featuers
for feat in &self.raw.features {
if feat.feat_type.name == "chromosome" {
self.store_chromosome_details(feat);
}
}
}
fn process_features(&mut self) {
// we need to process all genes before transcripts
for feat in &self.raw.features {
if feat.feat_type.name == "gene" || feat.feat_type.name == "pseudogene" {
self.store_gene_details(feat);
}
}
for feat in &self.raw.features {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.store_transcript_details(feat)
}
}
for feat in &self.raw.features {
if feat.feat_type.name == "polypeptide"{
self.store_protein_details(feat);
}
}
for feat in &self.raw.features {
if !TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) &&
!TRANSCRIPT_PART_TYPES.contains(&feat.feat_type.name.as_str()) &&
!HANDLED_FEATURE_TYPES.contains(&feat.feat_type.name.as_str())
{
// for now, ignore features without locations
if feat.featurelocs.borrow().len() > 0 {
let feature_short = make_feature_short(&self.chromosomes, &feat);
self.other_features.insert(feat.uniquename.clone(), feature_short);
}
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<RcString, HashSet<RcString>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert_with(HashSet::new)
.insert(object_termid);
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: RcString,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in &self.raw.feature_relationships {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in &FEATURE_REL_CONFIGS {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let mut is_inferred_interaction: bool = false;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0);
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) =>
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
},
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(ref evidence_long) = prop.value {
for (evidence_code, ev_details) in &self.config.evidence_types {
if &ev_details.long == evidence_long {
evidence = Some(evidence_code.clone());
}
}
if evidence.is_none() {
evidence = Some(evidence_long.clone());
}
}
}
if prop.prop_type.name == "is_inferred" {
if let Some(is_inferred_value) = prop.value.clone() {
if is_inferred_value == "yes" {
is_inferred_interaction = true;
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism_taxonid = {
self.genes[subject_uniquename].taxonid
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism_taxonid = {
self.genes[object_uniquename].taxonid
};
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction =>
if !is_inferred_interaction {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
{
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if gene_uniquename != other_gene_uniquename {
let other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
if rel_name == "interacts_physically" {
other_gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
other_gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_taxonid: other_gene_organism_taxonid,
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == gene_details.taxonid {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == gene_details.taxonid {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
// for orthologs and paralogs, store the reverse annotation too
let other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_taxonid: gene_organism_taxonid,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == other_gene_details.taxonid {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == other_gene_details.taxonid {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
},
}
}
}
}
for ref_details in self.references.values_mut() {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for gene_details in self.genes.values_mut() {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
// find the extension_display_names config for the given termid and relation type name
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionDisplayNames> {
let ext_configs = &self.config.extension_display_names;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendant_of) = ext_config.if_descendant_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendant_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &str,
genes: &[RcString],
maybe_genotype_uniquename: &Option<RcString>,
reference_uniquename: &Option<RcString>,
annotation_termid: &str,
extension: &[ExtPart]) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
let (annotation_gene_uniquenames, annotation_genotype_uniquename) =
if maybe_genotype_uniquename.is_some() {
(genes.clone(), maybe_genotype_uniquename.clone())
} else {
(genes.clone(), None)
};
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.into(),
ext_rel_display_name: reciprocal_display_name,
genes: annotation_gene_uniquenames.to_vec(),
genotype_uniquename: annotation_genotype_uniquename,
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for term_details in self.terms.values() {
for term_annotations in term_details.cv_annotations.values() {
for term_annotation in term_annotations {
'ANNOTATION: for annotation_id in &term_annotation.annotations {
let annotation = self.annotation_details
.get(&annotation_id).expect("can't find OntAnnotationDetail");
if let Some(ref genotype_uniquename) = annotation.genotype {
let genotype = &self.genotypes[genotype_uniquename];
if genotype.expressed_alleles.len() > 1 {
break 'ANNOTATION;
}
}
let new_annotations =
self.make_target_of_for_ext(&term_details.cv_name,
&annotation.genes,
&annotation.genotype,
&annotation.reference,
&term_details.termid,
&annotation.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert_with(HashSet::new)
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn set_deletion_viability(&mut self) {
let some_null = Some(RcString::from("Null"));
let mut gene_statuses = HashMap::new();
let condition_string =
|condition_ids: HashSet<RcString>| {
let mut ids_vec: Vec<RcString> = condition_ids.iter().cloned().collect();
ids_vec.sort();
RcString::from(&ids_vec.join(" "))
};
let viable_termid = &self.config.viability_terms.viable;
let inviable_termid = &self.config.viability_terms.inviable;
for (gene_uniquename, gene_details) in &mut self.genes {
let mut new_status = DeletionViability::Unknown;
if let Some(single_allele_term_annotations) =
gene_details.cv_annotations.get("single_allele_phenotype") {
let mut viable_conditions: HashMap<RcString, TermId> = HashMap::new();
let mut inviable_conditions: HashMap<RcString, TermId> = HashMap::new();
for term_annotation in single_allele_term_annotations {
'ANNOTATION: for annotation_id in &term_annotation.annotations {
let annotation = self.annotation_details
.get(&annotation_id).expect("can't find OntAnnotationDetail");
let genotype_uniquename = annotation.genotype.as_ref().unwrap();
let genotype = &self.genotypes[genotype_uniquename];
let expressed_allele = &genotype.expressed_alleles[0];
let allele = &self.alleles[&expressed_allele.allele_uniquename];
if allele.allele_type != "deletion" &&
expressed_allele.expression != some_null {
continue 'ANNOTATION;
}
let term = &self.terms[&term_annotation.term];
let interesting_parents = &term.interesting_parents;
let conditions_as_string =
condition_string(annotation.conditions.clone());
if interesting_parents.contains(viable_termid) ||
*viable_termid == term_annotation.term {
viable_conditions.insert(conditions_as_string,
term_annotation.term.clone());
} else {
if interesting_parents.contains(inviable_termid) ||
*inviable_termid == term_annotation.term {
inviable_conditions.insert(conditions_as_string,
term_annotation.term.clone());
}
}
}
}
if viable_conditions.is_empty() {
if !inviable_conditions.is_empty() {
new_status = DeletionViability::Inviable;
}
} else {
if inviable_conditions.is_empty() {
new_status = DeletionViability::Viable;
} else {
new_status = DeletionViability::DependsOnConditions;
let viable_conditions_set: HashSet<RcString> =
viable_conditions.keys().cloned().collect();
let inviable_conditions_set: HashSet<RcString> =
inviable_conditions.keys().cloned().collect();
let intersecting_conditions =
viable_conditions_set.intersection(&inviable_conditions_set);
if intersecting_conditions.clone().count() > 0 {
println!("{} is viable and inviable with", gene_uniquename);
for cond in intersecting_conditions {
if cond.is_empty() {
println!(" no conditions");
} else {
println!(" conditions: {}", cond);
}
println!(" viable term: {}",
viable_conditions[cond]);
println!(" inviable term: {}",
inviable_conditions[cond]);
}
}
}
}
}
gene_statuses.insert(gene_uniquename.clone(), new_status);
}
for (gene_uniquename, status) in &gene_statuses {
if let Some(ref mut gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details.deletion_viability = status.clone();
}
}
}
fn set_term_details_subsets(&mut self) {
'TERM: for go_slim_conf in self.config.go_slim_terms.clone() {
let slim_termid = &go_slim_conf.termid;
for term_details in self.terms.values_mut() {
if term_details.termid == *slim_termid {
term_details.subsets.push("goslim_pombe".into());
break 'TERM;
}
}
}
}
fn make_gene_short_map(&self) -> IdGeneShortMap {
let mut ret_map = HashMap::new();
for gene_uniquename in self.genes.keys() {
ret_map.insert(gene_uniquename.clone(),
make_gene_short(&self.genes, &gene_uniquename));
}
ret_map
}
fn make_all_cv_summaries(&mut self) {
let gene_short_map = self.make_gene_short_map();
for term_details in self.terms.values_mut() {
make_cv_summaries(term_details, self.config, &self.children_by_termid,
true, true, &gene_short_map, &self.annotation_details);
}
for gene_details in self.genes.values_mut() {
make_cv_summaries(gene_details, &self.config, &self.children_by_termid,
false, true, &gene_short_map, &self.annotation_details);
}
for genotype_details in self.genotypes.values_mut() {
make_cv_summaries(genotype_details, &self.config, &self.children_by_termid,
false, false, &gene_short_map, &self.annotation_details);
}
for reference_details in self.references.values_mut() {
make_cv_summaries( reference_details, &self.config, &self.children_by_termid,
true, true, &gene_short_map, &self.annotation_details);
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
let cv_config =
self.config.cv_config_by_name(&cvterm.cv.name);
let annotation_feature_type =
cv_config.feature_type.clone();
let synonyms =
cvterm.cvtermsynonyms.borrow().iter().map(|syn| {
SynonymDetails {
synonym_type: (*syn).synonym_type.name.clone(),
name: syn.name.clone(),
}
}).collect::<Vec<_>>();
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
annotation_feature_type,
interesting_parents: HashSet::new(),
subsets: vec![],
termid: cvterm.termid(),
synonyms,
definition: cvterm.definition.clone(),
direct_ancestors: vec![],
genes_annotated_with: HashSet::new(),
is_obsolete: cvterm.is_obsolete,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
gene_count: 0,
genotype_count: 0,
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &str,
ext_rel_name: &str) -> RcString {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
RcString::from(&str::replace(&ext_rel_name, "_", " "))
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = RcString::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
if let Some(captures) = PROMOTER_RE.captures(&ext_range) {
let gene_uniquename = RcString::from(&captures["gene"]);
ExtRange::Promoter(gene_uniquename)
} else {
ExtRange::Gene(ext_range.clone())
}
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert_with(Vec::new).push(ExtPart {
rel_type_name: ext_rel_name,
rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
} else {
let object_term_short =
self.make_term_short(&object_term.termid());
if let Some(ref mut subject_term_details) = self.terms.get_mut(&subject_term.termid()) {
subject_term_details.direct_ancestors.push(TermAndRelation {
termid: object_term_short.termid.clone(),
term_name: object_term_short.name.clone(),
relation_name: rel_type.name.clone(),
});
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
let object_termid = object_term.termid();
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
let ext_range =
if object_termid.starts_with("PR:") {
ExtRange::GeneProduct(object_termid)
} else {
ExtRange::Term(object_termid)
};
self.parts_of_extensions.entry(subject_termid)
.or_insert_with(Vec::new).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name,
ext_range,
});
} else {
panic!("can't find details for {}\n", object_termid);
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in &self.raw.feature_synonyms {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn process_feature_publications(&mut self) {
for feature_pub in &self.raw.feature_pubs {
let feature = &feature_pub.feature;
let publication = &feature_pub.publication;
if publication.uniquename.starts_with("PMID:") {
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.feature_publications.insert(publication.uniquename.clone());
}
}
}
}
fn make_genotype_short(&self, genotype_display_name: &str) -> GenotypeShort {
if let Some(ref details) = self.genotypes.get(genotype_display_name) {
GenotypeShort {
display_uniquename: details.display_uniquename.clone(),
name: details.name.clone(),
expressed_alleles: details.expressed_alleles.clone(),
}
} else {
panic!("can't find genotype {}", genotype_display_name);
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles[allele_uniquename].clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in &self.raw.feature_cvterms {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if cvterm.cv.name == "PomBase gene products" {
if feature.feat_type.name == "polypeptide" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
if feature.feat_type.name == "gene" {
vec![feature.uniquename.clone()]
} else {
vec![]
}
}
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: RcString) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value)
} else {
ExtRange::Misc(prod_value)
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &RcString) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
RcString::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: &RcString) -> WithFromValue {
let db_prefix_patt = RcString::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = RcString::from(&re.replace_all(&with_or_from_value, ""));
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value.clone())
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &RcString, evidence_code: Option<RcString>,
extension: &mut Vec<ExtPart>,
with_value: &RcString) -> Option<WithFromValue> {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if evidence_code.is_some() &&
evidence_code.unwrap() == "IPI" &&
// add new IDs to the interesting_parents config
(base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents.contains("GO:0005515") ||
base_term_short.termid == "GO:0003723" ||
base_term_short.interesting_parents.contains("GO:0003723")) {
extension.push(self.get_with_extension(with_value));
} else {
return Some(self.make_with_or_from_value(with_value));
}
None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in &self.raw.feature_cvterms {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let termid = cvterm.termid();
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<RcString, RcString> = HashMap::new();
let mut conditions: HashSet<TermId> = HashSet::new();
let mut withs: HashSet<WithFromValue> = HashSet::new();
let mut froms: HashSet<WithFromValue> = HashSet::new();
let mut qualifiers: Vec<Qualifier> = vec![];
let mut assigned_by: Option<RcString> = None;
let mut evidence: Option<RcString> = None;
let mut genotype_background: Option<RcString> = None;
// need to get evidence first as it's used later
// See: https://github.com/pombase/website/issues/455
for prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
if &prop.type_name() == "evidence" {
if let Some(ref evidence_long) = prop.value {
for (evidence_code, ev_details) in &self.config.evidence_types {
if &ev_details.long == evidence_long {
evidence = Some(evidence_code.clone());
}
}
if evidence.is_none() {
evidence = Some(evidence_long.clone());
}
}
}
}
for prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.insert(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"assigned_by" =>
if let Some(value) = prop.value.clone() {
assigned_by = Some(value);
},
"with" => {
if let Some(ref with_value) = prop.value.clone() {
if let Some(with_gene_short) =
self.make_with_extension(&termid, evidence.clone(),
&mut extension, with_value) {
withs.insert(with_gene_short);
}
}
},
"from" => {
if let Some(value) = prop.value.clone() {
froms.insert(self.make_with_or_from_value(&value));
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(value));
}
},
_ => ()
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let expressed_alleles =
&self.alleles_of_genotypes[&feature.uniquename];
let genotype_display_name =
make_genotype_display_name(&expressed_alleles, &self.alleles);
maybe_genotype_uniquename = Some(genotype_display_name.clone());
genotype_background =
self.genotype_backgrounds.get(&feature.uniquename)
.map(|s| s.clone());
expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
gene_uniquenames_vec =
gene_uniquenames_vec.iter().map(|gene_uniquename: &RcString| {
self.make_gene_short(&gene_uniquename).uniquename
}).collect();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell,
avg_copies_per_cell,
scale,
})
} else {
None
};
if gene_uniquenames_vec.len() > 1 && maybe_genotype_uniquename.is_none() {
panic!("non-genotype annotation has more than one gene");
}
let annotation_detail = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
genes: gene_uniquenames_vec,
reference: reference_uniquename,
genotype: maybe_genotype_uniquename,
genotype_background,
withs,
froms,
residue: extra_props_clone.remove("residue"),
gene_ex_props,
qualifiers,
evidence,
conditions,
extension,
assigned_by,
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation_detail);
}
}
fn make_term_annotations(&self, termid: &RcString, detail_ids: &[OntAnnotationId],
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_details = &self.terms[termid];
let cv_name = term_details.cv_name.clone();
match cv_name.as_ref() {
"gene_ex" => {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: termid.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut quant_annotations =
OntTermAnnotations {
term: termid.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for annotation_id in detail_ids {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
if annotation.gene_ex_props.is_some() {
quant_annotations.annotations.push(*annotation_id)
} else {
qual_annotations.annotations.push(*annotation_id)
}
}
let mut return_vec = vec![];
if !qual_annotations.annotations.is_empty() {
return_vec.push((RcString::from("qualitative_gene_expression"),
qual_annotations));
}
if !quant_annotations.annotations.is_empty() {
return_vec.push((RcString::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
},
"fission_yeast_phenotype" => {
let mut single_allele =
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut multi_allele =
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for annotation_id in detail_ids {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
let genotype_uniquename = annotation.genotype.as_ref().unwrap();
if let Some(genotype_details) = self.genotypes.get(genotype_uniquename) {
if genotype_details.expressed_alleles.len() == 1 {
single_allele.annotations.push(*annotation_id);
} else {
multi_allele.annotations.push(*annotation_id);
}
} else {
panic!("can't find genotype details for {}\n", genotype_uniquename);
}
}
let mut return_vec = vec![];
if !single_allele.annotations.is_empty() {
return_vec.push((RcString::from("single_allele_phenotype"),
single_allele));
}
if !multi_allele.annotations.is_empty() {
return_vec.push((RcString::from("multi_allele_phenotype"),
multi_allele));
}
return_vec
},
_ => {
vec![(cv_name,
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: detail_ids.to_owned(),
summary: None,
})]
}
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotation_map = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<RcString, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut ont_annotations = vec![];
for (termid, annotations) in ont_annotation_map {
let mut sorted_annotations = annotations.clone();
if !is_not {
let cv_config = {
let term = &self.terms[termid];
&self.config.cv_config_by_name(&term.cv_name)
};
{
let cmp_detail_with_maps =
|id1: &i32, id2: &i32| {
let annotation1 = self.annotation_details.
get(&id1).expect("can't find OntAnnotationDetail");
let annotation2 = self.annotation_details.
get(&id2).expect("can't find OntAnnotationDetail");
let result =
cmp_ont_annotation_detail(cv_config,
annotation1, annotation2, &self.genes,
&self.genotypes,
&self.terms);
result.unwrap_or_else(|err| panic!("error from cmp_ont_annotation_detail: {}", err))
};
sorted_annotations.sort_by(cmp_detail_with_maps);
}
let new_annotations =
self.make_term_annotations(&termid, &sorted_annotations, is_not);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
for (cv_name, new_annotation) in new_annotations {
term_details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
}
for annotation_id in sorted_annotations {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation.genes {
gene_annotation_by_term.entry(gene_uniquename.clone())
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![])
.push(annotation_id);
}
if let Some(ref genotype_uniquename) = annotation.genotype {
let existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![]);
if !existing.contains(&annotation_id) {
existing.push(annotation_id);
}
}
if let Some(reference_uniquename) = annotation.reference.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![])
.push(annotation_id);
}
for condition_termid in &annotation.conditions {
let cv_name =
if let Some(ref term_details) = self.terms.get(condition_termid) {
term_details.cv_name.clone()
} else {
panic!("can't find term details for {}", condition_termid);
};
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
condition_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: condition_termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
condition_term_details.cv_annotations.get_mut(&cv_name)
.unwrap()[0]
.annotations.push(annotation_id);
}
}
// Add annotations to terms referred to in extensions. They
// are added to fake CV that have a name starting with
// "extension:". The CV name will end with ":genotype" if the
// annotation is a phentoype/genotype, and will end with ":end"
// otherwise. The middle of the fake CV name is the display
// name for the extension relation.
// eg. "extension:directly activates:gene"
for ext_part in &annotation.extension {
if let ExtRange::Term(ref part_termid) = ext_part.ext_range {
let cv_name = "extension:".to_owned() + &ext_part.rel_type_display_name;
if let Some(ref mut part_term_details) =
self.terms.get_mut(part_termid)
{
let extension_cv_name =
if annotation.genotype.is_some() {
cv_name.clone() + ":genotype"
} else {
cv_name.clone() + ":gene"
};
part_term_details.cv_annotations
.entry(RcString::from(&extension_cv_name))
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: part_termid.to_owned(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
part_term_details.cv_annotations.get_mut(&extension_cv_name)
.unwrap()[0]
.annotations.push(annotation_id);
}
}
}
let gene_short_list =
annotation.genes.iter().map(|uniquename: &RcString| {
self.make_gene_short(uniquename)
}).collect::<HashSet<_>>();
let reference_short =
annotation.reference.as_ref().map_or(None, |uniquename: &RcString| {
make_reference_short(&self.references, uniquename)
});
let genotype_short =
annotation.genotype.as_ref().map(|uniquename: &RcString| {
self.make_genotype_short(uniquename)
});
let conditions =
annotation.conditions.iter().map(|termid| {
self.make_term_short(termid)
}).collect::<HashSet<_>>();
let ont_annotation = OntAnnotation {
term_short: self.make_term_short(&termid),
id: annotation.id,
genes: gene_short_list,
reference_short,
genotype_short,
genotype_background: annotation.genotype_background.clone(),
withs: annotation.withs.clone(),
froms: annotation.froms.clone(),
residue: annotation.residue.clone(),
gene_ex_props: annotation.gene_ex_props.clone(),
qualifiers: annotation.qualifiers.clone(),
evidence: annotation.evidence.clone(),
conditions,
extension: annotation.extension.clone(),
assigned_by: annotation.assigned_by.clone(),
};
ont_annotations.push(ont_annotation);
}
}
let mut term_names = HashMap::new();
for (termid, term_details) in &self.terms {
term_names.insert(termid.clone(), term_details.name.to_lowercase());
}
let ont_term_cmp = |ont_term_1: &OntTermAnnotations, ont_term_2: &OntTermAnnotations| {
if !ont_term_1.is_not && ont_term_2.is_not {
return Ordering::Less;
}
if ont_term_1.is_not && !ont_term_2.is_not {
return Ordering::Greater;
}
let term1 = &term_names[&ont_term_1.term];
let term2 = &term_names[&ont_term_2.term];
term1.cmp(&term2)
};
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
}
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for cv_annotations in gene_details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
}
let details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for cv_annotations in details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert_with(Vec::new)
.push(new_annotation.clone());
}
}
let ref_details = self.references.get_mut(reference_uniquename).unwrap();
for cv_annotations in ref_details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for ont_annotation in ont_annotations.drain(0..) {
self.ont_annotations.push(ont_annotation);
}
}
// return true if the term could or should appear in the interesting_parents
// field of the TermDetails and TermShort structs
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
self.possible_interesting_parents.contains(&InterestingParent {
termid: termid.into(),
rel_name: rel_name.into(),
})
}
fn process_cvtermpath(&mut self) {
let mut new_annotations: HashMap<(CvName, TermId), HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
let mut children_by_termid: HashMap<TermId, HashSet<TermId>> = HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if rel_term_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) {
continue;
}
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) {
continue;
}
if subject_term_details.cv_annotations.keys().len() > 0 {
if let Some(object_term_details) = self.terms.get(&object_termid) {
if object_term_details.cv_annotations.keys().len() > 0 {
children_by_termid
.entry(object_termid.clone())
.or_insert_with(HashSet::new)
.insert(subject_termid.clone());
}
}
}
for (cv_name, term_annotations) in &subject_term_details.cv_annotations {
for term_annotation in term_annotations {
for annotation_id in &term_annotation.annotations {
let dest_termid = object_termid.clone();
let source_termid = subject_termid.clone();
if !term_annotation.is_not {
new_annotations.entry((cv_name.clone(), dest_termid))
.or_insert_with(HashMap::new)
.entry(source_termid)
.or_insert_with(HashMap::new)
.entry(*annotation_id)
.or_insert_with(HashSet::new)
.insert(rel_term_name.clone());
}
}
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for ((dest_cv_name, dest_termid), dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_annotations: Vec<OntAnnotationId> = vec![];
let mut all_rel_names: HashSet<RcString> = HashSet::new();
for (annotation_id, rel_names) in source_annotations_map {
new_annotations.push(annotation_id);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
let dest_cv_config = &self.config.cv_config_by_name(&dest_cv_name);
{
let cmp_detail_with_genotypes =
|id1: &i32, id2: &i32| {
let annotation1 = self.annotation_details.
get(&id1).expect("can't find OntAnnotationDetail");
let annotation2 = self.annotation_details.
get(&id2).expect("can't find OntAnnotationDetail");
let result =
cmp_ont_annotation_detail(dest_cv_config,
annotation1, annotation2, &self.genes,
&self.genotypes, &self.terms);
result.unwrap_or_else(|err| {
panic!("error from cmp_ont_annotation_detail: {} with terms: {} and {}",
err, source_termid, dest_termid)
})
};
new_annotations.sort_by(cmp_detail_with_genotypes);
}
let new_annotations =
self.make_term_annotations(&source_termid, &new_annotations, false);
let dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
for (_, new_annotation) in new_annotations {
let mut new_annotation_clone = new_annotation.clone();
new_annotation_clone.rel_names.extend(all_rel_names.clone());
dest_term_details.cv_annotations
.entry(dest_cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation_clone);
}
}
}
let mut term_names = HashMap::new();
for (termid, term_details) in &self.terms {
term_names.insert(termid.clone(), term_details.name.to_lowercase());
}
let ont_term_cmp = |ont_term_1: &OntTermAnnotations, ont_term_2: &OntTermAnnotations| {
if !ont_term_1.is_not && ont_term_2.is_not {
return Ordering::Less;
}
if ont_term_1.is_not && !ont_term_2.is_not {
return Ordering::Greater;
}
let term1 = &term_names[&ont_term_1.term];
let term2 = &term_names[&ont_term_2.term];
term1.cmp(&term2)
};
for term_details in self.terms.values_mut() {
for term_annotations in term_details.cv_annotations.values_mut() {
term_annotations.sort_by(&ont_term_cmp);
}
}
self.children_by_termid = children_by_termid;
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
let mut cv_versions = HashMap::new();
for cvprop in &self.raw.cvprops {
if cvprop.prop_type.name == "cv_version" {
cv_versions.insert(cvprop.cv.name.clone(), cvprop.value.clone());
}
}
const PKG_NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: RcString::from(PKG_NAME),
export_prog_version: RcString::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
cv_versions,
}
}
pub fn get_api_genotype_annotation(&self) -> HashMap<TermId, Vec<APIGenotypeAnnotation>>
{
let mut app_genotype_annotation = HashMap::new();
for term_details in self.terms.values() {
for annotations_vec in term_details.cv_annotations.values() {
for ont_term_annotations in annotations_vec {
'DETAILS: for annotation_id in &ont_term_annotations.annotations {
let annotation_details = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
if annotation_details.genotype.is_none() {
continue 'DETAILS;
}
let genotype_uniquename = annotation_details.genotype.clone().unwrap();
let genotype =
&term_details.genotypes_by_uniquename[&genotype_uniquename];
let mut api_annotation = APIGenotypeAnnotation {
is_multi: genotype.expressed_alleles.len() > 1,
alleles: vec![],
};
for allele in &genotype.expressed_alleles {
let allele_uniquename = &allele.allele_uniquename;
let allele_short =
self.alleles.get(allele_uniquename).expect("Can't find allele");
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
let allele_details = APIAlleleDetails {
gene: allele_gene_uniquename,
allele_type: allele_short.allele_type.clone(),
expression: allele.expression.clone(),
};
api_annotation.alleles.push(allele_details);
}
app_genotype_annotation
.entry(term_details.termid.clone())
.or_insert_with(|| vec![])
.push(api_annotation);
}
}
}
}
app_genotype_annotation
}
fn make_gene_query_go_data(&self, gene_details: &GeneDetails, term_config: &Vec<TermId>,
cv_name: &str) -> Option<GeneQueryTermData>
{
let component_term_annotations =
gene_details.cv_annotations.get(cv_name);
if component_term_annotations.is_none() {
return None;
}
let in_component = |check_termid: &str| {
for term_annotation in component_term_annotations.unwrap() {
let maybe_term_details = self.terms.get(&term_annotation.term);
let term_details =
maybe_term_details .unwrap_or_else(|| {
panic!("can't find TermDetails for {}", &term_annotation.term)
});
let interesting_parents = &term_details.interesting_parents;
if !term_annotation.is_not &&
(term_annotation.term == check_termid ||
interesting_parents.contains(check_termid))
{
return true;
}
}
false
};
for go_component_termid in term_config {
if in_component(go_component_termid) {
return Some(GeneQueryTermData::Term(TermAndName {
termid: go_component_termid.to_owned(),
name: self.terms.get(go_component_termid).unwrap().name.clone(),
}));
}
}
Some(GeneQueryTermData::Other)
}
fn get_ortholog_taxonids(&self, gene_details: &GeneDetails)
-> HashSet<u32>
{
let mut return_set = HashSet::new();
for ortholog_annotation in &gene_details.ortholog_annotations {
return_set.insert(ortholog_annotation.ortholog_taxonid);
}
return_set
}
fn make_gene_query_data_map(&self) -> HashMap<GeneUniquename, GeneQueryData> {
let mut gene_query_data_map = HashMap::new();
for gene_details in self.genes.values() {
let ortholog_taxonids = self.get_ortholog_taxonids(gene_details);
let cc_term_config = &self.config.query_data_config.go_components;
let process_term_config = &self.config.query_data_config.go_process_superslim;
let function_term_config = &self.config.query_data_config.go_function;
let go_component =
self.make_gene_query_go_data(gene_details, cc_term_config,
"cellular_component");
let go_process_superslim =
self.make_gene_query_go_data(gene_details, process_term_config,
"biological_process");
let go_function =
self.make_gene_query_go_data(gene_details, function_term_config,
"molecular_function");
let gene_query_data = GeneQueryData {
gene_uniquename: gene_details.uniquename.clone(),
deletion_viability: gene_details.deletion_viability.clone(),
go_component,
go_process_superslim,
go_function,
ortholog_taxonids,
};
gene_query_data_map.insert(gene_details.uniquename.clone(), gene_query_data);
}
gene_query_data_map
}
pub fn make_api_maps(mut self) -> APIMaps {
let mut gene_summaries: HashMap<GeneUniquename, APIGeneSummary> = HashMap::new();
let mut gene_name_gene_map = HashMap::new();
let mut interactors_of_genes = HashMap::new();
for (gene_uniquename, gene_details) in &self.genes {
if self.config.load_organism_taxonid == gene_details.taxonid {
let gene_summary = self.make_api_gene_summary(&gene_uniquename);
if let Some(ref gene_name) = gene_summary.name {
gene_name_gene_map.insert(gene_name.clone(), gene_uniquename.clone());
}
gene_summaries.insert(gene_uniquename.clone(), gene_summary);
let mut interactors = vec![];
for interaction_annotation in &gene_details.physical_interactions {
let interactor_uniquename =
if gene_uniquename == &interaction_annotation.gene_uniquename {
interaction_annotation.interactor_uniquename.clone()
} else {
interaction_annotation.gene_uniquename.clone()
};
let interactor = APIInteractor {
interaction_type: InteractionType::Physical,
interactor_uniquename,
};
if !interactors.contains(&interactor) {
interactors.push(interactor);
}
}
for interaction_annotation in &gene_details.genetic_interactions {
let interactor_uniquename =
if gene_uniquename == &interaction_annotation.gene_uniquename {
interaction_annotation.interactor_uniquename.clone()
} else {
interaction_annotation.gene_uniquename.clone()
};
let interactor = APIInteractor {
interaction_type: InteractionType::Genetic,
interactor_uniquename,
};
if !interactors.contains(&interactor) {
interactors.push(interactor);
}
}
interactors_of_genes.insert(gene_uniquename.clone(), interactors);
}
}
let gene_query_data_map = self.make_gene_query_data_map();
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut terms_for_api: HashMap<TermId, TermDetails> = HashMap::new();
for termid in self.terms.keys() {
term_summaries.insert(self.make_term_short(termid));
}
let termid_genotype_annotation: HashMap<TermId, Vec<APIGenotypeAnnotation>> =
self.get_api_genotype_annotation();
for (termid, term_details) in self.terms.drain() {
let cv_config = &self.config.cv_config;
if let Some(term_config) = cv_config.get(&term_details.cv_name) {
if term_config.feature_type == "gene" {
termid_genes.insert(termid.clone(),
term_details.genes_annotated_with.clone());
}
}
terms_for_api.insert(termid.clone(), term_details);
}
APIMaps {
gene_summaries,
gene_query_data_map,
termid_genes,
termid_genotype_annotation,
term_summaries,
genes: self.genes,
gene_name_gene_map,
genotypes: self.genotypes,
terms: terms_for_api,
interactors_of_genes,
references: self.references,
other_features: self.other_features,
annotation_details: self.annotation_details,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &RcString,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<RcString, ReferenceShortOptionMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
seen_genotypes: &mut HashMap<RcString, GenotypeShortMap>,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_terms: &mut HashMap<RcString, TermShortOptionMap>) {
for feat_annotations in cv_annotations.values() {
for feat_annotation in feat_annotations.iter() {
self.add_term_to_hash(seen_terms, identifier,
&feat_annotation.term);
for annotation_detail_id in &feat_annotation.annotations {
let annotation_detail = self.annotation_details.
get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
self.add_ref_to_hash(seen_references, identifier,
&annotation_detail.reference);
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(seen_terms, identifier,
&condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier,
&gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
self.add_genotype_to_hash(seen_genotypes, seen_alleles, seen_genes,
identifier, genotype_uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
let mut genes_annotated_with_map: HashMap<TermId, HashSet<GeneUniquename>> =
HashMap::new();
for (termid, term_details) in &self.terms {
for (cv_name, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
self.add_term_to_hash(&mut seen_terms, termid,
&term_annotation.term);
for annotation_detail_id in &term_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
self.add_gene_to_hash(&mut seen_genes, termid,
gene_uniquename);
if !cv_name.starts_with("extension:") {
// prevent extension annotations from appears
// in the normal query builder searches
genes_annotated_with_map
.entry(termid.clone()).or_insert_with(HashSet::new)
.insert(gene_uniquename.clone());
}
}
self.add_ref_to_hash(&mut seen_references, termid,
&annotation_detail.reference);
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid,
condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid,
gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles,
&mut seen_genes, &termid,
genotype_uniquename);
}
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
if let Some(gene_uniquename_set) = genes_annotated_with_map.remove(termid) {
term_details.genes_annotated_with = gene_uniquename_set;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&interaction.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&interaction.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&interaction.interactor_uniquename);
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&ortholog_annotation.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&ortholog_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&ortholog_annotation.ortholog_uniquename);
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
¶log_annotation.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
¶log_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
¶log_annotation.paralog_uniquename);
}
for target_of_annotation in &gene_details.target_of_annotations {
for annotation_gene_uniquename in &target_of_annotation.genes {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
annotation_gene_uniquename);
}
if let Some(ref annotation_genotype_uniquename) = target_of_annotation.genotype_uniquename {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
gene_uniquename,
&annotation_genotype_uniquename)
}
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&target_of_annotation.reference_uniquename);
}
for publication in &gene_details.feature_publications {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&Some(publication.clone()));
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
let mut seen_genes: HashMap<RcString, GeneShortOptionMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
let mut seen_terms: HashMap<GeneUniquename, TermShortOptionMap> = HashMap::new();
{
for (reference_uniquename, reference_details) in &self.references {
for feat_annotations in reference_details.cv_annotations.values() {
for feat_annotation in feat_annotations.iter() {
self.add_term_to_hash(&mut seen_terms, reference_uniquename,
&feat_annotation.term);
for annotation_detail_id in &feat_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
gene_uniquename)
}
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(&mut seen_terms, reference_uniquename,
condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms,
reference_uniquename,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes,
reference_uniquename,
gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
let genotype = self.make_genotype_short(genotype_uniquename);
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
reference_uniquename,
&genotype.display_uniquename);
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter()
.chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&interaction.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&interaction.interactor_uniquename);
}
for ortholog_annotation in &reference_details.ortholog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&ortholog_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&ortholog_annotation.ortholog_uniquename);
}
for paralog_annotation in &reference_details.paralog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
¶log_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
¶log_annotation.paralog_uniquename);
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut term_seen_single_allele_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
let mut seen_single_allele_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for term_annotations in term_details.cv_annotations.values() {
for term_annotation in term_annotations {
for annotation_detail_id in &term_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
seen_genes.insert(gene_uniquename.clone());
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
seen_genotypes.insert(genotype_uniquename.clone());
let genotype = &self.genotypes[genotype_uniquename];
if genotype.expressed_alleles.len() == 1 {
seen_single_allele_genotypes.insert(genotype_uniquename.clone());
}
}
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
term_seen_single_allele_genotypes.insert(termid.clone(), seen_single_allele_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for rel_annotations in reference_details.cv_annotations.values() {
for rel_annotation in rel_annotations {
for annotation_detail_id in &rel_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
if !rel_annotation.is_not {
for gene_uniquename in &annotation_detail.genes {
seen_genes.insert(gene_uniquename.clone());
}
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for term_details in self.terms.values_mut() {
term_details.single_allele_genotype_uniquenames =
term_seen_single_allele_genotypes.remove(&term_details.termid).unwrap();
term_details.gene_count =
term_seen_genes[&term_details.termid].len();
term_details.genotype_count =
term_seen_genotypes[&term_details.termid].len();
}
}
fn make_non_bp_slim_gene_subset(&self, go_slim_subset: &TermSubsetDetails)
-> IdGeneSubsetMap
{
let slim_termid_set: HashSet<RcString> =
go_slim_subset.elements
.iter().map(|element| element.termid.clone()).collect();
let mut non_slim_with_bp_annotation = HashSet::new();
let mut non_slim_without_bp_annotation = HashSet::new();
let has_parent_in_slim = |term_annotations: &Vec<OntTermAnnotations>| {
for term_annotation in term_annotations {
let interesting_parents =
&self.terms[&term_annotation.term].interesting_parents;
if !term_annotation.is_not &&
(slim_termid_set.contains(&term_annotation.term) ||
interesting_parents.intersection(&slim_termid_set).count() > 0)
{
return true;
}
}
false
};
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
if gene_details.feature_type != "mRNA gene" {
continue;
}
if gene_details.characterisation_status == Some(RcString::from("transposon")) ||
gene_details.characterisation_status == Some(RcString::from("dubious"))
{
continue;
}
let mut bp_count = 0;
if let Some(annotations) =
gene_details.cv_annotations.get("biological_process") {
if has_parent_in_slim(&annotations) {
continue
}
bp_count = annotations.len();
}
if bp_count == 0 {
non_slim_without_bp_annotation.insert(gene_details.uniquename.clone());
} else {
non_slim_with_bp_annotation.insert(gene_details.uniquename.clone());
}
}
let mut return_map = HashMap::new();
let with_annotation_display_name =
String::from("Proteins with biological process ") +
"annotation that are not in a slim category";
return_map.insert("non_go_slim_with_bp_annotation".into(),
GeneSubsetDetails {
name: "non_go_slim_with_bp_annotation".into(),
display_name: RcString::from(&with_annotation_display_name),
elements: non_slim_with_bp_annotation,
});
let without_annotation_display_name =
String::from("Proteins with no biological process ") +
"annotation and are not in a slim category";
return_map.insert("non_go_slim_without_bp_annotation".into(),
GeneSubsetDetails {
name: "non_go_slim_without_bp_annotation".into(),
display_name: RcString::from(&without_annotation_display_name),
elements: non_slim_without_bp_annotation,
});
return_map
}
fn make_bp_go_slim_subset(&self) -> TermSubsetDetails {
let mut all_genes = HashSet::new();
let mut go_slim_subset: HashSet<TermSubsetElement> = HashSet::new();
for go_slim_conf in self.config.go_slim_terms.clone() {
let slim_termid = go_slim_conf.termid;
let term_details = self.terms.get(&slim_termid)
.unwrap_or_else(|| panic!("can't find TermDetails for {}", &slim_termid));
let subset_element = TermSubsetElement {
name: term_details.name.clone(),
termid: slim_termid.clone(),
gene_count: term_details.genes_annotated_with.len(),
};
for gene in &term_details.genes_annotated_with {
all_genes.insert(gene);
}
go_slim_subset.insert(subset_element);
}
TermSubsetDetails {
name: "goslim_pombe".into(),
total_gene_count: all_genes.len(),
elements: go_slim_subset,
}
}
fn make_feature_type_subsets(&self, subsets: &mut IdGeneSubsetMap) {
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
let subset_name =
RcString::from("feature_type:") + &gene_details.feature_type;
let re = Regex::new(r"[\s,:]+").unwrap();
let subset_name_no_spaces = RcString::from(&re.replace_all(&subset_name, "_"));
subsets.entry(subset_name_no_spaces.clone())
.or_insert(GeneSubsetDetails {
name: subset_name_no_spaces,
display_name: RcString::from(&subset_name),
elements: HashSet::new()
})
.elements.insert(gene_details.uniquename.clone());
}
}
// make subsets using the characterisation_status field of GeneDetails
fn make_characterisation_status_subsets(&self, subsets: &mut IdGeneSubsetMap) {
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
if gene_details.feature_type != "mRNA gene" {
continue;
}
if let Some(ref characterisation_status) = gene_details.characterisation_status {
let subset_name =
RcString::from("characterisation_status:") + &characterisation_status;
let re = Regex::new(r"[\s,:]+").unwrap();
let subset_name_no_spaces = RcString::from(&re.replace_all(&subset_name, "_"));
subsets.entry(subset_name_no_spaces.clone())
.or_insert(GeneSubsetDetails {
name: subset_name_no_spaces,
display_name: RcString::from(&subset_name),
elements: HashSet::new()
})
.elements.insert(gene_details.uniquename.clone());
}
}
}
// make InterPro subsets using the interpro_matches field of GeneDetails
fn make_interpro_subsets(&mut self, subsets: &mut IdGeneSubsetMap) {
for (gene_uniquename, gene_details) in &self.genes {
for interpro_match in &gene_details.interpro_matches {
let mut new_subset_names = vec![];
if !interpro_match.interpro_id.is_empty() {
let subset_name =
String::from("interpro:") + &interpro_match.interpro_id;
new_subset_names.push((RcString::from(&subset_name),
interpro_match.interpro_name.clone()));
}
let subset_name = String::from("interpro:") +
&interpro_match.dbname.clone() + ":" + &interpro_match.id;
new_subset_names.push((RcString::from(&subset_name), interpro_match.name.clone()));
for (subset_name, display_name) in new_subset_names {
subsets.entry(subset_name.clone())
.or_insert(GeneSubsetDetails {
name: subset_name,
display_name,
elements: HashSet::new(),
})
.elements.insert(gene_uniquename.clone());
}
}
}
}
// populated the subsets HashMap
fn make_subsets(&mut self) {
let bp_go_slim_subset = self.make_bp_go_slim_subset();
let mut gene_subsets =
self.make_non_bp_slim_gene_subset(&bp_go_slim_subset);
self.term_subsets.insert("bp_goslim_pombe".into(), bp_go_slim_subset);
self.make_feature_type_subsets(&mut gene_subsets);
self.make_characterisation_status_subsets(&mut gene_subsets);
self.make_interpro_subsets(&mut gene_subsets);
self.gene_subsets = gene_subsets;
}
// sort the list of genes in the ChromosomeDetails by start_pos
pub fn sort_chromosome_genes(&mut self) {
let mut genes_to_sort: HashMap<ChromosomeName, Vec<GeneUniquename>> =
HashMap::new();
{
let sorter = |uniquename1: &GeneUniquename, uniquename2: &GeneUniquename| {
let gene1 = &self.genes[uniquename1];
let gene2 = &self.genes[uniquename2];
if let Some(ref gene1_loc) = gene1.location {
if let Some(ref gene2_loc) = gene2.location {
let cmp = gene1_loc.start_pos.cmp(&gene2_loc.start_pos);
if cmp != Ordering::Equal {
return cmp;
}
}
}
if gene1.name.is_some() {
if gene2.name.is_some() {
gene1.name.cmp(&gene2.name)
} else {
Ordering::Less
}
} else {
if gene2.name.is_some() {
Ordering::Greater
} else {
gene1.uniquename.cmp(&gene2.uniquename)
}
}
};
for (chr_uniquename, chr_details) in &self.chromosomes {
genes_to_sort.insert(chr_uniquename.clone(),
chr_details.gene_uniquenames.clone());
}
for gene_uniquenames in genes_to_sort.values_mut() {
gene_uniquenames.sort_by(&sorter);
}
}
for (chr_uniquename, gene_uniquenames) in genes_to_sort {
self.chromosomes.get_mut(&chr_uniquename).unwrap().gene_uniquenames =
gene_uniquenames;
}
}
// remove some of the refs that have no annotations.
// See: https://github.com/pombase/website/issues/628
fn remove_non_curatable_refs(&mut self) {
let filtered_refs = self.references.drain()
.filter(|&(_, ref reference_details)| {
if reference_has_annotation(reference_details) {
return true;
}
if let Some(ref canto_triage_status) = reference_details.canto_triage_status {
if canto_triage_status == "New" {
return false;
}
} else {
if reference_details.uniquename.starts_with("PMID:") {
print!("reference {} has no canto_triage_status\n", reference_details.uniquename);
}
}
if let Some (ref triage_status) = reference_details.canto_triage_status {
return triage_status != "Wrong organism" && triage_status != "Loaded in error";
}
// default to true because there are references that
// haven't or shouldn't be triaged, eg. GO_REF:...
true
})
.into_iter().collect();
self.references = filtered_refs;
}
fn make_solr_term_summaries(&mut self) -> Vec<SolrTermSummary> {
let mut return_summaries = vec![];
let term_name_split_re = Regex::new(r"\W+").unwrap();
for (termid, term_details) in &self.terms {
if term_details.cv_annotations.keys()
.filter(|cv_name| !cv_name.starts_with("extension:"))
.next().is_none() {
continue;
}
let trimmable_p = |c: char| {
c.is_whitespace() || c == ',' || c == ':'
|| c == ';' || c == '.' || c == '\''
};
let term_name_words =
term_name_split_re.split(&term_details.name)
.map(|s: &str| {
s.trim_matches(&trimmable_p).to_owned()
}).collect::<Vec<String>>();
let mut close_synonyms = vec![];
let mut close_synonym_words_vec: Vec<RcString> = vec![];
let mut distant_synonyms = vec![];
let mut distant_synonym_words_vec: Vec<RcString> = vec![];
let add_to_words_vec = |synonym: &str, words_vec: &mut Vec<RcString>| {
let synonym_words = term_name_split_re.split(&synonym);
for word in synonym_words {
let word_string = RcString::from(word.trim_matches(&trimmable_p));
if !words_vec.contains(&word_string) &&
!term_name_words.contains(&word_string) {
words_vec.push(word_string);
}
}
};
for synonym in &term_details.synonyms {
if synonym.synonym_type == "exact" || synonym.synonym_type == "narrow" {
add_to_words_vec(&synonym.name, &mut close_synonym_words_vec);
close_synonyms.push(synonym.name.clone());
} else {
add_to_words_vec(&synonym.name, &mut distant_synonym_words_vec);
distant_synonyms.push(synonym.name.clone());
}
}
distant_synonyms = distant_synonyms.into_iter()
.filter(|synonym| {
!close_synonyms.contains(&synonym)
})
.collect::<Vec<_>>();
let interesting_parents_for_solr =
term_details.interesting_parents.clone();
let term_summ = SolrTermSummary {
id: termid.clone(),
cv_name: term_details.cv_name.clone(),
name: term_details.name.clone(),
definition: term_details.definition.clone(),
close_synonyms,
close_synonym_words: RcString::from(&close_synonym_words_vec.join(" ")),
distant_synonyms,
distant_synonym_words: RcString::from(&distant_synonym_words_vec.join(" ")),
interesting_parents: interesting_parents_for_solr,
};
return_summaries.push(term_summ);
}
return_summaries
}
fn make_solr_reference_summaries(&mut self) -> Vec<SolrReferenceSummary> {
let mut return_summaries = vec![];
for reference_details in self.references.values() {
return_summaries.push(SolrReferenceSummary::from_reference_details(reference_details));
}
return_summaries
}
pub fn get_web_data(mut self) -> WebData {
self.process_dbxrefs();
self.process_references();
self.process_chromosome_features();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_publications();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_deletion_viability();
self.set_term_details_subsets();
self.make_all_cv_summaries();
self.remove_non_curatable_refs();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
self.make_subsets();
self.sort_chromosome_genes();
let metadata = self.make_metadata();
let mut gene_summaries: Vec<GeneSummary> = vec![];
for (gene_uniquename, gene_details) in &self.genes {
if self.config.load_organism_taxonid == gene_details.taxonid {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
}
let solr_term_summaries = self.make_solr_term_summaries();
let solr_reference_summaries = self.make_solr_reference_summaries();
let solr_data = SolrData {
term_summaries: solr_term_summaries,
gene_summaries: gene_summaries.clone(),
reference_summaries: solr_reference_summaries,
};
let chromosomes = self.chromosomes.clone();
let mut chromosome_summaries = vec![];
for chr_details in self.chromosomes.values() {
chromosome_summaries.push(chr_details.make_chromosome_short());
}
let term_subsets = self.term_subsets.clone();
let gene_subsets = self.gene_subsets.clone();
let recent_references = self.recent_references.clone();
let all_community_curated = self.all_community_curated.clone();
let ont_annotations = self.ont_annotations.clone();
WebData {
metadata,
chromosomes,
chromosome_summaries,
recent_references,
all_community_curated,
api_maps: self.make_api_maps(),
search_gene_summaries: gene_summaries,
term_subsets,
gene_subsets,
solr_data,
ont_annotations,
}
}
}
Check that residues are all ASCII chars
Refs pombase/website#744
use std::rc::Rc;
use std::collections::{BTreeMap, HashMap};
use std::collections::HashSet;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::u32;
use regex::Regex;
use db::*;
use types::*;
use web::data::*;
use web::config::*;
use web::cv_summary::make_cv_summaries;
use web::util::cmp_str_dates;
use pombase_rc_string::RcString;
use interpro::UniprotResult;
fn make_organism(rc_organism: &Rc<Organism>) -> ConfigOrganism {
let mut maybe_taxonid: Option<u32> = None;
for prop in rc_organism.organismprops.borrow().iter() {
if prop.prop_type.name == "taxon_id" {
maybe_taxonid = Some(prop.value.parse().unwrap());
}
}
ConfigOrganism {
taxonid: maybe_taxonid.unwrap(),
genus: rc_organism.genus.clone(),
species: rc_organism.species.clone(),
assembly_version: None,
}
}
type TermShortOptionMap = HashMap<TermId, Option<TermShort>>;
type UniprotIdentifier = RcString;
pub struct WebDataBuild<'a> {
raw: &'a Raw,
domain_data: &'a HashMap<UniprotIdentifier, UniprotResult>,
config: &'a Config,
genes: UniquenameGeneMap,
genotypes: UniquenameGenotypeMap,
genotype_backgrounds: HashMap<GenotypeUniquename, RcString>,
alleles: UniquenameAlleleMap,
other_features: UniquenameFeatureShortMap,
terms: TermIdDetailsMap,
chromosomes: ChrNameDetailsMap,
references: UniquenameReferenceMap,
all_ont_annotations: HashMap<TermId, Vec<OntAnnotationId>>,
all_not_ont_annotations: HashMap<TermId, Vec<OntAnnotationId>>,
genes_of_transcripts: HashMap<RcString, RcString>,
transcripts_of_polypeptides: HashMap<RcString, RcString>,
parts_of_transcripts: HashMap<RcString, Vec<FeatureShort>>,
genes_of_alleles: HashMap<RcString, RcString>,
alleles_of_genotypes: HashMap<RcString, Vec<ExpressedAllele>>,
// a map from IDs of terms from the "PomBase annotation extension terms" cv
// to a Vec of the details of each of the extension
parts_of_extensions: HashMap<TermId, Vec<ExtPart>>,
base_term_of_extensions: HashMap<TermId, TermId>,
children_by_termid: HashMap<TermId, HashSet<TermId>>,
dbxrefs_of_features: HashMap<RcString, HashSet<RcString>>,
possible_interesting_parents: HashSet<InterestingParent>,
recent_references: RecentReferences,
all_community_curated: Vec<ReferenceShort>,
term_subsets: IdTermSubsetMap,
gene_subsets: IdGeneSubsetMap,
annotation_details: IdOntAnnotationDetailMap,
ont_annotations: Vec<OntAnnotation>,
}
fn get_maps() ->
(HashMap<RcString, ReferenceShortOptionMap>,
HashMap<RcString, GeneShortOptionMap>,
HashMap<RcString, GenotypeShortMap>,
HashMap<RcString, AlleleShortMap>,
HashMap<GeneUniquename, TermShortOptionMap>)
{
(HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new())
}
fn get_feat_rel_expression(feature: &Feature,
feature_relationship: &FeatureRelationship) -> Option<RcString> {
for feature_prop in feature.featureprops.borrow().iter() {
if feature_prop.prop_type.name == "allele_type" {
if let Some(ref value) = feature_prop.value {
if value == "deletion" {
return Some("Null".into());
}
}
}
}
for rel_prop in feature_relationship.feature_relationshipprops.borrow().iter() {
if rel_prop.prop_type.name == "expression" {
return rel_prop.value.clone();
}
}
None
}
fn reference_has_annotation(reference_details: &ReferenceDetails) -> bool {
!reference_details.cv_annotations.is_empty() ||
!reference_details.physical_interactions.is_empty() ||
!reference_details.genetic_interactions.is_empty() ||
!reference_details.ortholog_annotations.is_empty() ||
!reference_details.paralog_annotations.is_empty()
}
fn is_gene_type(feature_type_name: &str) -> bool {
feature_type_name == "gene" || feature_type_name == "pseudogene"
}
pub fn compare_ext_part_with_config(config: &Config, ep1: &ExtPart, ep2: &ExtPart) -> Ordering {
let rel_order_conf = &config.extension_relation_order;
let order_conf = &rel_order_conf.relation_order;
let always_last_conf = &rel_order_conf.always_last;
let maybe_ep1_index = order_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_index = order_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_index) = maybe_ep1_index {
if let Some(ep2_index) = maybe_ep2_index {
ep1_index.cmp(&ep2_index)
} else {
Ordering::Less
}
} else {
if maybe_ep2_index.is_some() {
Ordering::Greater
} else {
let maybe_ep1_last_index = always_last_conf.iter().position(|r| *r == ep1.rel_type_name);
let maybe_ep2_last_index = always_last_conf.iter().position(|r| *r == ep2.rel_type_name);
if let Some(ep1_last_index) = maybe_ep1_last_index {
if let Some(ep2_last_index) = maybe_ep2_last_index {
ep1_last_index.cmp(&ep2_last_index)
} else {
Ordering::Greater
}
} else {
if maybe_ep2_last_index.is_some() {
Ordering::Less
} else {
let name_cmp = ep1.rel_type_name.cmp(&ep2.rel_type_name);
if name_cmp == Ordering::Equal {
if ep1.ext_range.is_gene() && !ep2.ext_range.is_gene() {
Ordering::Less
} else {
if !ep1.ext_range.is_gene() && ep2.ext_range.is_gene() {
Ordering::Greater
} else {
Ordering::Equal
}
}
} else {
name_cmp
}
}
}
}
}
}
fn string_from_ext_range(ext_range: &ExtRange,
genes: &UniquenameGeneMap, terms: &TermIdDetailsMap) -> RcString {
match *ext_range {
ExtRange::Gene(ref gene_uniquename) | ExtRange::Promoter(ref gene_uniquename) => {
let gene = genes.get(gene_uniquename)
.unwrap_or_else(|| panic!("can't find gene: {}", gene_uniquename));
gene_display_name(gene)
},
ExtRange::SummaryGenes(_) => panic!("can't handle SummaryGenes\n"),
ExtRange::Term(ref termid) => RcString::from(&terms.get(termid).unwrap().name),
ExtRange::SummaryModifiedResidues(_) => panic!("can't handle ModifiedResidues\n"),
ExtRange::SummaryTerms(_) => panic!("can't handle SummaryGenes\n"),
ExtRange::Misc(ref misc) => misc.clone(),
ExtRange::Domain(ref domain) => domain.clone(),
ExtRange::GeneProduct(ref gene_product) => gene_product.clone(),
}
}
fn cmp_ext_part(ext_part1: &ExtPart, ext_part2: &ExtPart,
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let ord = ext_part1.rel_type_display_name.cmp(&ext_part2.rel_type_display_name);
if ord == Ordering::Equal {
let ext_part1_str = string_from_ext_range(&ext_part1.ext_range, genes, terms);
let ext_part2_str = string_from_ext_range(&ext_part2.ext_range, genes, terms);
ext_part1_str.to_lowercase().cmp(&ext_part2_str.to_lowercase())
} else {
ord
}
}
// compare the extension up to the last common index
fn cmp_extension_prefix(cv_config: &CvConfig, ext1: &[ExtPart], ext2: &[ExtPart],
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let conf_rel_ranges = &cv_config.summary_relation_ranges_to_collect;
let is_grouping_rel_name =
|ext: &ExtPart| !conf_rel_ranges.contains(&ext.rel_type_name);
// put the extension that will be grouped in the summary at the end
// See: https://github.com/pombase/pombase-chado/issues/636
let (mut ext1_for_cmp, ext1_rest): (Vec<ExtPart>, Vec<ExtPart>) =
ext1.to_vec().into_iter().partition(&is_grouping_rel_name);
ext1_for_cmp.extend(ext1_rest.into_iter());
let (mut ext2_for_cmp, ext2_rest): (Vec<ExtPart>, Vec<ExtPart>) =
ext2.to_vec().into_iter().partition(&is_grouping_rel_name);
ext2_for_cmp.extend(ext2_rest.into_iter());
let iter = ext1_for_cmp.iter().zip(&ext2_for_cmp).enumerate();
for (_, (ext1_part, ext2_part)) in iter {
let ord = cmp_ext_part(ext1_part, ext2_part, genes, terms);
if ord != Ordering::Equal {
return ord
}
}
Ordering::Equal
}
fn cmp_extension(cv_config: &CvConfig, ext1: &[ExtPart], ext2: &[ExtPart],
genes: &UniquenameGeneMap,
terms: &TermIdDetailsMap) -> Ordering {
let cmp = cmp_extension_prefix(cv_config, ext1, ext2, genes, terms);
if cmp == Ordering::Equal {
ext1.len().cmp(&ext2.len())
} else {
cmp
}
}
fn cmp_genotypes(genotype1: &GenotypeDetails, genotype2: &GenotypeDetails) -> Ordering {
genotype1.display_uniquename.to_lowercase().cmp(&genotype2.display_uniquename.to_lowercase())
}
fn allele_display_name(allele: &AlleleShort) -> RcString {
let name = allele.name.clone().unwrap_or_else(|| RcString::from("unnamed"));
let allele_type = allele.allele_type.clone();
let description = allele.description.clone().unwrap_or_else(|| allele_type.clone());
if allele_type == "deletion" && name.ends_with("delta") ||
allele_type.starts_with("wild_type") && name.ends_with('+') {
let normalised_description = description.replace("[\\s_]+", "");
let normalised_allele_type = allele_type.replace("[\\s_]+", "");
if normalised_description != normalised_allele_type {
return RcString::from(&(name + "(" + description.as_str() + ")"));
} else {
return name;
}
}
let display_name =
if allele_type == "deletion" {
name + "-" + description.as_str()
} else {
name + "-" + description.as_str() + "-" + &allele.allele_type
};
RcString::from(&display_name)
}
fn gene_display_name(gene: &GeneDetails) -> RcString {
if let Some(ref name) = gene.name {
name.clone()
} else {
gene.uniquename.clone()
}
}
pub fn make_genotype_display_name(genotype_expressed_alleles: &[ExpressedAllele],
allele_map: &UniquenameAlleleMap) -> RcString {
let mut allele_display_names: Vec<String> =
genotype_expressed_alleles.iter().map(|expressed_allele| {
let allele_short = allele_map.get(&expressed_allele.allele_uniquename).unwrap();
let mut display_name = allele_display_name(allele_short).to_string();
if allele_short.allele_type != "deletion" {
if display_name == "unnamed-unrecorded-unrecorded" {
display_name = format!("{}-{}", allele_short.gene_uniquename,
display_name);
}
if let Some(ref expression) = expressed_allele.expression {
display_name += &format!("-expression-{}", expression.to_lowercase());
}
}
display_name
}).collect();
allele_display_names.sort();
let joined_alleles = allele_display_names.join(" ");
RcString::from(&str::replace(&joined_alleles, " ", "_"))
}
fn make_phase(feature_loc: &Featureloc) -> Option<Phase> {
if let Some(phase) = feature_loc.phase {
match phase {
0 => Some(Phase::Zero),
1 => Some(Phase::One),
2 => Some(Phase::Two),
_ => panic!(),
}
} else {
None
}
}
fn make_location(chromosome_map: &ChrNameDetailsMap,
feat: &Feature) -> Option<ChromosomeLocation> {
let feature_locs = feat.featurelocs.borrow();
match feature_locs.get(0) {
Some(feature_loc) => {
let start_pos =
if feature_loc.fmin + 1 >= 1 {
(feature_loc.fmin + 1) as u32
} else {
panic!("start_pos less than 1");
};
let end_pos =
if feature_loc.fmax >= 1 {
feature_loc.fmax as u32
} else {
panic!("start_end less than 1");
};
let feature_uniquename = &feature_loc.srcfeature.uniquename;
let chr_short = make_chromosome_short(chromosome_map, feature_uniquename);
Some(ChromosomeLocation {
chromosome_name: chr_short.name,
start_pos,
end_pos,
strand: match feature_loc.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => panic!(),
},
phase: make_phase(&feature_loc),
})
},
None => None,
}
}
fn complement_char(base: char) -> char {
match base {
'a' => 't',
'A' => 'T',
't' => 'a',
'T' => 'A',
'g' => 'c',
'G' => 'C',
'c' => 'g',
'C' => 'G',
_ => 'n',
}
}
fn rev_comp(residues: &str) -> Residues {
let residues: String = residues.chars()
.rev().map(complement_char)
.collect();
RcString::from(&residues)
}
fn get_loc_residues(chr: &ChromosomeDetails,
loc: &ChromosomeLocation) -> Residues {
let start = (loc.start_pos - 1) as usize;
let end = loc.end_pos as usize;
let residues: Residues = chr.residues[start..end].into();
if loc.strand == Strand::Forward {
residues
} else {
rev_comp(&residues)
}
}
fn make_feature_short(chromosome_map: &ChrNameDetailsMap, feat: &Feature) -> FeatureShort {
let maybe_loc = make_location(chromosome_map, feat);
if let Some(loc) = maybe_loc {
if let Some(chr) = chromosome_map.get(&loc.chromosome_name) {
let residues = get_loc_residues(chr, &loc);
let feature_type = match &feat.feat_type.name as &str {
"five_prime_UTR" => FeatureType::FivePrimeUtr,
"pseudogenic_exon" | "exon" => FeatureType::Exon,
"three_prime_UTR" => FeatureType::ThreePrimeUtr,
"dg_repeat" => FeatureType::DGRepeat,
"dh_repeat" => FeatureType::DHRepeat,
"gap" => FeatureType::Gap,
"gene_group" => FeatureType::GeneGroup,
"long_terminal_repeat" => FeatureType::LongTerminalRepeat,
"low_complexity_region" => FeatureType::LowComplexityRegion,
"LTR_retrotransposon" => FeatureType::LTRRetrotransposon,
"mating_type_region" => FeatureType::MatingTypeRegion,
"nuclear_mt_pseudogene" => FeatureType::NuclearMtPseudogene,
"origin_of_replication" => FeatureType::OriginOfReplication,
"polyA_signal_sequence" => FeatureType::PolyASignalSequence,
"polyA_site" => FeatureType::PolyASite,
"promoter" => FeatureType::Promoter,
"region" => FeatureType::Region,
"regional_centromere" => FeatureType::RegionalCentromere,
"regional_centromere_central_core" => FeatureType::RegionalCentromereCentralCore,
"regional_centromere_inner_repeat_region" => FeatureType::RegionalCentromereInnerRepeatRegion,
"repeat_region" => FeatureType::RepeatRegion,
"TR_box" => FeatureType::TRBox,
"SNP" => FeatureType::SNP,
_ => panic!("can't handle feature type: {}", feat.feat_type.name),
};
FeatureShort {
feature_type,
uniquename: feat.uniquename.clone(),
location: loc,
residues,
}
} else {
panic!("can't find chromosome {}", loc.chromosome_name);
}
} else {
panic!("{} has no featureloc", feat.uniquename);
}
}
pub fn make_chromosome_short<'a>(chromosome_map: &'a ChrNameDetailsMap,
chromosome_name: &'a str) -> ChromosomeShort {
if let Some(chr) = chromosome_map.get(chromosome_name) {
chr.make_chromosome_short()
} else {
panic!("can't find chromosome: {}", chromosome_name);
}
}
fn make_gene_short<'b>(gene_map: &'b UniquenameGeneMap,
gene_uniquename: &'b str) -> GeneShort {
if let Some(gene_details) = gene_map.get(gene_uniquename) {
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_reference_short<'a>(reference_map: &'a UniquenameReferenceMap,
reference_uniquename: &str) -> Option<ReferenceShort> {
if reference_uniquename == "null" {
None
} else {
let reference_details = reference_map.get(reference_uniquename)
.unwrap_or_else(|| panic!("missing reference in make_reference_short(): {}",
reference_uniquename));
let reference_short = ReferenceShort::from_reference_details(reference_details);
Some(reference_short)
}
}
// compare two gene vectors which must be ordered vecs
fn cmp_gene_vec(genes: &UniquenameGeneMap,
gene_vec1: &[GeneUniquename],
gene_vec2: &[GeneUniquename]) -> Ordering {
let gene_short_vec1: Vec<GeneShort> =
gene_vec1.iter().map(|gene_uniquename: &RcString| {
make_gene_short(genes, gene_uniquename)
}).collect();
let gene_short_vec2: Vec<GeneShort> =
gene_vec2.iter().map(|gene_uniquename: &RcString| {
make_gene_short(genes, gene_uniquename)
}).collect();
gene_short_vec1.cmp(&gene_short_vec2)
}
lazy_static! {
static ref MODIFICATION_RE: Regex = Regex::new(r"^(?P<aa>[A-Z])(?P<pos>\d+)$").unwrap();
static ref PROMOTER_RE: Regex = Regex::new(r"^(?P<gene>.*)-promoter$").unwrap();
}
fn cmp_residues(residue1: &Option<Residue>, residue2: &Option<Residue>) -> Ordering {
if let Some(ref res1) = *residue1 {
if let Some(ref res2) = *residue2 {
if let (Some(res1_captures), Some(res2_captures)) =
(MODIFICATION_RE.captures(res1), MODIFICATION_RE.captures(res2))
{
let res1_aa = res1_captures.name("aa").unwrap().as_str();
let res2_aa = res2_captures.name("aa").unwrap().as_str();
let aa_order = res1_aa.cmp(&res2_aa);
if aa_order == Ordering::Equal {
let res1_pos =
res1_captures.name("pos").unwrap().as_str().parse::<i32>().unwrap();
let res2_pos =
res2_captures.name("pos").unwrap().as_str().parse::<i32>().unwrap();
res1_pos.cmp(&res2_pos)
} else {
aa_order
}
} else {
res1.cmp(&res2)
}
} else {
Ordering::Less
}
} else {
if residue2.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
pub fn cmp_ont_annotation_detail(cv_config: &CvConfig,
detail1: &OntAnnotationDetail,
detail2: &OntAnnotationDetail,
genes: &UniquenameGeneMap,
genotypes: &UniquenameGenotypeMap,
terms: &TermIdDetailsMap) -> Result<Ordering, String> {
if let Some(ref detail1_genotype_uniquename) = detail1.genotype {
if let Some(ref detail2_genotype_uniquename) = detail2.genotype {
let genotype1 = genotypes.get(detail1_genotype_uniquename).unwrap();
let genotype2 = genotypes.get(detail2_genotype_uniquename).unwrap();
let ord = cmp_genotypes(genotype1, genotype2);
if ord == Ordering::Equal {
Ok(cmp_extension(cv_config, &detail1.extension, &detail2.extension,
genes, terms))
} else {
Ok(ord)
}
} else {
Err(format!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n", detail1, detail2))
}
} else {
if detail2.genotype.is_some() {
Err(format!("comparing two OntAnnotationDetail but one has a genotype and
one a gene:\n{:?}\n{:?}\n", detail1, detail2))
} else {
let ord = cmp_gene_vec(genes, &detail1.genes, &detail2.genes);
if ord == Ordering::Equal {
if let Some(ref sort_details_by) = cv_config.sort_details_by {
for sort_type in sort_details_by {
if sort_type == "modification" {
let res = cmp_residues(&detail1.residue, &detail2.residue);
if res != Ordering::Equal {
return Ok(res);
}
} else {
let res = cmp_extension(cv_config, &detail1.extension,
&detail2.extension, genes, terms);
if res != Ordering::Equal {
return Ok(res);
}
}
}
Ok(Ordering::Equal)
} else {
Ok(cmp_extension(cv_config, &detail1.extension, &detail2.extension,
genes, terms))
}
} else {
Ok(ord)
}
}
}
}
// Some ancestor terms are useful in the web code. This function uses the Config and returns
// the terms that might be useful.
fn get_possible_interesting_parents(config: &Config) -> HashSet<InterestingParent> {
let mut ret = HashSet::new();
for parent_conf in &config.interesting_parents {
ret.insert(parent_conf.clone());
}
for ext_conf in &config.extension_display_names {
if let Some(ref conf_termid) = ext_conf.if_descendant_of {
ret.insert(InterestingParent {
termid: conf_termid.clone(),
rel_name: RcString::from("is_a"),
});
}
}
let add_to_set = |set: &mut HashSet<_>, termid: RcString| {
for rel_name in &DESCENDANT_REL_NAMES {
set.insert(InterestingParent {
termid: termid.to_owned(),
rel_name: RcString::from(rel_name),
});
}
};
for go_slim_conf in &config.go_slim_terms {
add_to_set(&mut ret, go_slim_conf.termid.clone());
}
for go_termid in &config.query_data_config.go_components {
add_to_set(&mut ret, go_termid.clone());
}
for go_termid in &config.query_data_config.go_process_superslim {
add_to_set(&mut ret, go_termid.clone());
}
for go_termid in &config.query_data_config.go_function {
add_to_set(&mut ret, go_termid.clone());
}
ret.insert(InterestingParent {
termid: config.viability_terms.viable.clone(),
rel_name: RcString::from("is_a"),
});
ret.insert(InterestingParent {
termid: config.viability_terms.inviable.clone(),
rel_name: RcString::from("is_a"),
});
let add_filter_ancestor =
|set: &mut HashSet<_>, category: &AncestorFilterCategory, cv_name: &str| {
for ancestor in &category.ancestors {
for config_rel_name in &DESCENDANT_REL_NAMES {
if *config_rel_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&cv_name) {
continue;
}
set.insert(InterestingParent {
termid: ancestor.clone(),
rel_name: RcString::from(*config_rel_name),
});
}
}
};
for (cv_name, conf) in &config.cv_config {
for filter in &conf.filters {
for category in &filter.term_categories {
add_filter_ancestor(&mut ret, category, cv_name);
}
for category in &filter.extension_categories {
add_filter_ancestor(&mut ret, category, cv_name);
}
}
for split_by_parent_config in &conf.split_by_parents {
for ancestor in &split_by_parent_config.termids {
let ancestor_termid =
if ancestor.starts_with("NOT ") {
RcString::from(&ancestor[4..])
} else {
ancestor.clone()
};
ret.insert(InterestingParent {
termid: ancestor_termid,
rel_name: "is_a".into(),
});
}
}
}
ret
}
const MAX_RECENT_REFS: usize = 20;
fn make_recently_added(references_map: &UniquenameReferenceMap,
all_ref_uniquenames: &[RcString]) -> Vec<ReferenceShort> {
let mut date_sorted_pub_uniquenames = all_ref_uniquenames.to_owned();
{
let ref_added_date_cmp =
|ref_uniquename1: &ReferenceUniquename, ref_uniquename2: &ReferenceUniquename| {
let ref1 = references_map.get(ref_uniquename1).unwrap();
let ref2 = references_map.get(ref_uniquename2).unwrap();
if let Some(ref ref1_added_date) = ref1.canto_added_date {
if let Some(ref ref2_added_date) = ref2.canto_added_date {
cmp_str_dates(ref1_added_date, ref2_added_date).reverse()
} else {
Ordering::Less
}
} else {
if ref2.canto_added_date.is_some() {
Ordering::Greater
} else {
Ordering::Equal
}
}
};
date_sorted_pub_uniquenames.sort_by(ref_added_date_cmp);
}
let recently_added_iter =
date_sorted_pub_uniquenames.iter().take(MAX_RECENT_REFS);
let mut recently_added: Vec<ReferenceShort> = vec![];
for ref_uniquename in recently_added_iter {
let ref_short_maybe = make_reference_short(references_map, ref_uniquename);
if let Some(ref_short) = ref_short_maybe {
recently_added.push(ref_short);
}
}
recently_added
}
fn make_canto_curated(references_map: &UniquenameReferenceMap,
all_ref_uniquenames: &[RcString])
-> (Vec<ReferenceShort>, Vec<ReferenceShort>, Vec<ReferenceShort>) {
let mut sorted_pub_uniquenames: Vec<ReferenceUniquename> =
all_ref_uniquenames.iter()
.filter(|ref_uniquename| {
let reference = references_map.get(*ref_uniquename).unwrap();
(reference.canto_first_approved_date.is_some() ||
reference.canto_session_submitted_date.is_some()) &&
reference.canto_curator_role.is_some()
})
.cloned()
.collect();
{
let pub_date_cmp =
|ref_uniquename1: &ReferenceUniquename, ref_uniquename2: &ReferenceUniquename| {
let ref1 = references_map.get(ref_uniquename1).unwrap();
let ref2 = references_map.get(ref_uniquename2).unwrap();
// use first approval date, but fall back to the most recent approval date
let ref1_date =
ref1.canto_first_approved_date.as_ref()
.unwrap_or_else(|| ref1.canto_approved_date.as_ref()
.unwrap_or_else(|| ref1.canto_session_submitted_date.
as_ref().unwrap()));
let ref2_date =
ref2.canto_first_approved_date.as_ref()
.unwrap_or_else(|| ref2.canto_approved_date.as_ref()
.unwrap_or_else(|| ref2.canto_session_submitted_date.
as_ref().unwrap()));
cmp_str_dates(ref2_date, ref1_date)
};
sorted_pub_uniquenames.sort_by(pub_date_cmp);
}
let mut recent_admin_curated = vec![];
let mut recent_community_curated = vec![];
let mut all_community_curated = vec![];
let ref_uniquename_iter = sorted_pub_uniquenames.iter();
for ref_uniquename in ref_uniquename_iter {
let reference = references_map.get(ref_uniquename).unwrap();
if reference.canto_curator_role == Some("community".into()) {
let ref_short = make_reference_short(references_map, ref_uniquename).unwrap();
all_community_curated.push(ref_short.clone());
if recent_community_curated.len() <= MAX_RECENT_REFS {
recent_community_curated.push(ref_short);
}
} else {
if recent_admin_curated.len() <= MAX_RECENT_REFS {
let ref_short = make_reference_short(references_map, ref_uniquename).unwrap();
recent_admin_curated.push(ref_short);
}
}
}
(recent_admin_curated, recent_community_curated, all_community_curated)
}
fn add_introns_to_transcript(chromosome: &ChromosomeDetails,
transcript_uniquename: &str, parts: &mut Vec<FeatureShort>) {
let mut new_parts: Vec<FeatureShort> = vec![];
let mut intron_count = 0;
for part in parts.drain(0..) {
let mut maybe_new_intron = None;
if let Some(prev_part) = new_parts.last() {
let intron_start = prev_part.location.end_pos + 1;
let intron_end = part.location.start_pos - 1;
if intron_start > intron_end {
if intron_start > intron_end + 1 {
println!("no gap between exons at {}..{} in {}", intron_start, intron_end,
transcript_uniquename);
}
// if intron_start == intron_end-1 then it is a one base overlap that
// represents a frameshift in the reference See:
// https://github.com/pombase/curation/issues/1453#issuecomment-303214177
} else {
intron_count += 1;
let new_intron_loc = ChromosomeLocation {
chromosome_name: prev_part.location.chromosome_name.clone(),
start_pos: intron_start,
end_pos: intron_end,
strand: prev_part.location.strand.clone(),
phase: None,
};
let intron_uniquename =
format!("{}:intron:{}", transcript_uniquename, intron_count);
let intron_residues = get_loc_residues(chromosome, &new_intron_loc);
let intron_type =
if prev_part.feature_type == FeatureType::Exon &&
part.feature_type == FeatureType::Exon {
FeatureType::CdsIntron
} else {
if prev_part.feature_type == FeatureType::FivePrimeUtr {
FeatureType::FivePrimeUtrIntron
} else {
FeatureType::ThreePrimeUtrIntron
}
};
maybe_new_intron = Some(FeatureShort {
feature_type: intron_type,
uniquename: RcString::from(&intron_uniquename),
location: new_intron_loc,
residues: intron_residues,
});
}
}
if let Some(new_intron) = maybe_new_intron {
new_parts.push(new_intron);
}
new_parts.push(part);
}
*parts = new_parts;
}
fn validate_transcript_parts(transcript_uniquename: &str, parts: &[FeatureShort]) {
let mut seen_exon = false;
for part in parts {
if part.feature_type == FeatureType::Exon {
seen_exon = true;
break;
}
}
if !seen_exon {
panic!("transcript has no exons: {}", transcript_uniquename);
}
if parts[0].feature_type != FeatureType::Exon {
for i in 1..parts.len() {
let part = &parts[i];
if part.feature_type == FeatureType::Exon {
let last_utr_before_exons = &parts[i-1];
let first_exon = &parts[i];
if last_utr_before_exons.location.end_pos + 1 != first_exon.location.start_pos {
println!("{} and exon don't meet up: {} at pos {}",
last_utr_before_exons.feature_type, transcript_uniquename,
last_utr_before_exons.location.end_pos);
}
break;
} else {
if part.location.strand == Strand::Forward {
if part.feature_type != FeatureType::FivePrimeUtr {
println!("{:?}", parts);
panic!("wrong feature type '{}' before exons in {}",
part.feature_type, transcript_uniquename);
}
} else {
if part.feature_type != FeatureType::ThreePrimeUtr {
println!("{:?}", parts);
panic!("wrong feature type '{}' after exons in {}",
part.feature_type, transcript_uniquename);
}
}
}
}
}
let last_part = parts.last().unwrap();
if last_part.feature_type != FeatureType::Exon {
for i in (0..parts.len()-1).rev() {
let part = &parts[i];
if part.feature_type == FeatureType::Exon {
let first_utr_after_exons = &parts[i+1];
let last_exon = &parts[i];
if last_exon.location.end_pos + 1 != first_utr_after_exons.location.start_pos {
println!("{} and exon don't meet up: {} at pos {}",
first_utr_after_exons.feature_type, transcript_uniquename,
first_utr_after_exons.location.end_pos);
}
break;
} else {
if part.location.strand == Strand::Forward {
if part.feature_type != FeatureType::ThreePrimeUtr {
panic!("wrong feature type '{}' before exons in {}",
part.feature_type, transcript_uniquename);
}
} else {
if part.feature_type != FeatureType::FivePrimeUtr {
panic!("wrong feature type '{}' after exons in {}",
part.feature_type, transcript_uniquename);
}
}
}
}
}
}
impl <'a> WebDataBuild<'a> {
pub fn new(raw: &'a Raw, domain_data: &'a HashMap<UniprotIdentifier, UniprotResult>,
config: &'a Config) -> WebDataBuild<'a>
{
WebDataBuild {
raw,
domain_data,
config,
genes: BTreeMap::new(),
genotypes: HashMap::new(),
genotype_backgrounds: HashMap::new(),
alleles: HashMap::new(),
other_features: HashMap::new(),
terms: HashMap::new(),
chromosomes: BTreeMap::new(),
references: HashMap::new(),
all_ont_annotations: HashMap::new(),
all_not_ont_annotations: HashMap::new(),
recent_references: RecentReferences {
admin_curated: vec![],
community_curated: vec![],
pubmed: vec![],
},
all_community_curated: vec![],
genes_of_transcripts: HashMap::new(),
transcripts_of_polypeptides: HashMap::new(),
parts_of_transcripts: HashMap::new(),
genes_of_alleles: HashMap::new(),
alleles_of_genotypes: HashMap::new(),
parts_of_extensions: HashMap::new(),
base_term_of_extensions: HashMap::new(),
children_by_termid: HashMap::new(),
dbxrefs_of_features: HashMap::new(),
possible_interesting_parents: get_possible_interesting_parents(config),
term_subsets: HashMap::new(),
gene_subsets: HashMap::new(),
annotation_details: HashMap::new(),
ont_annotations: vec![],
}
}
fn add_ref_to_hash(&self,
seen_references: &mut HashMap<RcString, ReferenceShortOptionMap>,
identifier: &str,
maybe_reference_uniquename: &Option<ReferenceUniquename>) {
if let Some(reference_uniquename) = maybe_reference_uniquename {
if reference_uniquename != "null" {
seen_references
.entry(identifier.into())
.or_insert_with(HashMap::new)
.insert(reference_uniquename.clone(), None);
}
}
}
fn add_gene_to_hash(&self,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
other_gene_uniquename: &GeneUniquename) {
seen_genes
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(other_gene_uniquename.clone(), None);
}
fn add_genotype_to_hash(&self,
seen_genotypes: &mut HashMap<RcString, GenotypeShortMap>,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
genotype_uniquename: &RcString) {
let genotype_short = self.make_genotype_short(&genotype_uniquename);
for expressed_allele in &genotype_short.expressed_alleles {
self.add_allele_to_hash(seen_alleles, seen_genes, identifier,
&expressed_allele.allele_uniquename);
}
seen_genotypes
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(genotype_uniquename.clone(), genotype_short);
}
fn add_allele_to_hash(&self,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
identifier: &RcString,
allele_uniquename: &AlleleUniquename) -> AlleleShort {
let allele_short = self.make_allele_short(&allele_uniquename);
{
let allele_gene_uniquename = &allele_short.gene_uniquename;
self.add_gene_to_hash(seen_genes, identifier, allele_gene_uniquename);
seen_alleles
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(allele_uniquename.clone(), allele_short.clone());
}
allele_short
}
fn add_term_to_hash(&self,
seen_terms: &mut HashMap<TermId, TermShortOptionMap>,
identifier: &RcString,
other_termid: &TermId) {
seen_terms
.entry(identifier.clone())
.or_insert_with(HashMap::new)
.insert(other_termid.clone(), None);
}
fn get_gene<'b>(&'b self, gene_uniquename: &'b str) -> &'b GeneDetails {
if let Some(gene_details) = self.genes.get(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn get_gene_mut<'b>(&'b mut self, gene_uniquename: &'b str) -> &'b mut GeneDetails {
if let Some(gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details
} else {
panic!("can't find GeneDetails for gene uniquename {}", gene_uniquename)
}
}
fn make_gene_short(&self, gene_uniquename: &str) -> GeneShort {
let gene_details = self.get_gene(gene_uniquename);
GeneShort {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
}
}
fn make_gene_summary(&self, gene_uniquename: &str) -> GeneSummary {
let gene_details = self.get_gene(gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<RcString>>();
let mut ortholog_ids =
gene_details.ortholog_annotations.iter()
.map(|ortholog_annotation| {
IdAndOrganism {
identifier: ortholog_annotation.ortholog_uniquename.clone(),
taxonid: ortholog_annotation.ortholog_taxonid,
}
})
.collect::<Vec<IdAndOrganism>>();
for ortholog_annotation in &gene_details.ortholog_annotations {
let orth_uniquename = &ortholog_annotation.ortholog_uniquename;
if let Some(orth_gene) =
self.genes.get(orth_uniquename) {
if let Some(ref orth_name) = orth_gene.name {
let id_and_org = IdAndOrganism {
identifier: RcString::from(&orth_name),
taxonid: ortholog_annotation.ortholog_taxonid,
};
ortholog_ids.push(id_and_org);
}
} else {
panic!("missing GeneShort for: {:?}", orth_uniquename);
}
}
GeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
uniprot_identifier: gene_details.uniprot_identifier.clone(),
synonyms,
orthologs: ortholog_ids,
feature_type: gene_details.feature_type.clone(),
taxonid: gene_details.taxonid,
location: gene_details.location.clone(),
}
}
fn make_api_gene_summary(&self, gene_uniquename: &str) -> APIGeneSummary {
let gene_details = self.get_gene(gene_uniquename);
let synonyms =
gene_details.synonyms.iter()
.filter(|synonym| synonym.synonym_type == "exact")
.map(|synonym| synonym.name.clone())
.collect::<Vec<RcString>>();
let exon_count =
if let Some(transcript) = gene_details.transcripts.get(0) {
let mut count = 0;
for part in &transcript.parts {
if part.feature_type == FeatureType::Exon {
count += 1;
}
}
count
} else {
0
};
APIGeneSummary {
uniquename: gene_details.uniquename.clone(),
name: gene_details.name.clone(),
product: gene_details.product.clone(),
uniprot_identifier: gene_details.uniprot_identifier.clone(),
exact_synonyms: synonyms,
dbxrefs: gene_details.dbxrefs.clone(),
location: gene_details.location.clone(),
transcripts: gene_details.transcripts.clone(),
tm_domain_count: gene_details.tm_domain_coords.len(),
exon_count,
}
}
fn make_term_short(&self, termid: &str) -> TermShort {
if let Some(term_details) = self.terms.get(termid) {
TermShort::from_term_details(&term_details)
} else {
panic!("can't find TermDetails for termid: {}", termid)
}
}
fn add_characterisation_status(&mut self, gene_uniquename: &str,
cvterm_name: &RcString) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
gene_details.characterisation_status = Some(cvterm_name.clone());
}
fn add_gene_product(&mut self, gene_uniquename: &str, product: &RcString) {
let gene_details = self.get_gene_mut(gene_uniquename);
gene_details.product = Some(product.clone());
}
fn add_name_description(&mut self, gene_uniquename: &str, name_description: &str) {
let gene_details = self.get_gene_mut(gene_uniquename);
gene_details.name_descriptions.push(name_description.into());
}
fn add_annotation(&mut self, cvterm: &Cvterm, is_not: bool,
annotation_template: OntAnnotationDetail) {
let termid =
match self.base_term_of_extensions.get(&cvterm.termid()) {
Some(base_termid) => base_termid.clone(),
None => cvterm.termid(),
};
let extension_parts =
match self.parts_of_extensions.get(&cvterm.termid()) {
Some(parts) => parts.clone(),
None => vec![],
};
let mut new_extension = extension_parts.clone();
let mut existing_extensions = annotation_template.extension.clone();
new_extension.append(&mut existing_extensions);
{
let compare_ext_part_func =
|e1: &ExtPart, e2: &ExtPart| compare_ext_part_with_config(self.config, e1, e2);
new_extension.sort_by(compare_ext_part_func);
};
let ont_annotation_detail =
OntAnnotationDetail {
extension: new_extension,
.. annotation_template
};
let annotation_map = if is_not {
&mut self.all_not_ont_annotations
} else {
&mut self.all_ont_annotations
};
let entry = annotation_map.entry(termid.clone());
entry.or_insert_with(Vec::new).push(ont_annotation_detail.id);
self.annotation_details.insert(ont_annotation_detail.id,
ont_annotation_detail);
}
fn process_dbxrefs(&mut self) {
let mut map = HashMap::new();
for feature_dbxref in &self.raw.feature_dbxrefs {
let feature = &feature_dbxref.feature;
let dbxref = &feature_dbxref.dbxref;
map.entry(feature.uniquename.clone())
.or_insert_with(HashSet::new)
.insert(dbxref.identifier());
}
self.dbxrefs_of_features = map;
}
fn process_references(&mut self) {
let mut all_uniquenames = vec![];
for rc_publication in &self.raw.publications {
let reference_uniquename = &rc_publication.uniquename;
if reference_uniquename.to_lowercase() == "null" {
continue;
}
let mut pubmed_authors: Option<RcString> = None;
let mut pubmed_publication_date: Option<RcString> = None;
let mut pubmed_abstract: Option<RcString> = None;
let mut canto_triage_status: Option<RcString> = None;
let mut canto_curator_role: Option<RcString> = None;
let mut canto_curator_name: Option<RcString> = None;
let mut canto_first_approved_date: Option<RcString> = None;
let mut canto_approved_date: Option<RcString> = None;
let mut canto_added_date: Option<RcString> = None;
let mut canto_session_submitted_date: Option<RcString> = None;
for prop in rc_publication.publicationprops.borrow().iter() {
match &prop.prop_type.name as &str {
"pubmed_publication_date" =>
pubmed_publication_date = Some(prop.value.clone()),
"pubmed_authors" =>
pubmed_authors = Some(prop.value.clone()),
"pubmed_abstract" =>
pubmed_abstract = Some(prop.value.clone()),
"canto_triage_status" =>
canto_triage_status = Some(prop.value.clone()),
"canto_curator_role" =>
canto_curator_role = Some(prop.value.clone()),
"canto_curator_name" =>
canto_curator_name = Some(prop.value.clone()),
"canto_first_approved_date" =>
canto_first_approved_date = Some(prop.value.clone()),
"canto_approved_date" =>
canto_approved_date = Some(prop.value.clone()),
"canto_added_date" =>
canto_added_date = Some(prop.value.clone()),
"canto_session_submitted_date" =>
canto_session_submitted_date = Some(prop.value.clone()),
_ => ()
}
}
let mut authors_abbrev = None;
let mut publication_year = None;
if let Some(authors) = pubmed_authors.clone() {
if authors.contains(',') {
let author_re = Regex::new(r"^(?P<f>[^,]+),.*$").unwrap();
let replaced: String =
author_re.replace_all(&authors, "$f et al.").into();
authors_abbrev = Some(RcString::from(&replaced));
} else {
authors_abbrev = Some(authors.clone());
}
}
if let Some(publication_date) = pubmed_publication_date.clone() {
let date_re = Regex::new(r"^(.* )?(?P<y>\d\d\d\d)$").unwrap();
publication_year = Some(RcString::from(&date_re.replace_all(&publication_date, "$y")));
}
let mut approved_date = canto_first_approved_date.clone();
if approved_date.is_none() {
approved_date = canto_approved_date.clone();
}
if approved_date.is_none() {
approved_date = canto_session_submitted_date.clone();
}
approved_date =
if let Some(date) = approved_date {
let re = Regex::new(r"^(?P<date>\d\d\d\d-\d\d-\d\d).*").unwrap();
Some(RcString::from(&re.replace_all(&date, "$date")))
} else {
None
};
self.references.insert(reference_uniquename.clone(),
ReferenceDetails {
uniquename: reference_uniquename.clone(),
title: rc_publication.title.clone(),
citation: rc_publication.miniref.clone(),
pubmed_abstract: pubmed_abstract.clone(),
authors: pubmed_authors.clone(),
authors_abbrev,
pubmed_publication_date: pubmed_publication_date.clone(),
canto_triage_status,
canto_curator_role,
canto_curator_name,
canto_first_approved_date,
canto_approved_date,
canto_session_submitted_date,
canto_added_date,
approved_date,
publication_year,
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
});
if pubmed_publication_date.is_some() {
all_uniquenames.push(reference_uniquename.clone());
}
}
let (recent_admin_curated, recent_community_curated,
all_community_curated) =
make_canto_curated(&self.references, &all_uniquenames);
let recent_references = RecentReferences {
pubmed: make_recently_added(&self.references, &all_uniquenames),
admin_curated: recent_admin_curated,
community_curated: recent_community_curated,
};
self.recent_references = recent_references;
self.all_community_curated = all_community_curated;
}
// make maps from genes to transcript, transcripts to polypeptide,
// exon, intron, UTRs
fn make_feature_rel_maps(&mut self) {
for feature_rel in &self.raw.feature_relationships {
let subject_type_name = &feature_rel.subject.feat_type.name;
let rel_name = &feature_rel.rel_type.name;
let object_type_name = &feature_rel.object.feat_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
if TRANSCRIPT_FEATURE_TYPES.contains(&subject_type_name.as_str()) &&
rel_name == "part_of" && is_gene_type(object_type_name) {
self.genes_of_transcripts.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "polypeptide" &&
rel_name == "derives_from" &&
object_type_name == "mRNA" {
self.transcripts_of_polypeptides.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if subject_type_name == "allele" {
if feature_rel.rel_type.name == "instance_of" &&
(object_type_name == "gene" || object_type_name == "pseudogene") {
self.genes_of_alleles.insert(subject_uniquename.clone(),
object_uniquename.clone());
continue;
}
if feature_rel.rel_type.name == "part_of" &&
object_type_name == "genotype" {
let expression = get_feat_rel_expression(&feature_rel.subject, feature_rel);
let allele_and_expression =
ExpressedAllele {
allele_uniquename: subject_uniquename.clone(),
expression,
};
let entry = self.alleles_of_genotypes.entry(object_uniquename.clone());
entry.or_insert_with(Vec::new).push(allele_and_expression);
continue;
}
}
if TRANSCRIPT_PART_TYPES.contains(&subject_type_name.as_str()) {
let entry = self.parts_of_transcripts.entry(object_uniquename.clone());
let part = make_feature_short(&self.chromosomes, &feature_rel.subject);
entry.or_insert_with(Vec::new).push(part);
}
}
}
fn get_feature_dbxrefs(&self, feature: &Feature) -> HashSet<RcString> {
if let Some(dbxrefs) = self.dbxrefs_of_features.get(&feature.uniquename) {
dbxrefs.clone()
} else {
HashSet::new()
}
}
fn store_gene_details(&mut self, feat: &Feature) {
let maybe_location = make_location(&self.chromosomes, feat);
if let Some(ref location) = maybe_location {
if let Some(ref mut chr) = self.chromosomes.get_mut(&location.chromosome_name) {
chr.gene_uniquenames.push(feat.uniquename.clone());
}
}
let organism = make_organism(&feat.organism);
let dbxrefs = self.get_feature_dbxrefs(feat);
let mut orfeome_identifier = None;
for dbxref in &dbxrefs {
if dbxref.starts_with("SPD:") {
orfeome_identifier = Some(RcString::from(&dbxref[4..]));
}
}
let mut uniprot_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "uniprot_identifier" {
uniprot_identifier = prop.value.clone();
break;
}
}
let (interpro_matches, tm_domain_coords) =
if let Some(ref uniprot_identifier) = uniprot_identifier {
if let Some(result) = self.domain_data.get(uniprot_identifier as &str) {
let tm_domain_matches = result.tmhmm_matches.iter()
.map(|tm_match| (tm_match.start, tm_match.end))
.collect::<Vec<_>>();
(result.interpro_matches.clone(), tm_domain_matches)
} else {
(vec![], vec![])
}
} else {
(vec![], vec![])
};
let gene_feature = GeneDetails {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
taxonid: organism.taxonid,
product: None,
deletion_viability: DeletionViability::Unknown,
uniprot_identifier,
interpro_matches,
tm_domain_coords,
orfeome_identifier,
name_descriptions: vec![],
synonyms: vec![],
dbxrefs,
feature_type: feat.feat_type.name.clone(),
transcript_so_termid: feat.feat_type.termid(),
characterisation_status: None,
location: maybe_location,
gene_neighbourhood: vec![],
cv_annotations: HashMap::new(),
physical_interactions: vec![],
genetic_interactions: vec![],
ortholog_annotations: vec![],
paralog_annotations: vec![],
target_of_annotations: vec![],
transcripts: vec![],
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
feature_publications: HashSet::new(),
};
self.genes.insert(feat.uniquename.clone(), gene_feature);
}
fn get_transcript_parts(&mut self, transcript_uniquename: &str) -> Vec<FeatureShort> {
let mut parts = self.parts_of_transcripts.remove(transcript_uniquename)
.expect("can't find transcript");
if parts.is_empty() {
panic!("transcript has no parts: {}", transcript_uniquename);
}
let part_cmp = |a: &FeatureShort, b: &FeatureShort| {
a.location.start_pos.cmp(&b.location.start_pos)
};
parts.sort_by(&part_cmp);
validate_transcript_parts(transcript_uniquename, &parts);
let chr_name = &parts[0].location.chromosome_name.clone();
if let Some(chromosome) = self.chromosomes.get(chr_name) {
add_introns_to_transcript(chromosome, transcript_uniquename, &mut parts);
} else {
panic!("can't find chromosome details for: {}", chr_name);
}
if parts[0].location.strand == Strand::Reverse {
parts.reverse();
}
parts
}
fn store_transcript_details(&mut self, feat: &Feature) {
let transcript_uniquename = feat.uniquename.clone();
let parts = self.get_transcript_parts(&transcript_uniquename);
if parts.is_empty() {
panic!("transcript has no parts");
}
let mut transcript_start = u32::MAX;
let mut transcript_end = 0;
for part in &parts {
if part.location.start_pos < transcript_start {
transcript_start = part.location.start_pos;
}
if part.location.end_pos > transcript_end {
transcript_end = part.location.end_pos;
}
}
// use the first part as a template to get the chromosome details
let transcript_location =
ChromosomeLocation {
start_pos: transcript_start,
end_pos: transcript_end,
phase: None,
.. parts[0].location.clone()
};
let maybe_cds_location =
if feat.feat_type.name == "mRNA" {
let mut cds_start = u32::MAX;
let mut cds_end = 0;
for part in &parts {
if part.feature_type == FeatureType::Exon {
if part.location.start_pos < cds_start {
cds_start = part.location.start_pos;
}
if part.location.end_pos > cds_end {
cds_end = part.location.end_pos;
}
}
}
if cds_end == 0 {
None
} else {
if let Some(mrna_location) = feat.featurelocs.borrow().get(0) {
let first_part_loc = &parts[0].location;
Some(ChromosomeLocation {
chromosome_name: first_part_loc.chromosome_name.clone(),
start_pos: cds_start,
end_pos: cds_end,
strand: first_part_loc.strand.clone(),
phase: make_phase(&mrna_location),
})
} else {
None
}
}
} else {
None
};
let transcript = TranscriptDetails {
uniquename: transcript_uniquename.clone(),
location: transcript_location,
transcript_type: feat.feat_type.name.clone(),
parts,
protein: None,
cds_location: maybe_cds_location,
};
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&transcript_uniquename) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
if gene_details.feature_type != "pseudogene" {
let feature_type =
transcript.transcript_type.clone() + " " + &gene_details.feature_type;
gene_details.feature_type = RcString::from(&feature_type);
}
gene_details.transcripts.push(transcript);
gene_details.transcript_so_termid = feat.feat_type.termid();
} else {
panic!("can't find gene for transcript: {}", transcript_uniquename);
}
}
fn store_protein_details(&mut self, feat: &Feature) {
if let Some(residues) = feat.residues.clone() {
let protein_uniquename = feat.uniquename.clone();
let mut molecular_weight = None;
let mut average_residue_weight = None;
let mut charge_at_ph7 = None;
let mut isoelectric_point = None;
let mut codon_adaptation_index = None;
let parse_prop_as_f32 = |p: &Option<RcString>| {
if let Some(ref prop_value) = p {
let maybe_value = prop_value.parse();
if let Ok(parsed_prop) = maybe_value {
Some(parsed_prop)
} else {
println!("{}: couldn't parse {} as f32",
feat.uniquename, &prop_value);
None
}
} else {
None
}
};
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "molecular_weight" {
if let Some(value) = parse_prop_as_f32(&prop.value) {
molecular_weight = Some(value / 1000.0);
}
}
if prop.prop_type.name == "average_residue_weight" {
if let Some(value) = parse_prop_as_f32(&prop.value) {
average_residue_weight = Some(value / 1000.0);
}
}
if prop.prop_type.name == "charge_at_ph7" {
charge_at_ph7 = parse_prop_as_f32(&prop.value);
}
if prop.prop_type.name == "isoelectric_point" {
isoelectric_point = parse_prop_as_f32(&prop.value);
}
if prop.prop_type.name == "codon_adaptation_index" {
codon_adaptation_index = parse_prop_as_f32(&prop.value);
}
}
if molecular_weight.is_none() {
panic!("{} has no molecular_weight", feat.uniquename)
}
let protein = ProteinDetails {
uniquename: feat.uniquename.clone(),
sequence: RcString::from(&residues),
molecular_weight: molecular_weight.unwrap(),
average_residue_weight: average_residue_weight.unwrap(),
charge_at_ph7: charge_at_ph7.unwrap(),
isoelectric_point: isoelectric_point.unwrap(),
codon_adaptation_index: codon_adaptation_index.unwrap(),
};
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&protein_uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
if gene_details.transcripts.len() > 1 {
panic!("unimplemented - can't handle multiple transcripts for: {}",
gene_uniquename);
} else {
if gene_details.transcripts.is_empty() {
panic!("gene has no transcript: {}", gene_uniquename);
} else {
gene_details.transcripts[0].protein = Some(protein);
}
}
} else {
panic!("can't find gene for transcript: {}", transcript_uniquename);
}
} else {
panic!("can't find transcript of polypeptide: {}", protein_uniquename)
}
} else {
panic!("no residues for protein: {}", feat.uniquename);
}
}
fn store_chromosome_details(&mut self, feat: &Feature) {
let mut ena_identifier = None;
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "ena_id" {
ena_identifier = prop.value.clone()
}
}
if feat.residues.is_none() {
panic!("{:?}", feat.uniquename);
}
let org = make_organism(&feat.organism);
let residues = feat.residues.clone().unwrap();
if !residues.is_ascii() {
panic!("sequence for chromosome {} contains non-ascii characters",
feat.uniquename);
}
let chr = ChromosomeDetails {
name: feat.uniquename.clone(),
residues: RcString::from(&residues),
ena_identifier: RcString::from(&ena_identifier.unwrap()),
gene_uniquenames: vec![],
taxonid: org.taxonid,
};
self.chromosomes.insert(feat.uniquename.clone(), chr);
}
fn store_genotype_details(&mut self, feat: &Feature) {
let mut expressed_alleles =
self.alleles_of_genotypes[&feat.uniquename].clone();
let genotype_display_uniquename =
make_genotype_display_name(&expressed_alleles, &self.alleles);
{
let allele_cmp = |allele1: &ExpressedAllele, allele2: &ExpressedAllele| {
let allele1_display_name =
allele_display_name(&self.alleles[&allele1.allele_uniquename]);
let allele2_display_name =
allele_display_name(&self.alleles[&allele2.allele_uniquename]);
allele1_display_name.cmp(&allele2_display_name)
};
expressed_alleles.sort_by(&allele_cmp);
}
for prop in feat.featureprops.borrow().iter() {
if prop.prop_type.name == "genotype_background" {
if let Some(ref background) = prop.value {
self.genotype_backgrounds.insert(feat.uniquename.clone(),
background.clone());
}
}
}
let rc_display_name = RcString::from(&genotype_display_uniquename);
self.genotypes.insert(rc_display_name.clone(),
GenotypeDetails {
display_uniquename: rc_display_name,
name: feat.name.as_ref().map(|s| RcString::from(s)),
expressed_alleles,
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
});
}
fn store_allele_details(&mut self, feat: &Feature) {
let mut allele_type = None;
let mut description = None;
for prop in feat.featureprops.borrow().iter() {
match &prop.prop_type.name as &str {
"allele_type" =>
allele_type = prop.value.clone(),
"description" =>
description = prop.value.clone(),
_ => ()
}
}
if allele_type.is_none() {
panic!("no allele_type cvtermprop for {}", &feat.uniquename);
}
let gene_uniquename =
self.genes_of_alleles[&feat.uniquename].clone();
let allele_details = AlleleShort {
uniquename: feat.uniquename.clone(),
name: feat.name.clone(),
gene_uniquename,
allele_type: allele_type.unwrap(),
description,
};
self.alleles.insert(feat.uniquename.clone(), allele_details);
}
fn process_chromosome_features(&mut self) {
// we need to process all chromosomes before other featuers
for feat in &self.raw.features {
if feat.feat_type.name == "chromosome" {
self.store_chromosome_details(feat);
}
}
}
fn process_features(&mut self) {
// we need to process all genes before transcripts
for feat in &self.raw.features {
if feat.feat_type.name == "gene" || feat.feat_type.name == "pseudogene" {
self.store_gene_details(feat);
}
}
for feat in &self.raw.features {
if TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) {
self.store_transcript_details(feat)
}
}
for feat in &self.raw.features {
if feat.feat_type.name == "polypeptide"{
self.store_protein_details(feat);
}
}
for feat in &self.raw.features {
if !TRANSCRIPT_FEATURE_TYPES.contains(&feat.feat_type.name.as_str()) &&
!TRANSCRIPT_PART_TYPES.contains(&feat.feat_type.name.as_str()) &&
!HANDLED_FEATURE_TYPES.contains(&feat.feat_type.name.as_str())
{
// for now, ignore features without locations
if feat.featurelocs.borrow().len() > 0 {
let feature_short = make_feature_short(&self.chromosomes, &feat);
self.other_features.insert(feat.uniquename.clone(), feature_short);
}
}
}
}
fn add_interesting_parents(&mut self) {
let mut interesting_parents_by_termid: HashMap<RcString, HashSet<RcString>> =
HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if self.is_interesting_parent(&object_termid, &rel_term_name) {
interesting_parents_by_termid
.entry(subject_termid.clone())
.or_insert_with(HashSet::new)
.insert(object_termid);
};
}
for (termid, interesting_parents) in interesting_parents_by_termid {
let term_details = self.terms.get_mut(&termid).unwrap();
term_details.interesting_parents = interesting_parents;
}
}
fn process_allele_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "allele" {
self.store_allele_details(feat);
}
}
}
fn process_genotype_features(&mut self) {
for feat in &self.raw.features {
if feat.feat_type.name == "genotype" {
self.store_genotype_details(feat);
}
}
}
fn add_gene_neighbourhoods(&mut self) {
struct GeneAndLoc {
gene_uniquename: RcString,
loc: ChromosomeLocation,
};
let mut genes_and_locs: Vec<GeneAndLoc> = vec![];
for gene_details in self.genes.values() {
if let Some(ref location) = gene_details.location {
genes_and_locs.push(GeneAndLoc {
gene_uniquename: gene_details.uniquename.clone(),
loc: location.clone(),
});
}
}
let cmp = |a: &GeneAndLoc, b: &GeneAndLoc| {
let order = a.loc.chromosome_name.cmp(&b.loc.chromosome_name);
if order == Ordering::Equal {
a.loc.start_pos.cmp(&b.loc.start_pos)
} else {
order
}
};
genes_and_locs.sort_by(cmp);
for (i, this_gene_and_loc) in genes_and_locs.iter().enumerate() {
let mut nearby_genes: Vec<GeneShort> = vec![];
if i > 0 {
let start_index =
if i > GENE_NEIGHBOURHOOD_DISTANCE {
i - GENE_NEIGHBOURHOOD_DISTANCE
} else {
0
};
for back_index in (start_index..i).rev() {
let back_gene_and_loc = &genes_and_locs[back_index];
if back_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let back_gene_short = self.make_gene_short(&back_gene_and_loc.gene_uniquename);
nearby_genes.insert(0, back_gene_short);
}
}
let gene_short = self.make_gene_short(&this_gene_and_loc.gene_uniquename);
nearby_genes.push(gene_short);
if i < genes_and_locs.len() - 1 {
let end_index =
if i + GENE_NEIGHBOURHOOD_DISTANCE >= genes_and_locs.len() {
genes_and_locs.len()
} else {
i + GENE_NEIGHBOURHOOD_DISTANCE + 1
};
for forward_index in i+1..end_index {
let forward_gene_and_loc = &genes_and_locs[forward_index];
if forward_gene_and_loc.loc.chromosome_name !=
this_gene_and_loc.loc.chromosome_name {
break;
}
let forward_gene_short = self.make_gene_short(&forward_gene_and_loc.gene_uniquename);
nearby_genes.push(forward_gene_short);
}
}
let this_gene_details =
self.genes.get_mut(&this_gene_and_loc.gene_uniquename).unwrap();
this_gene_details.gene_neighbourhood.append(&mut nearby_genes);
}
}
// add interaction, ortholog and paralog annotations
fn process_annotation_feature_rels(&mut self) {
for feature_rel in &self.raw.feature_relationships {
let rel_name = &feature_rel.rel_type.name;
let subject_uniquename = &feature_rel.subject.uniquename;
let object_uniquename = &feature_rel.object.uniquename;
for rel_config in &FEATURE_REL_CONFIGS {
if rel_name == rel_config.rel_type_name &&
is_gene_type(&feature_rel.subject.feat_type.name) &&
is_gene_type(&feature_rel.object.feat_type.name) {
let mut evidence: Option<Evidence> = None;
let mut is_inferred_interaction: bool = false;
let borrowed_publications = feature_rel.publications.borrow();
let maybe_publication = borrowed_publications.get(0);
let maybe_reference_uniquename =
match maybe_publication {
Some(publication) =>
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
},
None => None,
};
for prop in feature_rel.feature_relationshipprops.borrow().iter() {
if prop.prop_type.name == "evidence" {
if let Some(ref evidence_long) = prop.value {
for (evidence_code, ev_details) in &self.config.evidence_types {
if &ev_details.long == evidence_long {
evidence = Some(evidence_code.clone());
}
}
if evidence.is_none() {
evidence = Some(evidence_long.clone());
}
}
}
if prop.prop_type.name == "is_inferred" {
if let Some(is_inferred_value) = prop.value.clone() {
if is_inferred_value == "yes" {
is_inferred_interaction = true;
}
}
}
}
let evidence_clone = evidence.clone();
let gene_uniquename = subject_uniquename;
let gene_organism_taxonid = {
self.genes[subject_uniquename].taxonid
};
let other_gene_uniquename = object_uniquename;
let other_gene_organism_taxonid = {
self.genes[object_uniquename].taxonid
};
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction =>
if !is_inferred_interaction {
let interaction_annotation =
InteractionAnnotation {
gene_uniquename: gene_uniquename.clone(),
interactor_uniquename: other_gene_uniquename.clone(),
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
{
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
if rel_name == "interacts_physically" {
gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if gene_uniquename != other_gene_uniquename {
let other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
if rel_name == "interacts_physically" {
other_gene_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
other_gene_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if rel_name == "interacts_physically" {
ref_details.physical_interactions.push(interaction_annotation.clone());
} else {
if rel_name == "interacts_genetically" {
ref_details.genetic_interactions.push(interaction_annotation.clone());
} else {
panic!("unknown interaction type: {}", rel_name);
}
};
}
},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: gene_uniquename.clone(),
ortholog_uniquename: other_gene_uniquename.clone(),
ortholog_taxonid: other_gene_organism_taxonid,
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == gene_details.taxonid {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: gene_uniquename.clone(),
paralog_uniquename: other_gene_uniquename.clone(),
evidence,
reference_uniquename: maybe_reference_uniquename.clone(),
};
let gene_details = self.genes.get_mut(subject_uniquename).unwrap();
gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == gene_details.taxonid {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
}
}
// for orthologs and paralogs, store the reverse annotation too
let other_gene_details = self.genes.get_mut(object_uniquename).unwrap();
match rel_config.annotation_type {
FeatureRelAnnotationType::Interaction => {},
FeatureRelAnnotationType::Ortholog => {
let ortholog_annotation =
OrthologAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
ortholog_uniquename: gene_uniquename.clone(),
ortholog_taxonid: gene_organism_taxonid,
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.ortholog_annotations.push(ortholog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == other_gene_details.taxonid {
ref_details.ortholog_annotations.push(ortholog_annotation);
}
}
},
FeatureRelAnnotationType::Paralog => {
let paralog_annotation =
ParalogAnnotation {
gene_uniquename: other_gene_uniquename.clone(),
paralog_uniquename: gene_uniquename.clone(),
evidence: evidence_clone,
reference_uniquename: maybe_reference_uniquename.clone(),
};
other_gene_details.paralog_annotations.push(paralog_annotation.clone());
if let Some(ref_details) =
if let Some(ref reference_uniquename) = maybe_reference_uniquename {
self.references.get_mut(reference_uniquename)
} else {
None
}
{
if self.config.load_organism_taxonid == other_gene_details.taxonid {
ref_details.paralog_annotations.push(paralog_annotation);
}
}
},
}
}
}
}
for ref_details in self.references.values_mut() {
ref_details.physical_interactions.sort();
ref_details.genetic_interactions.sort();
ref_details.ortholog_annotations.sort();
ref_details.paralog_annotations.sort();
}
for gene_details in self.genes.values_mut() {
gene_details.physical_interactions.sort();
gene_details.genetic_interactions.sort();
gene_details.ortholog_annotations.sort();
gene_details.paralog_annotations.sort();
}
}
// find the extension_display_names config for the given termid and relation type name
fn matching_ext_config(&self, annotation_termid: &str,
rel_type_name: &str) -> Option<ExtensionDisplayNames> {
let ext_configs = &self.config.extension_display_names;
if let Some(annotation_term_details) = self.terms.get(annotation_termid) {
for ext_config in ext_configs {
if ext_config.rel_name == rel_type_name {
if let Some(if_descendant_of) = ext_config.if_descendant_of.clone() {
if annotation_term_details.interesting_parents.contains(&if_descendant_of) {
return Some((*ext_config).clone());
}
} else {
return Some((*ext_config).clone());
}
}
}
} else {
panic!("can't find details for term: {}\n", annotation_termid);
}
None
}
// create and returns any TargetOfAnnotations implied by the extension
fn make_target_of_for_ext(&self, cv_name: &str,
genes: &[RcString],
maybe_genotype_uniquename: &Option<RcString>,
reference_uniquename: &Option<RcString>,
annotation_termid: &str,
extension: &[ExtPart]) -> Vec<(GeneUniquename, TargetOfAnnotation)> {
let mut ret_vec = vec![];
for ext_part in extension {
let maybe_ext_config =
self.matching_ext_config(annotation_termid, &ext_part.rel_type_name);
if let ExtRange::Gene(ref target_gene_uniquename) = ext_part.ext_range {
if let Some(ext_config) = maybe_ext_config {
if let Some(reciprocal_display_name) =
ext_config.reciprocal_display {
let (annotation_gene_uniquenames, annotation_genotype_uniquename) =
if maybe_genotype_uniquename.is_some() {
(genes.clone(), maybe_genotype_uniquename.clone())
} else {
(genes.clone(), None)
};
ret_vec.push(((*target_gene_uniquename).clone(),
TargetOfAnnotation {
ontology_name: cv_name.into(),
ext_rel_display_name: reciprocal_display_name,
genes: annotation_gene_uniquenames.to_vec(),
genotype_uniquename: annotation_genotype_uniquename,
reference_uniquename: reference_uniquename.clone(),
}));
}
}
}
}
ret_vec
}
fn add_target_of_annotations(&mut self) {
let mut target_of_annotations: HashMap<GeneUniquename, HashSet<TargetOfAnnotation>> =
HashMap::new();
for term_details in self.terms.values() {
for term_annotations in term_details.cv_annotations.values() {
for term_annotation in term_annotations {
'ANNOTATION: for annotation_id in &term_annotation.annotations {
let annotation = self.annotation_details
.get(&annotation_id).expect("can't find OntAnnotationDetail");
if let Some(ref genotype_uniquename) = annotation.genotype {
let genotype = &self.genotypes[genotype_uniquename];
if genotype.expressed_alleles.len() > 1 {
break 'ANNOTATION;
}
}
let new_annotations =
self.make_target_of_for_ext(&term_details.cv_name,
&annotation.genes,
&annotation.genotype,
&annotation.reference,
&term_details.termid,
&annotation.extension);
for (target_gene_uniquename, new_annotation) in new_annotations {
target_of_annotations
.entry(target_gene_uniquename.clone())
.or_insert_with(HashSet::new)
.insert(new_annotation);
}
}
}
}
}
for (gene_uniquename, mut target_of_annotations) in target_of_annotations {
let gene_details = self.genes.get_mut(&gene_uniquename).unwrap();
gene_details.target_of_annotations = target_of_annotations.drain().collect();
}
}
fn set_deletion_viability(&mut self) {
let some_null = Some(RcString::from("Null"));
let mut gene_statuses = HashMap::new();
let condition_string =
|condition_ids: HashSet<RcString>| {
let mut ids_vec: Vec<RcString> = condition_ids.iter().cloned().collect();
ids_vec.sort();
RcString::from(&ids_vec.join(" "))
};
let viable_termid = &self.config.viability_terms.viable;
let inviable_termid = &self.config.viability_terms.inviable;
for (gene_uniquename, gene_details) in &mut self.genes {
let mut new_status = DeletionViability::Unknown;
if let Some(single_allele_term_annotations) =
gene_details.cv_annotations.get("single_allele_phenotype") {
let mut viable_conditions: HashMap<RcString, TermId> = HashMap::new();
let mut inviable_conditions: HashMap<RcString, TermId> = HashMap::new();
for term_annotation in single_allele_term_annotations {
'ANNOTATION: for annotation_id in &term_annotation.annotations {
let annotation = self.annotation_details
.get(&annotation_id).expect("can't find OntAnnotationDetail");
let genotype_uniquename = annotation.genotype.as_ref().unwrap();
let genotype = &self.genotypes[genotype_uniquename];
let expressed_allele = &genotype.expressed_alleles[0];
let allele = &self.alleles[&expressed_allele.allele_uniquename];
if allele.allele_type != "deletion" &&
expressed_allele.expression != some_null {
continue 'ANNOTATION;
}
let term = &self.terms[&term_annotation.term];
let interesting_parents = &term.interesting_parents;
let conditions_as_string =
condition_string(annotation.conditions.clone());
if interesting_parents.contains(viable_termid) ||
*viable_termid == term_annotation.term {
viable_conditions.insert(conditions_as_string,
term_annotation.term.clone());
} else {
if interesting_parents.contains(inviable_termid) ||
*inviable_termid == term_annotation.term {
inviable_conditions.insert(conditions_as_string,
term_annotation.term.clone());
}
}
}
}
if viable_conditions.is_empty() {
if !inviable_conditions.is_empty() {
new_status = DeletionViability::Inviable;
}
} else {
if inviable_conditions.is_empty() {
new_status = DeletionViability::Viable;
} else {
new_status = DeletionViability::DependsOnConditions;
let viable_conditions_set: HashSet<RcString> =
viable_conditions.keys().cloned().collect();
let inviable_conditions_set: HashSet<RcString> =
inviable_conditions.keys().cloned().collect();
let intersecting_conditions =
viable_conditions_set.intersection(&inviable_conditions_set);
if intersecting_conditions.clone().count() > 0 {
println!("{} is viable and inviable with", gene_uniquename);
for cond in intersecting_conditions {
if cond.is_empty() {
println!(" no conditions");
} else {
println!(" conditions: {}", cond);
}
println!(" viable term: {}",
viable_conditions[cond]);
println!(" inviable term: {}",
inviable_conditions[cond]);
}
}
}
}
}
gene_statuses.insert(gene_uniquename.clone(), new_status);
}
for (gene_uniquename, status) in &gene_statuses {
if let Some(ref mut gene_details) = self.genes.get_mut(gene_uniquename) {
gene_details.deletion_viability = status.clone();
}
}
}
fn set_term_details_subsets(&mut self) {
'TERM: for go_slim_conf in self.config.go_slim_terms.clone() {
let slim_termid = &go_slim_conf.termid;
for term_details in self.terms.values_mut() {
if term_details.termid == *slim_termid {
term_details.subsets.push("goslim_pombe".into());
break 'TERM;
}
}
}
}
fn make_gene_short_map(&self) -> IdGeneShortMap {
let mut ret_map = HashMap::new();
for gene_uniquename in self.genes.keys() {
ret_map.insert(gene_uniquename.clone(),
make_gene_short(&self.genes, &gene_uniquename));
}
ret_map
}
fn make_all_cv_summaries(&mut self) {
let gene_short_map = self.make_gene_short_map();
for term_details in self.terms.values_mut() {
make_cv_summaries(term_details, self.config, &self.children_by_termid,
true, true, &gene_short_map, &self.annotation_details);
}
for gene_details in self.genes.values_mut() {
make_cv_summaries(gene_details, &self.config, &self.children_by_termid,
false, true, &gene_short_map, &self.annotation_details);
}
for genotype_details in self.genotypes.values_mut() {
make_cv_summaries(genotype_details, &self.config, &self.children_by_termid,
false, false, &gene_short_map, &self.annotation_details);
}
for reference_details in self.references.values_mut() {
make_cv_summaries( reference_details, &self.config, &self.children_by_termid,
true, true, &gene_short_map, &self.annotation_details);
}
}
fn process_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name != POMBASE_ANN_EXT_TERM_CV_NAME {
let cv_config =
self.config.cv_config_by_name(&cvterm.cv.name);
let annotation_feature_type =
cv_config.feature_type.clone();
let synonyms =
cvterm.cvtermsynonyms.borrow().iter().map(|syn| {
SynonymDetails {
synonym_type: (*syn).synonym_type.name.clone(),
name: syn.name.clone(),
}
}).collect::<Vec<_>>();
self.terms.insert(cvterm.termid(),
TermDetails {
name: cvterm.name.clone(),
cv_name: cvterm.cv.name.clone(),
annotation_feature_type,
interesting_parents: HashSet::new(),
subsets: vec![],
termid: cvterm.termid(),
synonyms,
definition: cvterm.definition.clone(),
direct_ancestors: vec![],
genes_annotated_with: HashSet::new(),
is_obsolete: cvterm.is_obsolete,
single_allele_genotype_uniquenames: HashSet::new(),
cv_annotations: HashMap::new(),
genes_by_uniquename: HashMap::new(),
genotypes_by_uniquename: HashMap::new(),
alleles_by_uniquename: HashMap::new(),
references_by_uniquename: HashMap::new(),
terms_by_termid: HashMap::new(),
annotation_details: HashMap::new(),
gene_count: 0,
genotype_count: 0,
});
}
}
}
fn get_ext_rel_display_name(&self, annotation_termid: &str,
ext_rel_name: &str) -> RcString {
if let Some(ext_conf) = self.matching_ext_config(annotation_termid, ext_rel_name) {
ext_conf.display_name.clone()
} else {
RcString::from(&str::replace(&ext_rel_name, "_", " "))
}
}
fn process_extension_cvterms(&mut self) {
for cvterm in &self.raw.cvterms {
if cvterm.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
for cvtermprop in cvterm.cvtermprops.borrow().iter() {
if (*cvtermprop).prop_type.name.starts_with(ANNOTATION_EXT_REL_PREFIX) {
let ext_rel_name_str =
&(*cvtermprop).prop_type.name[ANNOTATION_EXT_REL_PREFIX.len()..];
let ext_rel_name = RcString::from(ext_rel_name_str);
let ext_range = (*cvtermprop).value.clone();
let range: ExtRange = if ext_range.starts_with("SP") {
if let Some(captures) = PROMOTER_RE.captures(&ext_range) {
let gene_uniquename = RcString::from(&captures["gene"]);
ExtRange::Promoter(gene_uniquename)
} else {
ExtRange::Gene(ext_range.clone())
}
} else {
ExtRange::Misc(ext_range)
};
if let Some(base_termid) =
self.base_term_of_extensions.get(&cvterm.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(&base_termid, &ext_rel_name);
self.parts_of_extensions.entry(cvterm.termid())
.or_insert_with(Vec::new).push(ExtPart {
rel_type_name: ext_rel_name,
rel_type_display_name,
ext_range: range,
});
} else {
panic!("can't find details for term: {}\n", cvterm.termid());
}
}
}
}
}
}
fn process_cvterm_rels(&mut self) {
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name == "is_a" {
self.base_term_of_extensions.insert(subject_termid.clone(),
object_term.termid().clone());
}
} else {
let object_term_short =
self.make_term_short(&object_term.termid());
if let Some(ref mut subject_term_details) = self.terms.get_mut(&subject_term.termid()) {
subject_term_details.direct_ancestors.push(TermAndRelation {
termid: object_term_short.termid.clone(),
term_name: object_term_short.name.clone(),
relation_name: rel_type.name.clone(),
});
}
}
}
for cvterm_rel in &self.raw.cvterm_relationships {
let subject_term = &cvterm_rel.subject;
let object_term = &cvterm_rel.object;
let rel_type = &cvterm_rel.rel_type;
if subject_term.cv.name == POMBASE_ANN_EXT_TERM_CV_NAME {
let subject_termid = subject_term.termid();
if rel_type.name != "is_a" {
let object_termid = object_term.termid();
if let Some(base_termid) =
self.base_term_of_extensions.get(&subject_term.termid()) {
let rel_type_display_name =
self.get_ext_rel_display_name(base_termid, &rel_type.name);
let ext_range =
if object_termid.starts_with("PR:") {
ExtRange::GeneProduct(object_termid)
} else {
ExtRange::Term(object_termid)
};
self.parts_of_extensions.entry(subject_termid)
.or_insert_with(Vec::new).push(ExtPart {
rel_type_name: rel_type.name.clone(),
rel_type_display_name,
ext_range,
});
} else {
panic!("can't find details for {}\n", object_termid);
}
}
}
}
}
fn process_feature_synonyms(&mut self) {
for feature_synonym in &self.raw.feature_synonyms {
let feature = &feature_synonym.feature;
let synonym = &feature_synonym.synonym;
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.synonyms.push(SynonymDetails {
name: synonym.name.clone(),
synonym_type: synonym.synonym_type.name.clone()
});
}
}
}
fn process_feature_publications(&mut self) {
for feature_pub in &self.raw.feature_pubs {
let feature = &feature_pub.feature;
let publication = &feature_pub.publication;
if publication.uniquename.starts_with("PMID:") {
if let Some(ref mut gene_details) = self.genes.get_mut(&feature.uniquename) {
gene_details.feature_publications.insert(publication.uniquename.clone());
}
}
}
}
fn make_genotype_short(&self, genotype_display_name: &str) -> GenotypeShort {
if let Some(ref details) = self.genotypes.get(genotype_display_name) {
GenotypeShort {
display_uniquename: details.display_uniquename.clone(),
name: details.name.clone(),
expressed_alleles: details.expressed_alleles.clone(),
}
} else {
panic!("can't find genotype {}", genotype_display_name);
}
}
fn make_allele_short(&self, allele_uniquename: &str) -> AlleleShort {
self.alleles[allele_uniquename].clone()
}
// process feature properties stored as cvterms,
// eg. characterisation_status and product
fn process_props_from_feature_cvterms(&mut self) {
for feature_cvterm in &self.raw.feature_cvterms {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let gene_uniquenames_vec: Vec<GeneUniquename> =
if cvterm.cv.name == "PomBase gene products" {
if feature.feat_type.name == "polypeptide" {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
if feature.feat_type.name == "gene" {
vec![feature.uniquename.clone()]
} else {
vec![]
}
}
}
} else {
vec![]
};
for gene_uniquename in &gene_uniquenames_vec {
self.add_gene_product(&gene_uniquename, &cvterm.name);
}
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
if cvterm.cv.name == "PomBase gene characterisation status" {
self.add_characterisation_status(&feature.uniquename, &cvterm.name);
} else {
if cvterm.cv.name == "name_description" {
self.add_name_description(&feature.uniquename, &cvterm.name);
}
}
}
}
}
fn get_gene_prod_extension(&self, prod_value: RcString) -> ExtPart {
let ext_range =
if prod_value.starts_with("PR:") {
ExtRange::GeneProduct(prod_value)
} else {
ExtRange::Misc(prod_value)
};
ExtPart {
rel_type_name: "active_form".into(),
rel_type_display_name: "active form".into(),
ext_range,
}
}
// return a fake extension for "with" properties on protein binding annotations
fn get_with_extension(&self, with_value: &RcString) -> ExtPart {
let ext_range =
if with_value.starts_with("SP%") {
ExtRange::Gene(with_value.clone())
} else {
if with_value.starts_with("PomBase:SP") {
let gene_uniquename =
RcString::from(&with_value[8..]);
ExtRange::Gene(gene_uniquename)
} else {
if with_value.to_lowercase().starts_with("pfam:") {
ExtRange::Domain(with_value.clone())
} else {
ExtRange::Misc(with_value.clone())
}
}
};
// a with property on a protein binding (GO:0005515) is
// displayed as a binds extension
// https://github.com/pombase/website/issues/108
ExtPart {
rel_type_name: "binds".into(),
rel_type_display_name: "binds".into(),
ext_range,
}
}
fn make_with_or_from_value(&self, with_or_from_value: &RcString) -> WithFromValue {
let db_prefix_patt = RcString::from("^") + DB_NAME + ":";
let re = Regex::new(&db_prefix_patt).unwrap();
let gene_uniquename = RcString::from(&re.replace_all(&with_or_from_value, ""));
if self.genes.contains_key(&gene_uniquename) {
let gene_short = self.make_gene_short(&gene_uniquename);
WithFromValue::Gene(gene_short)
} else {
if self.terms.get(with_or_from_value).is_some() {
WithFromValue::Term(self.make_term_short(with_or_from_value))
} else {
WithFromValue::Identifier(with_or_from_value.clone())
}
}
}
// add the with value as a fake extension if the cvterm is_a protein binding,
// otherwise return the value
fn make_with_extension(&self, termid: &RcString, evidence_code: Option<RcString>,
extension: &mut Vec<ExtPart>,
with_value: &RcString) -> Option<WithFromValue> {
let base_termid =
match self.base_term_of_extensions.get(termid) {
Some(base_termid) => base_termid.clone(),
None => termid.clone(),
};
let base_term_short = self.make_term_short(&base_termid);
if evidence_code.is_some() &&
evidence_code.unwrap() == "IPI" &&
// add new IDs to the interesting_parents config
(base_term_short.termid == "GO:0005515" ||
base_term_short.interesting_parents.contains("GO:0005515") ||
base_term_short.termid == "GO:0003723" ||
base_term_short.interesting_parents.contains("GO:0003723")) {
extension.push(self.get_with_extension(with_value));
} else {
return Some(self.make_with_or_from_value(with_value));
}
None
}
// process annotation
fn process_feature_cvterms(&mut self) {
for feature_cvterm in &self.raw.feature_cvterms {
let feature = &feature_cvterm.feature;
let cvterm = &feature_cvterm.cvterm;
let termid = cvterm.termid();
let mut extension = vec![];
if cvterm.cv.name == "PomBase gene characterisation status" ||
cvterm.cv.name == "PomBase gene products" ||
cvterm.cv.name == "name_description" {
continue;
}
let publication = &feature_cvterm.publication;
let mut extra_props: HashMap<RcString, RcString> = HashMap::new();
let mut conditions: HashSet<TermId> = HashSet::new();
let mut withs: HashSet<WithFromValue> = HashSet::new();
let mut froms: HashSet<WithFromValue> = HashSet::new();
let mut qualifiers: Vec<Qualifier> = vec![];
let mut assigned_by: Option<RcString> = None;
let mut evidence: Option<RcString> = None;
let mut genotype_background: Option<RcString> = None;
// need to get evidence first as it's used later
// See: https://github.com/pombase/website/issues/455
for prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
if &prop.type_name() == "evidence" {
if let Some(ref evidence_long) = prop.value {
for (evidence_code, ev_details) in &self.config.evidence_types {
if &ev_details.long == evidence_long {
evidence = Some(evidence_code.clone());
}
}
if evidence.is_none() {
evidence = Some(evidence_long.clone());
}
}
}
}
for prop in feature_cvterm.feature_cvtermprops.borrow().iter() {
match &prop.type_name() as &str {
"residue" | "scale" |
"quant_gene_ex_copies_per_cell" |
"quant_gene_ex_avg_copies_per_cell" => {
if let Some(value) = prop.value.clone() {
extra_props.insert(prop.type_name().clone(), value);
}
},
"condition" =>
if let Some(value) = prop.value.clone() {
conditions.insert(value.clone());
},
"qualifier" =>
if let Some(value) = prop.value.clone() {
qualifiers.push(value);
},
"assigned_by" =>
if let Some(value) = prop.value.clone() {
assigned_by = Some(value);
},
"with" => {
if let Some(ref with_value) = prop.value.clone() {
if let Some(with_gene_short) =
self.make_with_extension(&termid, evidence.clone(),
&mut extension, with_value) {
withs.insert(with_gene_short);
}
}
},
"from" => {
if let Some(value) = prop.value.clone() {
froms.insert(self.make_with_or_from_value(&value));
}
},
"gene_product_form_id" => {
if let Some(value) = prop.value.clone() {
extension.push(self.get_gene_prod_extension(value));
}
},
_ => ()
}
}
let mut maybe_genotype_uniquename = None;
let mut gene_uniquenames_vec: Vec<GeneUniquename> =
match &feature.feat_type.name as &str {
"polypeptide" => {
if let Some(transcript_uniquename) =
self.transcripts_of_polypeptides.get(&feature.uniquename) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(transcript_uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
},
"genotype" => {
let expressed_alleles =
&self.alleles_of_genotypes[&feature.uniquename];
let genotype_display_name =
make_genotype_display_name(&expressed_alleles, &self.alleles);
maybe_genotype_uniquename = Some(genotype_display_name.clone());
genotype_background =
self.genotype_backgrounds.get(&feature.uniquename)
.map(|s| s.clone());
expressed_alleles.iter()
.map(|expressed_allele| {
let allele_short =
self.make_allele_short(&expressed_allele.allele_uniquename);
allele_short.gene_uniquename.clone()
})
.collect()
},
_ => {
if feature.feat_type.name == "gene" || feature.feat_type.name == "pseudogene" {
vec![feature.uniquename.clone()]
} else {
if TRANSCRIPT_FEATURE_TYPES.contains(&feature.feat_type.name.as_str()) {
if let Some(gene_uniquename) =
self.genes_of_transcripts.get(&feature.uniquename) {
vec![gene_uniquename.clone()]
} else {
vec![]
}
} else {
vec![]
}
}
}
};
gene_uniquenames_vec.dedup();
gene_uniquenames_vec =
gene_uniquenames_vec.iter().map(|gene_uniquename: &RcString| {
self.make_gene_short(&gene_uniquename).uniquename
}).collect();
let reference_uniquename =
if publication.uniquename == "null" {
None
} else {
Some(publication.uniquename.clone())
};
let mut extra_props_clone = extra_props.clone();
let copies_per_cell = extra_props_clone.remove("quant_gene_ex_copies_per_cell");
let avg_copies_per_cell = extra_props_clone.remove("quant_gene_ex_avg_copies_per_cell");
let scale = extra_props_clone.remove("scale");
let gene_ex_props =
if copies_per_cell.is_some() || avg_copies_per_cell.is_some() {
Some(GeneExProps {
copies_per_cell,
avg_copies_per_cell,
scale,
})
} else {
None
};
if gene_uniquenames_vec.len() > 1 && maybe_genotype_uniquename.is_none() {
panic!("non-genotype annotation has more than one gene");
}
let annotation_detail = OntAnnotationDetail {
id: feature_cvterm.feature_cvterm_id,
genes: gene_uniquenames_vec,
reference: reference_uniquename,
genotype: maybe_genotype_uniquename,
genotype_background,
withs,
froms,
residue: extra_props_clone.remove("residue"),
gene_ex_props,
qualifiers,
evidence,
conditions,
extension,
assigned_by,
};
self.add_annotation(cvterm.borrow(), feature_cvterm.is_not,
annotation_detail);
}
}
fn make_term_annotations(&self, termid: &RcString, detail_ids: &[OntAnnotationId],
is_not: bool)
-> Vec<(CvName, OntTermAnnotations)> {
let term_details = &self.terms[termid];
let cv_name = term_details.cv_name.clone();
match cv_name.as_ref() {
"gene_ex" => {
if is_not {
panic!("gene_ex annotations can't be NOT annotations");
}
let mut qual_annotations =
OntTermAnnotations {
term: termid.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut quant_annotations =
OntTermAnnotations {
term: termid.clone(),
is_not: false,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for annotation_id in detail_ids {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
if annotation.gene_ex_props.is_some() {
quant_annotations.annotations.push(*annotation_id)
} else {
qual_annotations.annotations.push(*annotation_id)
}
}
let mut return_vec = vec![];
if !qual_annotations.annotations.is_empty() {
return_vec.push((RcString::from("qualitative_gene_expression"),
qual_annotations));
}
if !quant_annotations.annotations.is_empty() {
return_vec.push((RcString::from("quantitative_gene_expression"),
quant_annotations));
}
return_vec
},
"fission_yeast_phenotype" => {
let mut single_allele =
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
let mut multi_allele =
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
for annotation_id in detail_ids {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
let genotype_uniquename = annotation.genotype.as_ref().unwrap();
if let Some(genotype_details) = self.genotypes.get(genotype_uniquename) {
if genotype_details.expressed_alleles.len() == 1 {
single_allele.annotations.push(*annotation_id);
} else {
multi_allele.annotations.push(*annotation_id);
}
} else {
panic!("can't find genotype details for {}\n", genotype_uniquename);
}
}
let mut return_vec = vec![];
if !single_allele.annotations.is_empty() {
return_vec.push((RcString::from("single_allele_phenotype"),
single_allele));
}
if !multi_allele.annotations.is_empty() {
return_vec.push((RcString::from("multi_allele_phenotype"),
multi_allele));
}
return_vec
},
_ => {
vec![(cv_name,
OntTermAnnotations {
term: termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: detail_ids.to_owned(),
summary: None,
})]
}
}
}
// store the OntTermAnnotations in the TermDetails, GeneDetails,
// GenotypeDetails and ReferenceDetails
fn store_ont_annotations(&mut self, is_not: bool) {
let ont_annotation_map = if is_not {
&self.all_not_ont_annotations
} else {
&self.all_ont_annotations
};
let mut gene_annotation_by_term: HashMap<GeneUniquename, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut genotype_annotation_by_term: HashMap<GenotypeUniquename, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut ref_annotation_by_term: HashMap<RcString, HashMap<TermId, Vec<OntAnnotationId>>> =
HashMap::new();
let mut ont_annotations = vec![];
for (termid, annotations) in ont_annotation_map {
let mut sorted_annotations = annotations.clone();
if !is_not {
let cv_config = {
let term = &self.terms[termid];
&self.config.cv_config_by_name(&term.cv_name)
};
{
let cmp_detail_with_maps =
|id1: &i32, id2: &i32| {
let annotation1 = self.annotation_details.
get(&id1).expect("can't find OntAnnotationDetail");
let annotation2 = self.annotation_details.
get(&id2).expect("can't find OntAnnotationDetail");
let result =
cmp_ont_annotation_detail(cv_config,
annotation1, annotation2, &self.genes,
&self.genotypes,
&self.terms);
result.unwrap_or_else(|err| panic!("error from cmp_ont_annotation_detail: {}", err))
};
sorted_annotations.sort_by(cmp_detail_with_maps);
}
let new_annotations =
self.make_term_annotations(&termid, &sorted_annotations, is_not);
if let Some(ref mut term_details) = self.terms.get_mut(termid) {
for (cv_name, new_annotation) in new_annotations {
term_details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
} else {
panic!("missing termid: {}\n", termid);
}
}
for annotation_id in sorted_annotations {
let annotation = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation.genes {
gene_annotation_by_term.entry(gene_uniquename.clone())
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![])
.push(annotation_id);
}
if let Some(ref genotype_uniquename) = annotation.genotype {
let existing =
genotype_annotation_by_term.entry(genotype_uniquename.clone())
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![]);
if !existing.contains(&annotation_id) {
existing.push(annotation_id);
}
}
if let Some(reference_uniquename) = annotation.reference.clone() {
ref_annotation_by_term.entry(reference_uniquename)
.or_insert_with(HashMap::new)
.entry(termid.clone())
.or_insert_with(|| vec![])
.push(annotation_id);
}
for condition_termid in &annotation.conditions {
let cv_name =
if let Some(ref term_details) = self.terms.get(condition_termid) {
term_details.cv_name.clone()
} else {
panic!("can't find term details for {}", condition_termid);
};
if let Some(ref mut condition_term_details) =
self.terms.get_mut(&condition_termid.clone())
{
condition_term_details.cv_annotations
.entry(cv_name.clone())
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: condition_termid.clone(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
condition_term_details.cv_annotations.get_mut(&cv_name)
.unwrap()[0]
.annotations.push(annotation_id);
}
}
// Add annotations to terms referred to in extensions. They
// are added to fake CV that have a name starting with
// "extension:". The CV name will end with ":genotype" if the
// annotation is a phentoype/genotype, and will end with ":end"
// otherwise. The middle of the fake CV name is the display
// name for the extension relation.
// eg. "extension:directly activates:gene"
for ext_part in &annotation.extension {
if let ExtRange::Term(ref part_termid) = ext_part.ext_range {
let cv_name = "extension:".to_owned() + &ext_part.rel_type_display_name;
if let Some(ref mut part_term_details) =
self.terms.get_mut(part_termid)
{
let extension_cv_name =
if annotation.genotype.is_some() {
cv_name.clone() + ":genotype"
} else {
cv_name.clone() + ":gene"
};
part_term_details.cv_annotations
.entry(RcString::from(&extension_cv_name))
.or_insert({
let mut new_vec = Vec::new();
let new_term_annotation =
OntTermAnnotations {
term: part_termid.to_owned(),
is_not,
rel_names: HashSet::new(),
annotations: vec![],
summary: None,
};
new_vec.push(new_term_annotation);
new_vec
});
part_term_details.cv_annotations.get_mut(&extension_cv_name)
.unwrap()[0]
.annotations.push(annotation_id);
}
}
}
let gene_short_list =
annotation.genes.iter().map(|uniquename: &RcString| {
self.make_gene_short(uniquename)
}).collect::<HashSet<_>>();
let reference_short =
annotation.reference.as_ref().map_or(None, |uniquename: &RcString| {
make_reference_short(&self.references, uniquename)
});
let genotype_short =
annotation.genotype.as_ref().map(|uniquename: &RcString| {
self.make_genotype_short(uniquename)
});
let conditions =
annotation.conditions.iter().map(|termid| {
self.make_term_short(termid)
}).collect::<HashSet<_>>();
let ont_annotation = OntAnnotation {
term_short: self.make_term_short(&termid),
id: annotation.id,
genes: gene_short_list,
reference_short,
genotype_short,
genotype_background: annotation.genotype_background.clone(),
withs: annotation.withs.clone(),
froms: annotation.froms.clone(),
residue: annotation.residue.clone(),
gene_ex_props: annotation.gene_ex_props.clone(),
qualifiers: annotation.qualifiers.clone(),
evidence: annotation.evidence.clone(),
conditions,
extension: annotation.extension.clone(),
assigned_by: annotation.assigned_by.clone(),
};
ont_annotations.push(ont_annotation);
}
}
let mut term_names = HashMap::new();
for (termid, term_details) in &self.terms {
term_names.insert(termid.clone(), term_details.name.to_lowercase());
}
let ont_term_cmp = |ont_term_1: &OntTermAnnotations, ont_term_2: &OntTermAnnotations| {
if !ont_term_1.is_not && ont_term_2.is_not {
return Ordering::Less;
}
if ont_term_1.is_not && !ont_term_2.is_not {
return Ordering::Greater;
}
let term1 = &term_names[&ont_term_1.term];
let term2 = &term_names[&ont_term_2.term];
term1.cmp(&term2)
};
for (gene_uniquename, term_annotation_map) in &gene_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
gene_details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
}
let gene_details = self.genes.get_mut(gene_uniquename).unwrap();
for cv_annotations in gene_details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for (genotype_uniquename, term_annotation_map) in &genotype_annotation_by_term {
for (termid, details) in term_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
details.cv_annotations.entry(cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation);
}
}
let details = self.genotypes.get_mut(genotype_uniquename).unwrap();
for cv_annotations in details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for (reference_uniquename, ref_annotation_map) in &ref_annotation_by_term {
for (termid, details) in ref_annotation_map {
let new_annotations =
self.make_term_annotations(&termid, &details, is_not);
let ref_details = self.references.get_mut(reference_uniquename).unwrap();
for (cv_name, new_annotation) in new_annotations {
ref_details.cv_annotations.entry(cv_name).or_insert_with(Vec::new)
.push(new_annotation.clone());
}
}
let ref_details = self.references.get_mut(reference_uniquename).unwrap();
for cv_annotations in ref_details.cv_annotations.values_mut() {
cv_annotations.sort_by(&ont_term_cmp)
}
}
for ont_annotation in ont_annotations.drain(0..) {
self.ont_annotations.push(ont_annotation);
}
}
// return true if the term could or should appear in the interesting_parents
// field of the TermDetails and TermShort structs
fn is_interesting_parent(&self, termid: &str, rel_name: &str) -> bool {
self.possible_interesting_parents.contains(&InterestingParent {
termid: termid.into(),
rel_name: rel_name.into(),
})
}
fn process_cvtermpath(&mut self) {
let mut new_annotations: HashMap<(CvName, TermId), HashMap<TermId, HashMap<i32, HashSet<RelName>>>> =
HashMap::new();
let mut children_by_termid: HashMap<TermId, HashSet<TermId>> = HashMap::new();
for cvtermpath in &self.raw.cvtermpaths {
let subject_term = &cvtermpath.subject;
let subject_termid = subject_term.termid();
let object_term = &cvtermpath.object;
let object_termid = object_term.termid();
if let Some(subject_term_details) = self.terms.get(&subject_termid) {
let rel_termid =
match cvtermpath.rel_type {
Some(ref rel_type) => {
rel_type.termid()
},
None => panic!("no relation type for {} <-> {}\n",
&subject_term.name, &object_term.name)
};
let rel_term_name =
self.make_term_short(&rel_termid).name;
if rel_term_name == "has_part" &&
!HAS_PART_CV_NAMES.contains(&subject_term_details.cv_name.as_str()) {
continue;
}
if !DESCENDANT_REL_NAMES.contains(&rel_term_name.as_str()) {
continue;
}
if subject_term_details.cv_annotations.keys().len() > 0 {
if let Some(object_term_details) = self.terms.get(&object_termid) {
if object_term_details.cv_annotations.keys().len() > 0 {
children_by_termid
.entry(object_termid.clone())
.or_insert_with(HashSet::new)
.insert(subject_termid.clone());
}
}
}
for (cv_name, term_annotations) in &subject_term_details.cv_annotations {
for term_annotation in term_annotations {
for annotation_id in &term_annotation.annotations {
let dest_termid = object_termid.clone();
let source_termid = subject_termid.clone();
if !term_annotation.is_not {
new_annotations.entry((cv_name.clone(), dest_termid))
.or_insert_with(HashMap::new)
.entry(source_termid)
.or_insert_with(HashMap::new)
.entry(*annotation_id)
.or_insert_with(HashSet::new)
.insert(rel_term_name.clone());
}
}
}
}
} else {
panic!("TermDetails not found for {}", &subject_termid);
}
}
for ((dest_cv_name, dest_termid), dest_annotations_map) in new_annotations.drain() {
for (source_termid, source_annotations_map) in dest_annotations_map {
let mut new_annotations: Vec<OntAnnotationId> = vec![];
let mut all_rel_names: HashSet<RcString> = HashSet::new();
for (annotation_id, rel_names) in source_annotations_map {
new_annotations.push(annotation_id);
for rel_name in rel_names {
all_rel_names.insert(rel_name);
}
}
let dest_cv_config = &self.config.cv_config_by_name(&dest_cv_name);
{
let cmp_detail_with_genotypes =
|id1: &i32, id2: &i32| {
let annotation1 = self.annotation_details.
get(&id1).expect("can't find OntAnnotationDetail");
let annotation2 = self.annotation_details.
get(&id2).expect("can't find OntAnnotationDetail");
let result =
cmp_ont_annotation_detail(dest_cv_config,
annotation1, annotation2, &self.genes,
&self.genotypes, &self.terms);
result.unwrap_or_else(|err| {
panic!("error from cmp_ont_annotation_detail: {} with terms: {} and {}",
err, source_termid, dest_termid)
})
};
new_annotations.sort_by(cmp_detail_with_genotypes);
}
let new_annotations =
self.make_term_annotations(&source_termid, &new_annotations, false);
let dest_term_details = {
self.terms.get_mut(&dest_termid).unwrap()
};
for (_, new_annotation) in new_annotations {
let mut new_annotation_clone = new_annotation.clone();
new_annotation_clone.rel_names.extend(all_rel_names.clone());
dest_term_details.cv_annotations
.entry(dest_cv_name.clone())
.or_insert_with(Vec::new)
.push(new_annotation_clone);
}
}
}
let mut term_names = HashMap::new();
for (termid, term_details) in &self.terms {
term_names.insert(termid.clone(), term_details.name.to_lowercase());
}
let ont_term_cmp = |ont_term_1: &OntTermAnnotations, ont_term_2: &OntTermAnnotations| {
if !ont_term_1.is_not && ont_term_2.is_not {
return Ordering::Less;
}
if ont_term_1.is_not && !ont_term_2.is_not {
return Ordering::Greater;
}
let term1 = &term_names[&ont_term_1.term];
let term2 = &term_names[&ont_term_2.term];
term1.cmp(&term2)
};
for term_details in self.terms.values_mut() {
for term_annotations in term_details.cv_annotations.values_mut() {
term_annotations.sort_by(&ont_term_cmp);
}
}
self.children_by_termid = children_by_termid;
}
fn make_metadata(&mut self) -> Metadata {
let mut db_creation_datetime = None;
for chadoprop in &self.raw.chadoprops {
if chadoprop.prop_type.name == "db_creation_datetime" {
db_creation_datetime = chadoprop.value.clone();
}
}
let mut cv_versions = HashMap::new();
for cvprop in &self.raw.cvprops {
if cvprop.prop_type.name == "cv_version" {
cv_versions.insert(cvprop.cv.name.clone(), cvprop.value.clone());
}
}
const PKG_NAME: &str = env!("CARGO_PKG_NAME");
const VERSION: &str = env!("CARGO_PKG_VERSION");
Metadata {
export_prog_name: RcString::from(PKG_NAME),
export_prog_version: RcString::from(VERSION),
db_creation_datetime: db_creation_datetime.unwrap(),
gene_count: self.genes.len(),
term_count: self.terms.len(),
cv_versions,
}
}
pub fn get_api_genotype_annotation(&self) -> HashMap<TermId, Vec<APIGenotypeAnnotation>>
{
let mut app_genotype_annotation = HashMap::new();
for term_details in self.terms.values() {
for annotations_vec in term_details.cv_annotations.values() {
for ont_term_annotations in annotations_vec {
'DETAILS: for annotation_id in &ont_term_annotations.annotations {
let annotation_details = self.annotation_details.
get(&annotation_id).expect("can't find OntAnnotationDetail");
if annotation_details.genotype.is_none() {
continue 'DETAILS;
}
let genotype_uniquename = annotation_details.genotype.clone().unwrap();
let genotype =
&term_details.genotypes_by_uniquename[&genotype_uniquename];
let mut api_annotation = APIGenotypeAnnotation {
is_multi: genotype.expressed_alleles.len() > 1,
alleles: vec![],
};
for allele in &genotype.expressed_alleles {
let allele_uniquename = &allele.allele_uniquename;
let allele_short =
self.alleles.get(allele_uniquename).expect("Can't find allele");
let allele_gene_uniquename =
allele_short.gene_uniquename.clone();
let allele_details = APIAlleleDetails {
gene: allele_gene_uniquename,
allele_type: allele_short.allele_type.clone(),
expression: allele.expression.clone(),
};
api_annotation.alleles.push(allele_details);
}
app_genotype_annotation
.entry(term_details.termid.clone())
.or_insert_with(|| vec![])
.push(api_annotation);
}
}
}
}
app_genotype_annotation
}
fn make_gene_query_go_data(&self, gene_details: &GeneDetails, term_config: &Vec<TermId>,
cv_name: &str) -> Option<GeneQueryTermData>
{
let component_term_annotations =
gene_details.cv_annotations.get(cv_name);
if component_term_annotations.is_none() {
return None;
}
let in_component = |check_termid: &str| {
for term_annotation in component_term_annotations.unwrap() {
let maybe_term_details = self.terms.get(&term_annotation.term);
let term_details =
maybe_term_details .unwrap_or_else(|| {
panic!("can't find TermDetails for {}", &term_annotation.term)
});
let interesting_parents = &term_details.interesting_parents;
if !term_annotation.is_not &&
(term_annotation.term == check_termid ||
interesting_parents.contains(check_termid))
{
return true;
}
}
false
};
for go_component_termid in term_config {
if in_component(go_component_termid) {
return Some(GeneQueryTermData::Term(TermAndName {
termid: go_component_termid.to_owned(),
name: self.terms.get(go_component_termid).unwrap().name.clone(),
}));
}
}
Some(GeneQueryTermData::Other)
}
fn get_ortholog_taxonids(&self, gene_details: &GeneDetails)
-> HashSet<u32>
{
let mut return_set = HashSet::new();
for ortholog_annotation in &gene_details.ortholog_annotations {
return_set.insert(ortholog_annotation.ortholog_taxonid);
}
return_set
}
fn make_gene_query_data_map(&self) -> HashMap<GeneUniquename, GeneQueryData> {
let mut gene_query_data_map = HashMap::new();
for gene_details in self.genes.values() {
let ortholog_taxonids = self.get_ortholog_taxonids(gene_details);
let cc_term_config = &self.config.query_data_config.go_components;
let process_term_config = &self.config.query_data_config.go_process_superslim;
let function_term_config = &self.config.query_data_config.go_function;
let go_component =
self.make_gene_query_go_data(gene_details, cc_term_config,
"cellular_component");
let go_process_superslim =
self.make_gene_query_go_data(gene_details, process_term_config,
"biological_process");
let go_function =
self.make_gene_query_go_data(gene_details, function_term_config,
"molecular_function");
let gene_query_data = GeneQueryData {
gene_uniquename: gene_details.uniquename.clone(),
deletion_viability: gene_details.deletion_viability.clone(),
go_component,
go_process_superslim,
go_function,
ortholog_taxonids,
};
gene_query_data_map.insert(gene_details.uniquename.clone(), gene_query_data);
}
gene_query_data_map
}
pub fn make_api_maps(mut self) -> APIMaps {
let mut gene_summaries: HashMap<GeneUniquename, APIGeneSummary> = HashMap::new();
let mut gene_name_gene_map = HashMap::new();
let mut interactors_of_genes = HashMap::new();
for (gene_uniquename, gene_details) in &self.genes {
if self.config.load_organism_taxonid == gene_details.taxonid {
let gene_summary = self.make_api_gene_summary(&gene_uniquename);
if let Some(ref gene_name) = gene_summary.name {
gene_name_gene_map.insert(gene_name.clone(), gene_uniquename.clone());
}
gene_summaries.insert(gene_uniquename.clone(), gene_summary);
let mut interactors = vec![];
for interaction_annotation in &gene_details.physical_interactions {
let interactor_uniquename =
if gene_uniquename == &interaction_annotation.gene_uniquename {
interaction_annotation.interactor_uniquename.clone()
} else {
interaction_annotation.gene_uniquename.clone()
};
let interactor = APIInteractor {
interaction_type: InteractionType::Physical,
interactor_uniquename,
};
if !interactors.contains(&interactor) {
interactors.push(interactor);
}
}
for interaction_annotation in &gene_details.genetic_interactions {
let interactor_uniquename =
if gene_uniquename == &interaction_annotation.gene_uniquename {
interaction_annotation.interactor_uniquename.clone()
} else {
interaction_annotation.gene_uniquename.clone()
};
let interactor = APIInteractor {
interaction_type: InteractionType::Genetic,
interactor_uniquename,
};
if !interactors.contains(&interactor) {
interactors.push(interactor);
}
}
interactors_of_genes.insert(gene_uniquename.clone(), interactors);
}
}
let gene_query_data_map = self.make_gene_query_data_map();
let mut term_summaries: HashSet<TermShort> = HashSet::new();
let mut termid_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut terms_for_api: HashMap<TermId, TermDetails> = HashMap::new();
for termid in self.terms.keys() {
term_summaries.insert(self.make_term_short(termid));
}
let termid_genotype_annotation: HashMap<TermId, Vec<APIGenotypeAnnotation>> =
self.get_api_genotype_annotation();
for (termid, term_details) in self.terms.drain() {
let cv_config = &self.config.cv_config;
if let Some(term_config) = cv_config.get(&term_details.cv_name) {
if term_config.feature_type == "gene" {
termid_genes.insert(termid.clone(),
term_details.genes_annotated_with.clone());
}
}
terms_for_api.insert(termid.clone(), term_details);
}
APIMaps {
gene_summaries,
gene_query_data_map,
termid_genes,
termid_genotype_annotation,
term_summaries,
genes: self.genes,
gene_name_gene_map,
genotypes: self.genotypes,
terms: terms_for_api,
interactors_of_genes,
references: self.references,
other_features: self.other_features,
annotation_details: self.annotation_details,
}
}
fn add_cv_annotations_to_maps(&self,
identifier: &RcString,
cv_annotations: &OntAnnotationMap,
seen_references: &mut HashMap<RcString, ReferenceShortOptionMap>,
seen_genes: &mut HashMap<RcString, GeneShortOptionMap>,
seen_genotypes: &mut HashMap<RcString, GenotypeShortMap>,
seen_alleles: &mut HashMap<RcString, AlleleShortMap>,
seen_terms: &mut HashMap<RcString, TermShortOptionMap>) {
for feat_annotations in cv_annotations.values() {
for feat_annotation in feat_annotations.iter() {
self.add_term_to_hash(seen_terms, identifier,
&feat_annotation.term);
for annotation_detail_id in &feat_annotation.annotations {
let annotation_detail = self.annotation_details.
get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
self.add_ref_to_hash(seen_references, identifier,
&annotation_detail.reference);
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(seen_terms, identifier,
&condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(seen_terms, identifier,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(seen_genes, identifier,
&gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
self.add_genotype_to_hash(seen_genotypes, seen_alleles, seen_genes,
identifier, genotype_uniquename);
}
}
}
}
}
fn set_term_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
let mut genes_annotated_with_map: HashMap<TermId, HashSet<GeneUniquename>> =
HashMap::new();
for (termid, term_details) in &self.terms {
for (cv_name, term_annotations) in &term_details.cv_annotations {
for term_annotation in term_annotations {
self.add_term_to_hash(&mut seen_terms, termid,
&term_annotation.term);
for annotation_detail_id in &term_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
self.add_gene_to_hash(&mut seen_genes, termid,
gene_uniquename);
if !cv_name.starts_with("extension:") {
// prevent extension annotations from appears
// in the normal query builder searches
genes_annotated_with_map
.entry(termid.clone()).or_insert_with(HashSet::new)
.insert(gene_uniquename.clone());
}
}
self.add_ref_to_hash(&mut seen_references, termid,
&annotation_detail.reference);
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(&mut seen_terms, termid,
condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms, termid,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes, termid,
gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles,
&mut seen_genes, &termid,
genotype_uniquename);
}
}
}
}
}
for (termid, term_details) in &mut self.terms {
if let Some(genes) = seen_genes.remove(termid) {
term_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(termid) {
term_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(termid) {
term_details.alleles_by_uniquename = alleles;
}
if let Some(references) = seen_references.remove(termid) {
term_details.references_by_uniquename = references;
}
if let Some(terms) = seen_terms.remove(termid) {
term_details.terms_by_termid = terms;
}
if let Some(gene_uniquename_set) = genes_annotated_with_map.remove(termid) {
term_details.genes_annotated_with = gene_uniquename_set;
}
}
}
fn set_gene_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
{
for (gene_uniquename, gene_details) in &self.genes {
self.add_cv_annotations_to_maps(&gene_uniquename,
&gene_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
let interaction_iter =
gene_details.physical_interactions.iter().chain(&gene_details.genetic_interactions);
for interaction in interaction_iter {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&interaction.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&interaction.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&interaction.interactor_uniquename);
}
for ortholog_annotation in &gene_details.ortholog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&ortholog_annotation.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&ortholog_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
&ortholog_annotation.ortholog_uniquename);
}
for paralog_annotation in &gene_details.paralog_annotations {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
¶log_annotation.reference_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
¶log_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
¶log_annotation.paralog_uniquename);
}
for target_of_annotation in &gene_details.target_of_annotations {
for annotation_gene_uniquename in &target_of_annotation.genes {
self.add_gene_to_hash(&mut seen_genes, gene_uniquename,
annotation_gene_uniquename);
}
if let Some(ref annotation_genotype_uniquename) = target_of_annotation.genotype_uniquename {
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
gene_uniquename,
&annotation_genotype_uniquename)
}
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&target_of_annotation.reference_uniquename);
}
for publication in &gene_details.feature_publications {
self.add_ref_to_hash(&mut seen_references, gene_uniquename,
&Some(publication.clone()));
}
}
}
for (gene_uniquename, gene_details) in &mut self.genes {
if let Some(references) = seen_references.remove(gene_uniquename) {
gene_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(gene_uniquename) {
gene_details.alleles_by_uniquename = alleles;
}
if let Some(genes) = seen_genes.remove(gene_uniquename) {
gene_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(gene_uniquename) {
gene_details.genotypes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(gene_uniquename) {
gene_details.terms_by_termid = terms;
}
}
}
fn set_genotype_details_maps(&mut self) {
let (mut seen_references, mut seen_genes, mut seen_genotypes,
mut seen_alleles, mut seen_terms) = get_maps();
for (genotype_uniquename, genotype_details) in &self.genotypes {
self.add_cv_annotations_to_maps(&genotype_uniquename,
&genotype_details.cv_annotations,
&mut seen_references,
&mut seen_genes,
&mut seen_genotypes,
&mut seen_alleles,
&mut seen_terms);
}
for (genotype_uniquename, genotype_details) in &mut self.genotypes {
if let Some(references) = seen_references.remove(genotype_uniquename) {
genotype_details.references_by_uniquename = references;
}
if let Some(alleles) = seen_alleles.remove(genotype_uniquename) {
genotype_details.alleles_by_uniquename = alleles;
}
if let Some(genotypes) = seen_genes.remove(genotype_uniquename) {
genotype_details.genes_by_uniquename = genotypes;
}
if let Some(terms) = seen_terms.remove(genotype_uniquename) {
genotype_details.terms_by_termid = terms;
}
}
}
fn set_reference_details_maps(&mut self) {
let mut seen_genes: HashMap<RcString, GeneShortOptionMap> = HashMap::new();
type GenotypeShortMap = HashMap<GenotypeUniquename, GenotypeShort>;
let mut seen_genotypes: HashMap<ReferenceUniquename, GenotypeShortMap> = HashMap::new();
type AlleleShortMap = HashMap<AlleleUniquename, AlleleShort>;
let mut seen_alleles: HashMap<TermId, AlleleShortMap> = HashMap::new();
let mut seen_terms: HashMap<GeneUniquename, TermShortOptionMap> = HashMap::new();
{
for (reference_uniquename, reference_details) in &self.references {
for feat_annotations in reference_details.cv_annotations.values() {
for feat_annotation in feat_annotations.iter() {
self.add_term_to_hash(&mut seen_terms, reference_uniquename,
&feat_annotation.term);
for annotation_detail_id in &feat_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
gene_uniquename)
}
for condition_termid in &annotation_detail.conditions {
self.add_term_to_hash(&mut seen_terms, reference_uniquename,
condition_termid);
}
for ext_part in &annotation_detail.extension {
match ext_part.ext_range {
ExtRange::Term(ref range_termid) |
ExtRange::GeneProduct(ref range_termid) =>
self.add_term_to_hash(&mut seen_terms,
reference_uniquename,
range_termid),
ExtRange::Gene(ref gene_uniquename) |
ExtRange::Promoter(ref gene_uniquename) =>
self.add_gene_to_hash(&mut seen_genes,
reference_uniquename,
gene_uniquename),
_ => {},
}
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
let genotype = self.make_genotype_short(genotype_uniquename);
self.add_genotype_to_hash(&mut seen_genotypes, &mut seen_alleles, &mut seen_genes,
reference_uniquename,
&genotype.display_uniquename);
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter()
.chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&interaction.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&interaction.interactor_uniquename);
}
for ortholog_annotation in &reference_details.ortholog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&ortholog_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
&ortholog_annotation.ortholog_uniquename);
}
for paralog_annotation in &reference_details.paralog_annotations {
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
¶log_annotation.gene_uniquename);
self.add_gene_to_hash(&mut seen_genes, reference_uniquename,
¶log_annotation.paralog_uniquename);
}
}
}
for (reference_uniquename, reference_details) in &mut self.references {
if let Some(genes) = seen_genes.remove(reference_uniquename) {
reference_details.genes_by_uniquename = genes;
}
if let Some(genotypes) = seen_genotypes.remove(reference_uniquename) {
reference_details.genotypes_by_uniquename = genotypes;
}
if let Some(alleles) = seen_alleles.remove(reference_uniquename) {
reference_details.alleles_by_uniquename = alleles;
}
if let Some(terms) = seen_terms.remove(reference_uniquename) {
reference_details.terms_by_termid = terms;
}
}
}
pub fn set_counts(&mut self) {
let mut term_seen_genes: HashMap<TermId, HashSet<GeneUniquename>> = HashMap::new();
let mut term_seen_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut term_seen_single_allele_genotypes: HashMap<TermId, HashSet<GenotypeUniquename>> = HashMap::new();
let mut ref_seen_genes: HashMap<ReferenceUniquename, HashSet<GeneUniquename>> = HashMap::new();
for (termid, term_details) in &self.terms {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
let mut seen_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
let mut seen_single_allele_genotypes: HashSet<GenotypeUniquename> = HashSet::new();
for term_annotations in term_details.cv_annotations.values() {
for term_annotation in term_annotations {
for annotation_detail_id in &term_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
for gene_uniquename in &annotation_detail.genes {
seen_genes.insert(gene_uniquename.clone());
}
if let Some(ref genotype_uniquename) = annotation_detail.genotype {
seen_genotypes.insert(genotype_uniquename.clone());
let genotype = &self.genotypes[genotype_uniquename];
if genotype.expressed_alleles.len() == 1 {
seen_single_allele_genotypes.insert(genotype_uniquename.clone());
}
}
}
}
}
term_seen_genes.insert(termid.clone(), seen_genes);
term_seen_genotypes.insert(termid.clone(), seen_genotypes);
term_seen_single_allele_genotypes.insert(termid.clone(), seen_single_allele_genotypes);
}
for (reference_uniquename, reference_details) in &self.references {
let mut seen_genes: HashSet<GeneUniquename> = HashSet::new();
for rel_annotations in reference_details.cv_annotations.values() {
for rel_annotation in rel_annotations {
for annotation_detail_id in &rel_annotation.annotations {
let annotation_detail = self.annotation_details
.get(&annotation_detail_id).expect("can't find OntAnnotationDetail");
if !rel_annotation.is_not {
for gene_uniquename in &annotation_detail.genes {
seen_genes.insert(gene_uniquename.clone());
}
}
}
}
}
let interaction_iter =
reference_details.physical_interactions.iter().chain(&reference_details.genetic_interactions);
for interaction in interaction_iter {
seen_genes.insert(interaction.gene_uniquename.clone());
seen_genes.insert(interaction.interactor_uniquename.clone());
}
for ortholog_annotation in &reference_details.ortholog_annotations {
seen_genes.insert(ortholog_annotation.gene_uniquename.clone());
}
ref_seen_genes.insert(reference_uniquename.clone(), seen_genes);
}
for term_details in self.terms.values_mut() {
term_details.single_allele_genotype_uniquenames =
term_seen_single_allele_genotypes.remove(&term_details.termid).unwrap();
term_details.gene_count =
term_seen_genes[&term_details.termid].len();
term_details.genotype_count =
term_seen_genotypes[&term_details.termid].len();
}
}
fn make_non_bp_slim_gene_subset(&self, go_slim_subset: &TermSubsetDetails)
-> IdGeneSubsetMap
{
let slim_termid_set: HashSet<RcString> =
go_slim_subset.elements
.iter().map(|element| element.termid.clone()).collect();
let mut non_slim_with_bp_annotation = HashSet::new();
let mut non_slim_without_bp_annotation = HashSet::new();
let has_parent_in_slim = |term_annotations: &Vec<OntTermAnnotations>| {
for term_annotation in term_annotations {
let interesting_parents =
&self.terms[&term_annotation.term].interesting_parents;
if !term_annotation.is_not &&
(slim_termid_set.contains(&term_annotation.term) ||
interesting_parents.intersection(&slim_termid_set).count() > 0)
{
return true;
}
}
false
};
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
if gene_details.feature_type != "mRNA gene" {
continue;
}
if gene_details.characterisation_status == Some(RcString::from("transposon")) ||
gene_details.characterisation_status == Some(RcString::from("dubious"))
{
continue;
}
let mut bp_count = 0;
if let Some(annotations) =
gene_details.cv_annotations.get("biological_process") {
if has_parent_in_slim(&annotations) {
continue
}
bp_count = annotations.len();
}
if bp_count == 0 {
non_slim_without_bp_annotation.insert(gene_details.uniquename.clone());
} else {
non_slim_with_bp_annotation.insert(gene_details.uniquename.clone());
}
}
let mut return_map = HashMap::new();
let with_annotation_display_name =
String::from("Proteins with biological process ") +
"annotation that are not in a slim category";
return_map.insert("non_go_slim_with_bp_annotation".into(),
GeneSubsetDetails {
name: "non_go_slim_with_bp_annotation".into(),
display_name: RcString::from(&with_annotation_display_name),
elements: non_slim_with_bp_annotation,
});
let without_annotation_display_name =
String::from("Proteins with no biological process ") +
"annotation and are not in a slim category";
return_map.insert("non_go_slim_without_bp_annotation".into(),
GeneSubsetDetails {
name: "non_go_slim_without_bp_annotation".into(),
display_name: RcString::from(&without_annotation_display_name),
elements: non_slim_without_bp_annotation,
});
return_map
}
fn make_bp_go_slim_subset(&self) -> TermSubsetDetails {
let mut all_genes = HashSet::new();
let mut go_slim_subset: HashSet<TermSubsetElement> = HashSet::new();
for go_slim_conf in self.config.go_slim_terms.clone() {
let slim_termid = go_slim_conf.termid;
let term_details = self.terms.get(&slim_termid)
.unwrap_or_else(|| panic!("can't find TermDetails for {}", &slim_termid));
let subset_element = TermSubsetElement {
name: term_details.name.clone(),
termid: slim_termid.clone(),
gene_count: term_details.genes_annotated_with.len(),
};
for gene in &term_details.genes_annotated_with {
all_genes.insert(gene);
}
go_slim_subset.insert(subset_element);
}
TermSubsetDetails {
name: "goslim_pombe".into(),
total_gene_count: all_genes.len(),
elements: go_slim_subset,
}
}
fn make_feature_type_subsets(&self, subsets: &mut IdGeneSubsetMap) {
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
let subset_name =
RcString::from("feature_type:") + &gene_details.feature_type;
let re = Regex::new(r"[\s,:]+").unwrap();
let subset_name_no_spaces = RcString::from(&re.replace_all(&subset_name, "_"));
subsets.entry(subset_name_no_spaces.clone())
.or_insert(GeneSubsetDetails {
name: subset_name_no_spaces,
display_name: RcString::from(&subset_name),
elements: HashSet::new()
})
.elements.insert(gene_details.uniquename.clone());
}
}
// make subsets using the characterisation_status field of GeneDetails
fn make_characterisation_status_subsets(&self, subsets: &mut IdGeneSubsetMap) {
for gene_details in self.genes.values() {
if self.config.load_organism_taxonid != gene_details.taxonid {
continue;
}
if gene_details.feature_type != "mRNA gene" {
continue;
}
if let Some(ref characterisation_status) = gene_details.characterisation_status {
let subset_name =
RcString::from("characterisation_status:") + &characterisation_status;
let re = Regex::new(r"[\s,:]+").unwrap();
let subset_name_no_spaces = RcString::from(&re.replace_all(&subset_name, "_"));
subsets.entry(subset_name_no_spaces.clone())
.or_insert(GeneSubsetDetails {
name: subset_name_no_spaces,
display_name: RcString::from(&subset_name),
elements: HashSet::new()
})
.elements.insert(gene_details.uniquename.clone());
}
}
}
// make InterPro subsets using the interpro_matches field of GeneDetails
fn make_interpro_subsets(&mut self, subsets: &mut IdGeneSubsetMap) {
for (gene_uniquename, gene_details) in &self.genes {
for interpro_match in &gene_details.interpro_matches {
let mut new_subset_names = vec![];
if !interpro_match.interpro_id.is_empty() {
let subset_name =
String::from("interpro:") + &interpro_match.interpro_id;
new_subset_names.push((RcString::from(&subset_name),
interpro_match.interpro_name.clone()));
}
let subset_name = String::from("interpro:") +
&interpro_match.dbname.clone() + ":" + &interpro_match.id;
new_subset_names.push((RcString::from(&subset_name), interpro_match.name.clone()));
for (subset_name, display_name) in new_subset_names {
subsets.entry(subset_name.clone())
.or_insert(GeneSubsetDetails {
name: subset_name,
display_name,
elements: HashSet::new(),
})
.elements.insert(gene_uniquename.clone());
}
}
}
}
// populated the subsets HashMap
fn make_subsets(&mut self) {
let bp_go_slim_subset = self.make_bp_go_slim_subset();
let mut gene_subsets =
self.make_non_bp_slim_gene_subset(&bp_go_slim_subset);
self.term_subsets.insert("bp_goslim_pombe".into(), bp_go_slim_subset);
self.make_feature_type_subsets(&mut gene_subsets);
self.make_characterisation_status_subsets(&mut gene_subsets);
self.make_interpro_subsets(&mut gene_subsets);
self.gene_subsets = gene_subsets;
}
// sort the list of genes in the ChromosomeDetails by start_pos
pub fn sort_chromosome_genes(&mut self) {
let mut genes_to_sort: HashMap<ChromosomeName, Vec<GeneUniquename>> =
HashMap::new();
{
let sorter = |uniquename1: &GeneUniquename, uniquename2: &GeneUniquename| {
let gene1 = &self.genes[uniquename1];
let gene2 = &self.genes[uniquename2];
if let Some(ref gene1_loc) = gene1.location {
if let Some(ref gene2_loc) = gene2.location {
let cmp = gene1_loc.start_pos.cmp(&gene2_loc.start_pos);
if cmp != Ordering::Equal {
return cmp;
}
}
}
if gene1.name.is_some() {
if gene2.name.is_some() {
gene1.name.cmp(&gene2.name)
} else {
Ordering::Less
}
} else {
if gene2.name.is_some() {
Ordering::Greater
} else {
gene1.uniquename.cmp(&gene2.uniquename)
}
}
};
for (chr_uniquename, chr_details) in &self.chromosomes {
genes_to_sort.insert(chr_uniquename.clone(),
chr_details.gene_uniquenames.clone());
}
for gene_uniquenames in genes_to_sort.values_mut() {
gene_uniquenames.sort_by(&sorter);
}
}
for (chr_uniquename, gene_uniquenames) in genes_to_sort {
self.chromosomes.get_mut(&chr_uniquename).unwrap().gene_uniquenames =
gene_uniquenames;
}
}
// remove some of the refs that have no annotations.
// See: https://github.com/pombase/website/issues/628
fn remove_non_curatable_refs(&mut self) {
let filtered_refs = self.references.drain()
.filter(|&(_, ref reference_details)| {
if reference_has_annotation(reference_details) {
return true;
}
if let Some(ref canto_triage_status) = reference_details.canto_triage_status {
if canto_triage_status == "New" {
return false;
}
} else {
if reference_details.uniquename.starts_with("PMID:") {
print!("reference {} has no canto_triage_status\n", reference_details.uniquename);
}
}
if let Some (ref triage_status) = reference_details.canto_triage_status {
return triage_status != "Wrong organism" && triage_status != "Loaded in error";
}
// default to true because there are references that
// haven't or shouldn't be triaged, eg. GO_REF:...
true
})
.into_iter().collect();
self.references = filtered_refs;
}
fn make_solr_term_summaries(&mut self) -> Vec<SolrTermSummary> {
let mut return_summaries = vec![];
let term_name_split_re = Regex::new(r"\W+").unwrap();
for (termid, term_details) in &self.terms {
if term_details.cv_annotations.keys()
.filter(|cv_name| !cv_name.starts_with("extension:"))
.next().is_none() {
continue;
}
let trimmable_p = |c: char| {
c.is_whitespace() || c == ',' || c == ':'
|| c == ';' || c == '.' || c == '\''
};
let term_name_words =
term_name_split_re.split(&term_details.name)
.map(|s: &str| {
s.trim_matches(&trimmable_p).to_owned()
}).collect::<Vec<String>>();
let mut close_synonyms = vec![];
let mut close_synonym_words_vec: Vec<RcString> = vec![];
let mut distant_synonyms = vec![];
let mut distant_synonym_words_vec: Vec<RcString> = vec![];
let add_to_words_vec = |synonym: &str, words_vec: &mut Vec<RcString>| {
let synonym_words = term_name_split_re.split(&synonym);
for word in synonym_words {
let word_string = RcString::from(word.trim_matches(&trimmable_p));
if !words_vec.contains(&word_string) &&
!term_name_words.contains(&word_string) {
words_vec.push(word_string);
}
}
};
for synonym in &term_details.synonyms {
if synonym.synonym_type == "exact" || synonym.synonym_type == "narrow" {
add_to_words_vec(&synonym.name, &mut close_synonym_words_vec);
close_synonyms.push(synonym.name.clone());
} else {
add_to_words_vec(&synonym.name, &mut distant_synonym_words_vec);
distant_synonyms.push(synonym.name.clone());
}
}
distant_synonyms = distant_synonyms.into_iter()
.filter(|synonym| {
!close_synonyms.contains(&synonym)
})
.collect::<Vec<_>>();
let interesting_parents_for_solr =
term_details.interesting_parents.clone();
let term_summ = SolrTermSummary {
id: termid.clone(),
cv_name: term_details.cv_name.clone(),
name: term_details.name.clone(),
definition: term_details.definition.clone(),
close_synonyms,
close_synonym_words: RcString::from(&close_synonym_words_vec.join(" ")),
distant_synonyms,
distant_synonym_words: RcString::from(&distant_synonym_words_vec.join(" ")),
interesting_parents: interesting_parents_for_solr,
};
return_summaries.push(term_summ);
}
return_summaries
}
fn make_solr_reference_summaries(&mut self) -> Vec<SolrReferenceSummary> {
let mut return_summaries = vec![];
for reference_details in self.references.values() {
return_summaries.push(SolrReferenceSummary::from_reference_details(reference_details));
}
return_summaries
}
pub fn get_web_data(mut self) -> WebData {
self.process_dbxrefs();
self.process_references();
self.process_chromosome_features();
self.make_feature_rel_maps();
self.process_features();
self.add_gene_neighbourhoods();
self.process_props_from_feature_cvterms();
self.process_allele_features();
self.process_genotype_features();
self.process_cvterms();
self.add_interesting_parents();
self.process_cvterm_rels();
self.process_extension_cvterms();
self.process_feature_synonyms();
self.process_feature_publications();
self.process_feature_cvterms();
self.store_ont_annotations(false);
self.store_ont_annotations(true);
self.process_cvtermpath();
self.process_annotation_feature_rels();
self.add_target_of_annotations();
self.set_deletion_viability();
self.set_term_details_subsets();
self.make_all_cv_summaries();
self.remove_non_curatable_refs();
self.set_term_details_maps();
self.set_gene_details_maps();
self.set_genotype_details_maps();
self.set_reference_details_maps();
self.set_counts();
self.make_subsets();
self.sort_chromosome_genes();
let metadata = self.make_metadata();
let mut gene_summaries: Vec<GeneSummary> = vec![];
for (gene_uniquename, gene_details) in &self.genes {
if self.config.load_organism_taxonid == gene_details.taxonid {
gene_summaries.push(self.make_gene_summary(&gene_uniquename));
}
}
let solr_term_summaries = self.make_solr_term_summaries();
let solr_reference_summaries = self.make_solr_reference_summaries();
let solr_data = SolrData {
term_summaries: solr_term_summaries,
gene_summaries: gene_summaries.clone(),
reference_summaries: solr_reference_summaries,
};
let chromosomes = self.chromosomes.clone();
let mut chromosome_summaries = vec![];
for chr_details in self.chromosomes.values() {
chromosome_summaries.push(chr_details.make_chromosome_short());
}
let term_subsets = self.term_subsets.clone();
let gene_subsets = self.gene_subsets.clone();
let recent_references = self.recent_references.clone();
let all_community_curated = self.all_community_curated.clone();
let ont_annotations = self.ont_annotations.clone();
WebData {
metadata,
chromosomes,
chromosome_summaries,
recent_references,
all_community_curated,
api_maps: self.make_api_maps(),
search_gene_summaries: gene_summaries,
term_subsets,
gene_subsets,
solr_data,
ont_annotations,
}
}
}
|
extern crate cgmath;
pub mod cuboid;
pub mod component;
use self::cgmath::{
VectorSpace, Rotation,
Point3, Vector3, Quaternion
};
use core::{Data, EventEmitter, Listener};
use self::component::Component;
use std::any::Any;
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
/// Holds common virtual world object's properties and components.
pub struct Entity {
pub position: Point3<f32>,
pub orientation: Quaternion<f32>,
pub scale: f32,
emitter: EventEmitter<Any>,
components: Vec<Rc<Any>>
}
impl Entity {
/// Create a new entity.
pub fn new() -> Entity {
Entity::from(Point3::new(0.0, 0.0, 0.0), Quaternion::zero(), 1.0)
}
/// Create a new entity from properties.
pub fn from(position: Point3<f32>, orientation: Quaternion<f32>, scale: f32) -> Entity {
return Entity {
position: position,
orientation: orientation,
scale: scale,
emitter: EventEmitter::new(),
components: Vec::new()
};
}
/// Translate the entity `n` units towards it's orientation direction.
///
/// Negative value indicates backwards translation.
#[inline]
pub fn move_by(&mut self, units: f32) {
self.position += units * self.orientation.rotate_vector(Vector3::zero());
}
/// Rotate the entity.
#[inline]
pub fn look_at(&mut self, dir: Vector3<f32>, up: Vector3<f32>) {
self.orientation = Quaternion::look_at(dir, up);
}
/// Add a component to the entity.
///
/// Returns `Some` if the component is unique for the entity.
/// Any non unique components will be ignored and `None` will be returned.
pub fn add<T: Any + Component>(&mut self, component: T) -> Option<Rc<RefCell<T>>> {
if let None = self.component::<T>() {
// Wrap the component.
let wrapped = wrap!(component);
// Create a weak from the wrapper to clone later.
let weak = Rc::downgrade(&wrapped);
// Bypass rust safety checks.
let this = Data::from(self);
// Call the component's init method.
wrapped.borrow_mut().init(self,
&move |events, closure| {
// Create a listener from the given closure.
let listener = Listener::<Any>::new(weak.clone(), closure);
// Go through the events that the listener wants to listen for.
for event in events.into_iter() {
// Subscribe the listener to each of those events.
this.to::<Entity>().on(event, listener.clone());
}
}
);
// Finally take in the wrapped component.
self.components.push(wrapped.clone());
return Some(wrapped);
}
return None;
}
/// Get a component by type.
pub fn component<T: Any + Component>(&self) -> Option<&RefCell<T>> {
for component in &self.components {
if let Some(target) = component.downcast_ref::<RefCell<T>>() {
return Some(target);
}
}
return None
}
}
impl Deref for Entity {
type Target = EventEmitter<Any>;
fn deref(&self) -> &Self::Target {
&self.emitter
}
}
impl DerefMut for Entity {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.emitter
}
}
Line endings fix
extern crate cgmath;
pub mod cuboid;
pub mod component;
use self::cgmath::{
VectorSpace, Rotation,
Point3, Vector3, Quaternion
};
use core::{Data, EventEmitter, Listener};
use self::component::Component;
use std::any::Any;
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
/// Holds common virtual world object's properties and components.
pub struct Entity {
pub position: Point3<f32>,
pub orientation: Quaternion<f32>,
pub scale: f32,
emitter: EventEmitter<Any>,
components: Vec<Rc<Any>>
}
impl Entity {
/// Create a new entity.
pub fn new() -> Entity {
Entity::from(Point3::new(0.0, 0.0, 0.0), Quaternion::zero(), 1.0)
}
/// Create a new entity from properties.
pub fn from(position: Point3<f32>, orientation: Quaternion<f32>, scale: f32) -> Entity {
return Entity {
position: position,
orientation: orientation,
scale: scale,
emitter: EventEmitter::new(),
components: Vec::new()
};
}
/// Translate the entity `n` units towards it's orientation direction.
///
/// Negative value indicates backwards translation.
#[inline]
pub fn move_by(&mut self, units: f32) {
self.position += units * self.orientation.rotate_vector(Vector3::zero());
}
/// Rotate the entity.
#[inline]
pub fn look_at(&mut self, dir: Vector3<f32>, up: Vector3<f32>) {
self.orientation = Quaternion::look_at(dir, up);
}
/// Add a component to the entity.
///
/// Returns `Some` if the component is unique for the entity.
/// Any non unique components will be ignored and `None` will be returned.
pub fn add<T: Any + Component>(&mut self, component: T) -> Option<Rc<RefCell<T>>> {
if let None = self.component::<T>() {
// Wrap the component.
let wrapped = wrap!(component);
// Create a weak from the wrapper to clone later.
let weak = Rc::downgrade(&wrapped);
// Bypass rust safety checks.
let this = Data::from(self);
// Call the component's init method.
wrapped.borrow_mut().init(self,
&move |events, closure| {
// Create a listener from the given closure.
let listener = Listener::<Any>::new(weak.clone(), closure);
// Go through the events that the listener wants to listen for.
for event in events.into_iter() {
// Subscribe the listener to each of those events.
this.to::<Entity>().on(event, listener.clone());
}
}
);
// Finally take in the wrapped component.
self.components.push(wrapped.clone());
return Some(wrapped);
}
return None;
}
/// Get a component by type.
pub fn component<T: Any + Component>(&self) -> Option<&RefCell<T>> {
for component in &self.components {
if let Some(target) = component.downcast_ref::<RefCell<T>>() {
return Some(target);
}
}
return None
}
}
impl Deref for Entity {
type Target = EventEmitter<Any>;
fn deref(&self) -> &Self::Target {
&self.emitter
}
}
impl DerefMut for Entity {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.emitter
}
}
|
//! A `Builder` enables you to build instructions.
use either::{Either, Left, Right};
use llvm_sys::core::{LLVMBuildAdd, LLVMBuildAlloca, LLVMBuildAnd, LLVMBuildArrayAlloca, LLVMBuildArrayMalloc, LLVMBuildAtomicCmpXchg, LLVMBuildAtomicRMW, LLVMBuildBr, LLVMBuildCall, LLVMBuildCast, LLVMBuildCondBr, LLVMBuildExtractValue, LLVMBuildFAdd, LLVMBuildFCmp, LLVMBuildFDiv, LLVMBuildFence, LLVMBuildFMul, LLVMBuildFNeg, LLVMBuildFree, LLVMBuildFSub, LLVMBuildGEP, LLVMBuildICmp, LLVMBuildInsertValue, LLVMBuildIsNotNull, LLVMBuildIsNull, LLVMBuildLoad, LLVMBuildMalloc, LLVMBuildMul, LLVMBuildNeg, LLVMBuildNot, LLVMBuildOr, LLVMBuildPhi, LLVMBuildPointerCast, LLVMBuildRet, LLVMBuildRetVoid, LLVMBuildStore, LLVMBuildSub, LLVMBuildUDiv, LLVMBuildUnreachable, LLVMBuildXor, LLVMDisposeBuilder, LLVMGetElementType, LLVMGetInsertBlock, LLVMGetReturnType, LLVMGetTypeKind, LLVMInsertIntoBuilder, LLVMPositionBuilderAtEnd, LLVMTypeOf, LLVMBuildExtractElement, LLVMBuildInsertElement, LLVMBuildIntToPtr, LLVMBuildPtrToInt, LLVMInsertIntoBuilderWithName, LLVMClearInsertionPosition, LLVMCreateBuilder, LLVMPositionBuilder, LLVMPositionBuilderBefore, LLVMBuildAggregateRet, LLVMBuildStructGEP, LLVMBuildInBoundsGEP, LLVMBuildPtrDiff, LLVMBuildNSWAdd, LLVMBuildNUWAdd, LLVMBuildNSWSub, LLVMBuildNUWSub, LLVMBuildNSWMul, LLVMBuildNUWMul, LLVMBuildSDiv, LLVMBuildSRem, LLVMBuildURem, LLVMBuildFRem, LLVMBuildNSWNeg, LLVMBuildNUWNeg, LLVMBuildFPToUI, LLVMBuildFPToSI, LLVMBuildSIToFP, LLVMBuildUIToFP, LLVMBuildFPTrunc, LLVMBuildFPExt, LLVMBuildIntCast, LLVMBuildFPCast, LLVMBuildSExtOrBitCast, LLVMBuildZExtOrBitCast, LLVMBuildTruncOrBitCast, LLVMBuildSwitch, LLVMAddCase, LLVMBuildShl, LLVMBuildAShr, LLVMBuildLShr, LLVMBuildGlobalString, LLVMBuildGlobalStringPtr, LLVMBuildExactSDiv, LLVMBuildTrunc, LLVMBuildSExt, LLVMBuildZExt, LLVMBuildSelect, LLVMBuildAddrSpaceCast, LLVMBuildBitCast, LLVMBuildShuffleVector, LLVMBuildVAArg, LLVMBuildIndirectBr, LLVMAddDestination};
use llvm_sys::prelude::{LLVMBuilderRef, LLVMValueRef};
use llvm_sys::{LLVMTypeKind};
use crate::{AtomicOrdering, AtomicRMWBinOp, IntPredicate, FloatPredicate};
use crate::basic_block::BasicBlock;
use crate::values::{AggregateValue, AggregateValueEnum, AsValueRef, BasicValue, BasicValueEnum, PhiValue, FunctionValue, IntValue, PointerValue, VectorValue, InstructionValue, GlobalValue, IntMathValue, FloatMathValue, PointerMathValue, InstructionOpcode, CallSiteValue};
use crate::types::{AsTypeRef, BasicType, IntMathType, FloatMathType, PointerType, PointerMathType};
use std::ffi::CString;
#[derive(Debug)]
pub struct Builder {
builder: LLVMBuilderRef,
}
impl Builder {
pub(crate) fn new(builder: LLVMBuilderRef) -> Self {
debug_assert!(!builder.is_null());
Builder {
builder: builder
}
}
/// Creates a `Builder` belonging to the global `Context`.
///
/// # Example
///
/// ```no_run
/// use inkwell::builder::Builder;
///
/// let builder = Builder::create();
/// ```
pub fn create() -> Self {
let builder = unsafe {
LLVMCreateBuilder()
};
Builder::new(builder)
}
// REVIEW: Would probably make this API a bit simpler by taking Into<Option<&BasicValue>>
// So that you could just do build_return(&value) or build_return(None). Is that frowned upon?
/// Builds a function return instruction. It should be provided with `None` if the return type
/// is void otherwise `Some(&value)` should be provided.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which returns its argument:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = i32_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
/// builder.build_return(Some(&i32_arg));
/// ```
pub fn build_return(&self, value: Option<&dyn BasicValue>) -> InstructionValue {
let value = unsafe {
value.map_or_else(|| LLVMBuildRetVoid(self.builder), |value| LLVMBuildRet(self.builder, value.as_value_ref()))
};
InstructionValue::new(value)
}
/// Builds a function return instruction for a return type which is an aggregate type (ie structs and arrays).
/// It is not necessary to use this over `build_return` but may be more convenient to use.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // This builds a simple function which returns a struct (tuple) of two ints.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let i32_three = i32_type.const_int(3, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let struct_type = context.struct_type(&[i32_type.into(), i32_type.into()], false);
/// let fn_type = struct_type.fn_type(&[], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
/// builder.build_aggregate_return(&[i32_three.into(), i32_seven.into()]);
/// ```
pub fn build_aggregate_return(&self, values: &[BasicValueEnum]) -> InstructionValue {
let mut args: Vec<LLVMValueRef> = values.iter()
.map(|val| val.as_value_ref())
.collect();
let value = unsafe {
LLVMBuildAggregateRet(self.builder, args.as_mut_ptr(), args.len() as u32)
};
InstructionValue::new(value)
}
/// Builds a function call instruction. It can take either a `FunctionValue` or a `PointerValue`
/// which is a function pointer. It will panic if the `PointerValue` is not a function pointer.
/// This may be turned into a Result in the future, however.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which calls itself:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let fn_type = i32_type.fn_type(&[i32_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
///
/// let ret_val = builder.build_call(fn_value, &[i32_arg], "call")
/// .try_as_basic_value()
/// .left()
/// .unwrap();
///
/// builder.build_return(Some(&ret_val));
/// ```
pub fn build_call<F>(&self, function: F, args: &[BasicValueEnum], name: &str) -> CallSiteValue
where
F: Into<FunctionOrPointerValue>,
{
let fn_val_ref = match function.into() {
Left(val) => val.as_value_ref(),
Right(val) => {
// If using a pointer value, we must validate it's a valid function ptr
let value_ref = val.as_value_ref();
let ty_kind = unsafe { LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(value_ref))) };
let is_a_fn_ptr = match ty_kind {
LLVMTypeKind::LLVMFunctionTypeKind => true,
_ => false,
};
// REVIEW: We should probably turn this into a Result?
assert!(is_a_fn_ptr, "build_call called with a pointer which is not a function pointer");
value_ref
},
};
// LLVM gets upset when void return calls are named because they don't return anything
let name = unsafe {
match LLVMGetTypeKind(LLVMGetReturnType(LLVMGetElementType(LLVMTypeOf(fn_val_ref)))) {
LLVMTypeKind::LLVMVoidTypeKind => "",
_ => name,
}
};
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut args: Vec<LLVMValueRef> = args.iter()
.map(|val| val.as_value_ref())
.collect();
let value = unsafe {
LLVMBuildCall(self.builder, fn_val_ref, args.as_mut_ptr(), args.len() as u32, c_string.as_ptr())
};
CallSiteValue::new(value)
}
// REVIEW: Doesn't GEP work on array too?
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_gep(&self, ptr: PointerValue, ordered_indexes: &[IntValue], name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter()
.map(|val| val.as_value_ref())
.collect();
let value = LLVMBuildGEP(self.builder, ptr.as_value_ref(), index_values.as_mut_ptr(), index_values.len() as u32, c_string.as_ptr());
PointerValue::new(value)
}
// REVIEW: Doesn't GEP work on array too?
// REVIEW: This could be merge in with build_gep via a in_bounds: bool param
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_in_bounds_gep(&self, ptr: PointerValue, ordered_indexes: &[IntValue], name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter()
.map(|val| val.as_value_ref())
.collect();
let value = LLVMBuildInBoundsGEP(self.builder, ptr.as_value_ref(), index_values.as_mut_ptr(), index_values.len() as u32, c_string.as_ptr());
PointerValue::new(value)
}
// REVIEW: Shouldn't this take a StructValue? Or does it still need to be PointerValue<StructValue>?
// I think it's the latter. This might not be as unsafe as regular GEP. Should check to see if it lets us
// go OOB. Maybe we could use the PointerValue<StructValue>'s struct info to do bounds checking...
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_struct_gep(&self, ptr: PointerValue, index: u32, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = LLVMBuildStructGEP(self.builder, ptr.as_value_ref(), index, c_string.as_ptr());
PointerValue::new(value)
}
/// Builds an instruction which calculates the difference of two pointers.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which diffs two pointers
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into(), i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param1 = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_ptr_param2 = fn_value.get_nth_param(1).unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
/// builder.build_ptr_diff(i32_ptr_param1, i32_ptr_param2, "diff");
/// builder.build_return(None);
/// ```
pub fn build_ptr_diff(&self, lhs_ptr: PointerValue, rhs_ptr: PointerValue, name: &str) -> IntValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPtrDiff(self.builder, lhs_ptr.as_value_ref(), rhs_ptr.as_value_ref(), c_string.as_ptr())
};
IntValue::new(value)
}
// SubTypes: Maybe this should return PhiValue<T>? That way we could force incoming values to be of T::Value?
// That is, assuming LLVM complains about different phi types.. which I imagine it would. But this would get
// tricky with VoidType since it has no instance value?
// TODOC: Phi Instruction(s) must be first instruction(s) in a BasicBlock.
// REVIEW: Not sure if we can enforce the above somehow via types.
pub fn build_phi<T: BasicType>(&self, type_: T, name: &str) -> PhiValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPhi(self.builder, type_.as_type_ref(), c_string.as_ptr())
};
PhiValue::new(value)
}
/// Builds a store instruction. It allows you to store a value of type `T` in a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and stores a 7 in it.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let i32_seven = i32_type.const_int(7, false);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
/// builder.build_store(i32_ptr_param, i32_seven);
/// builder.build_return(None);
/// ```
pub fn build_store<V: BasicValue>(&self, ptr: PointerValue, value: V) -> InstructionValue {
let value = unsafe {
LLVMBuildStore(self.builder, value.as_value_ref(), ptr.as_value_ref())
};
InstructionValue::new(value)
}
/// Builds a load instruction. It allows you to retrieve a value of type `T` from a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and returns the pointed at i32.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = i32_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
///
/// let pointee = builder.build_load(i32_ptr_param, "load");
///
/// builder.build_return(Some(&pointee));
/// ```
pub fn build_load(&self, ptr: PointerValue, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildLoad(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// TODOC: Stack allocation
pub fn build_alloca<T: BasicType>(&self, ty: T, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAlloca(self.builder, ty.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Stack allocation
pub fn build_array_alloca<T: BasicType>(&self, ty: T, size: IntValue, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildArrayAlloca(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Heap allocation
pub fn build_malloc<T: BasicType>(&self, ty: T, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildMalloc(self.builder, ty.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Heap allocation
pub fn build_array_malloc<T: BasicType>(&self, ty: T, size: IntValue, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildArrayMalloc(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// SubType: <P>(&self, ptr: PointerValue<P>) -> InstructionValue {
pub fn build_free(&self, ptr: PointerValue) -> InstructionValue {
let val = unsafe {
LLVMBuildFree(self.builder, ptr.as_value_ref())
};
InstructionValue::new(val)
}
pub fn insert_instruction(&self, instruction: &InstructionValue, name: Option<&str>) {
match name {
Some(name) => {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMInsertIntoBuilderWithName(self.builder, instruction.as_value_ref(), c_string.as_ptr())
}
},
None => unsafe {
LLVMInsertIntoBuilder(self.builder, instruction.as_value_ref());
},
}
}
pub fn get_insert_block(&self) -> Option<BasicBlock> {
let bb = unsafe {
LLVMGetInsertBlock(self.builder)
};
BasicBlock::new(bb)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I: IntSubType>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
// if I::sign() == Unsigned { LLVMBuildUDiv() } else { LLVMBuildSDiv() }
pub fn build_int_unsigned_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildUDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_exact_signed_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExactSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_unsigned_rem<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildURem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_rem<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_s_extend<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSExt(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Does this need vector support?
pub fn build_address_space_cast(&self, ptr_val: PointerValue, ptr_type: PointerType, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAddrSpaceCast(self.builder, ptr_val.as_value_ref(), ptr_type.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
/// Builds a bitcast instruction. A bitcast reinterprets the bits of one value
/// into a value of another type which has the same bit width.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("bc");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = void_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("bc", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
///
/// builder.build_bitcast(i32_arg, f32_type, "i32tof32");
/// builder.build_return(None);
///
/// assert!(module.verify().is_ok());
/// ```
pub fn build_bitcast<T, V>(&self, val: V, ty: T, name: &str) -> BasicValueEnum
where
T: BasicType,
V: BasicValue,
{
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildBitCast(self.builder, val.as_value_ref(), ty.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
pub fn build_int_s_extend_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSExtOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_z_extend<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildZExt(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_z_extend_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildZExtOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_truncate<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildTrunc(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_truncate_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildTruncOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_rem<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_float_to_unsigned_int<T: FloatMathValue>(&self, float: T, int_type: <T::BaseType as FloatMathType>::MathConvType, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPToUI(self.builder, float.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
pub fn build_float_to_signed_int<T: FloatMathValue>(&self, float: T, int_type: <T::BaseType as FloatMathType>::MathConvType, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPToSI(self.builder, float.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_unsigned_int_to_float<T: IntMathValue>(&self, int: T, float_type: <T::BaseType as IntMathType>::MathConvType, name: &str) -> <<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildUIToFP(self.builder, int.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)
}
pub fn build_signed_int_to_float<T: IntMathValue>(&self, int: T, float_type: <T::BaseType as IntMathType>::MathConvType, name: &str) -> <<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSIToFP(self.builder, int.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)
}
pub fn build_float_trunc<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPTrunc(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_ext<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPExt(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_cast<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPCast(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <L, R>(&self, lhs: &IntValue<L>, rhs: &IntType<R>, name: &str) -> IntValue<R> {
pub fn build_int_cast<T: IntMathValue>(&self, int: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildIntCast(self.builder, int.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_div<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_add<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_xor<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildXor(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_and<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAnd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_or<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildOr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
/// Builds an `IntValue` containing the result of a logical left shift instruction.
///
/// # Example
/// A logical left shift is an operation in which an integer value's bits are shifted left by N number of positions.
///
/// ```rust,no_run
/// assert_eq!(0b0000_0001 << 0, 0b0000_0001);
/// assert_eq!(0b0000_0001 << 1, 0b0000_0010);
/// assert_eq!(0b0000_0011 << 2, 0b0000_1100);
/// ```
///
/// In Rust, a function that could do this for 8bit values looks like:
///
/// ```rust,no_run
/// fn left_shift(value: u8, n: u8) -> u8 {
/// value << n
/// }
/// ```
///
/// And in Inkwell, the corresponding function would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("left_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = function.append_basic_block("entry");
///
/// builder.position_at_end(&entry_block);
///
/// let shift = builder.build_left_shift(value, n, "left_shift"); // value << n
///
/// builder.build_return(Some(&shift));
/// ```
pub fn build_left_shift<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildShl(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
/// Builds an `IntValue` containing the result of a right shift instruction.
///
/// # Example
/// A right shift is an operation in which an integer value's bits are shifted right by N number of positions.
/// It may either be logical and have its leftmost N bit(s) filled with zeros or sign extended and filled with ones
/// if the leftmost bit was one.
///
/// ```rust,no_run
/// //fix doc error about overflowing_literals
/// //rendered rfc: https://github.com/rust-lang/rfcs/blob/master/text/2438-deny-integer-literal-overflow-lint.md
/// //tracking issue: https://github.com/rust-lang/rust/issues/54502
/// #![allow(overflowing_literals)]
///
/// // Logical Right Shift
/// assert_eq!(0b1100_0000u8 >> 2, 0b0011_0000);
/// assert_eq!(0b0000_0010u8 >> 1, 0b0000_0001);
/// assert_eq!(0b0000_1100u8 >> 2, 0b0000_0011);
///
/// // Sign Extended Right Shift
/// assert_eq!(0b0100_0000i8 >> 2, 0b0001_0000);
/// assert_eq!(0b1110_0000u8 as i8 >> 1, 0b1111_0000u8 as i8);
/// assert_eq!(0b1100_0000u8 as i8 >> 2, 0b1111_0000u8 as i8);
/// ```
///
/// In Rust, functions that could do this for 8bit values look like:
///
/// ```rust,no_run
/// fn logical_right_shift(value: u8, n: u8) -> u8 {
/// value >> n
/// }
///
/// fn sign_extended_right_shift(value: i8, n: u8) -> i8 {
/// value >> n
/// }
/// ```
/// Notice that, in Rust (and most other languages), whether or not a value is sign extended depends wholly on whether
/// or not the type is signed (ie an i8 is a signed 8 bit value). LLVM does not make this distinction for you.
///
/// In Inkwell, the corresponding functions would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("right_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = function.append_basic_block("entry");
///
/// builder.position_at_end(&entry_block);
///
/// // Whether or not your right shift is sign extended (true) or logical (false) depends
/// // on the boolean input parameter:
/// let shift = builder.build_right_shift(value, n, false, "right_shift"); // value >> n
///
/// builder.build_return(Some(&shift));
/// ```
pub fn build_right_shift<T: IntMathValue>(&self, lhs: T, rhs: T, sign_extend: bool, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
if sign_extend {
LLVMBuildAShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
} else {
LLVMBuildLShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
}
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_sub via flag param
pub fn build_int_nsw_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_sub via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_sub<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_mul<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_cast<T: BasicType, V: BasicValue>(&self, op: InstructionOpcode, from_value: V, to_type: T, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildCast(self.builder, op.into(), from_value.as_value_ref(), to_type.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// SubType: <F, T>(&self, from: &PointerValue<F>, to: &PointerType<T>, name: &str) -> PointerValue<T> {
pub fn build_pointer_cast<T: PointerMathValue>(&self, from: T, to: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPointerCast(self.builder, from.as_value_ref(), to.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, op, lhs: &IntValue<I>, rhs: &IntValue<I>, name) -> IntValue<bool> { ?
// Note: we need a way to get an appropriate return type, since this method's return value
// is always a bool (or vector of bools), not necessarily the same as the input value
// See https://github.com/TheDan64/inkwell/pull/47#discussion_r197599297
pub fn build_int_compare<T: IntMathValue>(&self, op: IntPredicate, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildICmp(self.builder, op.as_llvm_enum(), lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, op, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name) -> IntValue<bool> { ?
// Note: see comment on build_int_compare regarding return value type
pub fn build_float_compare<T: FloatMathValue>(&self, op: FloatPredicate, lhs: T, rhs: T, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFCmp(self.builder, op.as_llvm_enum(), lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
pub fn build_unconditional_branch(&self, destination_block: &BasicBlock) -> InstructionValue {
let value = unsafe {
LLVMBuildBr(self.builder, destination_block.basic_block)
};
InstructionValue::new(value)
}
pub fn build_conditional_branch(&self, comparison: IntValue, then_block: &BasicBlock, else_block: &BasicBlock) -> InstructionValue {
let value = unsafe {
LLVMBuildCondBr(self.builder, comparison.as_value_ref(), then_block.basic_block, else_block.basic_block)
};
InstructionValue::new(value)
}
pub fn build_indirect_branch<BV: BasicValue>(&self, address: BV, destinations: &[&BasicBlock]) -> InstructionValue {
let value = unsafe {
LLVMBuildIndirectBr(self.builder, address.as_value_ref(), destinations.len() as u32)
};
for destination in destinations {
unsafe {
LLVMAddDestination(value, destination.basic_block)
}
}
InstructionValue::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_neg via flag and subtypes
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nsw_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nuw_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, value: &FloatValue<F>, name) -> FloatValue<F> {
pub fn build_float_neg<T: FloatMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<bool> { ?
pub fn build_not<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNot(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: What if instruction and basic_block are completely unrelated?
// It'd be great if we could get the BB from the instruction behind the scenes
pub fn position_at(&self, basic_block: &BasicBlock, instruction: &InstructionValue) {
unsafe {
LLVMPositionBuilder(self.builder, basic_block.basic_block, instruction.as_value_ref())
}
}
pub fn position_before(&self, instruction: &InstructionValue) {
unsafe {
LLVMPositionBuilderBefore(self.builder, instruction.as_value_ref())
}
}
pub fn position_at_end(&self, basic_block: &BasicBlock) {
unsafe {
LLVMPositionBuilderAtEnd(self.builder, basic_block.basic_block);
}
}
/// Builds an extract value instruction which extracts a `BasicValueEnum`
/// from a struct or array.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca");
/// let array = builder.build_load(array_alloca, "array_load").into_array_value();
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_none());
///
/// assert!(builder.build_extract_value(array, 0, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 1, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 2, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 3, "extract").is_none());
/// ```
pub fn build_extract_value<AV: AggregateValue>(&self, agg: AV, index: u32, name: &str) -> Option<BasicValueEnum> {
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return None;
}
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExtractValue(self.builder, agg.as_value_ref(), index, c_string.as_ptr())
};
Some(BasicValueEnum::new(value))
}
/// Builds an insert value instruction which inserts a `BasicValue` into a struct
/// or array and returns the resulting aggregate value.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca");
/// let array = builder.build_load(array_alloca, "array_load").into_array_value();
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_none());
/// ```
pub fn build_insert_value<AV, BV>(&self, agg: AV, value: BV, index: u32, name: &str) -> Option<AggregateValueEnum>
where
AV: AggregateValue,
BV: BasicValue,
{
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return None;
}
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildInsertValue(self.builder, agg.as_value_ref(), value.as_value_ref(), index, c_string.as_ptr())
};
Some(AggregateValueEnum::new(value))
}
/// Builds an extract element instruction which extracts a `BasicValueEnum`
/// from a vector.
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = i32_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(&entry);
///
/// let extracted = builder.build_extract_element(vector_param, i32_zero, "insert");
///
/// builder.build_return(Some(&extracted));
/// ```
pub fn build_extract_element(&self, vector: VectorValue, index: IntValue, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExtractElement(self.builder, vector.as_value_ref(), index.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
/// Builds an insert element instruction which inserts a `BasicValue` into a vector
/// and returns the resulting vector.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = void_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(&entry);
/// builder.build_insert_element(vector_param, i32_seven, i32_zero, "insert");
/// builder.build_return(None);
/// ```
pub fn build_insert_element<V: BasicValue>(&self, vector: VectorValue, element: V, index: IntValue, name: &str) -> VectorValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildInsertElement(self.builder, vector.as_value_ref(), element.as_value_ref(), index.as_value_ref(), c_string.as_ptr())
};
VectorValue::new(value)
}
pub fn build_unreachable(&self) -> InstructionValue {
let val = unsafe {
LLVMBuildUnreachable(self.builder)
};
InstructionValue::new(val)
}
// REVIEW: Not sure if this should return InstructionValue or an actual value
// TODO: Better name for num?
pub fn build_fence(&self, atomic_ordering: AtomicOrdering, num: i32, name: &str) -> InstructionValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildFence(self.builder, atomic_ordering.as_llvm_enum(), num, c_string.as_ptr())
};
InstructionValue::new(val)
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_null<T: PointerMathValue>(&self, ptr: T, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildIsNull(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_not_null<T: PointerMathValue>(&self, ptr: T, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildIsNotNull(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)
}
// SubType: <I, P>(&self, int: &IntValue<I>, ptr_type: &PointerType<P>, name) -> PointerValue<P> {
pub fn build_int_to_ptr<T: IntMathValue>(&self, int: T, ptr_type: <T::BaseType as IntMathType>::PtrConvType, name: &str) -> <<T::BaseType as IntMathType>::PtrConvType as PointerMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildIntToPtr(self.builder, int.as_value_ref(), ptr_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::PtrConvType as PointerMathType>::ValueType::new(value)
}
// SubType: <I, P>(&self, ptr: &PointerValue<P>, int_type: &IntType<I>, name) -> IntValue<I> {
pub fn build_ptr_to_int<T: PointerMathValue>(&self, ptr: T, int_type: <T::BaseType as PointerMathType>::PtrConvType, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPtrToInt(self.builder, ptr.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(value)
}
pub fn clear_insertion_position(&self) {
unsafe {
LLVMClearInsertionPosition(self.builder)
}
}
// REVIEW: Returning InstructionValue is the safe move here; but if the value means something
// (IE the result of the switch) it should probably return BasicValueEnum?
// SubTypes: I think value and case values must be the same subtype (maybe). Case value might need to be constants
pub fn build_switch(&self, value: IntValue, else_block: &BasicBlock, cases: &[(IntValue, &BasicBlock)]) -> InstructionValue {
let switch_value = unsafe {
LLVMBuildSwitch(self.builder, value.as_value_ref(), else_block.basic_block, cases.len() as u32)
};
for &(value, basic_block) in cases {
unsafe {
LLVMAddCase(switch_value, value.as_value_ref(), basic_block.basic_block)
}
}
InstructionValue::new(switch_value)
}
// SubTypes: condition can only be IntValue<bool> or VectorValue<IntValue<Bool>>
pub fn build_select<BV: BasicValue, IMV: IntMathValue>(&self, condition: IMV, then: BV, else_: BV, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSelect(self.builder, condition.as_value_ref(), then.as_value_ref(), else_.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// The unsafety of this function should be fixable with subtypes. See GH #32
pub unsafe fn build_global_string(&self, value: &str, name: &str) -> GlobalValue {
let c_string_value = CString::new(value).expect("Conversion to CString failed unexpectedly");
let c_string_name = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = LLVMBuildGlobalString(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr());
GlobalValue::new(value)
}
// REVIEW: Does this similar fn have the same issue build_global_string does? If so, mark as unsafe
// and fix with subtypes.
pub fn build_global_string_ptr(&self, value: &str, name: &str) -> GlobalValue {
let c_string_value = CString::new(value).expect("Conversion to CString failed unexpectedly");
let c_string_name = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildGlobalStringPtr(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr())
};
GlobalValue::new(value)
}
// REVIEW: Do we need to constrain types here? subtypes?
pub fn build_shuffle_vector(&self, left: VectorValue, right: VectorValue, mask: VectorValue, name: &str) -> VectorValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildShuffleVector(self.builder, left.as_value_ref(), right.as_value_ref(), mask.as_value_ref(), c_string.as_ptr())
};
VectorValue::new(value)
}
// REVIEW: Is return type correct?
// SubTypes: I think this should be type: BT -> BT::Value
// https://llvm.org/docs/LangRef.html#i-va-arg
pub fn build_va_arg<BT: BasicType>(&self, list: PointerValue, type_: BT, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildVAArg(self.builder, list.as_value_ref(), type_.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
/// Builds an atomicrmw instruction. It allows you to atomically modify memory.
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering, AtomicRMWBinOp};
/// let context = Context::create();
/// let module = context.create_module("rmw");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_seven = i32_type.const_int(7, false);
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("rmw", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let builder = context.create_builder();
/// builder.position_at_end(&entry);
/// builder.build_atomicrmw(AtomicRMWBinOp::Add, i32_ptr_param, i32_seven, AtomicOrdering::Unordered);
/// builder.build_return(None);
/// ```
// https://llvm.org/docs/LangRef.html#atomicrmw-instruction
pub fn build_atomicrmw(&self, op: AtomicRMWBinOp, ptr: PointerValue, value: IntValue, ordering: AtomicOrdering) -> Result<InstructionValue, ()> {
// "The type of ‘<value>’ must be an integer type whose bit width is a power of two greater than or equal to eight and less than or equal to a target-specific size limit. The type of the ‘<pointer>’ operand must be a pointer to that type." -- https://releases.llvm.org/3.6.2/docs/LangRef.html#atomicrmw-instruction
// Newer LLVM's (9+) support additional FAdd and FSub operations as well as xchg on floating point types.
if value.get_type().get_bit_width() < 8 ||
!value.get_type().get_bit_width().is_power_of_two() {
return Err(());
}
if ptr.get_type().get_element_type() != value.get_type().into() {
return Err(());
}
let val = unsafe {
LLVMBuildAtomicRMW(self.builder, op.as_llvm_enum(), ptr.as_value_ref(), value.as_value_ref(), ordering.as_llvm_enum(), false as i32)
};
Ok(InstructionValue::new(val))
}
/// Builds a cmpxchg instruction. It allows you to atomically compare and replace memory.
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering};
/// let context = Context::create();
/// let module = context.create_module("cmpxchg");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("", fn_type, None);
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_seven = i32_type.const_int(7, false);
/// let i32_eight = i32_type.const_int(8, false);
/// let entry = fn_value.append_basic_block("entry");
/// let builder = context.create_builder();
/// builder.position_at_end(&entry);
/// builder.build_cmpxchg(i32_ptr_param, i32_seven, i32_eight, AtomicOrdering::AcquireRelease, AtomicOrdering::Monotonic);
/// builder.build_return(None);
/// ```
// https://llvm.org/docs/LangRef.html#cmpxchg-instruction
pub fn build_cmpxchg<V: BasicValue>(&self, ptr: PointerValue, cmp: V, new: V, success: AtomicOrdering, failure: AtomicOrdering) -> Result<InstructionValue, ()> {
let cmp = cmp.as_basic_value_enum();
let new = new.as_basic_value_enum();
if cmp.get_type() != new.get_type() {
return Err(());
}
if !cmp.as_basic_value_enum().is_int_value() && !cmp.as_basic_value_enum().is_pointer_value() {
return Err(());
}
if ptr.get_type().get_element_type().to_basic_type_enum() != cmp.get_type() {
return Err(());
}
// "Both ordering parameters must be at least monotonic, the ordering constraint on failure must be no stronger than that on success, and the failure ordering cannot be either release or acq_rel." -- https://llvm.org/docs/LangRef.html#cmpxchg-instruction
if success < AtomicOrdering::Monotonic || failure < AtomicOrdering::Monotonic {
return Err(());
}
if failure > success {
return Err(());
}
if failure == AtomicOrdering::Release || failure == AtomicOrdering::AcquireRelease {
return Err(());
}
let val = unsafe {
LLVMBuildAtomicCmpXchg(self.builder, ptr.as_value_ref(), cmp.as_value_ref(), new.as_value_ref(), success.as_llvm_enum(), failure.as_llvm_enum(), false as i32)
};
Ok(InstructionValue::new(val))
}
}
impl Drop for Builder {
fn drop(&mut self) {
unsafe {
LLVMDisposeBuilder(self.builder);
}
}
}
type FunctionOrPointerValue = Either<FunctionValue, PointerValue>;
impl Into<FunctionOrPointerValue> for FunctionValue {
fn into(self) -> FunctionOrPointerValue {
Left(self)
}
}
impl Into<FunctionOrPointerValue> for PointerValue {
fn into(self) -> FunctionOrPointerValue {
Right(self)
}
}
Add error messages to API misuse when constructing atomicrmw or cmpxchg instructions.
//! A `Builder` enables you to build instructions.
use either::{Either, Left, Right};
use llvm_sys::core::{LLVMBuildAdd, LLVMBuildAlloca, LLVMBuildAnd, LLVMBuildArrayAlloca, LLVMBuildArrayMalloc, LLVMBuildAtomicCmpXchg, LLVMBuildAtomicRMW, LLVMBuildBr, LLVMBuildCall, LLVMBuildCast, LLVMBuildCondBr, LLVMBuildExtractValue, LLVMBuildFAdd, LLVMBuildFCmp, LLVMBuildFDiv, LLVMBuildFence, LLVMBuildFMul, LLVMBuildFNeg, LLVMBuildFree, LLVMBuildFSub, LLVMBuildGEP, LLVMBuildICmp, LLVMBuildInsertValue, LLVMBuildIsNotNull, LLVMBuildIsNull, LLVMBuildLoad, LLVMBuildMalloc, LLVMBuildMul, LLVMBuildNeg, LLVMBuildNot, LLVMBuildOr, LLVMBuildPhi, LLVMBuildPointerCast, LLVMBuildRet, LLVMBuildRetVoid, LLVMBuildStore, LLVMBuildSub, LLVMBuildUDiv, LLVMBuildUnreachable, LLVMBuildXor, LLVMDisposeBuilder, LLVMGetElementType, LLVMGetInsertBlock, LLVMGetReturnType, LLVMGetTypeKind, LLVMInsertIntoBuilder, LLVMPositionBuilderAtEnd, LLVMTypeOf, LLVMBuildExtractElement, LLVMBuildInsertElement, LLVMBuildIntToPtr, LLVMBuildPtrToInt, LLVMInsertIntoBuilderWithName, LLVMClearInsertionPosition, LLVMCreateBuilder, LLVMPositionBuilder, LLVMPositionBuilderBefore, LLVMBuildAggregateRet, LLVMBuildStructGEP, LLVMBuildInBoundsGEP, LLVMBuildPtrDiff, LLVMBuildNSWAdd, LLVMBuildNUWAdd, LLVMBuildNSWSub, LLVMBuildNUWSub, LLVMBuildNSWMul, LLVMBuildNUWMul, LLVMBuildSDiv, LLVMBuildSRem, LLVMBuildURem, LLVMBuildFRem, LLVMBuildNSWNeg, LLVMBuildNUWNeg, LLVMBuildFPToUI, LLVMBuildFPToSI, LLVMBuildSIToFP, LLVMBuildUIToFP, LLVMBuildFPTrunc, LLVMBuildFPExt, LLVMBuildIntCast, LLVMBuildFPCast, LLVMBuildSExtOrBitCast, LLVMBuildZExtOrBitCast, LLVMBuildTruncOrBitCast, LLVMBuildSwitch, LLVMAddCase, LLVMBuildShl, LLVMBuildAShr, LLVMBuildLShr, LLVMBuildGlobalString, LLVMBuildGlobalStringPtr, LLVMBuildExactSDiv, LLVMBuildTrunc, LLVMBuildSExt, LLVMBuildZExt, LLVMBuildSelect, LLVMBuildAddrSpaceCast, LLVMBuildBitCast, LLVMBuildShuffleVector, LLVMBuildVAArg, LLVMBuildIndirectBr, LLVMAddDestination};
use llvm_sys::prelude::{LLVMBuilderRef, LLVMValueRef};
use llvm_sys::{LLVMTypeKind};
use crate::{AtomicOrdering, AtomicRMWBinOp, IntPredicate, FloatPredicate};
use crate::basic_block::BasicBlock;
use crate::values::{AggregateValue, AggregateValueEnum, AsValueRef, BasicValue, BasicValueEnum, PhiValue, FunctionValue, IntValue, PointerValue, VectorValue, InstructionValue, GlobalValue, IntMathValue, FloatMathValue, PointerMathValue, InstructionOpcode, CallSiteValue};
use crate::types::{AsTypeRef, BasicType, IntMathType, FloatMathType, PointerType, PointerMathType};
use std::ffi::CString;
#[derive(Debug)]
pub struct Builder {
builder: LLVMBuilderRef,
}
impl Builder {
pub(crate) fn new(builder: LLVMBuilderRef) -> Self {
debug_assert!(!builder.is_null());
Builder {
builder: builder
}
}
/// Creates a `Builder` belonging to the global `Context`.
///
/// # Example
///
/// ```no_run
/// use inkwell::builder::Builder;
///
/// let builder = Builder::create();
/// ```
pub fn create() -> Self {
let builder = unsafe {
LLVMCreateBuilder()
};
Builder::new(builder)
}
// REVIEW: Would probably make this API a bit simpler by taking Into<Option<&BasicValue>>
// So that you could just do build_return(&value) or build_return(None). Is that frowned upon?
/// Builds a function return instruction. It should be provided with `None` if the return type
/// is void otherwise `Some(&value)` should be provided.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which returns its argument:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = i32_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
/// builder.build_return(Some(&i32_arg));
/// ```
pub fn build_return(&self, value: Option<&dyn BasicValue>) -> InstructionValue {
let value = unsafe {
value.map_or_else(|| LLVMBuildRetVoid(self.builder), |value| LLVMBuildRet(self.builder, value.as_value_ref()))
};
InstructionValue::new(value)
}
/// Builds a function return instruction for a return type which is an aggregate type (ie structs and arrays).
/// It is not necessary to use this over `build_return` but may be more convenient to use.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // This builds a simple function which returns a struct (tuple) of two ints.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let i32_three = i32_type.const_int(3, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let struct_type = context.struct_type(&[i32_type.into(), i32_type.into()], false);
/// let fn_type = struct_type.fn_type(&[], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
/// builder.build_aggregate_return(&[i32_three.into(), i32_seven.into()]);
/// ```
pub fn build_aggregate_return(&self, values: &[BasicValueEnum]) -> InstructionValue {
let mut args: Vec<LLVMValueRef> = values.iter()
.map(|val| val.as_value_ref())
.collect();
let value = unsafe {
LLVMBuildAggregateRet(self.builder, args.as_mut_ptr(), args.len() as u32)
};
InstructionValue::new(value)
}
/// Builds a function call instruction. It can take either a `FunctionValue` or a `PointerValue`
/// which is a function pointer. It will panic if the `PointerValue` is not a function pointer.
/// This may be turned into a Result in the future, however.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// // A simple function which calls itself:
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let fn_type = i32_type.fn_type(&[i32_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
///
/// let ret_val = builder.build_call(fn_value, &[i32_arg], "call")
/// .try_as_basic_value()
/// .left()
/// .unwrap();
///
/// builder.build_return(Some(&ret_val));
/// ```
pub fn build_call<F>(&self, function: F, args: &[BasicValueEnum], name: &str) -> CallSiteValue
where
F: Into<FunctionOrPointerValue>,
{
let fn_val_ref = match function.into() {
Left(val) => val.as_value_ref(),
Right(val) => {
// If using a pointer value, we must validate it's a valid function ptr
let value_ref = val.as_value_ref();
let ty_kind = unsafe { LLVMGetTypeKind(LLVMGetElementType(LLVMTypeOf(value_ref))) };
let is_a_fn_ptr = match ty_kind {
LLVMTypeKind::LLVMFunctionTypeKind => true,
_ => false,
};
// REVIEW: We should probably turn this into a Result?
assert!(is_a_fn_ptr, "build_call called with a pointer which is not a function pointer");
value_ref
},
};
// LLVM gets upset when void return calls are named because they don't return anything
let name = unsafe {
match LLVMGetTypeKind(LLVMGetReturnType(LLVMGetElementType(LLVMTypeOf(fn_val_ref)))) {
LLVMTypeKind::LLVMVoidTypeKind => "",
_ => name,
}
};
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut args: Vec<LLVMValueRef> = args.iter()
.map(|val| val.as_value_ref())
.collect();
let value = unsafe {
LLVMBuildCall(self.builder, fn_val_ref, args.as_mut_ptr(), args.len() as u32, c_string.as_ptr())
};
CallSiteValue::new(value)
}
// REVIEW: Doesn't GEP work on array too?
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_gep(&self, ptr: PointerValue, ordered_indexes: &[IntValue], name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter()
.map(|val| val.as_value_ref())
.collect();
let value = LLVMBuildGEP(self.builder, ptr.as_value_ref(), index_values.as_mut_ptr(), index_values.len() as u32, c_string.as_ptr());
PointerValue::new(value)
}
// REVIEW: Doesn't GEP work on array too?
// REVIEW: This could be merge in with build_gep via a in_bounds: bool param
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_in_bounds_gep(&self, ptr: PointerValue, ordered_indexes: &[IntValue], name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let mut index_values: Vec<LLVMValueRef> = ordered_indexes.iter()
.map(|val| val.as_value_ref())
.collect();
let value = LLVMBuildInBoundsGEP(self.builder, ptr.as_value_ref(), index_values.as_mut_ptr(), index_values.len() as u32, c_string.as_ptr());
PointerValue::new(value)
}
// REVIEW: Shouldn't this take a StructValue? Or does it still need to be PointerValue<StructValue>?
// I think it's the latter. This might not be as unsafe as regular GEP. Should check to see if it lets us
// go OOB. Maybe we could use the PointerValue<StructValue>'s struct info to do bounds checking...
/// GEP is very likely to segfault if indexes are used incorrectly, and is therefore an unsafe function. Maybe we can change this in the future.
pub unsafe fn build_struct_gep(&self, ptr: PointerValue, index: u32, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = LLVMBuildStructGEP(self.builder, ptr.as_value_ref(), index, c_string.as_ptr());
PointerValue::new(value)
}
/// Builds an instruction which calculates the difference of two pointers.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which diffs two pointers
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into(), i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param1 = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_ptr_param2 = fn_value.get_nth_param(1).unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
/// builder.build_ptr_diff(i32_ptr_param1, i32_ptr_param2, "diff");
/// builder.build_return(None);
/// ```
pub fn build_ptr_diff(&self, lhs_ptr: PointerValue, rhs_ptr: PointerValue, name: &str) -> IntValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPtrDiff(self.builder, lhs_ptr.as_value_ref(), rhs_ptr.as_value_ref(), c_string.as_ptr())
};
IntValue::new(value)
}
// SubTypes: Maybe this should return PhiValue<T>? That way we could force incoming values to be of T::Value?
// That is, assuming LLVM complains about different phi types.. which I imagine it would. But this would get
// tricky with VoidType since it has no instance value?
// TODOC: Phi Instruction(s) must be first instruction(s) in a BasicBlock.
// REVIEW: Not sure if we can enforce the above somehow via types.
pub fn build_phi<T: BasicType>(&self, type_: T, name: &str) -> PhiValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPhi(self.builder, type_.as_type_ref(), c_string.as_ptr())
};
PhiValue::new(value)
}
/// Builds a store instruction. It allows you to store a value of type `T` in a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and stores a 7 in it.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let i32_seven = i32_type.const_int(7, false);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
/// builder.build_store(i32_ptr_param, i32_seven);
/// builder.build_return(None);
/// ```
pub fn build_store<V: BasicValue>(&self, ptr: PointerValue, value: V) -> InstructionValue {
let value = unsafe {
LLVMBuildStore(self.builder, value.as_value_ref(), ptr.as_value_ref())
};
InstructionValue::new(value)
}
/// Builds a load instruction. It allows you to retrieve a value of type `T` from a pointer to a type `T`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::AddressSpace;
///
/// // Builds a function which takes an i32 pointer and returns the pointed at i32.
/// let context = Context::create();
/// let module = context.create_module("ret");
/// let builder = context.create_builder();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = i32_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("ret", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
///
/// builder.position_at_end(&entry);
///
/// let pointee = builder.build_load(i32_ptr_param, "load");
///
/// builder.build_return(Some(&pointee));
/// ```
pub fn build_load(&self, ptr: PointerValue, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildLoad(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// TODOC: Stack allocation
pub fn build_alloca<T: BasicType>(&self, ty: T, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAlloca(self.builder, ty.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Stack allocation
pub fn build_array_alloca<T: BasicType>(&self, ty: T, size: IntValue, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildArrayAlloca(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Heap allocation
pub fn build_malloc<T: BasicType>(&self, ty: T, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildMalloc(self.builder, ty.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// TODOC: Heap allocation
pub fn build_array_malloc<T: BasicType>(&self, ty: T, size: IntValue, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildArrayMalloc(self.builder, ty.as_type_ref(), size.as_value_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
// SubType: <P>(&self, ptr: PointerValue<P>) -> InstructionValue {
pub fn build_free(&self, ptr: PointerValue) -> InstructionValue {
let val = unsafe {
LLVMBuildFree(self.builder, ptr.as_value_ref())
};
InstructionValue::new(val)
}
pub fn insert_instruction(&self, instruction: &InstructionValue, name: Option<&str>) {
match name {
Some(name) => {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMInsertIntoBuilderWithName(self.builder, instruction.as_value_ref(), c_string.as_ptr())
}
},
None => unsafe {
LLVMInsertIntoBuilder(self.builder, instruction.as_value_ref());
},
}
}
pub fn get_insert_block(&self) -> Option<BasicBlock> {
let bb = unsafe {
LLVMGetInsertBlock(self.builder)
};
BasicBlock::new(bb)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I: IntSubType>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
// if I::sign() == Unsigned { LLVMBuildUDiv() } else { LLVMBuildSDiv() }
pub fn build_int_unsigned_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildUDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_exact_signed_div<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExactSDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_unsigned_rem<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildURem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// TODO: Possibly make this generic over sign via struct metadata or subtypes
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_signed_rem<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_s_extend<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSExt(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Does this need vector support?
pub fn build_address_space_cast(&self, ptr_val: PointerValue, ptr_type: PointerType, name: &str) -> PointerValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAddrSpaceCast(self.builder, ptr_val.as_value_ref(), ptr_type.as_type_ref(), c_string.as_ptr())
};
PointerValue::new(value)
}
/// Builds a bitcast instruction. A bitcast reinterprets the bits of one value
/// into a value of another type which has the same bit width.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("bc");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let arg_types = [i32_type.into()];
/// let fn_type = void_type.fn_type(&arg_types, false);
/// let fn_value = module.add_function("bc", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let i32_arg = fn_value.get_first_param().unwrap();
///
/// builder.position_at_end(&entry);
///
/// builder.build_bitcast(i32_arg, f32_type, "i32tof32");
/// builder.build_return(None);
///
/// assert!(module.verify().is_ok());
/// ```
pub fn build_bitcast<T, V>(&self, val: V, ty: T, name: &str) -> BasicValueEnum
where
T: BasicType,
V: BasicValue,
{
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildBitCast(self.builder, val.as_value_ref(), ty.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
pub fn build_int_s_extend_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSExtOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_z_extend<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildZExt(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_z_extend_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildZExtOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_truncate<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildTrunc(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_int_truncate_or_bit_cast<T: IntMathValue>(&self, int_value: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildTruncOrBitCast(self.builder, int_value.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_rem<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFRem(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_float_to_unsigned_int<T: FloatMathValue>(&self, float: T, int_type: <T::BaseType as FloatMathType>::MathConvType, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPToUI(self.builder, float.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
pub fn build_float_to_signed_int<T: FloatMathValue>(&self, float: T, int_type: <T::BaseType as FloatMathType>::MathConvType, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPToSI(self.builder, float.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
// REVIEW: Consolidate these two casts into one via subtypes
pub fn build_unsigned_int_to_float<T: IntMathValue>(&self, int: T, float_type: <T::BaseType as IntMathType>::MathConvType, name: &str) -> <<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildUIToFP(self.builder, int.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)
}
pub fn build_signed_int_to_float<T: IntMathValue>(&self, int: T, float_type: <T::BaseType as IntMathType>::MathConvType, name: &str) -> <<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSIToFP(self.builder, int.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::MathConvType as FloatMathType>::ValueType::new(value)
}
pub fn build_float_trunc<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPTrunc(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_ext<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPExt(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_cast<T: FloatMathValue>(&self, float: T, float_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFPCast(self.builder, float.as_value_ref(), float_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <L, R>(&self, lhs: &IntValue<L>, rhs: &IntType<R>, name: &str) -> IntValue<R> {
pub fn build_int_cast<T: IntMathValue>(&self, int: T, int_type: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildIntCast(self.builder, int.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_float_div<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFDiv(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_add via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_add<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_add<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFAdd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_xor<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildXor(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_and<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildAnd(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: (&self, lhs: &IntValue<bool>, rhs: &IntValue<bool>, name: &str) -> IntValue<bool> {
pub fn build_or<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildOr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
/// Builds an `IntValue` containing the result of a logical left shift instruction.
///
/// # Example
/// A logical left shift is an operation in which an integer value's bits are shifted left by N number of positions.
///
/// ```rust,no_run
/// assert_eq!(0b0000_0001 << 0, 0b0000_0001);
/// assert_eq!(0b0000_0001 << 1, 0b0000_0010);
/// assert_eq!(0b0000_0011 << 2, 0b0000_1100);
/// ```
///
/// In Rust, a function that could do this for 8bit values looks like:
///
/// ```rust,no_run
/// fn left_shift(value: u8, n: u8) -> u8 {
/// value << n
/// }
/// ```
///
/// And in Inkwell, the corresponding function would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("left_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = function.append_basic_block("entry");
///
/// builder.position_at_end(&entry_block);
///
/// let shift = builder.build_left_shift(value, n, "left_shift"); // value << n
///
/// builder.build_return(Some(&shift));
/// ```
pub fn build_left_shift<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildShl(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
/// Builds an `IntValue` containing the result of a right shift instruction.
///
/// # Example
/// A right shift is an operation in which an integer value's bits are shifted right by N number of positions.
/// It may either be logical and have its leftmost N bit(s) filled with zeros or sign extended and filled with ones
/// if the leftmost bit was one.
///
/// ```rust,no_run
/// //fix doc error about overflowing_literals
/// //rendered rfc: https://github.com/rust-lang/rfcs/blob/master/text/2438-deny-integer-literal-overflow-lint.md
/// //tracking issue: https://github.com/rust-lang/rust/issues/54502
/// #![allow(overflowing_literals)]
///
/// // Logical Right Shift
/// assert_eq!(0b1100_0000u8 >> 2, 0b0011_0000);
/// assert_eq!(0b0000_0010u8 >> 1, 0b0000_0001);
/// assert_eq!(0b0000_1100u8 >> 2, 0b0000_0011);
///
/// // Sign Extended Right Shift
/// assert_eq!(0b0100_0000i8 >> 2, 0b0001_0000);
/// assert_eq!(0b1110_0000u8 as i8 >> 1, 0b1111_0000u8 as i8);
/// assert_eq!(0b1100_0000u8 as i8 >> 2, 0b1111_0000u8 as i8);
/// ```
///
/// In Rust, functions that could do this for 8bit values look like:
///
/// ```rust,no_run
/// fn logical_right_shift(value: u8, n: u8) -> u8 {
/// value >> n
/// }
///
/// fn sign_extended_right_shift(value: i8, n: u8) -> i8 {
/// value >> n
/// }
/// ```
/// Notice that, in Rust (and most other languages), whether or not a value is sign extended depends wholly on whether
/// or not the type is signed (ie an i8 is a signed 8 bit value). LLVM does not make this distinction for you.
///
/// In Inkwell, the corresponding functions would look roughly like:
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// // Setup
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let builder = context.create_builder();
/// let i8_type = context.i8_type();
/// let fn_type = i8_type.fn_type(&[i8_type.into(), i8_type.into()], false);
///
/// // Function Definition
/// let function = module.add_function("right_shift", fn_type, None);
/// let value = function.get_first_param().unwrap().into_int_value();
/// let n = function.get_nth_param(1).unwrap().into_int_value();
/// let entry_block = function.append_basic_block("entry");
///
/// builder.position_at_end(&entry_block);
///
/// // Whether or not your right shift is sign extended (true) or logical (false) depends
/// // on the boolean input parameter:
/// let shift = builder.build_right_shift(value, n, false, "right_shift"); // value >> n
///
/// builder.build_return(Some(&shift));
/// ```
pub fn build_right_shift<T: IntMathValue>(&self, lhs: T, rhs: T, sign_extend: bool, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
if sign_extend {
LLVMBuildAShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
} else {
LLVMBuildLShr(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
}
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_sub via flag param
pub fn build_int_nsw_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_sub via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_sub<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_sub<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFSub(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nsw_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_mul via flag param
// SubType: <I>(&self, lhs: &IntValue<I>, rhs: &IntValue<I>, name: &str) -> IntValue<I> {
pub fn build_int_nuw_mul<T: IntMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name: &str) -> FloatValue<F> {
pub fn build_float_mul<T: FloatMathValue>(&self, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFMul(self.builder, lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
pub fn build_cast<T: BasicType, V: BasicValue>(&self, op: InstructionOpcode, from_value: V, to_type: T, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildCast(self.builder, op.into(), from_value.as_value_ref(), to_type.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// SubType: <F, T>(&self, from: &PointerValue<F>, to: &PointerType<T>, name: &str) -> PointerValue<T> {
pub fn build_pointer_cast<T: PointerMathValue>(&self, from: T, to: T::BaseType, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPointerCast(self.builder, from.as_value_ref(), to.as_type_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, op, lhs: &IntValue<I>, rhs: &IntValue<I>, name) -> IntValue<bool> { ?
// Note: we need a way to get an appropriate return type, since this method's return value
// is always a bool (or vector of bools), not necessarily the same as the input value
// See https://github.com/TheDan64/inkwell/pull/47#discussion_r197599297
pub fn build_int_compare<T: IntMathValue>(&self, op: IntPredicate, lhs: T, rhs: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildICmp(self.builder, op.as_llvm_enum(), lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, op, lhs: &FloatValue<F>, rhs: &FloatValue<F>, name) -> IntValue<bool> { ?
// Note: see comment on build_int_compare regarding return value type
pub fn build_float_compare<T: FloatMathValue>(&self, op: FloatPredicate, lhs: T, rhs: T, name: &str) -> <<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFCmp(self.builder, op.as_llvm_enum(), lhs.as_value_ref(), rhs.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as FloatMathType>::MathConvType as IntMathType>::ValueType::new(value)
}
pub fn build_unconditional_branch(&self, destination_block: &BasicBlock) -> InstructionValue {
let value = unsafe {
LLVMBuildBr(self.builder, destination_block.basic_block)
};
InstructionValue::new(value)
}
pub fn build_conditional_branch(&self, comparison: IntValue, then_block: &BasicBlock, else_block: &BasicBlock) -> InstructionValue {
let value = unsafe {
LLVMBuildCondBr(self.builder, comparison.as_value_ref(), then_block.basic_block, else_block.basic_block)
};
InstructionValue::new(value)
}
pub fn build_indirect_branch<BV: BasicValue>(&self, address: BV, destinations: &[&BasicBlock]) -> InstructionValue {
let value = unsafe {
LLVMBuildIndirectBr(self.builder, address.as_value_ref(), destinations.len() as u32)
};
for destination in destinations {
unsafe {
LLVMAddDestination(value, destination.basic_block)
}
}
InstructionValue::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: Possibly incorperate into build_int_neg via flag and subtypes
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nsw_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNSWNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<I> {
pub fn build_int_nuw_neg<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNUWNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <F>(&self, value: &FloatValue<F>, name) -> FloatValue<F> {
pub fn build_float_neg<T: FloatMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildFNeg(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// SubType: <I>(&self, value: &IntValue<I>, name) -> IntValue<bool> { ?
pub fn build_not<T: IntMathValue>(&self, value: T, name: &str) -> T {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildNot(self.builder, value.as_value_ref(), c_string.as_ptr())
};
T::new(value)
}
// REVIEW: What if instruction and basic_block are completely unrelated?
// It'd be great if we could get the BB from the instruction behind the scenes
pub fn position_at(&self, basic_block: &BasicBlock, instruction: &InstructionValue) {
unsafe {
LLVMPositionBuilder(self.builder, basic_block.basic_block, instruction.as_value_ref())
}
}
pub fn position_before(&self, instruction: &InstructionValue) {
unsafe {
LLVMPositionBuilderBefore(self.builder, instruction.as_value_ref())
}
}
pub fn position_at_end(&self, basic_block: &BasicBlock) {
unsafe {
LLVMPositionBuilderAtEnd(self.builder, basic_block.basic_block);
}
}
/// Builds an extract value instruction which extracts a `BasicValueEnum`
/// from a struct or array.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca");
/// let array = builder.build_load(array_alloca, "array_load").into_array_value();
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_none());
///
/// assert!(builder.build_extract_value(array, 0, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 1, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 2, "extract").unwrap().is_int_value());
/// assert!(builder.build_extract_value(array, 3, "extract").is_none());
/// ```
pub fn build_extract_value<AV: AggregateValue>(&self, agg: AV, index: u32, name: &str) -> Option<BasicValueEnum> {
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return None;
}
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExtractValue(self.builder, agg.as_value_ref(), index, c_string.as_ptr())
};
Some(BasicValueEnum::new(value))
}
/// Builds an insert value instruction which inserts a `BasicValue` into a struct
/// or array and returns the resulting aggregate value.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let f32_type = context.f32_type();
/// let i32_type = context.i32_type();
/// let struct_type = context.struct_type(&[i32_type.into(), f32_type.into()], false);
/// let array_type = i32_type.array_type(3);
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("av_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
///
/// builder.position_at_end(&entry);
///
/// let array_alloca = builder.build_alloca(array_type, "array_alloca");
/// let array = builder.build_load(array_alloca, "array_load").into_array_value();
/// let const_int1 = i32_type.const_int(2, false);
/// let const_int2 = i32_type.const_int(5, false);
/// let const_int3 = i32_type.const_int(6, false);
///
/// assert!(builder.build_insert_value(array, const_int1, 0, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int2, 1, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 2, "insert").is_some());
/// assert!(builder.build_insert_value(array, const_int3, 3, "insert").is_none());
/// ```
pub fn build_insert_value<AV, BV>(&self, agg: AV, value: BV, index: u32, name: &str) -> Option<AggregateValueEnum>
where
AV: AggregateValue,
BV: BasicValue,
{
let size = match agg.as_aggregate_value_enum() {
AggregateValueEnum::ArrayValue(av) => av.get_type().len(),
AggregateValueEnum::StructValue(sv) => sv.get_type().count_fields(),
};
if index >= size {
return None;
}
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildInsertValue(self.builder, agg.as_value_ref(), value.as_value_ref(), index, c_string.as_ptr())
};
Some(AggregateValueEnum::new(value))
}
/// Builds an extract element instruction which extracts a `BasicValueEnum`
/// from a vector.
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = i32_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(&entry);
///
/// let extracted = builder.build_extract_element(vector_param, i32_zero, "insert");
///
/// builder.build_return(Some(&extracted));
/// ```
pub fn build_extract_element(&self, vector: VectorValue, index: IntValue, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildExtractElement(self.builder, vector.as_value_ref(), index.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
/// Builds an insert element instruction which inserts a `BasicValue` into a vector
/// and returns the resulting vector.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("av");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_zero = i32_type.const_int(0, false);
/// let i32_seven = i32_type.const_int(7, false);
/// let vec_type = i32_type.vec_type(2);
/// let fn_type = void_type.fn_type(&[vec_type.into()], false);
/// let fn_value = module.add_function("vec_fn", fn_type, None);
/// let builder = context.create_builder();
/// let entry = fn_value.append_basic_block("entry");
/// let vector_param = fn_value.get_first_param().unwrap().into_vector_value();
///
/// builder.position_at_end(&entry);
/// builder.build_insert_element(vector_param, i32_seven, i32_zero, "insert");
/// builder.build_return(None);
/// ```
pub fn build_insert_element<V: BasicValue>(&self, vector: VectorValue, element: V, index: IntValue, name: &str) -> VectorValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildInsertElement(self.builder, vector.as_value_ref(), element.as_value_ref(), index.as_value_ref(), c_string.as_ptr())
};
VectorValue::new(value)
}
pub fn build_unreachable(&self) -> InstructionValue {
let val = unsafe {
LLVMBuildUnreachable(self.builder)
};
InstructionValue::new(val)
}
// REVIEW: Not sure if this should return InstructionValue or an actual value
// TODO: Better name for num?
pub fn build_fence(&self, atomic_ordering: AtomicOrdering, num: i32, name: &str) -> InstructionValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildFence(self.builder, atomic_ordering.as_llvm_enum(), num, c_string.as_ptr())
};
InstructionValue::new(val)
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_null<T: PointerMathValue>(&self, ptr: T, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildIsNull(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)
}
// SubType: <P>(&self, ptr: &PointerValue<P>, name) -> IntValue<bool> {
pub fn build_is_not_null<T: PointerMathValue>(&self, ptr: T, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let val = unsafe {
LLVMBuildIsNotNull(self.builder, ptr.as_value_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(val)
}
// SubType: <I, P>(&self, int: &IntValue<I>, ptr_type: &PointerType<P>, name) -> PointerValue<P> {
pub fn build_int_to_ptr<T: IntMathValue>(&self, int: T, ptr_type: <T::BaseType as IntMathType>::PtrConvType, name: &str) -> <<T::BaseType as IntMathType>::PtrConvType as PointerMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildIntToPtr(self.builder, int.as_value_ref(), ptr_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as IntMathType>::PtrConvType as PointerMathType>::ValueType::new(value)
}
// SubType: <I, P>(&self, ptr: &PointerValue<P>, int_type: &IntType<I>, name) -> IntValue<I> {
pub fn build_ptr_to_int<T: PointerMathValue>(&self, ptr: T, int_type: <T::BaseType as PointerMathType>::PtrConvType, name: &str) -> <<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildPtrToInt(self.builder, ptr.as_value_ref(), int_type.as_type_ref(), c_string.as_ptr())
};
<<T::BaseType as PointerMathType>::PtrConvType as IntMathType>::ValueType::new(value)
}
pub fn clear_insertion_position(&self) {
unsafe {
LLVMClearInsertionPosition(self.builder)
}
}
// REVIEW: Returning InstructionValue is the safe move here; but if the value means something
// (IE the result of the switch) it should probably return BasicValueEnum?
// SubTypes: I think value and case values must be the same subtype (maybe). Case value might need to be constants
pub fn build_switch(&self, value: IntValue, else_block: &BasicBlock, cases: &[(IntValue, &BasicBlock)]) -> InstructionValue {
let switch_value = unsafe {
LLVMBuildSwitch(self.builder, value.as_value_ref(), else_block.basic_block, cases.len() as u32)
};
for &(value, basic_block) in cases {
unsafe {
LLVMAddCase(switch_value, value.as_value_ref(), basic_block.basic_block)
}
}
InstructionValue::new(switch_value)
}
// SubTypes: condition can only be IntValue<bool> or VectorValue<IntValue<Bool>>
pub fn build_select<BV: BasicValue, IMV: IntMathValue>(&self, condition: IMV, then: BV, else_: BV, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildSelect(self.builder, condition.as_value_ref(), then.as_value_ref(), else_.as_value_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
// The unsafety of this function should be fixable with subtypes. See GH #32
pub unsafe fn build_global_string(&self, value: &str, name: &str) -> GlobalValue {
let c_string_value = CString::new(value).expect("Conversion to CString failed unexpectedly");
let c_string_name = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = LLVMBuildGlobalString(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr());
GlobalValue::new(value)
}
// REVIEW: Does this similar fn have the same issue build_global_string does? If so, mark as unsafe
// and fix with subtypes.
pub fn build_global_string_ptr(&self, value: &str, name: &str) -> GlobalValue {
let c_string_value = CString::new(value).expect("Conversion to CString failed unexpectedly");
let c_string_name = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildGlobalStringPtr(self.builder, c_string_value.as_ptr(), c_string_name.as_ptr())
};
GlobalValue::new(value)
}
// REVIEW: Do we need to constrain types here? subtypes?
pub fn build_shuffle_vector(&self, left: VectorValue, right: VectorValue, mask: VectorValue, name: &str) -> VectorValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildShuffleVector(self.builder, left.as_value_ref(), right.as_value_ref(), mask.as_value_ref(), c_string.as_ptr())
};
VectorValue::new(value)
}
// REVIEW: Is return type correct?
// SubTypes: I think this should be type: BT -> BT::Value
// https://llvm.org/docs/LangRef.html#i-va-arg
pub fn build_va_arg<BT: BasicType>(&self, list: PointerValue, type_: BT, name: &str) -> BasicValueEnum {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMBuildVAArg(self.builder, list.as_value_ref(), type_.as_type_ref(), c_string.as_ptr())
};
BasicValueEnum::new(value)
}
/// Builds an atomicrmw instruction. It allows you to atomically modify memory.
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering, AtomicRMWBinOp};
/// let context = Context::create();
/// let module = context.create_module("rmw");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_seven = i32_type.const_int(7, false);
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("rmw", fn_type, None);
/// let entry = fn_value.append_basic_block("entry");
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let builder = context.create_builder();
/// builder.position_at_end(&entry);
/// builder.build_atomicrmw(AtomicRMWBinOp::Add, i32_ptr_param, i32_seven, AtomicOrdering::Unordered);
/// builder.build_return(None);
/// ```
// https://llvm.org/docs/LangRef.html#atomicrmw-instruction
pub fn build_atomicrmw(&self, op: AtomicRMWBinOp, ptr: PointerValue, value: IntValue, ordering: AtomicOrdering) -> Result<InstructionValue, &'static str> {
// "The type of ‘<value>’ must be an integer type whose bit width is a power of two greater than or equal to eight and less than or equal to a target-specific size limit. The type of the ‘<pointer>’ operand must be a pointer to that type." -- https://releases.llvm.org/3.6.2/docs/LangRef.html#atomicrmw-instruction
// Newer LLVM's (9+) support additional FAdd and FSub operations as well as xchg on floating point types.
if value.get_type().get_bit_width() < 8 ||
!value.get_type().get_bit_width().is_power_of_two() {
return Err("The bitwidth of value must be a power of 2 and greater than 8.");
}
if ptr.get_type().get_element_type() != value.get_type().into() {
return Err("Pointer's pointee type must match the value's type.");
}
let val = unsafe {
LLVMBuildAtomicRMW(self.builder, op.as_llvm_enum(), ptr.as_value_ref(), value.as_value_ref(), ordering.as_llvm_enum(), false as i32)
};
Ok(InstructionValue::new(val))
}
/// Builds a cmpxchg instruction. It allows you to atomically compare and replace memory.
///
/// # Example
///
/// ```
/// use inkwell::context::Context;
/// use inkwell::{AddressSpace, AtomicOrdering};
/// let context = Context::create();
/// let module = context.create_module("cmpxchg");
/// let void_type = context.void_type();
/// let i32_type = context.i32_type();
/// let i32_ptr_type = i32_type.ptr_type(AddressSpace::Generic);
/// let fn_type = void_type.fn_type(&[i32_ptr_type.into()], false);
/// let fn_value = module.add_function("", fn_type, None);
/// let i32_ptr_param = fn_value.get_first_param().unwrap().into_pointer_value();
/// let i32_seven = i32_type.const_int(7, false);
/// let i32_eight = i32_type.const_int(8, false);
/// let entry = fn_value.append_basic_block("entry");
/// let builder = context.create_builder();
/// builder.position_at_end(&entry);
/// builder.build_cmpxchg(i32_ptr_param, i32_seven, i32_eight, AtomicOrdering::AcquireRelease, AtomicOrdering::Monotonic);
/// builder.build_return(None);
/// ```
// https://llvm.org/docs/LangRef.html#cmpxchg-instruction
pub fn build_cmpxchg<V: BasicValue>(&self, ptr: PointerValue, cmp: V, new: V, success: AtomicOrdering, failure: AtomicOrdering) -> Result<InstructionValue, &'static str> {
let cmp = cmp.as_basic_value_enum();
let new = new.as_basic_value_enum();
if cmp.get_type() != new.get_type() {
return Err("The value to compare against and the value to replace with must have the same type.");
}
if !cmp.as_basic_value_enum().is_int_value() && !cmp.as_basic_value_enum().is_pointer_value() {
return Err("The values must have pointer or integer type.");
}
if ptr.get_type().get_element_type().to_basic_type_enum() != cmp.get_type() {
return Err("The pointer does not point to an element of the value type.");
}
// "Both ordering parameters must be at least monotonic, the ordering constraint on failure must be no stronger than that on success, and the failure ordering cannot be either release or acq_rel." -- https://llvm.org/docs/LangRef.html#cmpxchg-instruction
if success < AtomicOrdering::Monotonic || failure < AtomicOrdering::Monotonic {
return Err("Both success and failure orderings must be Monotonic or stronger.");
}
if failure > success {
return Err("The failure ordering may not be stronger than the success ordering.");
}
if failure == AtomicOrdering::Release || failure == AtomicOrdering::AcquireRelease {
return Err("The failure ordering may not be release or acquire release.");
}
let val = unsafe {
LLVMBuildAtomicCmpXchg(self.builder, ptr.as_value_ref(), cmp.as_value_ref(), new.as_value_ref(), success.as_llvm_enum(), failure.as_llvm_enum(), false as i32)
};
Ok(InstructionValue::new(val))
}
}
impl Drop for Builder {
fn drop(&mut self) {
unsafe {
LLVMDisposeBuilder(self.builder);
}
}
}
type FunctionOrPointerValue = Either<FunctionValue, PointerValue>;
impl Into<FunctionOrPointerValue> for FunctionValue {
fn into(self) -> FunctionOrPointerValue {
Left(self)
}
}
impl Into<FunctionOrPointerValue> for PointerValue {
fn into(self) -> FunctionOrPointerValue {
Right(self)
}
}
|
use std::io;
use std::sync::mpsc::TryRecvError;
use futures::{Future, Poll};
use futures_io::IoFuture;
use mio::channel;
use {ReadinessStream, LoopHandle};
/// The transmission half of a channel used for sending messages to a receiver.
///
/// A `Sender` can be `clone`d to have multiple threads or instances sending
/// messages to one receiver.
///
/// This type is created by the `LoopHandle::channel` method.
pub struct Sender<T> {
tx: channel::Sender<T>,
}
/// The receiving half of a channel used for processing messages sent by a
/// `Sender`.
///
/// A `Receiver` cannot be cloned and is not `Sync`, so only one thread can
/// receive messages at a time.
///
/// This type is created by the `LoopHandle::channel` method.
pub struct Receiver<T> {
rx: ReadinessStream<channel::Receiver<T>>,
}
impl LoopHandle {
/// Creates a new in-memory channel used for sending data across `Send +
/// 'static` boundaries, frequently threads.
///
/// This type can be used to conveniently send messages between futures.
/// Unlike the futures crate `channel` method and types, the returned tx/rx
/// pair is a multi-producer single-consumer (mpsc) channel *with no
/// backpressure*. Currently it's left up to the application to implement a
/// mechanism, if necessary, to avoid messages piling up.
///
/// The returned `Sender` can be used to send messages that are processed by
/// the returned `Receiver`. The `Sender` can be cloned to send messages
/// from multiple sources simultaneously.
pub fn channel<T>(self) -> (Sender<T>, IoFuture<Receiver<T>>)
where T: Send + 'static,
{
let (tx, rx) = channel::channel();
let rx = ReadinessStream::new(self, rx).map(|rx| Receiver { rx: rx });
(Sender { tx: tx }, rx.boxed())
}
}
impl<T> Sender<T> {
/// Sends a message to the corresponding receiver of this sender.
///
/// The message provided will be enqueued on the channel immediately, and
/// this function will return immediately. Keep in mind that the
/// underlying channel has infinite capacity, and this may not always be
/// desired.
///
/// If an I/O error happens while sending the message, or if the receiver
/// has gone away, then an error will be returned. Note that I/O errors here
/// are generally quite abnormal.
pub fn send(&self, t: T) -> io::Result<()> {
self.tx.send(t).map_err(|e| {
match e {
channel::SendError::Io(e) => e,
channel::SendError::Disconnected(_) => {
io::Error::new(io::ErrorKind::Other,
"channel has been disconnected")
}
}
})
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Sender<T> {
Sender { tx: self.tx.clone() }
}
}
impl<T> Receiver<T> {
/// Attempts to receive a message sent on this channel.
///
/// This method will attempt to dequeue any messages sent on this channel
/// from any corresponding sender. If no message is available, but senders
/// are still detected, then `Poll::NotReady` is returned and the current
/// future task is scheduled to receive a notification when a message is
/// available.
///
/// If an I/O error happens or if all senders have gone away (the channel is
/// disconnected) then `Poll::Err` will be returned.
pub fn recv(&self) -> Poll<T, io::Error> {
match self.rx.get_ref().try_recv() {
Ok(t) => Poll::Ok(t),
Err(TryRecvError::Empty) => {
self.rx.need_read();
Poll::NotReady
}
Err(TryRecvError::Disconnected) => {
Poll::Err(io::Error::new(io::ErrorKind::Other,
"channel has been disconnected"))
}
}
}
}
Implement Stream for Receiver
That's... what it is!
use std::io;
use std::sync::mpsc::TryRecvError;
use futures::{Future, Poll};
use futures::stream::Stream;
use futures_io::IoFuture;
use mio::channel;
use {ReadinessStream, LoopHandle};
/// The transmission half of a channel used for sending messages to a receiver.
///
/// A `Sender` can be `clone`d to have multiple threads or instances sending
/// messages to one receiver.
///
/// This type is created by the `LoopHandle::channel` method.
pub struct Sender<T> {
tx: channel::Sender<T>,
}
/// The receiving half of a channel used for processing messages sent by a
/// `Sender`.
///
/// A `Receiver` cannot be cloned, so only one thread can receive messages at a
/// time.
///
/// This type is created by the `LoopHandle::channel` method and implements the
/// `Stream` trait to represent received messages.
pub struct Receiver<T> {
rx: ReadinessStream<channel::Receiver<T>>,
}
impl LoopHandle {
/// Creates a new in-memory channel used for sending data across `Send +
/// 'static` boundaries, frequently threads.
///
/// This type can be used to conveniently send messages between futures.
/// Unlike the futures crate `channel` method and types, the returned tx/rx
/// pair is a multi-producer single-consumer (mpsc) channel *with no
/// backpressure*. Currently it's left up to the application to implement a
/// mechanism, if necessary, to avoid messages piling up.
///
/// The returned `Sender` can be used to send messages that are processed by
/// the returned `Receiver`. The `Sender` can be cloned to send messages
/// from multiple sources simultaneously.
pub fn channel<T>(self) -> (Sender<T>, IoFuture<Receiver<T>>)
where T: Send + 'static,
{
let (tx, rx) = channel::channel();
let rx = ReadinessStream::new(self, rx).map(|rx| Receiver { rx: rx });
(Sender { tx: tx }, rx.boxed())
}
}
impl<T> Sender<T> {
/// Sends a message to the corresponding receiver of this sender.
///
/// The message provided will be enqueued on the channel immediately, and
/// this function will return immediately. Keep in mind that the
/// underlying channel has infinite capacity, and this may not always be
/// desired.
///
/// If an I/O error happens while sending the message, or if the receiver
/// has gone away, then an error will be returned. Note that I/O errors here
/// are generally quite abnormal.
pub fn send(&self, t: T) -> io::Result<()> {
self.tx.send(t).map_err(|e| {
match e {
channel::SendError::Io(e) => e,
channel::SendError::Disconnected(_) => {
io::Error::new(io::ErrorKind::Other,
"channel has been disconnected")
}
}
})
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Sender<T> {
Sender { tx: self.tx.clone() }
}
}
impl<T> Stream for Receiver<T> {
type Item = T;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<T>, io::Error> {
match self.rx.get_ref().try_recv() {
Ok(t) => Poll::Ok(Some(t)),
Err(TryRecvError::Empty) => {
self.rx.need_read();
Poll::NotReady
}
Err(TryRecvError::Disconnected) => Poll::Ok(None),
}
}
}
|
extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;
use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;
use self::winapi::windef::HWND;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;
static mut CLOSE_APP: bool = false;
// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
pub bmi_header: BITMAPINFOHEADER,
pub bmi_colors: [RGBQUAD; 3],
}
unsafe extern "system" fn wnd_proc(window: winapi::HWND, msg: winapi::UINT,
wparam: winapi::WPARAM, lparam: winapi::LPARAM)
-> winapi::LRESULT
{
match msg {
winapi::winuser::WM_KEYDOWN => {
if (wparam & 0xff) == 27 {
CLOSE_APP = true;
}
}
winapi::winuser::WM_PAINT => {
let mut rect: winapi::RECT = mem::uninitialized();
let buffer = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);
user32::GetClientRect(window, &mut rect);
let mut bitmap_info: BitmapInfo = mem::zeroed();
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bitmap_info.bmi_header.biPlanes = 1;
bitmap_info.bmi_header.biBitCount = 32;
bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
bitmap_info.bmi_header.biWidth = width;
bitmap_info.bmi_header.biHeight = -height;
bitmap_info.bmi_colors[0].rgbRed = 0xff;
bitmap_info.bmi_colors[1].rgbGreen = 0xff;
bitmap_info.bmi_colors[2].rgbBlue = 0xff;
let dc = user32::GetDC(window);
gdi32::StretchDIBits(dc, 0, 0, width, height, 0, 0, width, height,
mem::transmute(buffer),
mem::transmute(&bitmap_info),
winapi::wingdi::DIB_RGB_COLORS,
winapi::wingdi::SRCCOPY);
user32::ValidateRect(window, ptr::null_mut());
user32::ReleaseDC(window, dc);
}
_ => (),
}
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
pub enum MinifbError {
UnableToCreateWindow,
}
fn to_wstring(str : &str) -> *const u16 {
let v : Vec<u16> = OsStr::new(str).encode_wide(). chain(Some(0).into_iter()).collect();
v.as_ptr()
}
pub struct Minifb {
window: HWND,
}
impl Minifb {
fn open_window(name: &str, width: usize, height: usize) -> HWND {
unsafe {
let class_name = to_wstring("minifb_window");
let s = CString::new(name).unwrap();
let class = WNDCLASSW {
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleA(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name,
};
user32::RegisterClassW(&class);
let mut rect = winapi::RECT {
left: 0, right: width as winapi::LONG,
top: 0, bottom: height as winapi::LONG,
};
user32::AdjustWindowRect(&mut rect, winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION, 0);
rect.right -= rect.left;
rect.bottom -= rect.top;
let handle = user32::CreateWindowExA(0,
"minifb_window".as_ptr() as *mut _, s.as_ptr(),
winapi::WS_OVERLAPPEDWINDOW & !winapi::WS_MAXIMIZEBOX & !winapi::WS_THICKFRAME,
winapi::CW_USEDEFAULT, winapi::CW_USEDEFAULT,
rect.right, rect.bottom,
ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
if !handle.is_null() {
user32::ShowWindow(handle, winapi::SW_NORMAL);
}
return handle;
}
}
pub fn new(name: &str, width: usize, height: usize) -> Option<Minifb> {
let handle = Minifb::open_window(name, width, height);
match handle.is_null() {
true => None,
false => Some(Minifb { window : handle }),
}
}
pub fn update(&mut self, buffer: &[u32]) -> bool {
unsafe {
let mut msg = mem::uninitialized();
user32::SetWindowLongPtrW(self.window, winapi::winuser::GWLP_USERDATA, buffer.as_ptr() as i64);
user32::InvalidateRect(self.window, ptr::null_mut(), winapi::TRUE);
while user32::PeekMessageW(&mut msg, self.window, 0, 0, winapi::winuser::PM_REMOVE) != 0 {
user32::TranslateMessage(&mut msg);
user32::DispatchMessageW(&mut msg);
}
}
unsafe {
return !CLOSE_APP;
}
}
}
Ran rustfmt
extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;
use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;
use self::winapi::windef::HWND;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;
static mut CLOSE_APP: bool = false;
// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
pub bmi_header: BITMAPINFOHEADER,
pub bmi_colors: [RGBQUAD; 3],
}
unsafe extern "system" fn wnd_proc(window: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM)
-> winapi::LRESULT {
match msg {
winapi::winuser::WM_KEYDOWN => {
if (wparam & 0xff) == 27 {
CLOSE_APP = true;
}
}
winapi::winuser::WM_PAINT => {
let mut rect: winapi::RECT = mem::uninitialized();
let buffer = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);
user32::GetClientRect(window, &mut rect);
let mut bitmap_info: BitmapInfo = mem::zeroed();
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bitmap_info.bmi_header.biPlanes = 1;
bitmap_info.bmi_header.biBitCount = 32;
bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
bitmap_info.bmi_header.biWidth = width;
bitmap_info.bmi_header.biHeight = -height;
bitmap_info.bmi_colors[0].rgbRed = 0xff;
bitmap_info.bmi_colors[1].rgbGreen = 0xff;
bitmap_info.bmi_colors[2].rgbBlue = 0xff;
let dc = user32::GetDC(window);
gdi32::StretchDIBits(dc,
0,
0,
width,
height,
0,
0,
width,
height,
mem::transmute(buffer),
mem::transmute(&bitmap_info),
winapi::wingdi::DIB_RGB_COLORS,
winapi::wingdi::SRCCOPY);
user32::ValidateRect(window, ptr::null_mut());
user32::ReleaseDC(window, dc);
}
_ => (),
}
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
pub enum MinifbError {
UnableToCreateWindow,
}
fn to_wstring(str: &str) -> *const u16 {
let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect();
v.as_ptr()
}
pub struct Minifb {
window: HWND,
}
impl Minifb {
fn open_window(name: &str, width: usize, height: usize) -> HWND {
unsafe {
let class_name = to_wstring("minifb_window");
let s = CString::new(name).unwrap();
let class = WNDCLASSW {
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleA(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name,
};
user32::RegisterClassW(&class);
let mut rect = winapi::RECT {
left: 0,
right: width as winapi::LONG,
top: 0,
bottom: height as winapi::LONG,
};
user32::AdjustWindowRect(&mut rect,
winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION,
0);
rect.right -= rect.left;
rect.bottom -= rect.top;
let handle = user32::CreateWindowExA(0,
"minifb_window".as_ptr() as *mut _,
s.as_ptr(),
winapi::WS_OVERLAPPEDWINDOW &
!winapi::WS_MAXIMIZEBOX &
!winapi::WS_THICKFRAME,
winapi::CW_USEDEFAULT,
winapi::CW_USEDEFAULT,
rect.right,
rect.bottom,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut());
if !handle.is_null() {
user32::ShowWindow(handle, winapi::SW_NORMAL);
}
return handle;
}
}
pub fn new(name: &str, width: usize, height: usize) -> Option<Minifb> {
let handle = Minifb::open_window(name, width, height);
match handle.is_null() {
true => None,
false => Some(Minifb { window: handle }),
}
}
pub fn update(&mut self, buffer: &[u32]) -> bool {
unsafe {
let mut msg = mem::uninitialized();
user32::SetWindowLongPtrW(self.window,
winapi::winuser::GWLP_USERDATA,
buffer.as_ptr() as i64);
user32::InvalidateRect(self.window, ptr::null_mut(), winapi::TRUE);
while user32::PeekMessageW(&mut msg, self.window, 0, 0, winapi::winuser::PM_REMOVE) !=
0 {
user32::TranslateMessage(&mut msg);
user32::DispatchMessageW(&mut msg);
}
}
unsafe {
return !CLOSE_APP;
}
}
}
|
#![cfg(target_os = "windows")]
extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;
use Scale;
use Vsync;
use Key;
use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;
use self::winapi::windef::HWND;
use self::winapi::windef::HDC;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;
static mut CLOSE_APP: bool = false;
// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
pub bmi_header: BITMAPINFOHEADER,
pub bmi_colors: [RGBQUAD; 3],
}
fn update_key_state(window: &mut Window, wparam: u32, state: bool) {
match wparam & 0x1ff {
0x00B => window.keys[Key::Key0 as usize] = state,
0x002 => window.keys[Key::Key1 as usize] = state,
0x003 => window.keys[Key::Key2 as usize] = state,
0x004 => window.keys[Key::Key3 as usize] = state,
0x005 => window.keys[Key::Key4 as usize] = state,
0x006 => window.keys[Key::Key5 as usize] = state,
0x007 => window.keys[Key::Key6 as usize] = state,
0x008 => window.keys[Key::Key7 as usize] = state,
0x009 => window.keys[Key::Key8 as usize] = state,
0x00A => window.keys[Key::Key9 as usize] = state,
0x01E => window.keys[Key::A as usize] = state,
0x030 => window.keys[Key::B as usize] = state,
0x02E => window.keys[Key::C as usize] = state,
0x020 => window.keys[Key::D as usize] = state,
0x012 => window.keys[Key::E as usize] = state,
0x021 => window.keys[Key::F as usize] = state,
0x022 => window.keys[Key::G as usize] = state,
0x023 => window.keys[Key::H as usize] = state,
0x017 => window.keys[Key::I as usize] = state,
0x024 => window.keys[Key::J as usize] = state,
0x025 => window.keys[Key::K as usize] = state,
0x026 => window.keys[Key::L as usize] = state,
0x032 => window.keys[Key::M as usize] = state,
0x031 => window.keys[Key::N as usize] = state,
0x018 => window.keys[Key::O as usize] = state,
0x019 => window.keys[Key::P as usize] = state,
0x010 => window.keys[Key::Q as usize] = state,
0x013 => window.keys[Key::R as usize] = state,
0x01F => window.keys[Key::S as usize] = state,
0x014 => window.keys[Key::T as usize] = state,
0x016 => window.keys[Key::U as usize] = state,
0x02F => window.keys[Key::V as usize] = state,
0x011 => window.keys[Key::W as usize] = state,
0x02D => window.keys[Key::X as usize] = state,
0x015 => window.keys[Key::Y as usize] = state,
0x02C => window.keys[Key::Z as usize] = state,
0x03B => window.keys[Key::F1 as usize] = state,
0x03C => window.keys[Key::F2 as usize] = state,
0x03D => window.keys[Key::F3 as usize] = state,
0x03E => window.keys[Key::F4 as usize] = state,
0x03F => window.keys[Key::F5 as usize] = state,
0x040 => window.keys[Key::F6 as usize] = state,
0x041 => window.keys[Key::F7 as usize] = state,
0x042 => window.keys[Key::F8 as usize] = state,
0x043 => window.keys[Key::F9 as usize] = state,
0x044 => window.keys[Key::F10 as usize] = state,
0x057 => window.keys[Key::F11 as usize] = state,
0x058 => window.keys[Key::F12 as usize] = state,
0x150 => window.keys[Key::Down as usize] = state,
0x14B => window.keys[Key::Left as usize] = state,
0x14D => window.keys[Key::Right as usize] = state,
0x148 => window.keys[Key::Up as usize] = state,
0x028 => window.keys[Key::Apostrophe as usize] = state,
0x02B => window.keys[Key::Backslash as usize] = state,
0x033 => window.keys[Key::Comma as usize] = state,
0x00D => window.keys[Key::Equal as usize] = state,
0x01A => window.keys[Key::LeftBracket as usize] = state,
0x00C => window.keys[Key::Minus as usize] = state,
0x034 => window.keys[Key::Period as usize] = state,
0x01B => window.keys[Key::RightBracket as usize] = state,
0x027 => window.keys[Key::Semicolon as usize] = state,
0x035 => window.keys[Key::Slash as usize] = state,
0x00E => window.keys[Key::Backspace as usize] = state,
0x153 => window.keys[Key::Delete as usize] = state,
0x14F => window.keys[Key::End as usize] = state,
0x01C => window.keys[Key::Enter as usize] = state,
0x001 => window.keys[Key::Escape as usize] = state,
0x147 => window.keys[Key::Home as usize] = state,
0x152 => window.keys[Key::Insert as usize] = state,
0x15D => window.keys[Key::Menu as usize] = state,
0x151 => window.keys[Key::PageDown as usize] = state,
0x149 => window.keys[Key::PageUp as usize] = state,
0x045 => window.keys[Key::Pause as usize] = state,
0x039 => window.keys[Key::Space as usize] = state,
0x00F => window.keys[Key::Tab as usize] = state,
0x03A => window.keys[Key::CapsLock as usize] = state,
_ => (),
}
}
unsafe extern "system" fn wnd_proc(window: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM)
-> winapi::LRESULT {
// This make sure we actually don't do anything before the user data has been setup for the
// window
let user_data = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);
if user_data == 0 {
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
let mut wnd: &mut Window = mem::transmute(user_data);
match msg {
winapi::winuser::WM_KEYDOWN => {
update_key_state(wnd, (lparam as u32) >> 16, true);
if (wparam & 0x1ff) == 27 {
CLOSE_APP = true;
}
}
winapi::winuser::WM_KEYUP => {
update_key_state(wnd, (lparam as u32) >> 16, false);
}
winapi::winuser::WM_PAINT => {
let mut rect: winapi::RECT = mem::uninitialized();
user32::GetClientRect(window, &mut rect);
let mut bitmap_info: BitmapInfo = mem::zeroed();
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bitmap_info.bmi_header.biPlanes = 1;
bitmap_info.bmi_header.biBitCount = 32;
bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
bitmap_info.bmi_header.biWidth = width;
bitmap_info.bmi_header.biHeight = -height;
bitmap_info.bmi_colors[0].rgbRed = 0xff;
bitmap_info.bmi_colors[1].rgbGreen = 0xff;
bitmap_info.bmi_colors[2].rgbBlue = 0xff;
gdi32::StretchDIBits(wnd.dc.unwrap(),
0,
0,
width,
height,
0,
0,
width,
height,
mem::transmute(wnd.buffer.as_ptr()),
mem::transmute(&bitmap_info),
winapi::wingdi::DIB_RGB_COLORS,
winapi::wingdi::SRCCOPY);
user32::ValidateRect(window, ptr::null_mut());
}
_ => (),
}
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
pub enum MinifbError {
UnableToCreateWindow,
}
fn to_wstring(str: &str) -> *const u16 {
let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect();
v.as_ptr()
}
pub struct Window {
dc: Option<HDC>,
window: Option<HWND>,
keys: [bool; 512],
buffer: Vec<u32>,
}
impl Window {
fn open_window(name: &str, width: usize, height: usize, _: Scale, _: Vsync) -> HWND {
unsafe {
let class_name = to_wstring("minifb_window");
let s = CString::new(name).unwrap();
let class = WNDCLASSW {
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleA(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name,
};
user32::RegisterClassW(&class);
let mut rect = winapi::RECT {
left: 0,
right: width as winapi::LONG,
top: 0,
bottom: height as winapi::LONG,
};
user32::AdjustWindowRect(&mut rect,
winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION,
0);
rect.right -= rect.left;
rect.bottom -= rect.top;
let handle = user32::CreateWindowExA(0,
"minifb_window".as_ptr() as *mut _,
s.as_ptr(),
winapi::WS_OVERLAPPEDWINDOW &
!winapi::WS_MAXIMIZEBOX &
!winapi::WS_THICKFRAME,
winapi::CW_USEDEFAULT,
winapi::CW_USEDEFAULT,
rect.right,
rect.bottom,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut());
if !handle.is_null() {
user32::ShowWindow(handle, winapi::SW_NORMAL);
}
return handle;
}
}
pub fn new(name: &str,
width: usize,
height: usize,
scale: Scale,
vsync: Vsync)
-> Result<Window, &str> {
unsafe {
let handle = Self::open_window(name, width, height, scale, vsync);
if handle.is_null() {
return Err("Unable to create Window");
}
let window = Window {
dc: Some(user32::GetDC(handle)),
window: Some(handle),
keys: [false; 512],
buffer: Vec::new(),
};
Ok(window)
}
}
pub fn get_keys(&self) -> Vec<Key> {
let mut index: u8 = 0;
let mut keys: Vec<Key> = Vec::new();
for i in self.keys.iter() {
if *i {
unsafe {
keys.push(mem::transmute(index));
}
}
index += 1;
}
keys
}
pub fn update(&mut self, buffer: &[u32]) -> bool {
unsafe {
let mut msg = mem::uninitialized();
let window = self.window.unwrap();
// TODO: Optimize
self.buffer = buffer.iter().cloned().collect();
user32::SetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA, mem::transmute(self));
user32::InvalidateRect(window, ptr::null_mut(), winapi::TRUE);
while user32::PeekMessageW(&mut msg, window, 0, 0, winapi::winuser::PM_REMOVE) != 0 {
user32::TranslateMessage(&mut msg);
user32::DispatchMessageW(&mut msg);
}
}
unsafe {
return !CLOSE_APP;
}
}
}
impl Drop for Window {
fn drop(&mut self) {
unsafe {
if self.dc.is_some() {
user32::ReleaseDC(self.window.unwrap(), self.dc.unwrap());
}
if self.window.is_some() {
user32::CloseWindow(self.window.unwrap());
}
}
}
}
Fixed overflow on windows
#![cfg(target_os = "windows")]
extern crate user32;
extern crate kernel32;
extern crate winapi;
extern crate gdi32;
use Scale;
use Vsync;
use Key;
use std::ffi::CString;
use std::ptr;
use std::os::windows::ffi::OsStrExt;
use std::ffi::OsStr;
use std::mem;
use self::winapi::windef::HWND;
use self::winapi::windef::HDC;
use self::winapi::winuser::WS_OVERLAPPEDWINDOW;
use self::winapi::winuser::WNDCLASSW;
use self::winapi::wingdi::BITMAPINFOHEADER;
use self::winapi::wingdi::RGBQUAD;
static mut CLOSE_APP: bool = false;
// Wrap this so we can have a proper numbef of bmiColors to write in
#[repr(C)]
struct BitmapInfo {
pub bmi_header: BITMAPINFOHEADER,
pub bmi_colors: [RGBQUAD; 3],
}
fn update_key_state(window: &mut Window, wparam: u32, state: bool) {
match wparam & 0x1ff {
0x00B => window.keys[Key::Key0 as usize] = state,
0x002 => window.keys[Key::Key1 as usize] = state,
0x003 => window.keys[Key::Key2 as usize] = state,
0x004 => window.keys[Key::Key3 as usize] = state,
0x005 => window.keys[Key::Key4 as usize] = state,
0x006 => window.keys[Key::Key5 as usize] = state,
0x007 => window.keys[Key::Key6 as usize] = state,
0x008 => window.keys[Key::Key7 as usize] = state,
0x009 => window.keys[Key::Key8 as usize] = state,
0x00A => window.keys[Key::Key9 as usize] = state,
0x01E => window.keys[Key::A as usize] = state,
0x030 => window.keys[Key::B as usize] = state,
0x02E => window.keys[Key::C as usize] = state,
0x020 => window.keys[Key::D as usize] = state,
0x012 => window.keys[Key::E as usize] = state,
0x021 => window.keys[Key::F as usize] = state,
0x022 => window.keys[Key::G as usize] = state,
0x023 => window.keys[Key::H as usize] = state,
0x017 => window.keys[Key::I as usize] = state,
0x024 => window.keys[Key::J as usize] = state,
0x025 => window.keys[Key::K as usize] = state,
0x026 => window.keys[Key::L as usize] = state,
0x032 => window.keys[Key::M as usize] = state,
0x031 => window.keys[Key::N as usize] = state,
0x018 => window.keys[Key::O as usize] = state,
0x019 => window.keys[Key::P as usize] = state,
0x010 => window.keys[Key::Q as usize] = state,
0x013 => window.keys[Key::R as usize] = state,
0x01F => window.keys[Key::S as usize] = state,
0x014 => window.keys[Key::T as usize] = state,
0x016 => window.keys[Key::U as usize] = state,
0x02F => window.keys[Key::V as usize] = state,
0x011 => window.keys[Key::W as usize] = state,
0x02D => window.keys[Key::X as usize] = state,
0x015 => window.keys[Key::Y as usize] = state,
0x02C => window.keys[Key::Z as usize] = state,
0x03B => window.keys[Key::F1 as usize] = state,
0x03C => window.keys[Key::F2 as usize] = state,
0x03D => window.keys[Key::F3 as usize] = state,
0x03E => window.keys[Key::F4 as usize] = state,
0x03F => window.keys[Key::F5 as usize] = state,
0x040 => window.keys[Key::F6 as usize] = state,
0x041 => window.keys[Key::F7 as usize] = state,
0x042 => window.keys[Key::F8 as usize] = state,
0x043 => window.keys[Key::F9 as usize] = state,
0x044 => window.keys[Key::F10 as usize] = state,
0x057 => window.keys[Key::F11 as usize] = state,
0x058 => window.keys[Key::F12 as usize] = state,
0x150 => window.keys[Key::Down as usize] = state,
0x14B => window.keys[Key::Left as usize] = state,
0x14D => window.keys[Key::Right as usize] = state,
0x148 => window.keys[Key::Up as usize] = state,
0x028 => window.keys[Key::Apostrophe as usize] = state,
0x02B => window.keys[Key::Backslash as usize] = state,
0x033 => window.keys[Key::Comma as usize] = state,
0x00D => window.keys[Key::Equal as usize] = state,
0x01A => window.keys[Key::LeftBracket as usize] = state,
0x00C => window.keys[Key::Minus as usize] = state,
0x034 => window.keys[Key::Period as usize] = state,
0x01B => window.keys[Key::RightBracket as usize] = state,
0x027 => window.keys[Key::Semicolon as usize] = state,
0x035 => window.keys[Key::Slash as usize] = state,
0x00E => window.keys[Key::Backspace as usize] = state,
0x153 => window.keys[Key::Delete as usize] = state,
0x14F => window.keys[Key::End as usize] = state,
0x01C => window.keys[Key::Enter as usize] = state,
0x001 => window.keys[Key::Escape as usize] = state,
0x147 => window.keys[Key::Home as usize] = state,
0x152 => window.keys[Key::Insert as usize] = state,
0x15D => window.keys[Key::Menu as usize] = state,
0x151 => window.keys[Key::PageDown as usize] = state,
0x149 => window.keys[Key::PageUp as usize] = state,
0x045 => window.keys[Key::Pause as usize] = state,
0x039 => window.keys[Key::Space as usize] = state,
0x00F => window.keys[Key::Tab as usize] = state,
0x03A => window.keys[Key::CapsLock as usize] = state,
_ => (),
}
}
unsafe extern "system" fn wnd_proc(window: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM)
-> winapi::LRESULT {
// This make sure we actually don't do anything before the user data has been setup for the
// window
let user_data = user32::GetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA);
if user_data == 0 {
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
let mut wnd: &mut Window = mem::transmute(user_data);
match msg {
winapi::winuser::WM_KEYDOWN => {
update_key_state(wnd, (lparam as u32) >> 16, true);
if (wparam & 0x1ff) == 27 {
CLOSE_APP = true;
}
}
winapi::winuser::WM_KEYUP => {
update_key_state(wnd, (lparam as u32) >> 16, false);
}
winapi::winuser::WM_PAINT => {
let mut rect: winapi::RECT = mem::uninitialized();
user32::GetClientRect(window, &mut rect);
let mut bitmap_info: BitmapInfo = mem::zeroed();
let width = rect.right - rect.left;
let height = rect.bottom - rect.top;
bitmap_info.bmi_header.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32;
bitmap_info.bmi_header.biPlanes = 1;
bitmap_info.bmi_header.biBitCount = 32;
bitmap_info.bmi_header.biCompression = winapi::wingdi::BI_BITFIELDS;
bitmap_info.bmi_header.biWidth = width;
bitmap_info.bmi_header.biHeight = -height;
bitmap_info.bmi_colors[0].rgbRed = 0xff;
bitmap_info.bmi_colors[1].rgbGreen = 0xff;
bitmap_info.bmi_colors[2].rgbBlue = 0xff;
gdi32::StretchDIBits(wnd.dc.unwrap(),
0,
0,
width,
height,
0,
0,
width,
height,
mem::transmute(wnd.buffer.as_ptr()),
mem::transmute(&bitmap_info),
winapi::wingdi::DIB_RGB_COLORS,
winapi::wingdi::SRCCOPY);
user32::ValidateRect(window, ptr::null_mut());
}
_ => (),
}
return user32::DefWindowProcW(window, msg, wparam, lparam);
}
pub enum MinifbError {
UnableToCreateWindow,
}
fn to_wstring(str: &str) -> *const u16 {
let v: Vec<u16> = OsStr::new(str).encode_wide().chain(Some(0).into_iter()).collect();
v.as_ptr()
}
pub struct Window {
dc: Option<HDC>,
window: Option<HWND>,
keys: [bool; 512],
buffer: Vec<u32>,
}
impl Window {
fn open_window(name: &str, width: usize, height: usize, _: Scale, _: Vsync) -> HWND {
unsafe {
let class_name = to_wstring("minifb_window");
let s = CString::new(name).unwrap();
let class = WNDCLASSW {
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleA(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(),
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name,
};
user32::RegisterClassW(&class);
let mut rect = winapi::RECT {
left: 0,
right: width as winapi::LONG,
top: 0,
bottom: height as winapi::LONG,
};
user32::AdjustWindowRect(&mut rect,
winapi::WS_POPUP | winapi::WS_SYSMENU | winapi::WS_CAPTION,
0);
rect.right -= rect.left;
rect.bottom -= rect.top;
let handle = user32::CreateWindowExA(0,
"minifb_window".as_ptr() as *mut _,
s.as_ptr(),
winapi::WS_OVERLAPPEDWINDOW &
!winapi::WS_MAXIMIZEBOX &
!winapi::WS_THICKFRAME,
winapi::CW_USEDEFAULT,
winapi::CW_USEDEFAULT,
rect.right,
rect.bottom,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut());
if !handle.is_null() {
user32::ShowWindow(handle, winapi::SW_NORMAL);
}
return handle;
}
}
pub fn new(name: &str,
width: usize,
height: usize,
scale: Scale,
vsync: Vsync)
-> Result<Window, &str> {
unsafe {
let handle = Self::open_window(name, width, height, scale, vsync);
if handle.is_null() {
return Err("Unable to create Window");
}
let window = Window {
dc: Some(user32::GetDC(handle)),
window: Some(handle),
keys: [false; 512],
buffer: Vec::new(),
};
Ok(window)
}
}
pub fn get_keys(&self) -> Vec<Key> {
let mut index: u16 = 0;
let mut keys: Vec<Key> = Vec::new();
for i in self.keys.iter() {
if *i {
unsafe {
keys.push(mem::transmute(index as u8));
}
}
index += 1;
}
keys
}
pub fn update(&mut self, buffer: &[u32]) -> bool {
unsafe {
let mut msg = mem::uninitialized();
let window = self.window.unwrap();
// TODO: Optimize
self.buffer = buffer.iter().cloned().collect();
user32::SetWindowLongPtrW(window, winapi::winuser::GWLP_USERDATA, mem::transmute(self));
user32::InvalidateRect(window, ptr::null_mut(), winapi::TRUE);
while user32::PeekMessageW(&mut msg, window, 0, 0, winapi::winuser::PM_REMOVE) != 0 {
user32::TranslateMessage(&mut msg);
user32::DispatchMessageW(&mut msg);
}
}
unsafe {
return !CLOSE_APP;
}
}
}
impl Drop for Window {
fn drop(&mut self) {
unsafe {
if self.dc.is_some() {
user32::ReleaseDC(self.window.unwrap(), self.dc.unwrap());
}
if self.window.is_some() {
user32::CloseWindow(self.window.unwrap());
}
}
}
}
|
use super::super::*;
use sixty_four::*;
pub use v256::{
f64x4, bool64fx4, u64x4, i64x4, bool64ix4,
f32x8, bool32fx8, u32x8, i32x8, bool32ix8,
u16x16, i16x16, bool16ix16,
u8x32, i8x32, bool8ix32,
};
#[allow(dead_code)]
extern "platform-intrinsic" {
fn x86_mm256_addsub_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_addsub_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_dp_ps(x: f32x8, y: f32x8, z: i32) -> f32x8;
fn x86_mm256_hadd_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_hadd_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_hsub_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_hsub_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_max_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_max_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_min_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_min_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_movemask_ps(x: f32x8) -> i32;
fn x86_mm256_movemask_pd(x: f64x4) -> i32;
fn x86_mm_permutevar_ps(x: f32x4, y: i32x4) -> f32x4;
fn x86_mm_permutevar_pd(x: f64x2, y: i64x2) -> f64x2;
fn x86_mm256_permutevar_ps(x: f32x8, y: i32x8) -> f32x8;
fn x86_mm256_permutevar_pd(x: f64x4, y: i64x4) -> f64x4;
fn x86_mm256_rcp_ps(x: f32x8) -> f32x8;
fn x86_mm256_rsqrt_ps(x: f32x8) -> f32x8;
fn x86_mm256_sqrt_ps(x: f32x8) -> f32x8;
fn x86_mm256_sqrt_pd(x: f64x4) -> f64x4;
fn x86_mm_testc_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testc_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testc_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testc_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testc_si256(x: u64x4, y: u64x4) -> i32;
fn x86_mm_testnzc_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testnzc_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testnzc_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testnzc_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testnzc_si256(x: u64x4, y: u64x4) -> i32;
fn x86_mm_testz_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testz_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testz_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testz_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testz_si256(x: u64x4, y: u64x4) -> i32;
}
Expose most 128-bit AVX operations via traits.
use super::super::*;
use sixty_four::*;
pub use v256::{
f64x4, bool64fx4, u64x4, i64x4, bool64ix4,
f32x8, bool32fx8, u32x8, i32x8, bool32ix8,
u16x16, i16x16, bool16ix16,
u8x32, i8x32, bool8ix32,
};
#[allow(dead_code)]
extern "platform-intrinsic" {
fn x86_mm256_addsub_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_addsub_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_dp_ps(x: f32x8, y: f32x8, z: i32) -> f32x8;
fn x86_mm256_hadd_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_hadd_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_hsub_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_hsub_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_max_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_max_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_min_ps(x: f32x8, y: f32x8) -> f32x8;
fn x86_mm256_min_pd(x: f64x4, y: f64x4) -> f64x4;
fn x86_mm256_movemask_ps(x: f32x8) -> i32;
fn x86_mm256_movemask_pd(x: f64x4) -> i32;
fn x86_mm_permutevar_ps(x: f32x4, y: i32x4) -> f32x4;
fn x86_mm_permutevar_pd(x: f64x2, y: i64x2) -> f64x2;
fn x86_mm256_permutevar_ps(x: f32x8, y: i32x8) -> f32x8;
fn x86_mm256_permutevar_pd(x: f64x4, y: i64x4) -> f64x4;
fn x86_mm256_rcp_ps(x: f32x8) -> f32x8;
fn x86_mm256_rsqrt_ps(x: f32x8) -> f32x8;
fn x86_mm256_sqrt_ps(x: f32x8) -> f32x8;
fn x86_mm256_sqrt_pd(x: f64x4) -> f64x4;
fn x86_mm_testc_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testc_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testc_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testc_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testc_si256(x: u64x4, y: u64x4) -> i32;
fn x86_mm_testnzc_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testnzc_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testnzc_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testnzc_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testnzc_si256(x: u64x4, y: u64x4) -> i32;
fn x86_mm_testz_ps(x: f32x4, y: f32x4) -> i32;
fn x86_mm256_testz_ps(x: f32x8, y: f32x8) -> i32;
fn x86_mm_testz_pd(x: f64x2, y: f64x2) -> i32;
fn x86_mm256_testz_pd(x: f64x4, y: f64x4) -> i32;
fn x86_mm256_testz_si256(x: u64x4, y: u64x4) -> i32;
}
// 128-bit vectors:
// 32 bit floats
pub trait AvxF32x4 {
fn permutevar(self, other: i32x4) -> f32x4;
}
impl AvxF32x4 for f32x4 {
fn permutevar(self, other: i32x4) -> f32x4 {
unsafe { x86_mm_permutevar_ps(self, other) }
}
}
pub trait AvxBool32fx4 {}
impl AvxBool32fx4 for bool32fx4 {}
// 64 bit floats
pub trait AvxF64x2 {
fn permutevar(self, other: i64x2) -> f64x2;
}
impl AvxF64x2 for f64x2 {
fn permutevar(self, other: i64x2) -> f64x2 {
unsafe { x86_mm_permutevar_pd(self, other) }
}
}
pub trait AvxBool64fx2 {}
impl AvxBool64fx2 for bool64fx2 {}
// 64 bit integers
pub trait AvxU64x2 {}
impl AvxU64x2 for u64x2 {}
pub trait AvxI64x2 {}
impl AvxI64x2 for i64x2 {}
pub trait AvxBool64ix2 {}
impl AvxBool64ix2 for bool64ix2 {}
// 32 bit integers
pub trait AvxU32x4 {}
impl AvxU32x4 for u32x4 {}
pub trait AvxI32x4 {}
impl AvxI32x4 for i32x4 {}
pub trait AvxBool32ix4 {}
impl AvxBool32ix4 for bool32ix4 {}
// 16 bit integers
pub trait AvxU16x8 {}
impl AvxU16x8 for u16x8 {}
pub trait AvxI16x8 {}
impl AvxI16x8 for i16x8 {}
pub trait AvxBool16ix8 {}
impl AvxBool16ix8 for bool16ix8 {}
// 8 bit integers
pub trait AvxU8x16 {}
impl AvxU8x16 for u8x16 {}
pub trait AvxI8x16 {}
impl AvxI8x16 for i8x16 {}
pub trait AvxBool8ix16 {}
impl AvxBool8ix16 for bool8ix16 {}
|
#![allow(non_camel_case_types)]
use libc::{c_void, c_char, c_uchar, c_short, c_ushort, c_int, c_uint, c_long, c_ulong};
// APACHE PORTABLE RUNTIME
pub const APR_RFC822_DATE_LEN: apr_size_t = 30;
// run this hook first, before ANYTHING
pub const APR_HOOK_REALLY_FIRST: c_int = -10;
// run this hook first
pub const APR_HOOK_FIRST: c_int = 0;
// run this hook somewhere
pub const APR_HOOK_MIDDLE: c_int = 10;
// run this hook after every other hook which is defined
pub const APR_HOOK_LAST: c_int = 20;
// run this hook last, after EVERYTHING
pub const APR_HOOK_REALLY_LAST: c_int = 30;
pub type apr_byte_t = c_uchar;
pub type apr_int16_t = c_short;
pub type apr_uint16_t = c_ushort;
pub type apr_int32_t = c_int;
pub type apr_uint32_t = c_uint;
pub type apr_int64_t = c_long;
pub type apr_uint64_t = c_ulong;
pub type apr_size_t = c_ulong;
pub type apr_ssize_t = c_long;
pub type apr_off_t = c_long;
pub type apr_socklen_t = c_uint;
pub type apr_ino_t = c_ulong;
pub type apr_uintptr_t = apr_uint64_t;
pub type apr_status_t = c_int;
pub type apr_signum_t = c_int;
pub type apr_time_t = apr_int64_t;
pub type apr_port_t = apr_uint16_t;
#[repr(C)]
pub struct apr_array_header_t {
pub pool: *mut apr_pool_t,
pub elt_size: c_int,
pub nelts: c_int,
pub nalloc: c_int,
pub elts: *mut c_char,
}
#[repr(C)]
pub struct apr_table_entry_t {
pub key: *mut c_char,
pub val: *mut c_char,
pub key_checksum: apr_uint32_t,
}
#[repr(C)]
pub struct apr_bucket_alloc_t;
#[repr(C)]
pub struct apr_bucket_brigade;
#[repr(C)]
pub struct apr_finfo_t;
#[repr(C)]
pub struct apr_pool_t;
#[repr(C)]
pub struct apr_sockaddr_t;
#[repr(C)]
pub struct apr_table_t;
#[repr(C)]
pub struct apr_thread_mutex_t;
#[repr(C)]
pub struct apr_thread_t;
#[repr(C)]
pub struct apr_uri_t;
extern "C" {
pub fn apr_version_string() -> *const c_char;
pub fn apu_version_string() -> *const c_char;
pub fn apr_table_get(t: *const apr_table_t, key: *const c_char) -> *const c_char;
pub fn apr_table_set(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_add(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_elts(t: *const apr_table_t) -> *const apr_array_header_t;
pub fn apr_pstrmemdup(p: *mut apr_pool_t, s: *const c_char, n: apr_size_t) -> *mut c_char;
pub fn apr_palloc(p: *mut apr_pool_t, size: apr_size_t) -> *mut c_void;
pub fn apr_base64_encode_len(len: c_int) -> c_int;
pub fn apr_base64_encode(coded_dst: *mut c_char, plain_src: *const c_char, len_plain_src: c_int) -> c_int;
pub fn apr_base64_decode_len(coded_src: *const c_char) -> c_int;
pub fn apr_base64_decode(plain_dst: *mut c_char, coded_src: *const c_char) -> c_int;
pub fn apr_time_now() -> apr_time_t;
pub fn apr_rfc822_date(date_str: *mut c_char, t: apr_time_t) -> apr_status_t;
}
pub fn strdup<T: Into<Vec<u8>>>(pool: *mut apr_pool_t, data: T) -> *mut c_char {
let bytes = data.into();
unsafe {
apr_pstrmemdup(
pool,
bytes.as_ptr() as *const c_char,
bytes.len() as apr_size_t
)
}
}
// APACHE HTTPD
pub const MODULE_MAGIC_COOKIE: c_ulong = 0x41503234u64; /* "AP24" */
pub const MODULE_MAGIC_NUMBER_MAJOR: c_int = 20120211;
pub const MODULE_MAGIC_NUMBER_MINOR: c_int = 36;
pub const OK: c_int = 0;
pub const DECLINED: c_int = -1;
pub const DONE: c_int = -2;
pub const SUSPENDED: c_int = -3;
pub const HTTP_CONTINUE: c_int = 100;
pub const HTTP_SWITCHING_PROTOCOLS: c_int = 101;
pub const HTTP_PROCESSING: c_int = 102;
pub const HTTP_OK: c_int = 200;
pub const HTTP_CREATED: c_int = 201;
pub const HTTP_ACCEPTED: c_int = 202;
pub const HTTP_NON_AUTHORITATIVE: c_int = 203;
pub const HTTP_NO_CONTENT: c_int = 204;
pub const HTTP_RESET_CONTENT: c_int = 205;
pub const HTTP_PARTIAL_CONTENT: c_int = 206;
pub const HTTP_MULTI_STATUS: c_int = 207;
pub const HTTP_ALREADY_REPORTED: c_int = 208;
pub const HTTP_IM_USED: c_int = 226;
pub const HTTP_MULTIPLE_CHOICES: c_int = 300;
pub const HTTP_MOVED_PERMANENTLY: c_int = 301;
pub const HTTP_MOVED_TEMPORARILY: c_int = 302;
pub const HTTP_SEE_OTHER: c_int = 303;
pub const HTTP_NOT_MODIFIED: c_int = 304;
pub const HTTP_USE_PROXY: c_int = 305;
pub const HTTP_TEMPORARY_REDIRECT: c_int = 307;
pub const HTTP_PERMANENT_REDIRECT: c_int = 308;
pub const HTTP_BAD_REQUEST: c_int = 400;
pub const HTTP_UNAUTHORIZED: c_int = 401;
pub const HTTP_PAYMENT_REQUIRED: c_int = 402;
pub const HTTP_FORBIDDEN: c_int = 403;
pub const HTTP_NOT_FOUND: c_int = 404;
pub const HTTP_METHOD_NOT_ALLOWED: c_int = 405;
pub const HTTP_NOT_ACCEPTABLE: c_int = 406;
pub const HTTP_PROXY_AUTHENTICATION_REQUIRED: c_int = 407;
pub const HTTP_REQUEST_TIME_OUT: c_int = 408;
pub const HTTP_CONFLICT: c_int = 409;
pub const HTTP_GONE: c_int = 410;
pub const HTTP_LENGTH_REQUIRED: c_int = 411;
pub const HTTP_PRECONDITION_FAILED: c_int = 412;
pub const HTTP_REQUEST_ENTITY_TOO_LARGE: c_int = 413;
pub const HTTP_REQUEST_URI_TOO_LARGE: c_int = 414;
pub const HTTP_UNSUPPORTED_MEDIA_TYPE: c_int = 415;
pub const HTTP_RANGE_NOT_SATISFIABLE: c_int = 416;
pub const HTTP_EXPECTATION_FAILED: c_int = 417;
pub const HTTP_IM_A_TEAPOT: c_int = 418;
pub const HTTP_UNPROCESSABLE_ENTITY: c_int = 422;
pub const HTTP_LOCKED: c_int = 423;
pub const HTTP_FAILED_DEPENDENCY: c_int = 424;
pub const HTTP_UPGRADE_REQUIRED: c_int = 426;
pub const HTTP_PRECONDITION_REQUIRED: c_int = 428;
pub const HTTP_TOO_MANY_REQUESTS: c_int = 429;
pub const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: c_int = 431;
pub const HTTP_INTERNAL_SERVER_ERROR: c_int = 500;
pub const HTTP_NOT_IMPLEMENTED: c_int = 501;
pub const HTTP_BAD_GATEWAY: c_int = 502;
pub const HTTP_SERVICE_UNAVAILABLE: c_int = 503;
pub const HTTP_GATEWAY_TIME_OUT: c_int = 504;
pub const HTTP_VERSION_NOT_SUPPORTED: c_int = 505;
pub const HTTP_VARIANT_ALSO_VARIES: c_int = 506;
pub const HTTP_INSUFFICIENT_STORAGE: c_int = 507;
pub const HTTP_LOOP_DETECTED: c_int = 508;
pub const HTTP_NOT_EXTENDED: c_int = 510;
pub const HTTP_NETWORK_AUTHENTICATION_REQUIRED: c_int = 511;
pub const PROXYREQ_NONE: c_int = 0;
pub const PROXYREQ_PROXY: c_int = 1;
pub const PROXYREQ_REVERSE: c_int = 2;
pub const PROXYREQ_RESPONSE: c_int = 3;
pub const RAW_ARGS: c_uint = 0;
pub const TAKE1: c_uint = 1;
pub const TAKE2: c_uint = 2;
pub const ITERATE: c_uint = 3;
pub const ITERATE2: c_uint = 4;
pub const FLAG: c_uint = 5;
pub const NO_ARGS: c_uint = 6;
pub const TAKE12: c_uint = 7;
pub const TAKE3: c_uint = 8;
pub const TAKE23: c_uint = 9;
pub const TAKE123: c_uint = 10;
pub const TAKE13: c_uint = 11;
pub const TAKE_ARGV: c_uint = 12;
#[repr(C)]
pub struct request_rec {
pub pool: *mut apr_pool_t,
pub connection: *mut conn_rec,
pub server: *mut server_rec,
pub next: *mut request_rec,
pub prev: *mut request_rec,
pub main: *mut request_rec,
pub the_request: *mut c_char,
pub assbackwards: c_int,
pub proxyreq: c_int,
pub header_only: c_int,
pub proto_num: c_int,
pub protocol: *mut c_char,
pub hostname: *const c_char,
pub request_time: apr_time_t,
pub status_line: *const c_char,
pub status: c_int,
pub method_number: c_int,
pub method: *const c_char,
pub allowed: apr_int64_t,
pub allowed_xmethods: *mut apr_array_header_t,
pub allowed_methods: *mut ap_method_list_t,
pub sent_bodyct: apr_off_t,
pub bytes_sent: apr_off_t,
pub mtime: apr_time_t,
pub range: *const c_char,
pub clength: apr_off_t,
pub chunked: c_int,
pub read_body: c_int,
pub read_chunked: c_int,
pub expecting_100: c_uint,
pub kept_body: *mut apr_bucket_brigade,
pub body_table: *mut apr_table_t,
pub remaining: apr_off_t,
pub read_length: apr_off_t,
pub headers_in: *mut apr_table_t,
pub headers_out: *mut apr_table_t,
pub err_headers_out: *mut apr_table_t,
pub subprocess_env: *mut apr_table_t,
pub notes: *mut apr_table_t,
pub content_type: *const c_char,
pub handler: *const c_char,
pub content_encoding: *const c_char,
pub content_languages: *mut apr_array_header_t,
pub vlist_validator: *mut c_char,
pub user: *mut c_char,
pub ap_auth_type: *mut c_char,
pub unparsed_uri: *mut c_char,
pub uri: *mut c_char,
pub filename: *mut c_char,
pub canonical_filename: *mut c_char,
pub path_info: *mut c_char,
pub args: *mut c_char,
pub used_path_info: c_int,
pub eos_sent: c_int,
pub per_dir_config: *mut ap_conf_vector_t,
pub request_config: *mut ap_conf_vector_t,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub htaccess: *const htaccess_result,
pub output_filters: *mut ap_filter_t,
pub input_filters: *mut ap_filter_t,
pub proto_output_filters: *mut ap_filter_t,
pub proto_input_filters: *mut ap_filter_t,
pub no_cache: c_int,
pub no_local_copy: c_int,
pub invoke_mtx: *mut apr_thread_mutex_t,
pub parsed_uri: apr_uri_t,
pub finfo: apr_finfo_t,
pub useragent_addr: *mut apr_sockaddr_t,
pub useragent_ip: *mut c_char,
pub trailers_in: *mut apr_table_t,
pub trailers_out: *mut apr_table_t,
}
#[repr(C)]
pub struct conn_rec {
pub pool: *mut apr_pool_t,
pub base_server: *mut server_rec,
pub vhost_lookup_data: *mut c_void,
pub local_addr: *mut apr_sockaddr_t,
pub client_addr: *mut apr_sockaddr_t,
pub client_ip: *mut c_char,
pub remote_host: *mut c_char,
pub remote_logname: *mut c_char,
pub local_ip: *mut c_char,
pub local_host: *mut c_char,
pub id: c_long,
pub conn_config: *mut ap_conf_vector_t,
pub notes: *mut apr_table_t,
pub input_filters: *mut ap_filter_t,
pub output_filters: *mut ap_filter_t,
pub sbh: *mut c_void,
pub bucket_alloc: *mut apr_bucket_alloc_t,
pub cs: *mut conn_state_t,
pub data_in_input_filters: c_int,
pub data_in_output_filters: c_int,
pub _bindgen_bitfield_1_: c_uint,
pub _bindgen_bitfield_2_: c_int,
pub aborted: c_uint,
pub keepalive: ap_conn_keepalive_e,
pub keepalives: c_int,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub current_thread: *mut apr_thread_t,
}
#[repr(C)]
pub struct ap_logconf {
pub module_levels: *mut c_char,
pub level: c_int,
}
#[repr(C)]
pub struct module {
pub version: c_int,
pub minor_version: c_int,
pub module_index: c_int,
pub name: *const c_char,
pub dynamic_load_handle: *mut c_void,
pub next: *mut module,
pub magic: c_ulong,
pub rewrite_args: Option<rewrite_args_fn>,
pub create_dir_config: Option<create_dir_config_fn>,
pub merge_dir_config: Option<merge_config_fn>,
pub create_server_config: Option<create_server_config_fn>,
pub merge_server_config: Option<merge_config_fn>,
pub cmds: *const command_rec,
pub register_hooks: Option<register_hooks_fn>
}
#[repr(C)]
pub struct cmd_func {
pub _bindgen_data_: [u64; 1usize],
}
impl cmd_func {
pub unsafe fn no_args(&mut self) -> *mut Option<no_args_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn raw_args(&mut self) -> *mut Option<raw_args_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take_argv(&mut self) -> *mut Option<take_argv_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take1(&mut self) -> *mut Option<take1_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take2(&mut self) -> *mut Option<take2_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take3(&mut self) -> *mut Option<take3_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn flag(&mut self) -> *mut Option<flag_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
}
#[repr(C)]
pub struct command_rec {
pub name: *const c_char,
pub func: cmd_func,
pub cmd_data: *mut c_void,
pub req_override: c_int,
pub args_how: cmd_how,
pub errmsg: *const c_char,
}
#[repr(C)]
pub struct ap_filter_t;
#[repr(C)]
pub struct ap_conn_keepalive_e;
#[repr(C)]
pub struct ap_conf_vector_t;
#[repr(C)]
pub struct ap_method_list_t;
#[repr(C)]
pub struct conn_state_t;
#[repr(C)]
pub struct htaccess_result;
#[repr(C)]
pub struct process_rec;
#[repr(C)]
pub struct server_rec;
#[repr(C)]
pub struct cmd_parms;
pub type cmd_how = c_uint;
pub type rewrite_args_fn = extern "C" fn(
process: *mut process_rec
);
pub type create_dir_config_fn = extern "C" fn(
p: *mut apr_pool_t, dir: *mut c_char
) -> *mut c_void;
pub type merge_config_fn = extern "C" fn(
p: *mut apr_pool_t, base_conf: *mut c_void, new_conf: *mut c_void
) -> *mut c_void;
pub type create_server_config_fn = extern "C" fn(
p: *mut apr_pool_t, s: *mut server_rec
) -> *mut c_void;
pub type register_hooks_fn = extern "C" fn(
p: *mut apr_pool_t
);
pub type no_args_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void) -> *const c_char;
pub type raw_args_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, args: *const c_char) -> *const c_char;
pub type take_argv_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, argc: c_int, argv: *const *mut c_char) -> *const c_char;
pub type take1_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char) -> *const c_char;
pub type take2_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char, w2: *const c_char) -> *const c_char;
pub type take3_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char, w2: *const c_char, w3: *const c_char) -> *const c_char;
pub type flag_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, on: c_int) -> *const c_char;
pub type hook_handler_fn = extern "C" fn(r: *mut request_rec) -> c_int;
pub type hook_pre_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t) -> c_int;
pub type hook_check_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_test_config_fn = extern "C" fn(conf: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_post_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
extern "C" {
pub fn ap_get_server_banner() -> *const c_char;
pub fn ap_get_server_description() -> *const c_char;
pub fn ap_get_server_built() -> *const c_char;
pub fn ap_show_mpm() -> *const c_char;
pub fn ap_escape_html2(p: *mut apr_pool_t, s: *const c_char, toasc: c_int) -> *mut c_char;
pub fn ap_rwrite(buf: *const c_void, nbyte: c_int, r: *const request_rec) -> c_int;
pub fn ap_set_content_type(r: *const request_rec, ct: *const c_char) -> ();
pub fn ap_get_basic_auth_pw(r: *const request_rec, pw: *mut *const c_char) -> c_int;
pub fn ap_context_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_context_prefix(r: *const request_rec) -> *const c_char;
pub fn ap_run_http_scheme(r: *const request_rec) -> *const c_char;
pub fn ap_run_default_port(r: *const request_rec) -> apr_port_t;
pub fn ap_is_initial_req(r: *const request_rec) -> c_int;
pub fn ap_some_auth_required(r: *const request_rec) -> c_int;
pub fn ap_cookie_read(r: *const request_rec, name: *const c_char, val: *mut *const c_char,
remove: c_int) -> apr_status_t;
pub fn ap_cookie_write(r: *const request_rec, name: *const c_char, val: *const c_char,
attrs: *const c_char, maxage: c_int, ...) -> apr_status_t;
pub fn ap_escape_urlencoded(p: *mut apr_pool_t, s: *const c_char) -> *mut c_char;
pub fn ap_unescape_urlencoded(query: *mut c_char) -> c_int;
pub fn ap_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_name(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_port(r: *const request_rec) -> apr_port_t;
pub fn ap_auth_name(r: *const request_rec) -> *const c_char;
pub fn ap_set_last_modified(r: *mut request_rec) -> ();
pub fn ap_update_mtime(r: *mut request_rec, dependency_mtime: apr_time_t) -> ();
pub fn ap_hook_handler(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_pre_config(f: Option<hook_pre_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_config(f: Option<hook_check_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_test_config(f: Option<hook_test_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_post_config(f: Option<hook_post_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_create_request(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_translate_name(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_map_to_storage(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_user_id(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_fixups(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_type_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker_ex(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_auth_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_insert_error_filter(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_log_transaction(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
}
cmd_how flags ffi definition.
#![allow(non_camel_case_types)]
use libc::{c_void, c_char, c_uchar, c_short, c_ushort, c_int, c_uint, c_long, c_ulong};
// APACHE PORTABLE RUNTIME
pub const APR_RFC822_DATE_LEN: apr_size_t = 30;
// run this hook first, before ANYTHING
pub const APR_HOOK_REALLY_FIRST: c_int = -10;
// run this hook first
pub const APR_HOOK_FIRST: c_int = 0;
// run this hook somewhere
pub const APR_HOOK_MIDDLE: c_int = 10;
// run this hook after every other hook which is defined
pub const APR_HOOK_LAST: c_int = 20;
// run this hook last, after EVERYTHING
pub const APR_HOOK_REALLY_LAST: c_int = 30;
pub type apr_byte_t = c_uchar;
pub type apr_int16_t = c_short;
pub type apr_uint16_t = c_ushort;
pub type apr_int32_t = c_int;
pub type apr_uint32_t = c_uint;
pub type apr_int64_t = c_long;
pub type apr_uint64_t = c_ulong;
pub type apr_size_t = c_ulong;
pub type apr_ssize_t = c_long;
pub type apr_off_t = c_long;
pub type apr_socklen_t = c_uint;
pub type apr_ino_t = c_ulong;
pub type apr_uintptr_t = apr_uint64_t;
pub type apr_status_t = c_int;
pub type apr_signum_t = c_int;
pub type apr_time_t = apr_int64_t;
pub type apr_port_t = apr_uint16_t;
#[repr(C)]
pub struct apr_array_header_t {
pub pool: *mut apr_pool_t,
pub elt_size: c_int,
pub nelts: c_int,
pub nalloc: c_int,
pub elts: *mut c_char,
}
#[repr(C)]
pub struct apr_table_entry_t {
pub key: *mut c_char,
pub val: *mut c_char,
pub key_checksum: apr_uint32_t,
}
#[repr(C)]
pub struct apr_bucket_alloc_t;
#[repr(C)]
pub struct apr_bucket_brigade;
#[repr(C)]
pub struct apr_finfo_t;
#[repr(C)]
pub struct apr_pool_t;
#[repr(C)]
pub struct apr_sockaddr_t;
#[repr(C)]
pub struct apr_table_t;
#[repr(C)]
pub struct apr_thread_mutex_t;
#[repr(C)]
pub struct apr_thread_t;
#[repr(C)]
pub struct apr_uri_t;
extern "C" {
pub fn apr_version_string() -> *const c_char;
pub fn apu_version_string() -> *const c_char;
pub fn apr_table_get(t: *const apr_table_t, key: *const c_char) -> *const c_char;
pub fn apr_table_set(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_add(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_elts(t: *const apr_table_t) -> *const apr_array_header_t;
pub fn apr_pstrmemdup(p: *mut apr_pool_t, s: *const c_char, n: apr_size_t) -> *mut c_char;
pub fn apr_palloc(p: *mut apr_pool_t, size: apr_size_t) -> *mut c_void;
pub fn apr_base64_encode_len(len: c_int) -> c_int;
pub fn apr_base64_encode(coded_dst: *mut c_char, plain_src: *const c_char, len_plain_src: c_int) -> c_int;
pub fn apr_base64_decode_len(coded_src: *const c_char) -> c_int;
pub fn apr_base64_decode(plain_dst: *mut c_char, coded_src: *const c_char) -> c_int;
pub fn apr_time_now() -> apr_time_t;
pub fn apr_rfc822_date(date_str: *mut c_char, t: apr_time_t) -> apr_status_t;
}
pub fn strdup<T: Into<Vec<u8>>>(pool: *mut apr_pool_t, data: T) -> *mut c_char {
let bytes = data.into();
unsafe {
apr_pstrmemdup(
pool,
bytes.as_ptr() as *const c_char,
bytes.len() as apr_size_t
)
}
}
// APACHE HTTPD
pub const MODULE_MAGIC_COOKIE: c_ulong = 0x41503234u64; /* "AP24" */
pub const MODULE_MAGIC_NUMBER_MAJOR: c_int = 20120211;
pub const MODULE_MAGIC_NUMBER_MINOR: c_int = 36;
pub const OK: c_int = 0;
pub const DECLINED: c_int = -1;
pub const DONE: c_int = -2;
pub const SUSPENDED: c_int = -3;
pub const HTTP_CONTINUE: c_int = 100;
pub const HTTP_SWITCHING_PROTOCOLS: c_int = 101;
pub const HTTP_PROCESSING: c_int = 102;
pub const HTTP_OK: c_int = 200;
pub const HTTP_CREATED: c_int = 201;
pub const HTTP_ACCEPTED: c_int = 202;
pub const HTTP_NON_AUTHORITATIVE: c_int = 203;
pub const HTTP_NO_CONTENT: c_int = 204;
pub const HTTP_RESET_CONTENT: c_int = 205;
pub const HTTP_PARTIAL_CONTENT: c_int = 206;
pub const HTTP_MULTI_STATUS: c_int = 207;
pub const HTTP_ALREADY_REPORTED: c_int = 208;
pub const HTTP_IM_USED: c_int = 226;
pub const HTTP_MULTIPLE_CHOICES: c_int = 300;
pub const HTTP_MOVED_PERMANENTLY: c_int = 301;
pub const HTTP_MOVED_TEMPORARILY: c_int = 302;
pub const HTTP_SEE_OTHER: c_int = 303;
pub const HTTP_NOT_MODIFIED: c_int = 304;
pub const HTTP_USE_PROXY: c_int = 305;
pub const HTTP_TEMPORARY_REDIRECT: c_int = 307;
pub const HTTP_PERMANENT_REDIRECT: c_int = 308;
pub const HTTP_BAD_REQUEST: c_int = 400;
pub const HTTP_UNAUTHORIZED: c_int = 401;
pub const HTTP_PAYMENT_REQUIRED: c_int = 402;
pub const HTTP_FORBIDDEN: c_int = 403;
pub const HTTP_NOT_FOUND: c_int = 404;
pub const HTTP_METHOD_NOT_ALLOWED: c_int = 405;
pub const HTTP_NOT_ACCEPTABLE: c_int = 406;
pub const HTTP_PROXY_AUTHENTICATION_REQUIRED: c_int = 407;
pub const HTTP_REQUEST_TIME_OUT: c_int = 408;
pub const HTTP_CONFLICT: c_int = 409;
pub const HTTP_GONE: c_int = 410;
pub const HTTP_LENGTH_REQUIRED: c_int = 411;
pub const HTTP_PRECONDITION_FAILED: c_int = 412;
pub const HTTP_REQUEST_ENTITY_TOO_LARGE: c_int = 413;
pub const HTTP_REQUEST_URI_TOO_LARGE: c_int = 414;
pub const HTTP_UNSUPPORTED_MEDIA_TYPE: c_int = 415;
pub const HTTP_RANGE_NOT_SATISFIABLE: c_int = 416;
pub const HTTP_EXPECTATION_FAILED: c_int = 417;
pub const HTTP_IM_A_TEAPOT: c_int = 418;
pub const HTTP_UNPROCESSABLE_ENTITY: c_int = 422;
pub const HTTP_LOCKED: c_int = 423;
pub const HTTP_FAILED_DEPENDENCY: c_int = 424;
pub const HTTP_UPGRADE_REQUIRED: c_int = 426;
pub const HTTP_PRECONDITION_REQUIRED: c_int = 428;
pub const HTTP_TOO_MANY_REQUESTS: c_int = 429;
pub const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: c_int = 431;
pub const HTTP_INTERNAL_SERVER_ERROR: c_int = 500;
pub const HTTP_NOT_IMPLEMENTED: c_int = 501;
pub const HTTP_BAD_GATEWAY: c_int = 502;
pub const HTTP_SERVICE_UNAVAILABLE: c_int = 503;
pub const HTTP_GATEWAY_TIME_OUT: c_int = 504;
pub const HTTP_VERSION_NOT_SUPPORTED: c_int = 505;
pub const HTTP_VARIANT_ALSO_VARIES: c_int = 506;
pub const HTTP_INSUFFICIENT_STORAGE: c_int = 507;
pub const HTTP_LOOP_DETECTED: c_int = 508;
pub const HTTP_NOT_EXTENDED: c_int = 510;
pub const HTTP_NETWORK_AUTHENTICATION_REQUIRED: c_int = 511;
pub const PROXYREQ_NONE: c_int = 0;
pub const PROXYREQ_PROXY: c_int = 1;
pub const PROXYREQ_REVERSE: c_int = 2;
pub const PROXYREQ_RESPONSE: c_int = 3;
pub const RAW_ARGS: c_uint = 0;
pub const TAKE1: c_uint = 1;
pub const TAKE2: c_uint = 2;
pub const ITERATE: c_uint = 3;
pub const ITERATE2: c_uint = 4;
pub const FLAG: c_uint = 5;
pub const NO_ARGS: c_uint = 6;
pub const TAKE12: c_uint = 7;
pub const TAKE3: c_uint = 8;
pub const TAKE23: c_uint = 9;
pub const TAKE123: c_uint = 10;
pub const TAKE13: c_uint = 11;
pub const TAKE_ARGV: c_uint = 12;
pub const OR_NONE: c_uint = 0;
pub const OR_LIMIT: c_uint = 1;
pub const OR_OPTIONS: c_uint = 2;
pub const OR_FILEINFO: c_uint = 4;
pub const OR_AUTHCFG: c_uint = 8;
pub const OR_INDEXES: c_uint = 16;
pub const OR_UNSET: c_uint = 32;
pub const ACCESS_CONF: c_uint = 64;
pub const RSRC_CONF: c_uint = 128;
pub const EXEC_ON_READ: c_uint = 256;
pub const NONFATAL_OVERRIDE: c_uint = 512;
pub const NONFATAL_UNKNOWN: c_uint = 1024;
pub const NONFATAL_ALL: c_uint = NONFATAL_OVERRIDE | NONFATAL_UNKNOWN;
pub const OR_ALL: c_uint = OR_LIMIT | OR_OPTIONS | OR_FILEINFO | OR_AUTHCFG | OR_INDEXES;
#[repr(C)]
pub struct request_rec {
pub pool: *mut apr_pool_t,
pub connection: *mut conn_rec,
pub server: *mut server_rec,
pub next: *mut request_rec,
pub prev: *mut request_rec,
pub main: *mut request_rec,
pub the_request: *mut c_char,
pub assbackwards: c_int,
pub proxyreq: c_int,
pub header_only: c_int,
pub proto_num: c_int,
pub protocol: *mut c_char,
pub hostname: *const c_char,
pub request_time: apr_time_t,
pub status_line: *const c_char,
pub status: c_int,
pub method_number: c_int,
pub method: *const c_char,
pub allowed: apr_int64_t,
pub allowed_xmethods: *mut apr_array_header_t,
pub allowed_methods: *mut ap_method_list_t,
pub sent_bodyct: apr_off_t,
pub bytes_sent: apr_off_t,
pub mtime: apr_time_t,
pub range: *const c_char,
pub clength: apr_off_t,
pub chunked: c_int,
pub read_body: c_int,
pub read_chunked: c_int,
pub expecting_100: c_uint,
pub kept_body: *mut apr_bucket_brigade,
pub body_table: *mut apr_table_t,
pub remaining: apr_off_t,
pub read_length: apr_off_t,
pub headers_in: *mut apr_table_t,
pub headers_out: *mut apr_table_t,
pub err_headers_out: *mut apr_table_t,
pub subprocess_env: *mut apr_table_t,
pub notes: *mut apr_table_t,
pub content_type: *const c_char,
pub handler: *const c_char,
pub content_encoding: *const c_char,
pub content_languages: *mut apr_array_header_t,
pub vlist_validator: *mut c_char,
pub user: *mut c_char,
pub ap_auth_type: *mut c_char,
pub unparsed_uri: *mut c_char,
pub uri: *mut c_char,
pub filename: *mut c_char,
pub canonical_filename: *mut c_char,
pub path_info: *mut c_char,
pub args: *mut c_char,
pub used_path_info: c_int,
pub eos_sent: c_int,
pub per_dir_config: *mut ap_conf_vector_t,
pub request_config: *mut ap_conf_vector_t,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub htaccess: *const htaccess_result,
pub output_filters: *mut ap_filter_t,
pub input_filters: *mut ap_filter_t,
pub proto_output_filters: *mut ap_filter_t,
pub proto_input_filters: *mut ap_filter_t,
pub no_cache: c_int,
pub no_local_copy: c_int,
pub invoke_mtx: *mut apr_thread_mutex_t,
pub parsed_uri: apr_uri_t,
pub finfo: apr_finfo_t,
pub useragent_addr: *mut apr_sockaddr_t,
pub useragent_ip: *mut c_char,
pub trailers_in: *mut apr_table_t,
pub trailers_out: *mut apr_table_t,
}
#[repr(C)]
pub struct conn_rec {
pub pool: *mut apr_pool_t,
pub base_server: *mut server_rec,
pub vhost_lookup_data: *mut c_void,
pub local_addr: *mut apr_sockaddr_t,
pub client_addr: *mut apr_sockaddr_t,
pub client_ip: *mut c_char,
pub remote_host: *mut c_char,
pub remote_logname: *mut c_char,
pub local_ip: *mut c_char,
pub local_host: *mut c_char,
pub id: c_long,
pub conn_config: *mut ap_conf_vector_t,
pub notes: *mut apr_table_t,
pub input_filters: *mut ap_filter_t,
pub output_filters: *mut ap_filter_t,
pub sbh: *mut c_void,
pub bucket_alloc: *mut apr_bucket_alloc_t,
pub cs: *mut conn_state_t,
pub data_in_input_filters: c_int,
pub data_in_output_filters: c_int,
pub _bindgen_bitfield_1_: c_uint,
pub _bindgen_bitfield_2_: c_int,
pub aborted: c_uint,
pub keepalive: ap_conn_keepalive_e,
pub keepalives: c_int,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub current_thread: *mut apr_thread_t,
}
#[repr(C)]
pub struct ap_logconf {
pub module_levels: *mut c_char,
pub level: c_int,
}
#[repr(C)]
pub struct module {
pub version: c_int,
pub minor_version: c_int,
pub module_index: c_int,
pub name: *const c_char,
pub dynamic_load_handle: *mut c_void,
pub next: *mut module,
pub magic: c_ulong,
pub rewrite_args: Option<rewrite_args_fn>,
pub create_dir_config: Option<create_dir_config_fn>,
pub merge_dir_config: Option<merge_config_fn>,
pub create_server_config: Option<create_server_config_fn>,
pub merge_server_config: Option<merge_config_fn>,
pub cmds: *const command_rec,
pub register_hooks: Option<register_hooks_fn>
}
#[repr(C)]
pub struct cmd_func {
pub _bindgen_data_: [u64; 1usize],
}
impl cmd_func {
pub unsafe fn no_args(&mut self) -> *mut Option<no_args_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn raw_args(&mut self) -> *mut Option<raw_args_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take_argv(&mut self) -> *mut Option<take_argv_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take1(&mut self) -> *mut Option<take1_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take2(&mut self) -> *mut Option<take2_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn take3(&mut self) -> *mut Option<take3_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn flag(&mut self) -> *mut Option<flag_fn> {
::std::mem::transmute(&self._bindgen_data_)
}
}
#[repr(C)]
pub struct command_rec {
pub name: *const c_char,
pub func: cmd_func,
pub cmd_data: *mut c_void,
pub req_override: c_int,
pub args_how: cmd_how,
pub errmsg: *const c_char,
}
#[repr(C)]
pub struct ap_filter_t;
#[repr(C)]
pub struct ap_conn_keepalive_e;
#[repr(C)]
pub struct ap_conf_vector_t;
#[repr(C)]
pub struct ap_method_list_t;
#[repr(C)]
pub struct conn_state_t;
#[repr(C)]
pub struct htaccess_result;
#[repr(C)]
pub struct process_rec;
#[repr(C)]
pub struct server_rec;
#[repr(C)]
pub struct cmd_parms;
pub type cmd_how = c_uint;
pub type rewrite_args_fn = extern "C" fn(
process: *mut process_rec
);
pub type create_dir_config_fn = extern "C" fn(
p: *mut apr_pool_t, dir: *mut c_char
) -> *mut c_void;
pub type merge_config_fn = extern "C" fn(
p: *mut apr_pool_t, base_conf: *mut c_void, new_conf: *mut c_void
) -> *mut c_void;
pub type create_server_config_fn = extern "C" fn(
p: *mut apr_pool_t, s: *mut server_rec
) -> *mut c_void;
pub type register_hooks_fn = extern "C" fn(
p: *mut apr_pool_t
);
pub type no_args_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void) -> *const c_char;
pub type raw_args_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, args: *const c_char) -> *const c_char;
pub type take_argv_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, argc: c_int, argv: *const *mut c_char) -> *const c_char;
pub type take1_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char) -> *const c_char;
pub type take2_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char, w2: *const c_char) -> *const c_char;
pub type take3_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, w: *const c_char, w2: *const c_char, w3: *const c_char) -> *const c_char;
pub type flag_fn = extern "C" fn(parms: *mut cmd_parms, mconfig: *mut c_void, on: c_int) -> *const c_char;
pub type hook_handler_fn = extern "C" fn(r: *mut request_rec) -> c_int;
pub type hook_pre_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t) -> c_int;
pub type hook_check_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_test_config_fn = extern "C" fn(conf: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_post_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
extern "C" {
pub fn ap_get_server_banner() -> *const c_char;
pub fn ap_get_server_description() -> *const c_char;
pub fn ap_get_server_built() -> *const c_char;
pub fn ap_show_mpm() -> *const c_char;
pub fn ap_escape_html2(p: *mut apr_pool_t, s: *const c_char, toasc: c_int) -> *mut c_char;
pub fn ap_rwrite(buf: *const c_void, nbyte: c_int, r: *const request_rec) -> c_int;
pub fn ap_set_content_type(r: *const request_rec, ct: *const c_char) -> ();
pub fn ap_get_basic_auth_pw(r: *const request_rec, pw: *mut *const c_char) -> c_int;
pub fn ap_context_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_context_prefix(r: *const request_rec) -> *const c_char;
pub fn ap_run_http_scheme(r: *const request_rec) -> *const c_char;
pub fn ap_run_default_port(r: *const request_rec) -> apr_port_t;
pub fn ap_is_initial_req(r: *const request_rec) -> c_int;
pub fn ap_some_auth_required(r: *const request_rec) -> c_int;
pub fn ap_cookie_read(r: *const request_rec, name: *const c_char, val: *mut *const c_char,
remove: c_int) -> apr_status_t;
pub fn ap_cookie_write(r: *const request_rec, name: *const c_char, val: *const c_char,
attrs: *const c_char, maxage: c_int, ...) -> apr_status_t;
pub fn ap_escape_urlencoded(p: *mut apr_pool_t, s: *const c_char) -> *mut c_char;
pub fn ap_unescape_urlencoded(query: *mut c_char) -> c_int;
pub fn ap_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_name(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_port(r: *const request_rec) -> apr_port_t;
pub fn ap_auth_name(r: *const request_rec) -> *const c_char;
pub fn ap_set_last_modified(r: *mut request_rec) -> ();
pub fn ap_update_mtime(r: *mut request_rec, dependency_mtime: apr_time_t) -> ();
pub fn ap_hook_handler(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_pre_config(f: Option<hook_pre_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_config(f: Option<hook_check_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_test_config(f: Option<hook_test_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_post_config(f: Option<hook_post_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_create_request(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_translate_name(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_map_to_storage(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_user_id(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_fixups(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_type_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker_ex(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_auth_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_insert_error_filter(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_log_transaction(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
}
|
#![allow(non_camel_case_types)]
use libc::{c_void, c_char, c_uchar, c_short, c_ushort, c_int, c_uint, c_long, c_ulong};
// APACHE PORTABLE RUNTIME
pub const APR_RFC822_DATE_LEN: apr_size_t = 30;
// run this hook first, before ANYTHING
pub const APR_HOOK_REALLY_FIRST: c_int = -10;
// run this hook first
pub const APR_HOOK_FIRST: c_int = 0;
// run this hook somewhere
pub const APR_HOOK_MIDDLE: c_int = 10;
// run this hook after every other hook which is defined
pub const APR_HOOK_LAST: c_int = 20;
// run this hook last, after EVERYTHING
pub const APR_HOOK_REALLY_LAST: c_int = 30;
pub type apr_byte_t = c_uchar;
pub type apr_int16_t = c_short;
pub type apr_uint16_t = c_ushort;
pub type apr_int32_t = c_int;
pub type apr_uint32_t = c_uint;
pub type apr_int64_t = c_long;
pub type apr_uint64_t = c_ulong;
pub type apr_size_t = c_ulong;
pub type apr_ssize_t = c_long;
pub type apr_off_t = c_long;
pub type apr_socklen_t = c_uint;
pub type apr_ino_t = c_ulong;
pub type apr_uintptr_t = apr_uint64_t;
pub type apr_status_t = c_int;
pub type apr_signum_t = c_int;
pub type apr_time_t = apr_int64_t;
pub type apr_port_t = apr_uint16_t;
#[repr(C)]
pub struct apr_array_header_t {
pub pool: *mut apr_pool_t,
pub elt_size: c_int,
pub nelts: c_int,
pub nalloc: c_int,
pub elts: *mut c_char,
}
#[repr(C)]
pub struct apr_table_entry_t {
pub key: *mut c_char,
pub val: *mut c_char,
pub key_checksum: apr_uint32_t,
}
#[repr(C)]
pub struct apr_bucket_alloc_t;
#[repr(C)]
pub struct apr_bucket_brigade;
#[repr(C)]
pub struct apr_finfo_t;
#[repr(C)]
pub struct apr_pool_t;
#[repr(C)]
pub struct apr_sockaddr_t;
#[repr(C)]
pub struct apr_table_t;
#[repr(C)]
pub struct apr_thread_mutex_t;
#[repr(C)]
pub struct apr_thread_t;
#[repr(C)]
pub struct apr_uri_t;
extern "C" {
pub fn apr_version_string() -> *const c_char;
pub fn apu_version_string() -> *const c_char;
pub fn apr_table_get(t: *const apr_table_t, key: *const c_char) -> *const c_char;
pub fn apr_table_set(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_add(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_elts(t: *const apr_table_t) -> *const apr_array_header_t;
pub fn apr_pstrmemdup(p: *mut apr_pool_t, s: *const c_char, n: apr_size_t) -> *mut c_char;
pub fn apr_palloc(p: *mut apr_pool_t, size: apr_size_t) -> *mut c_void;
pub fn apr_base64_encode_len(len: c_int) -> c_int;
pub fn apr_base64_encode(coded_dst: *mut c_char, plain_src: *const c_char, len_plain_src: c_int) -> c_int;
pub fn apr_base64_decode_len(coded_src: *const c_char) -> c_int;
pub fn apr_base64_decode(plain_dst: *mut c_char, coded_src: *const c_char) -> c_int;
pub fn apr_time_now() -> apr_time_t;
pub fn apr_rfc822_date(date_str: *mut c_char, t: apr_time_t) -> apr_status_t;
}
pub fn dup_c_str<T: Into<Vec<u8>>>(pool: *mut apr_pool_t, data: T) -> *mut c_char {
let bytes = data.into();
unsafe {
apr_pstrmemdup(
pool,
bytes.as_ptr() as *const c_char,
bytes.len() as apr_size_t
)
}
}
// APACHE HTTPD
pub const MODULE_MAGIC_COOKIE: c_ulong = 0x41503234u64; /* "AP24" */
pub const MODULE_MAGIC_NUMBER_MAJOR: c_int = 20120211;
pub const MODULE_MAGIC_NUMBER_MINOR: c_int = 36;
pub const OK: c_int = 0;
pub const DECLINED: c_int = -1;
pub const DONE: c_int = -2;
pub const SUSPENDED: c_int = -3;
pub const HTTP_CONTINUE: c_int = 100;
pub const HTTP_SWITCHING_PROTOCOLS: c_int = 101;
pub const HTTP_PROCESSING: c_int = 102;
pub const HTTP_OK: c_int = 200;
pub const HTTP_CREATED: c_int = 201;
pub const HTTP_ACCEPTED: c_int = 202;
pub const HTTP_NON_AUTHORITATIVE: c_int = 203;
pub const HTTP_NO_CONTENT: c_int = 204;
pub const HTTP_RESET_CONTENT: c_int = 205;
pub const HTTP_PARTIAL_CONTENT: c_int = 206;
pub const HTTP_MULTI_STATUS: c_int = 207;
pub const HTTP_ALREADY_REPORTED: c_int = 208;
pub const HTTP_IM_USED: c_int = 226;
pub const HTTP_MULTIPLE_CHOICES: c_int = 300;
pub const HTTP_MOVED_PERMANENTLY: c_int = 301;
pub const HTTP_MOVED_TEMPORARILY: c_int = 302;
pub const HTTP_SEE_OTHER: c_int = 303;
pub const HTTP_NOT_MODIFIED: c_int = 304;
pub const HTTP_USE_PROXY: c_int = 305;
pub const HTTP_TEMPORARY_REDIRECT: c_int = 307;
pub const HTTP_PERMANENT_REDIRECT: c_int = 308;
pub const HTTP_BAD_REQUEST: c_int = 400;
pub const HTTP_UNAUTHORIZED: c_int = 401;
pub const HTTP_PAYMENT_REQUIRED: c_int = 402;
pub const HTTP_FORBIDDEN: c_int = 403;
pub const HTTP_NOT_FOUND: c_int = 404;
pub const HTTP_METHOD_NOT_ALLOWED: c_int = 405;
pub const HTTP_NOT_ACCEPTABLE: c_int = 406;
pub const HTTP_PROXY_AUTHENTICATION_REQUIRED: c_int = 407;
pub const HTTP_REQUEST_TIME_OUT: c_int = 408;
pub const HTTP_CONFLICT: c_int = 409;
pub const HTTP_GONE: c_int = 410;
pub const HTTP_LENGTH_REQUIRED: c_int = 411;
pub const HTTP_PRECONDITION_FAILED: c_int = 412;
pub const HTTP_REQUEST_ENTITY_TOO_LARGE: c_int = 413;
pub const HTTP_REQUEST_URI_TOO_LARGE: c_int = 414;
pub const HTTP_UNSUPPORTED_MEDIA_TYPE: c_int = 415;
pub const HTTP_RANGE_NOT_SATISFIABLE: c_int = 416;
pub const HTTP_EXPECTATION_FAILED: c_int = 417;
pub const HTTP_IM_A_TEAPOT: c_int = 418;
pub const HTTP_UNPROCESSABLE_ENTITY: c_int = 422;
pub const HTTP_LOCKED: c_int = 423;
pub const HTTP_FAILED_DEPENDENCY: c_int = 424;
pub const HTTP_UPGRADE_REQUIRED: c_int = 426;
pub const HTTP_PRECONDITION_REQUIRED: c_int = 428;
pub const HTTP_TOO_MANY_REQUESTS: c_int = 429;
pub const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: c_int = 431;
pub const HTTP_INTERNAL_SERVER_ERROR: c_int = 500;
pub const HTTP_NOT_IMPLEMENTED: c_int = 501;
pub const HTTP_BAD_GATEWAY: c_int = 502;
pub const HTTP_SERVICE_UNAVAILABLE: c_int = 503;
pub const HTTP_GATEWAY_TIME_OUT: c_int = 504;
pub const HTTP_VERSION_NOT_SUPPORTED: c_int = 505;
pub const HTTP_VARIANT_ALSO_VARIES: c_int = 506;
pub const HTTP_INSUFFICIENT_STORAGE: c_int = 507;
pub const HTTP_LOOP_DETECTED: c_int = 508;
pub const HTTP_NOT_EXTENDED: c_int = 510;
pub const HTTP_NETWORK_AUTHENTICATION_REQUIRED: c_int = 511;
pub const PROXYREQ_NONE: c_int = 0;
pub const PROXYREQ_PROXY: c_int = 1;
pub const PROXYREQ_REVERSE: c_int = 2;
pub const PROXYREQ_RESPONSE: c_int = 3;
#[repr(C)]
pub struct request_rec {
pub pool: *mut apr_pool_t,
pub connection: *mut conn_rec,
pub server: *mut server_rec,
pub next: *mut request_rec,
pub prev: *mut request_rec,
pub main: *mut request_rec,
pub the_request: *mut c_char,
pub assbackwards: c_int,
pub proxyreq: c_int,
pub header_only: c_int,
pub proto_num: c_int,
pub protocol: *mut c_char,
pub hostname: *const c_char,
pub request_time: apr_time_t,
pub status_line: *const c_char,
pub status: c_int,
pub method_number: c_int,
pub method: *const c_char,
pub allowed: apr_int64_t,
pub allowed_xmethods: *mut apr_array_header_t,
pub allowed_methods: *mut ap_method_list_t,
pub sent_bodyct: apr_off_t,
pub bytes_sent: apr_off_t,
pub mtime: apr_time_t,
pub range: *const c_char,
pub clength: apr_off_t,
pub chunked: c_int,
pub read_body: c_int,
pub read_chunked: c_int,
pub expecting_100: c_uint,
pub kept_body: *mut apr_bucket_brigade,
pub body_table: *mut apr_table_t,
pub remaining: apr_off_t,
pub read_length: apr_off_t,
pub headers_in: *mut apr_table_t,
pub headers_out: *mut apr_table_t,
pub err_headers_out: *mut apr_table_t,
pub subprocess_env: *mut apr_table_t,
pub notes: *mut apr_table_t,
pub content_type: *const c_char,
pub handler: *const c_char,
pub content_encoding: *const c_char,
pub content_languages: *mut apr_array_header_t,
pub vlist_validator: *mut c_char,
pub user: *mut c_char,
pub ap_auth_type: *mut c_char,
pub unparsed_uri: *mut c_char,
pub uri: *mut c_char,
pub filename: *mut c_char,
pub canonical_filename: *mut c_char,
pub path_info: *mut c_char,
pub args: *mut c_char,
pub used_path_info: c_int,
pub eos_sent: c_int,
pub per_dir_config: *mut ap_conf_vector_t,
pub request_config: *mut ap_conf_vector_t,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub htaccess: *const htaccess_result,
pub output_filters: *mut ap_filter_t,
pub input_filters: *mut ap_filter_t,
pub proto_output_filters: *mut ap_filter_t,
pub proto_input_filters: *mut ap_filter_t,
pub no_cache: c_int,
pub no_local_copy: c_int,
pub invoke_mtx: *mut apr_thread_mutex_t,
pub parsed_uri: apr_uri_t,
pub finfo: apr_finfo_t,
pub useragent_addr: *mut apr_sockaddr_t,
pub useragent_ip: *mut c_char,
pub trailers_in: *mut apr_table_t,
pub trailers_out: *mut apr_table_t,
}
#[repr(C)]
pub struct conn_rec {
pub pool: *mut apr_pool_t,
pub base_server: *mut server_rec,
pub vhost_lookup_data: *mut c_void,
pub local_addr: *mut apr_sockaddr_t,
pub client_addr: *mut apr_sockaddr_t,
pub client_ip: *mut c_char,
pub remote_host: *mut c_char,
pub remote_logname: *mut c_char,
pub local_ip: *mut c_char,
pub local_host: *mut c_char,
pub id: c_long,
pub conn_config: *mut ap_conf_vector_t,
pub notes: *mut apr_table_t,
pub input_filters: *mut ap_filter_t,
pub output_filters: *mut ap_filter_t,
pub sbh: *mut c_void,
pub bucket_alloc: *mut apr_bucket_alloc_t,
pub cs: *mut conn_state_t,
pub data_in_input_filters: c_int,
pub data_in_output_filters: c_int,
pub _bindgen_bitfield_1_: c_uint,
pub _bindgen_bitfield_2_: c_int,
pub aborted: c_uint,
pub keepalive: ap_conn_keepalive_e,
pub keepalives: c_int,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub current_thread: *mut apr_thread_t,
}
#[repr(C)]
pub struct ap_logconf {
pub module_levels: *mut c_char,
pub level: c_int,
}
#[repr(C)]
pub struct module {
pub version: c_int,
pub minor_version: c_int,
pub module_index: c_int,
pub name: *const c_char,
pub dynamic_load_handle: *mut c_void,
pub next: *mut module,
pub magic: c_ulong,
pub rewrite_args: Option<rewrite_args_fn>,
pub create_dir_config: Option<create_dir_config_fn>,
pub merge_dir_config: Option<merge_config_fn>,
pub create_server_config: Option<create_server_config_fn>,
pub merge_server_config: Option<merge_config_fn>,
pub cmds: *const command_rec,
pub register_hooks: ::std::option::Option<register_hooks_fn>
}
#[repr(C)]
pub struct ap_filter_t;
#[repr(C)]
pub struct ap_conn_keepalive_e;
#[repr(C)]
pub struct ap_conf_vector_t;
#[repr(C)]
pub struct ap_method_list_t;
#[repr(C)]
pub struct conn_state_t;
#[repr(C)]
pub struct htaccess_result;
#[repr(C)]
pub struct process_rec;
#[repr(C)]
pub struct server_rec;
#[repr(C)]
pub struct command_rec;
pub type rewrite_args_fn = extern "C" fn(
process: *mut process_rec
);
pub type create_dir_config_fn = extern "C" fn(
p: *mut apr_pool_t, dir: *mut c_char
) -> *mut c_void;
pub type merge_config_fn = extern "C" fn(
p: *mut apr_pool_t, base_conf: *mut c_void, new_conf: *mut c_void
) -> *mut c_void;
pub type create_server_config_fn = extern "C" fn(
p: *mut apr_pool_t, s: *mut server_rec
) -> *mut c_void;
pub type register_hooks_fn = extern "C" fn(
p: *mut apr_pool_t
);
pub type hook_handler_fn = extern "C" fn(r: *mut request_rec) -> c_int;
pub type hook_pre_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t) -> c_int;
pub type hook_check_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_test_config_fn = extern "C" fn(conf: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_post_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
extern "C" {
pub fn ap_get_server_banner() -> *const c_char;
pub fn ap_get_server_description() -> *const c_char;
pub fn ap_get_server_built() -> *const c_char;
pub fn ap_show_mpm() -> *const c_char;
pub fn ap_escape_html2(p: *mut apr_pool_t, s: *const c_char, toasc: c_int) -> *mut c_char;
pub fn ap_rwrite(buf: *const c_void, nbyte: c_int, r: *const request_rec) -> c_int;
pub fn ap_set_content_type(r: *const request_rec, ct: *const c_char) -> ();
pub fn ap_get_basic_auth_pw(r: *const request_rec, pw: *mut *const c_char) -> c_int;
pub fn ap_context_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_context_prefix(r: *const request_rec) -> *const c_char;
pub fn ap_run_http_scheme(r: *const request_rec) -> *const c_char;
pub fn ap_run_default_port(r: *const request_rec) -> apr_port_t;
pub fn ap_is_initial_req(r: *const request_rec) -> c_int;
pub fn ap_some_auth_required(r: *const request_rec) -> c_int;
pub fn ap_cookie_read(r: *const request_rec, name: *const c_char, val: *mut *const c_char,
remove: c_int) -> apr_status_t;
pub fn ap_cookie_write(r: *const request_rec, name: *const c_char, val: *const c_char,
attrs: *const c_char, maxage: c_int, ...) -> apr_status_t;
pub fn ap_escape_urlencoded(p: *mut apr_pool_t, s: *const c_char) -> *mut c_char;
pub fn ap_unescape_urlencoded(query: *mut c_char) -> c_int;
pub fn ap_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_name(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_port(r: *const request_rec) -> apr_port_t;
pub fn ap_auth_name(r: *const request_rec) -> *const c_char;
pub fn ap_set_last_modified(r: *mut request_rec) -> ();
pub fn ap_update_mtime(r: *mut request_rec, dependency_mtime: apr_time_t) -> ();
pub fn ap_hook_handler(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_pre_config(f: Option<hook_pre_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_config(f: Option<hook_check_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_test_config(f: Option<hook_test_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_post_config(f: Option<hook_post_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_create_request(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_translate_name(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_map_to_storage(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_user_id(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_fixups(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_type_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker_ex(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_auth_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_insert_error_filter(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_log_transaction(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
}
Removing superfluous definition of std::option.
#![allow(non_camel_case_types)]
use libc::{c_void, c_char, c_uchar, c_short, c_ushort, c_int, c_uint, c_long, c_ulong};
// APACHE PORTABLE RUNTIME
pub const APR_RFC822_DATE_LEN: apr_size_t = 30;
// run this hook first, before ANYTHING
pub const APR_HOOK_REALLY_FIRST: c_int = -10;
// run this hook first
pub const APR_HOOK_FIRST: c_int = 0;
// run this hook somewhere
pub const APR_HOOK_MIDDLE: c_int = 10;
// run this hook after every other hook which is defined
pub const APR_HOOK_LAST: c_int = 20;
// run this hook last, after EVERYTHING
pub const APR_HOOK_REALLY_LAST: c_int = 30;
pub type apr_byte_t = c_uchar;
pub type apr_int16_t = c_short;
pub type apr_uint16_t = c_ushort;
pub type apr_int32_t = c_int;
pub type apr_uint32_t = c_uint;
pub type apr_int64_t = c_long;
pub type apr_uint64_t = c_ulong;
pub type apr_size_t = c_ulong;
pub type apr_ssize_t = c_long;
pub type apr_off_t = c_long;
pub type apr_socklen_t = c_uint;
pub type apr_ino_t = c_ulong;
pub type apr_uintptr_t = apr_uint64_t;
pub type apr_status_t = c_int;
pub type apr_signum_t = c_int;
pub type apr_time_t = apr_int64_t;
pub type apr_port_t = apr_uint16_t;
#[repr(C)]
pub struct apr_array_header_t {
pub pool: *mut apr_pool_t,
pub elt_size: c_int,
pub nelts: c_int,
pub nalloc: c_int,
pub elts: *mut c_char,
}
#[repr(C)]
pub struct apr_table_entry_t {
pub key: *mut c_char,
pub val: *mut c_char,
pub key_checksum: apr_uint32_t,
}
#[repr(C)]
pub struct apr_bucket_alloc_t;
#[repr(C)]
pub struct apr_bucket_brigade;
#[repr(C)]
pub struct apr_finfo_t;
#[repr(C)]
pub struct apr_pool_t;
#[repr(C)]
pub struct apr_sockaddr_t;
#[repr(C)]
pub struct apr_table_t;
#[repr(C)]
pub struct apr_thread_mutex_t;
#[repr(C)]
pub struct apr_thread_t;
#[repr(C)]
pub struct apr_uri_t;
extern "C" {
pub fn apr_version_string() -> *const c_char;
pub fn apu_version_string() -> *const c_char;
pub fn apr_table_get(t: *const apr_table_t, key: *const c_char) -> *const c_char;
pub fn apr_table_set(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_add(t: *mut apr_table_t, key: *const c_char, val: *const c_char) -> ();
pub fn apr_table_elts(t: *const apr_table_t) -> *const apr_array_header_t;
pub fn apr_pstrmemdup(p: *mut apr_pool_t, s: *const c_char, n: apr_size_t) -> *mut c_char;
pub fn apr_palloc(p: *mut apr_pool_t, size: apr_size_t) -> *mut c_void;
pub fn apr_base64_encode_len(len: c_int) -> c_int;
pub fn apr_base64_encode(coded_dst: *mut c_char, plain_src: *const c_char, len_plain_src: c_int) -> c_int;
pub fn apr_base64_decode_len(coded_src: *const c_char) -> c_int;
pub fn apr_base64_decode(plain_dst: *mut c_char, coded_src: *const c_char) -> c_int;
pub fn apr_time_now() -> apr_time_t;
pub fn apr_rfc822_date(date_str: *mut c_char, t: apr_time_t) -> apr_status_t;
}
pub fn dup_c_str<T: Into<Vec<u8>>>(pool: *mut apr_pool_t, data: T) -> *mut c_char {
let bytes = data.into();
unsafe {
apr_pstrmemdup(
pool,
bytes.as_ptr() as *const c_char,
bytes.len() as apr_size_t
)
}
}
// APACHE HTTPD
pub const MODULE_MAGIC_COOKIE: c_ulong = 0x41503234u64; /* "AP24" */
pub const MODULE_MAGIC_NUMBER_MAJOR: c_int = 20120211;
pub const MODULE_MAGIC_NUMBER_MINOR: c_int = 36;
pub const OK: c_int = 0;
pub const DECLINED: c_int = -1;
pub const DONE: c_int = -2;
pub const SUSPENDED: c_int = -3;
pub const HTTP_CONTINUE: c_int = 100;
pub const HTTP_SWITCHING_PROTOCOLS: c_int = 101;
pub const HTTP_PROCESSING: c_int = 102;
pub const HTTP_OK: c_int = 200;
pub const HTTP_CREATED: c_int = 201;
pub const HTTP_ACCEPTED: c_int = 202;
pub const HTTP_NON_AUTHORITATIVE: c_int = 203;
pub const HTTP_NO_CONTENT: c_int = 204;
pub const HTTP_RESET_CONTENT: c_int = 205;
pub const HTTP_PARTIAL_CONTENT: c_int = 206;
pub const HTTP_MULTI_STATUS: c_int = 207;
pub const HTTP_ALREADY_REPORTED: c_int = 208;
pub const HTTP_IM_USED: c_int = 226;
pub const HTTP_MULTIPLE_CHOICES: c_int = 300;
pub const HTTP_MOVED_PERMANENTLY: c_int = 301;
pub const HTTP_MOVED_TEMPORARILY: c_int = 302;
pub const HTTP_SEE_OTHER: c_int = 303;
pub const HTTP_NOT_MODIFIED: c_int = 304;
pub const HTTP_USE_PROXY: c_int = 305;
pub const HTTP_TEMPORARY_REDIRECT: c_int = 307;
pub const HTTP_PERMANENT_REDIRECT: c_int = 308;
pub const HTTP_BAD_REQUEST: c_int = 400;
pub const HTTP_UNAUTHORIZED: c_int = 401;
pub const HTTP_PAYMENT_REQUIRED: c_int = 402;
pub const HTTP_FORBIDDEN: c_int = 403;
pub const HTTP_NOT_FOUND: c_int = 404;
pub const HTTP_METHOD_NOT_ALLOWED: c_int = 405;
pub const HTTP_NOT_ACCEPTABLE: c_int = 406;
pub const HTTP_PROXY_AUTHENTICATION_REQUIRED: c_int = 407;
pub const HTTP_REQUEST_TIME_OUT: c_int = 408;
pub const HTTP_CONFLICT: c_int = 409;
pub const HTTP_GONE: c_int = 410;
pub const HTTP_LENGTH_REQUIRED: c_int = 411;
pub const HTTP_PRECONDITION_FAILED: c_int = 412;
pub const HTTP_REQUEST_ENTITY_TOO_LARGE: c_int = 413;
pub const HTTP_REQUEST_URI_TOO_LARGE: c_int = 414;
pub const HTTP_UNSUPPORTED_MEDIA_TYPE: c_int = 415;
pub const HTTP_RANGE_NOT_SATISFIABLE: c_int = 416;
pub const HTTP_EXPECTATION_FAILED: c_int = 417;
pub const HTTP_IM_A_TEAPOT: c_int = 418;
pub const HTTP_UNPROCESSABLE_ENTITY: c_int = 422;
pub const HTTP_LOCKED: c_int = 423;
pub const HTTP_FAILED_DEPENDENCY: c_int = 424;
pub const HTTP_UPGRADE_REQUIRED: c_int = 426;
pub const HTTP_PRECONDITION_REQUIRED: c_int = 428;
pub const HTTP_TOO_MANY_REQUESTS: c_int = 429;
pub const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: c_int = 431;
pub const HTTP_INTERNAL_SERVER_ERROR: c_int = 500;
pub const HTTP_NOT_IMPLEMENTED: c_int = 501;
pub const HTTP_BAD_GATEWAY: c_int = 502;
pub const HTTP_SERVICE_UNAVAILABLE: c_int = 503;
pub const HTTP_GATEWAY_TIME_OUT: c_int = 504;
pub const HTTP_VERSION_NOT_SUPPORTED: c_int = 505;
pub const HTTP_VARIANT_ALSO_VARIES: c_int = 506;
pub const HTTP_INSUFFICIENT_STORAGE: c_int = 507;
pub const HTTP_LOOP_DETECTED: c_int = 508;
pub const HTTP_NOT_EXTENDED: c_int = 510;
pub const HTTP_NETWORK_AUTHENTICATION_REQUIRED: c_int = 511;
pub const PROXYREQ_NONE: c_int = 0;
pub const PROXYREQ_PROXY: c_int = 1;
pub const PROXYREQ_REVERSE: c_int = 2;
pub const PROXYREQ_RESPONSE: c_int = 3;
#[repr(C)]
pub struct request_rec {
pub pool: *mut apr_pool_t,
pub connection: *mut conn_rec,
pub server: *mut server_rec,
pub next: *mut request_rec,
pub prev: *mut request_rec,
pub main: *mut request_rec,
pub the_request: *mut c_char,
pub assbackwards: c_int,
pub proxyreq: c_int,
pub header_only: c_int,
pub proto_num: c_int,
pub protocol: *mut c_char,
pub hostname: *const c_char,
pub request_time: apr_time_t,
pub status_line: *const c_char,
pub status: c_int,
pub method_number: c_int,
pub method: *const c_char,
pub allowed: apr_int64_t,
pub allowed_xmethods: *mut apr_array_header_t,
pub allowed_methods: *mut ap_method_list_t,
pub sent_bodyct: apr_off_t,
pub bytes_sent: apr_off_t,
pub mtime: apr_time_t,
pub range: *const c_char,
pub clength: apr_off_t,
pub chunked: c_int,
pub read_body: c_int,
pub read_chunked: c_int,
pub expecting_100: c_uint,
pub kept_body: *mut apr_bucket_brigade,
pub body_table: *mut apr_table_t,
pub remaining: apr_off_t,
pub read_length: apr_off_t,
pub headers_in: *mut apr_table_t,
pub headers_out: *mut apr_table_t,
pub err_headers_out: *mut apr_table_t,
pub subprocess_env: *mut apr_table_t,
pub notes: *mut apr_table_t,
pub content_type: *const c_char,
pub handler: *const c_char,
pub content_encoding: *const c_char,
pub content_languages: *mut apr_array_header_t,
pub vlist_validator: *mut c_char,
pub user: *mut c_char,
pub ap_auth_type: *mut c_char,
pub unparsed_uri: *mut c_char,
pub uri: *mut c_char,
pub filename: *mut c_char,
pub canonical_filename: *mut c_char,
pub path_info: *mut c_char,
pub args: *mut c_char,
pub used_path_info: c_int,
pub eos_sent: c_int,
pub per_dir_config: *mut ap_conf_vector_t,
pub request_config: *mut ap_conf_vector_t,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub htaccess: *const htaccess_result,
pub output_filters: *mut ap_filter_t,
pub input_filters: *mut ap_filter_t,
pub proto_output_filters: *mut ap_filter_t,
pub proto_input_filters: *mut ap_filter_t,
pub no_cache: c_int,
pub no_local_copy: c_int,
pub invoke_mtx: *mut apr_thread_mutex_t,
pub parsed_uri: apr_uri_t,
pub finfo: apr_finfo_t,
pub useragent_addr: *mut apr_sockaddr_t,
pub useragent_ip: *mut c_char,
pub trailers_in: *mut apr_table_t,
pub trailers_out: *mut apr_table_t,
}
#[repr(C)]
pub struct conn_rec {
pub pool: *mut apr_pool_t,
pub base_server: *mut server_rec,
pub vhost_lookup_data: *mut c_void,
pub local_addr: *mut apr_sockaddr_t,
pub client_addr: *mut apr_sockaddr_t,
pub client_ip: *mut c_char,
pub remote_host: *mut c_char,
pub remote_logname: *mut c_char,
pub local_ip: *mut c_char,
pub local_host: *mut c_char,
pub id: c_long,
pub conn_config: *mut ap_conf_vector_t,
pub notes: *mut apr_table_t,
pub input_filters: *mut ap_filter_t,
pub output_filters: *mut ap_filter_t,
pub sbh: *mut c_void,
pub bucket_alloc: *mut apr_bucket_alloc_t,
pub cs: *mut conn_state_t,
pub data_in_input_filters: c_int,
pub data_in_output_filters: c_int,
pub _bindgen_bitfield_1_: c_uint,
pub _bindgen_bitfield_2_: c_int,
pub aborted: c_uint,
pub keepalive: ap_conn_keepalive_e,
pub keepalives: c_int,
pub log: *const ap_logconf,
pub log_id: *const c_char,
pub current_thread: *mut apr_thread_t,
}
#[repr(C)]
pub struct ap_logconf {
pub module_levels: *mut c_char,
pub level: c_int,
}
#[repr(C)]
pub struct module {
pub version: c_int,
pub minor_version: c_int,
pub module_index: c_int,
pub name: *const c_char,
pub dynamic_load_handle: *mut c_void,
pub next: *mut module,
pub magic: c_ulong,
pub rewrite_args: Option<rewrite_args_fn>,
pub create_dir_config: Option<create_dir_config_fn>,
pub merge_dir_config: Option<merge_config_fn>,
pub create_server_config: Option<create_server_config_fn>,
pub merge_server_config: Option<merge_config_fn>,
pub cmds: *const command_rec,
pub register_hooks: Option<register_hooks_fn>
}
#[repr(C)]
pub struct ap_filter_t;
#[repr(C)]
pub struct ap_conn_keepalive_e;
#[repr(C)]
pub struct ap_conf_vector_t;
#[repr(C)]
pub struct ap_method_list_t;
#[repr(C)]
pub struct conn_state_t;
#[repr(C)]
pub struct htaccess_result;
#[repr(C)]
pub struct process_rec;
#[repr(C)]
pub struct server_rec;
#[repr(C)]
pub struct command_rec;
pub type rewrite_args_fn = extern "C" fn(
process: *mut process_rec
);
pub type create_dir_config_fn = extern "C" fn(
p: *mut apr_pool_t, dir: *mut c_char
) -> *mut c_void;
pub type merge_config_fn = extern "C" fn(
p: *mut apr_pool_t, base_conf: *mut c_void, new_conf: *mut c_void
) -> *mut c_void;
pub type create_server_config_fn = extern "C" fn(
p: *mut apr_pool_t, s: *mut server_rec
) -> *mut c_void;
pub type register_hooks_fn = extern "C" fn(
p: *mut apr_pool_t
);
pub type hook_handler_fn = extern "C" fn(r: *mut request_rec) -> c_int;
pub type hook_pre_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t) -> c_int;
pub type hook_check_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_test_config_fn = extern "C" fn(conf: *const apr_pool_t, s: *const server_rec) -> c_int;
pub type hook_post_config_fn = extern "C" fn(conf: *const apr_pool_t, log: *const apr_pool_t, temp: *const apr_pool_t, s: *const server_rec) -> c_int;
extern "C" {
pub fn ap_get_server_banner() -> *const c_char;
pub fn ap_get_server_description() -> *const c_char;
pub fn ap_get_server_built() -> *const c_char;
pub fn ap_show_mpm() -> *const c_char;
pub fn ap_escape_html2(p: *mut apr_pool_t, s: *const c_char, toasc: c_int) -> *mut c_char;
pub fn ap_rwrite(buf: *const c_void, nbyte: c_int, r: *const request_rec) -> c_int;
pub fn ap_set_content_type(r: *const request_rec, ct: *const c_char) -> ();
pub fn ap_get_basic_auth_pw(r: *const request_rec, pw: *mut *const c_char) -> c_int;
pub fn ap_context_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_context_prefix(r: *const request_rec) -> *const c_char;
pub fn ap_run_http_scheme(r: *const request_rec) -> *const c_char;
pub fn ap_run_default_port(r: *const request_rec) -> apr_port_t;
pub fn ap_is_initial_req(r: *const request_rec) -> c_int;
pub fn ap_some_auth_required(r: *const request_rec) -> c_int;
pub fn ap_cookie_read(r: *const request_rec, name: *const c_char, val: *mut *const c_char,
remove: c_int) -> apr_status_t;
pub fn ap_cookie_write(r: *const request_rec, name: *const c_char, val: *const c_char,
attrs: *const c_char, maxage: c_int, ...) -> apr_status_t;
pub fn ap_escape_urlencoded(p: *mut apr_pool_t, s: *const c_char) -> *mut c_char;
pub fn ap_unescape_urlencoded(query: *mut c_char) -> c_int;
pub fn ap_document_root(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_name(r: *const request_rec) -> *const c_char;
pub fn ap_get_server_port(r: *const request_rec) -> apr_port_t;
pub fn ap_auth_name(r: *const request_rec) -> *const c_char;
pub fn ap_set_last_modified(r: *mut request_rec) -> ();
pub fn ap_update_mtime(r: *mut request_rec, dependency_mtime: apr_time_t) -> ();
pub fn ap_hook_handler(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_pre_config(f: Option<hook_pre_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_config(f: Option<hook_check_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_test_config(f: Option<hook_test_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_post_config(f: Option<hook_post_config_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_create_request(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_translate_name(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_map_to_storage(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_check_user_id(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_fixups(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_type_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_access_checker_ex(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_auth_checker(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_insert_error_filter(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
pub fn ap_hook_log_transaction(f: Option<hook_handler_fn>, pre: *const *const c_char, succ: *const *const c_char, order: c_int);
}
|
/* automatically generated by rust-bindgen */
#![allow(raw_pointer_derive,non_camel_case_types,non_snake_case,non_upper_case_globals,missing_copy_implementations)]
pub use self::GstState::*;
pub type __builtin_va_list = ::libc::c_void;
pub type ptrdiff_t = ::libc::c_long;
pub type size_t = ::libc::c_ulong;
pub type wchar_t = ::libc::c_int;
pub type gint8 = ::libc::c_char;
pub type guint8 = ::libc::c_uchar;
pub type gint16 = ::libc::c_short;
pub type guint16 = ::libc::c_ushort;
pub type gint32 = ::libc::c_int;
pub type guint32 = ::libc::c_uint;
pub type gint64 = ::libc::c_long;
pub type guint64 = ::libc::c_ulong;
pub type gssize = ::libc::c_long;
pub type gsize = ::libc::c_ulong;
pub type goffset = gint64;
pub type gintptr = ::libc::c_long;
pub type guintptr = ::libc::c_ulong;
pub type GPid = ::libc::c_int;
pub type __u_char = ::libc::c_uchar;
pub type __u_short = ::libc::c_ushort;
pub type __u_int = ::libc::c_uint;
pub type __u_long = ::libc::c_ulong;
pub type __int8_t = ::libc::c_char;
pub type __uint8_t = ::libc::c_uchar;
pub type __int16_t = ::libc::c_short;
pub type __uint16_t = ::libc::c_ushort;
pub type __int32_t = ::libc::c_int;
pub type __uint32_t = ::libc::c_uint;
pub type __int64_t = ::libc::c_long;
pub type __uint64_t = ::libc::c_ulong;
pub type __quad_t = ::libc::c_long;
pub type __u_quad_t = ::libc::c_ulong;
pub type __dev_t = ::libc::c_ulong;
pub type __uid_t = ::libc::c_uint;
pub type __gid_t = ::libc::c_uint;
pub type __ino_t = ::libc::c_ulong;
pub type __ino64_t = ::libc::c_ulong;
pub type __mode_t = ::libc::c_uint;
pub type __nlink_t = ::libc::c_ulong;
pub type __off_t = ::libc::c_long;
pub type __off64_t = ::libc::c_long;
pub type __pid_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed1 {
pub __val: [::libc::c_int; 2u],
}
impl ::std::default::Default for Struct_Unnamed1 {
fn default() -> Struct_Unnamed1 { unsafe { ::std::mem::zeroed() } }
}
pub type __fsid_t = Struct_Unnamed1;
pub type __clock_t = ::libc::c_long;
pub type __rlim_t = ::libc::c_ulong;
pub type __rlim64_t = ::libc::c_ulong;
pub type __id_t = ::libc::c_uint;
pub type __time_t = ::libc::c_long;
pub type __useconds_t = ::libc::c_uint;
pub type __suseconds_t = ::libc::c_long;
pub type __daddr_t = ::libc::c_int;
pub type __key_t = ::libc::c_int;
pub type __clockid_t = ::libc::c_int;
pub type __timer_t = *mut ::libc::c_void;
pub type __blksize_t = ::libc::c_long;
pub type __blkcnt_t = ::libc::c_long;
pub type __blkcnt64_t = ::libc::c_long;
pub type __fsblkcnt_t = ::libc::c_ulong;
pub type __fsblkcnt64_t = ::libc::c_ulong;
pub type __fsfilcnt_t = ::libc::c_ulong;
pub type __fsfilcnt64_t = ::libc::c_ulong;
pub type __fsword_t = ::libc::c_long;
pub type __ssize_t = ::libc::c_long;
pub type __syscall_slong_t = ::libc::c_long;
pub type __syscall_ulong_t = ::libc::c_ulong;
pub type __loff_t = __off64_t;
pub type __qaddr_t = *mut __quad_t;
pub type __caddr_t = *mut ::libc::c_char;
pub type __intptr_t = ::libc::c_long;
pub type __socklen_t = ::libc::c_uint;
pub type clock_t = __clock_t;
pub type time_t = __time_t;
pub type clockid_t = __clockid_t;
pub type timer_t = __timer_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_timespec {
pub tv_sec: __time_t,
pub tv_nsec: __syscall_slong_t,
}
impl ::std::default::Default for Struct_timespec {
fn default() -> Struct_timespec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_tm {
pub tm_sec: ::libc::c_int,
pub tm_min: ::libc::c_int,
pub tm_hour: ::libc::c_int,
pub tm_mday: ::libc::c_int,
pub tm_mon: ::libc::c_int,
pub tm_year: ::libc::c_int,
pub tm_wday: ::libc::c_int,
pub tm_yday: ::libc::c_int,
pub tm_isdst: ::libc::c_int,
pub tm_gmtoff: ::libc::c_long,
pub tm_zone: *const ::libc::c_char,
}
impl ::std::default::Default for Struct_tm {
fn default() -> Struct_tm { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_itimerspec {
pub it_interval: Struct_timespec,
pub it_value: Struct_timespec,
}
impl ::std::default::Default for Struct_itimerspec {
fn default() -> Struct_itimerspec { unsafe { ::std::mem::zeroed() } }
}
pub type pid_t = __pid_t;
pub enum Struct___locale_data { }
#[repr(C)]
#[derive(Copy)]
pub struct Struct___locale_struct {
pub __locales: [*mut Struct___locale_data; 13u],
pub __ctype_b: *const ::libc::c_ushort,
pub __ctype_tolower: *const ::libc::c_int,
pub __ctype_toupper: *const ::libc::c_int,
pub __names: [*const ::libc::c_char; 13u],
}
impl ::std::default::Default for Struct___locale_struct {
fn default() -> Struct___locale_struct { unsafe { ::std::mem::zeroed() } }
}
pub type __locale_t = *mut Struct___locale_struct;
pub type locale_t = __locale_t;
pub type gchar = ::libc::c_char;
pub type gshort = ::libc::c_short;
pub type glong = ::libc::c_long;
pub type gint = ::libc::c_int;
pub type gboolean = gint;
pub type guchar = ::libc::c_uchar;
pub type gushort = ::libc::c_ushort;
pub type gulong = ::libc::c_ulong;
pub type guint = ::libc::c_uint;
pub type gfloat = ::libc::c_float;
pub type gdouble = ::libc::c_double;
pub type gpointer = *mut ::libc::c_void;
pub type gconstpointer = *const ::libc::c_void;
pub type GCompareFunc =
::std::option::Option<extern "C" fn(a: gconstpointer, b: gconstpointer)
-> gint>;
pub type GCompareDataFunc =
::std::option::Option<extern "C" fn
(a: gconstpointer, b: gconstpointer,
user_data: gpointer) -> gint>;
pub type GEqualFunc =
::std::option::Option<extern "C" fn(a: gconstpointer, b: gconstpointer)
-> gboolean>;
pub type GDestroyNotify =
::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GFunc =
::std::option::Option<extern "C" fn(data: gpointer, user_data: gpointer)>;
pub type GHashFunc =
::std::option::Option<extern "C" fn(key: gconstpointer) -> guint>;
pub type GHFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer,
user_data: gpointer)>;
pub type GFreeFunc = ::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GTranslateFunc =
::std::option::Option<extern "C" fn(str: *const gchar, data: gpointer)
-> *const gchar>;
pub type GDoubleIEEE754 = Union__GDoubleIEEE754;
pub type GFloatIEEE754 = Union__GFloatIEEE754;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GFloatIEEE754 {
pub _bindgen_data_: [u32; 1u],
}
impl Union__GFloatIEEE754 {
pub unsafe fn v_float(&mut self) -> *mut gfloat {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn mpn(&mut self) -> *mut Struct_Unnamed2 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GFloatIEEE754 {
fn default() -> Union__GFloatIEEE754 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed2 {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
}
impl ::std::default::Default for Struct_Unnamed2 {
fn default() -> Struct_Unnamed2 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union__GDoubleIEEE754 {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GDoubleIEEE754 {
pub unsafe fn v_double(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn mpn(&mut self) -> *mut Struct_Unnamed3 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GDoubleIEEE754 {
fn default() -> Union__GDoubleIEEE754 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed3 {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
}
impl ::std::default::Default for Struct_Unnamed3 {
fn default() -> Struct_Unnamed3 { unsafe { ::std::mem::zeroed() } }
}
pub type GTimeVal = Struct__GTimeVal;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTimeVal {
pub tv_sec: glong,
pub tv_usec: glong,
}
impl ::std::default::Default for Struct__GTimeVal {
fn default() -> Struct__GTimeVal { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GBytes { }
pub type GBytes = Struct__GBytes;
pub type GArray = Struct__GArray;
pub type GByteArray = Struct__GByteArray;
pub type GPtrArray = Struct__GPtrArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GArray {
pub data: *mut gchar,
pub len: guint,
}
impl ::std::default::Default for Struct__GArray {
fn default() -> Struct__GArray { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GByteArray {
pub data: *mut guint8,
pub len: guint,
}
impl ::std::default::Default for Struct__GByteArray {
fn default() -> Struct__GByteArray { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPtrArray {
pub pdata: *mut gpointer,
pub len: guint,
}
impl ::std::default::Default for Struct__GPtrArray {
fn default() -> Struct__GPtrArray { unsafe { ::std::mem::zeroed() } }
}
pub type va_list = __builtin_va_list;
pub type __gnuc_va_list = __builtin_va_list;
pub type GQuark = guint32;
pub type GError = Struct__GError;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GError {
pub domain: GQuark,
pub code: gint,
pub message: *mut gchar,
}
impl ::std::default::Default for Struct__GError {
fn default() -> Struct__GError { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed4 = ::libc::c_uint;
pub const G_THREAD_ERROR_AGAIN: ::libc::c_uint = 0;
pub type GThreadError = Enum_Unnamed4;
pub type GThreadFunc =
::std::option::Option<extern "C" fn(data: gpointer) -> gpointer>;
pub type GThread = Struct__GThread;
pub type GMutex = Union__GMutex;
pub type GRecMutex = Struct__GRecMutex;
pub type GRWLock = Struct__GRWLock;
pub type GCond = Struct__GCond;
pub type GPrivate = Struct__GPrivate;
pub type GOnce = Struct__GOnce;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GMutex {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GMutex {
pub unsafe fn p(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn i(&mut self) -> *mut [guint; 2u] {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GMutex {
fn default() -> Union__GMutex { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GRWLock {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GRWLock {
fn default() -> Struct__GRWLock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCond {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GCond {
fn default() -> Struct__GCond { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GRecMutex {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GRecMutex {
fn default() -> Struct__GRecMutex { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPrivate {
pub p: gpointer,
pub notify: GDestroyNotify,
pub future: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GPrivate {
fn default() -> Struct__GPrivate { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed5 = ::libc::c_uint;
pub const G_ONCE_STATUS_NOTCALLED: ::libc::c_uint = 0;
pub const G_ONCE_STATUS_PROGRESS: ::libc::c_uint = 1;
pub const G_ONCE_STATUS_READY: ::libc::c_uint = 2;
pub type GOnceStatus = Enum_Unnamed5;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GOnce {
pub status: GOnceStatus,
pub retval: gpointer,
}
impl ::std::default::Default for Struct__GOnce {
fn default() -> Struct__GOnce { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GAsyncQueue { }
pub type GAsyncQueue = Struct__GAsyncQueue;
pub type __sig_atomic_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed6 {
pub __val: [::libc::c_ulong; 16u],
}
impl ::std::default::Default for Struct_Unnamed6 {
fn default() -> Struct_Unnamed6 { unsafe { ::std::mem::zeroed() } }
}
pub type __sigset_t = Struct_Unnamed6;
pub type sig_atomic_t = __sig_atomic_t;
pub type sigset_t = __sigset_t;
pub type uid_t = __uid_t;
#[repr(C)]
#[derive(Copy)]
pub struct Union_sigval {
pub _bindgen_data_: [u64; 1u],
}
impl Union_sigval {
pub unsafe fn sival_int(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn sival_ptr(&mut self) -> *mut *mut ::libc::c_void {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_sigval {
fn default() -> Union_sigval { unsafe { ::std::mem::zeroed() } }
}
pub type sigval_t = Union_sigval;
pub type __sigchld_clock_t = __clock_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed7 {
pub si_signo: ::libc::c_int,
pub si_errno: ::libc::c_int,
pub si_code: ::libc::c_int,
pub _sifields: Union_Unnamed8,
}
impl ::std::default::Default for Struct_Unnamed7 {
fn default() -> Struct_Unnamed7 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed8 {
pub _bindgen_data_: [u64; 14u],
}
impl Union_Unnamed8 {
pub unsafe fn _pad(&mut self) -> *mut [::libc::c_int; 28u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _kill(&mut self) -> *mut Struct_Unnamed9 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _timer(&mut self) -> *mut Struct_Unnamed10 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _rt(&mut self) -> *mut Struct_Unnamed11 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigchld(&mut self) -> *mut Struct_Unnamed12 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigfault(&mut self) -> *mut Struct_Unnamed13 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigpoll(&mut self) -> *mut Struct_Unnamed14 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigsys(&mut self) -> *mut Struct_Unnamed15 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed8 {
fn default() -> Union_Unnamed8 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed9 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
}
impl ::std::default::Default for Struct_Unnamed9 {
fn default() -> Struct_Unnamed9 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed10 {
pub si_tid: ::libc::c_int,
pub si_overrun: ::libc::c_int,
pub si_sigval: sigval_t,
}
impl ::std::default::Default for Struct_Unnamed10 {
fn default() -> Struct_Unnamed10 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed11 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
pub si_sigval: sigval_t,
}
impl ::std::default::Default for Struct_Unnamed11 {
fn default() -> Struct_Unnamed11 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed12 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
pub si_status: ::libc::c_int,
pub si_utime: __sigchld_clock_t,
pub si_stime: __sigchld_clock_t,
}
impl ::std::default::Default for Struct_Unnamed12 {
fn default() -> Struct_Unnamed12 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed13 {
pub si_addr: *mut ::libc::c_void,
pub si_addr_lsb: ::libc::c_short,
}
impl ::std::default::Default for Struct_Unnamed13 {
fn default() -> Struct_Unnamed13 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed14 {
pub si_band: ::libc::c_long,
pub si_fd: ::libc::c_int,
}
impl ::std::default::Default for Struct_Unnamed14 {
fn default() -> Struct_Unnamed14 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed15 {
pub _call_addr: *mut ::libc::c_void,
pub _syscall: ::libc::c_int,
pub _arch: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed15 {
fn default() -> Struct_Unnamed15 { unsafe { ::std::mem::zeroed() } }
}
pub type siginfo_t = Struct_Unnamed7;
pub type Enum_Unnamed16 = ::libc::c_int;
pub const SI_ASYNCNL: ::libc::c_int = -60;
pub const SI_TKILL: ::libc::c_int = -6;
pub const SI_SIGIO: ::libc::c_int = -5;
pub const SI_ASYNCIO: ::libc::c_int = -4;
pub const SI_MESGQ: ::libc::c_int = -3;
pub const SI_TIMER: ::libc::c_int = -2;
pub const SI_QUEUE: ::libc::c_int = -1;
pub const SI_USER: ::libc::c_int = 0;
pub const SI_KERNEL: ::libc::c_int = 128;
pub type Enum_Unnamed17 = ::libc::c_uint;
pub const ILL_ILLOPC: ::libc::c_uint = 1;
pub const ILL_ILLOPN: ::libc::c_uint = 2;
pub const ILL_ILLADR: ::libc::c_uint = 3;
pub const ILL_ILLTRP: ::libc::c_uint = 4;
pub const ILL_PRVOPC: ::libc::c_uint = 5;
pub const ILL_PRVREG: ::libc::c_uint = 6;
pub const ILL_COPROC: ::libc::c_uint = 7;
pub const ILL_BADSTK: ::libc::c_uint = 8;
pub type Enum_Unnamed18 = ::libc::c_uint;
pub const FPE_INTDIV: ::libc::c_uint = 1;
pub const FPE_INTOVF: ::libc::c_uint = 2;
pub const FPE_FLTDIV: ::libc::c_uint = 3;
pub const FPE_FLTOVF: ::libc::c_uint = 4;
pub const FPE_FLTUND: ::libc::c_uint = 5;
pub const FPE_FLTRES: ::libc::c_uint = 6;
pub const FPE_FLTINV: ::libc::c_uint = 7;
pub const FPE_FLTSUB: ::libc::c_uint = 8;
pub type Enum_Unnamed19 = ::libc::c_uint;
pub const SEGV_MAPERR: ::libc::c_uint = 1;
pub const SEGV_ACCERR: ::libc::c_uint = 2;
pub type Enum_Unnamed20 = ::libc::c_uint;
pub const BUS_ADRALN: ::libc::c_uint = 1;
pub const BUS_ADRERR: ::libc::c_uint = 2;
pub const BUS_OBJERR: ::libc::c_uint = 3;
pub const BUS_MCEERR_AR: ::libc::c_uint = 4;
pub const BUS_MCEERR_AO: ::libc::c_uint = 5;
pub type Enum_Unnamed21 = ::libc::c_uint;
pub const TRAP_BRKPT: ::libc::c_uint = 1;
pub const TRAP_TRACE: ::libc::c_uint = 2;
pub type Enum_Unnamed22 = ::libc::c_uint;
pub const CLD_EXITED: ::libc::c_uint = 1;
pub const CLD_KILLED: ::libc::c_uint = 2;
pub const CLD_DUMPED: ::libc::c_uint = 3;
pub const CLD_TRAPPED: ::libc::c_uint = 4;
pub const CLD_STOPPED: ::libc::c_uint = 5;
pub const CLD_CONTINUED: ::libc::c_uint = 6;
pub type Enum_Unnamed23 = ::libc::c_uint;
pub const POLL_IN: ::libc::c_uint = 1;
pub const POLL_OUT: ::libc::c_uint = 2;
pub const POLL_MSG: ::libc::c_uint = 3;
pub const POLL_ERR: ::libc::c_uint = 4;
pub const POLL_PRI: ::libc::c_uint = 5;
pub const POLL_HUP: ::libc::c_uint = 6;
pub type pthread_attr_t = Union_pthread_attr_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigevent {
pub sigev_value: sigval_t,
pub sigev_signo: ::libc::c_int,
pub sigev_notify: ::libc::c_int,
pub _sigev_un: Union_Unnamed24,
}
impl ::std::default::Default for Struct_sigevent {
fn default() -> Struct_sigevent { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed24 {
pub _bindgen_data_: [u64; 6u],
}
impl Union_Unnamed24 {
pub unsafe fn _pad(&mut self) -> *mut [::libc::c_int; 12u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _tid(&mut self) -> *mut __pid_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigev_thread(&mut self) -> *mut Struct_Unnamed25 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed24 {
fn default() -> Union_Unnamed24 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed25 {
pub _function: ::std::option::Option<extern "C" fn(arg1: sigval_t)>,
pub _attribute: *mut pthread_attr_t,
}
impl ::std::default::Default for Struct_Unnamed25 {
fn default() -> Struct_Unnamed25 { unsafe { ::std::mem::zeroed() } }
}
pub type sigevent_t = Struct_sigevent;
pub type Enum_Unnamed26 = ::libc::c_uint;
pub const SIGEV_SIGNAL: ::libc::c_uint = 0;
pub const SIGEV_NONE: ::libc::c_uint = 1;
pub const SIGEV_THREAD: ::libc::c_uint = 2;
pub const SIGEV_THREAD_ID: ::libc::c_uint = 4;
pub type __sighandler_t =
::std::option::Option<extern "C" fn(arg1: ::libc::c_int)>;
pub type sig_t = __sighandler_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigaction {
pub __sigaction_handler: Union_Unnamed27,
pub sa_mask: __sigset_t,
pub sa_flags: ::libc::c_int,
pub sa_restorer: ::std::option::Option<extern "C" fn()>,
}
impl ::std::default::Default for Struct_sigaction {
fn default() -> Struct_sigaction { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed27 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed27 {
pub unsafe fn sa_handler(&mut self) -> *mut __sighandler_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn sa_sigaction(&mut self)
->
*mut ::std::option::Option<extern "C" fn
(arg1: ::libc::c_int,
arg2: *mut siginfo_t,
arg3: *mut ::libc::c_void)> {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed27 {
fn default() -> Union_Unnamed27 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigvec {
pub sv_handler: __sighandler_t,
pub sv_mask: ::libc::c_int,
pub sv_flags: ::libc::c_int,
}
impl ::std::default::Default for Struct_sigvec {
fn default() -> Struct_sigvec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpx_sw_bytes {
pub magic1: __uint32_t,
pub extended_size: __uint32_t,
pub xstate_bv: __uint64_t,
pub xstate_size: __uint32_t,
pub padding: [__uint32_t; 7u],
}
impl ::std::default::Default for Struct__fpx_sw_bytes {
fn default() -> Struct__fpx_sw_bytes { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
}
impl ::std::default::Default for Struct__fpreg {
fn default() -> Struct__fpreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpxreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
pub padding: [::libc::c_ushort; 3u],
}
impl ::std::default::Default for Struct__fpxreg {
fn default() -> Struct__fpxreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xmmreg {
pub element: [__uint32_t; 4u],
}
impl ::std::default::Default for Struct__xmmreg {
fn default() -> Struct__xmmreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpstate {
pub cwd: __uint16_t,
pub swd: __uint16_t,
pub ftw: __uint16_t,
pub fop: __uint16_t,
pub rip: __uint64_t,
pub rdp: __uint64_t,
pub mxcsr: __uint32_t,
pub mxcr_mask: __uint32_t,
pub _st: [Struct__fpxreg; 8u],
pub _xmm: [Struct__xmmreg; 16u],
pub padding: [__uint32_t; 24u],
}
impl ::std::default::Default for Struct__fpstate {
fn default() -> Struct__fpstate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigcontext {
pub r8: __uint64_t,
pub r9: __uint64_t,
pub r10: __uint64_t,
pub r11: __uint64_t,
pub r12: __uint64_t,
pub r13: __uint64_t,
pub r14: __uint64_t,
pub r15: __uint64_t,
pub rdi: __uint64_t,
pub rsi: __uint64_t,
pub rbp: __uint64_t,
pub rbx: __uint64_t,
pub rdx: __uint64_t,
pub rax: __uint64_t,
pub rcx: __uint64_t,
pub rsp: __uint64_t,
pub rip: __uint64_t,
pub eflags: __uint64_t,
pub cs: ::libc::c_ushort,
pub gs: ::libc::c_ushort,
pub fs: ::libc::c_ushort,
pub __pad0: ::libc::c_ushort,
pub err: __uint64_t,
pub trapno: __uint64_t,
pub oldmask: __uint64_t,
pub cr2: __uint64_t,
pub _bindgen_data_1_: [u64; 1u],
pub __reserved1: [__uint64_t; 8u],
}
impl Struct_sigcontext {
pub unsafe fn fpstate(&mut self) -> *mut *mut Struct__fpstate {
::std::mem::transmute(&self._bindgen_data_1_)
}
pub unsafe fn __fpstate_word(&mut self) -> *mut __uint64_t {
::std::mem::transmute(&self._bindgen_data_1_)
}
}
impl ::std::default::Default for Struct_sigcontext {
fn default() -> Struct_sigcontext { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xsave_hdr {
pub xstate_bv: __uint64_t,
pub reserved1: [__uint64_t; 2u],
pub reserved2: [__uint64_t; 5u],
}
impl ::std::default::Default for Struct__xsave_hdr {
fn default() -> Struct__xsave_hdr { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__ymmh_state {
pub ymmh_space: [__uint32_t; 64u],
}
impl ::std::default::Default for Struct__ymmh_state {
fn default() -> Struct__ymmh_state { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xstate {
pub fpstate: Struct__fpstate,
pub xstate_hdr: Struct__xsave_hdr,
pub ymmh: Struct__ymmh_state,
}
impl ::std::default::Default for Struct__xstate {
fn default() -> Struct__xstate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigstack {
pub ss_sp: *mut ::libc::c_void,
pub ss_onstack: ::libc::c_int,
}
impl ::std::default::Default for Struct_sigstack {
fn default() -> Struct_sigstack { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed28 = ::libc::c_uint;
pub const SS_ONSTACK: ::libc::c_uint = 1;
pub const SS_DISABLE: ::libc::c_uint = 2;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigaltstack {
pub ss_sp: *mut ::libc::c_void,
pub ss_flags: ::libc::c_int,
pub ss_size: size_t,
}
impl ::std::default::Default for Struct_sigaltstack {
fn default() -> Struct_sigaltstack { unsafe { ::std::mem::zeroed() } }
}
pub type stack_t = Struct_sigaltstack;
pub type greg_t = ::libc::c_longlong;
pub type gregset_t = [greg_t; 23u];
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_fpxreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
pub padding: [::libc::c_ushort; 3u],
}
impl ::std::default::Default for Struct__libc_fpxreg {
fn default() -> Struct__libc_fpxreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_xmmreg {
pub element: [__uint32_t; 4u],
}
impl ::std::default::Default for Struct__libc_xmmreg {
fn default() -> Struct__libc_xmmreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_fpstate {
pub cwd: __uint16_t,
pub swd: __uint16_t,
pub ftw: __uint16_t,
pub fop: __uint16_t,
pub rip: __uint64_t,
pub rdp: __uint64_t,
pub mxcsr: __uint32_t,
pub mxcr_mask: __uint32_t,
pub _st: [Struct__libc_fpxreg; 8u],
pub _xmm: [Struct__libc_xmmreg; 16u],
pub padding: [__uint32_t; 24u],
}
impl ::std::default::Default for Struct__libc_fpstate {
fn default() -> Struct__libc_fpstate { unsafe { ::std::mem::zeroed() } }
}
pub type fpregset_t = *mut Struct__libc_fpstate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed29 {
pub gregs: gregset_t,
pub fpregs: fpregset_t,
pub __reserved1: [::libc::c_ulonglong; 8u],
}
impl ::std::default::Default for Struct_Unnamed29 {
fn default() -> Struct_Unnamed29 { unsafe { ::std::mem::zeroed() } }
}
pub type mcontext_t = Struct_Unnamed29;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_ucontext {
pub uc_flags: ::libc::c_ulong,
pub uc_link: *mut Struct_ucontext,
pub uc_stack: stack_t,
pub uc_mcontext: mcontext_t,
pub uc_sigmask: __sigset_t,
pub __fpregs_mem: Struct__libc_fpstate,
}
impl ::std::default::Default for Struct_ucontext {
fn default() -> Struct_ucontext { unsafe { ::std::mem::zeroed() } }
}
pub type ucontext_t = Struct_ucontext;
pub type pthread_t = ::libc::c_ulong;
#[repr(C)]
#[derive(Copy)]
pub struct Union_pthread_attr_t {
pub _bindgen_data_: [u64; 7u],
}
impl Union_pthread_attr_t {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 56u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_pthread_attr_t {
fn default() -> Union_pthread_attr_t { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_internal_list {
pub __prev: *mut Struct___pthread_internal_list,
pub __next: *mut Struct___pthread_internal_list,
}
impl ::std::default::Default for Struct___pthread_internal_list {
fn default() -> Struct___pthread_internal_list {
unsafe { ::std::mem::zeroed() }
}
}
pub type __pthread_list_t = Struct___pthread_internal_list;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed30 {
pub _bindgen_data_: [u64; 5u],
}
impl Union_Unnamed30 {
pub unsafe fn __data(&mut self) -> *mut Struct___pthread_mutex_s {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 40u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed30 {
fn default() -> Union_Unnamed30 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_mutex_s {
pub __lock: ::libc::c_int,
pub __count: ::libc::c_uint,
pub __owner: ::libc::c_int,
pub __nusers: ::libc::c_uint,
pub __kind: ::libc::c_int,
pub __spins: ::libc::c_short,
pub __elision: ::libc::c_short,
pub __list: __pthread_list_t,
}
impl ::std::default::Default for Struct___pthread_mutex_s {
fn default() -> Struct___pthread_mutex_s {
unsafe { ::std::mem::zeroed() }
}
}
pub type pthread_mutex_t = Union_Unnamed30;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed31 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed31 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed31 {
fn default() -> Union_Unnamed31 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_mutexattr_t = Union_Unnamed31;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed32 {
pub _bindgen_data_: [u64; 6u],
}
impl Union_Unnamed32 {
pub unsafe fn __data(&mut self) -> *mut Struct_Unnamed33 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 48u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_longlong {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed32 {
fn default() -> Union_Unnamed32 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed33 {
pub __lock: ::libc::c_int,
pub __futex: ::libc::c_uint,
pub __total_seq: ::libc::c_ulonglong,
pub __wakeup_seq: ::libc::c_ulonglong,
pub __woken_seq: ::libc::c_ulonglong,
pub __mutex: *mut ::libc::c_void,
pub __nwaiters: ::libc::c_uint,
pub __broadcast_seq: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed33 {
fn default() -> Struct_Unnamed33 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_cond_t = Union_Unnamed32;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed34 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed34 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed34 {
fn default() -> Union_Unnamed34 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_condattr_t = Union_Unnamed34;
pub type pthread_key_t = ::libc::c_uint;
pub type pthread_once_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed35 {
pub _bindgen_data_: [u64; 7u],
}
impl Union_Unnamed35 {
pub unsafe fn __data(&mut self) -> *mut Struct_Unnamed36 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 56u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed35 {
fn default() -> Union_Unnamed35 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed36 {
pub __lock: ::libc::c_int,
pub __nr_readers: ::libc::c_uint,
pub __readers_wakeup: ::libc::c_uint,
pub __writer_wakeup: ::libc::c_uint,
pub __nr_readers_queued: ::libc::c_uint,
pub __nr_writers_queued: ::libc::c_uint,
pub __writer: ::libc::c_int,
pub __shared: ::libc::c_int,
pub __pad1: ::libc::c_ulong,
pub __pad2: ::libc::c_ulong,
pub __flags: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed36 {
fn default() -> Struct_Unnamed36 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_rwlock_t = Union_Unnamed35;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed37 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed37 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 8u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed37 {
fn default() -> Union_Unnamed37 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_rwlockattr_t = Union_Unnamed37;
pub type pthread_spinlock_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed38 {
pub _bindgen_data_: [u64; 4u],
}
impl Union_Unnamed38 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 32u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed38 {
fn default() -> Union_Unnamed38 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_barrier_t = Union_Unnamed38;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed39 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed39 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed39 {
fn default() -> Union_Unnamed39 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_barrierattr_t = Union_Unnamed39;
pub type Enum_Unnamed40 = ::libc::c_uint;
pub const G_BOOKMARK_FILE_ERROR_INVALID_URI: ::libc::c_uint = 0;
pub const G_BOOKMARK_FILE_ERROR_INVALID_VALUE: ::libc::c_uint = 1;
pub const G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED: ::libc::c_uint = 2;
pub const G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND: ::libc::c_uint = 3;
pub const G_BOOKMARK_FILE_ERROR_READ: ::libc::c_uint = 4;
pub const G_BOOKMARK_FILE_ERROR_UNKNOWN_ENCODING: ::libc::c_uint = 5;
pub const G_BOOKMARK_FILE_ERROR_WRITE: ::libc::c_uint = 6;
pub const G_BOOKMARK_FILE_ERROR_FILE_NOT_FOUND: ::libc::c_uint = 7;
pub type GBookmarkFileError = Enum_Unnamed40;
pub enum Struct__GBookmarkFile { }
pub type GBookmarkFile = Struct__GBookmarkFile;
pub type Enum_Unnamed41 = ::libc::c_uint;
pub const G_CHECKSUM_MD5: ::libc::c_uint = 0;
pub const G_CHECKSUM_SHA1: ::libc::c_uint = 1;
pub const G_CHECKSUM_SHA256: ::libc::c_uint = 2;
pub const G_CHECKSUM_SHA512: ::libc::c_uint = 3;
pub type GChecksumType = Enum_Unnamed41;
pub enum Struct__GChecksum { }
pub type GChecksum = Struct__GChecksum;
pub type Enum_Unnamed42 = ::libc::c_uint;
pub const G_CONVERT_ERROR_NO_CONVERSION: ::libc::c_uint = 0;
pub const G_CONVERT_ERROR_ILLEGAL_SEQUENCE: ::libc::c_uint = 1;
pub const G_CONVERT_ERROR_FAILED: ::libc::c_uint = 2;
pub const G_CONVERT_ERROR_PARTIAL_INPUT: ::libc::c_uint = 3;
pub const G_CONVERT_ERROR_BAD_URI: ::libc::c_uint = 4;
pub const G_CONVERT_ERROR_NOT_ABSOLUTE_PATH: ::libc::c_uint = 5;
pub const G_CONVERT_ERROR_NO_MEMORY: ::libc::c_uint = 6;
pub type GConvertError = Enum_Unnamed42;
pub enum Struct__GIConv { }
pub type GIConv = *mut Struct__GIConv;
pub enum Struct__GData { }
pub type GData = Struct__GData;
pub type GDataForeachFunc =
::std::option::Option<extern "C" fn
(key_id: GQuark, data: gpointer,
user_data: gpointer)>;
pub type GDuplicateFunc =
::std::option::Option<extern "C" fn(data: gpointer, user_data: gpointer)
-> gpointer>;
pub type GTime = gint32;
pub type GDateYear = guint16;
pub type GDateDay = guint8;
pub type GDate = Struct__GDate;
pub type Enum_Unnamed43 = ::libc::c_uint;
pub const G_DATE_DAY: ::libc::c_uint = 0;
pub const G_DATE_MONTH: ::libc::c_uint = 1;
pub const G_DATE_YEAR: ::libc::c_uint = 2;
pub type GDateDMY = Enum_Unnamed43;
pub type Enum_Unnamed44 = ::libc::c_uint;
pub const G_DATE_BAD_WEEKDAY: ::libc::c_uint = 0;
pub const G_DATE_MONDAY: ::libc::c_uint = 1;
pub const G_DATE_TUESDAY: ::libc::c_uint = 2;
pub const G_DATE_WEDNESDAY: ::libc::c_uint = 3;
pub const G_DATE_THURSDAY: ::libc::c_uint = 4;
pub const G_DATE_FRIDAY: ::libc::c_uint = 5;
pub const G_DATE_SATURDAY: ::libc::c_uint = 6;
pub const G_DATE_SUNDAY: ::libc::c_uint = 7;
pub type GDateWeekday = Enum_Unnamed44;
pub type Enum_Unnamed45 = ::libc::c_uint;
pub const G_DATE_BAD_MONTH: ::libc::c_uint = 0;
pub const G_DATE_JANUARY: ::libc::c_uint = 1;
pub const G_DATE_FEBRUARY: ::libc::c_uint = 2;
pub const G_DATE_MARCH: ::libc::c_uint = 3;
pub const G_DATE_APRIL: ::libc::c_uint = 4;
pub const G_DATE_MAY: ::libc::c_uint = 5;
pub const G_DATE_JUNE: ::libc::c_uint = 6;
pub const G_DATE_JULY: ::libc::c_uint = 7;
pub const G_DATE_AUGUST: ::libc::c_uint = 8;
pub const G_DATE_SEPTEMBER: ::libc::c_uint = 9;
pub const G_DATE_OCTOBER: ::libc::c_uint = 10;
pub const G_DATE_NOVEMBER: ::libc::c_uint = 11;
pub const G_DATE_DECEMBER: ::libc::c_uint = 12;
pub type GDateMonth = Enum_Unnamed45;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GDate {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
}
impl ::std::default::Default for Struct__GDate {
fn default() -> Struct__GDate { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTimeZone { }
pub type GTimeZone = Struct__GTimeZone;
pub type Enum_Unnamed46 = ::libc::c_uint;
pub const G_TIME_TYPE_STANDARD: ::libc::c_uint = 0;
pub const G_TIME_TYPE_DAYLIGHT: ::libc::c_uint = 1;
pub const G_TIME_TYPE_UNIVERSAL: ::libc::c_uint = 2;
pub type GTimeType = Enum_Unnamed46;
pub type GTimeSpan = gint64;
pub enum Struct__GDateTime { }
pub type GDateTime = Struct__GDateTime;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_dirent {
pub d_ino: __ino_t,
pub d_off: __off_t,
pub d_reclen: ::libc::c_ushort,
pub d_type: ::libc::c_uchar,
pub d_name: [::libc::c_char; 256u],
}
impl ::std::default::Default for Struct_dirent {
fn default() -> Struct_dirent { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed47 = ::libc::c_uint;
pub const DT_UNKNOWN: ::libc::c_uint = 0;
pub const DT_FIFO: ::libc::c_uint = 1;
pub const DT_CHR: ::libc::c_uint = 2;
pub const DT_DIR: ::libc::c_uint = 4;
pub const DT_BLK: ::libc::c_uint = 6;
pub const DT_REG: ::libc::c_uint = 8;
pub const DT_LNK: ::libc::c_uint = 10;
pub const DT_SOCK: ::libc::c_uint = 12;
pub const DT_WHT: ::libc::c_uint = 14;
pub enum Struct___dirstream { }
pub type DIR = Struct___dirstream;
pub enum Struct__GDir { }
pub type GDir = Struct__GDir;
pub type Enum_Unnamed48 = ::libc::c_uint;
pub const G_FILE_ERROR_EXIST: ::libc::c_uint = 0;
pub const G_FILE_ERROR_ISDIR: ::libc::c_uint = 1;
pub const G_FILE_ERROR_ACCES: ::libc::c_uint = 2;
pub const G_FILE_ERROR_NAMETOOLONG: ::libc::c_uint = 3;
pub const G_FILE_ERROR_NOENT: ::libc::c_uint = 4;
pub const G_FILE_ERROR_NOTDIR: ::libc::c_uint = 5;
pub const G_FILE_ERROR_NXIO: ::libc::c_uint = 6;
pub const G_FILE_ERROR_NODEV: ::libc::c_uint = 7;
pub const G_FILE_ERROR_ROFS: ::libc::c_uint = 8;
pub const G_FILE_ERROR_TXTBSY: ::libc::c_uint = 9;
pub const G_FILE_ERROR_FAULT: ::libc::c_uint = 10;
pub const G_FILE_ERROR_LOOP: ::libc::c_uint = 11;
pub const G_FILE_ERROR_NOSPC: ::libc::c_uint = 12;
pub const G_FILE_ERROR_NOMEM: ::libc::c_uint = 13;
pub const G_FILE_ERROR_MFILE: ::libc::c_uint = 14;
pub const G_FILE_ERROR_NFILE: ::libc::c_uint = 15;
pub const G_FILE_ERROR_BADF: ::libc::c_uint = 16;
pub const G_FILE_ERROR_INVAL: ::libc::c_uint = 17;
pub const G_FILE_ERROR_PIPE: ::libc::c_uint = 18;
pub const G_FILE_ERROR_AGAIN: ::libc::c_uint = 19;
pub const G_FILE_ERROR_INTR: ::libc::c_uint = 20;
pub const G_FILE_ERROR_IO: ::libc::c_uint = 21;
pub const G_FILE_ERROR_PERM: ::libc::c_uint = 22;
pub const G_FILE_ERROR_NOSYS: ::libc::c_uint = 23;
pub const G_FILE_ERROR_FAILED: ::libc::c_uint = 24;
pub type GFileError = Enum_Unnamed48;
pub type Enum_Unnamed49 = ::libc::c_uint;
pub const G_FILE_TEST_IS_REGULAR: ::libc::c_uint = 1;
pub const G_FILE_TEST_IS_SYMLINK: ::libc::c_uint = 2;
pub const G_FILE_TEST_IS_DIR: ::libc::c_uint = 4;
pub const G_FILE_TEST_IS_EXECUTABLE: ::libc::c_uint = 8;
pub const G_FILE_TEST_EXISTS: ::libc::c_uint = 16;
pub type GFileTest = Enum_Unnamed49;
pub type GMemVTable = Struct__GMemVTable;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GMemVTable {
pub malloc: ::std::option::Option<extern "C" fn(n_bytes: gsize)
-> gpointer>,
pub realloc: ::std::option::Option<extern "C" fn
(mem: gpointer, n_bytes: gsize)
-> gpointer>,
pub free: ::std::option::Option<extern "C" fn(mem: gpointer)>,
pub calloc: ::std::option::Option<extern "C" fn
(n_blocks: gsize,
n_block_bytes: gsize) -> gpointer>,
pub try_malloc: ::std::option::Option<extern "C" fn(n_bytes: gsize)
-> gpointer>,
pub try_realloc: ::std::option::Option<extern "C" fn
(mem: gpointer, n_bytes: gsize)
-> gpointer>,
}
impl ::std::default::Default for Struct__GMemVTable {
fn default() -> Struct__GMemVTable { unsafe { ::std::mem::zeroed() } }
}
pub type GNode = Struct__GNode;
pub type Enum_Unnamed50 = ::libc::c_uint;
pub const G_TRAVERSE_LEAVES: ::libc::c_uint = 1;
pub const G_TRAVERSE_NON_LEAVES: ::libc::c_uint = 2;
pub const G_TRAVERSE_ALL: ::libc::c_uint = 3;
pub const G_TRAVERSE_MASK: ::libc::c_uint = 3;
pub const G_TRAVERSE_LEAFS: ::libc::c_uint = 1;
pub const G_TRAVERSE_NON_LEAFS: ::libc::c_uint = 2;
pub type GTraverseFlags = Enum_Unnamed50;
pub type Enum_Unnamed51 = ::libc::c_uint;
pub const G_IN_ORDER: ::libc::c_uint = 0;
pub const G_PRE_ORDER: ::libc::c_uint = 1;
pub const G_POST_ORDER: ::libc::c_uint = 2;
pub const G_LEVEL_ORDER: ::libc::c_uint = 3;
pub type GTraverseType = Enum_Unnamed51;
pub type GNodeTraverseFunc =
::std::option::Option<extern "C" fn(node: *mut GNode, data: gpointer)
-> gboolean>;
pub type GNodeForeachFunc =
::std::option::Option<extern "C" fn(node: *mut GNode, data: gpointer)>;
pub type GCopyFunc =
::std::option::Option<extern "C" fn(src: gconstpointer, data: gpointer)
-> gpointer>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GNode {
pub data: gpointer,
pub next: *mut GNode,
pub prev: *mut GNode,
pub parent: *mut GNode,
pub children: *mut GNode,
}
impl ::std::default::Default for Struct__GNode {
fn default() -> Struct__GNode { unsafe { ::std::mem::zeroed() } }
}
pub type GList = Struct__GList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GList {
pub data: gpointer,
pub next: *mut GList,
pub prev: *mut GList,
}
impl ::std::default::Default for Struct__GList {
fn default() -> Struct__GList { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GHashTable { }
pub type GHashTable = Struct__GHashTable;
pub type GHRFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer,
user_data: gpointer) -> gboolean>;
pub type GHashTableIter = Struct__GHashTableIter;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHashTableIter {
pub dummy1: gpointer,
pub dummy2: gpointer,
pub dummy3: gpointer,
pub dummy4: ::libc::c_int,
pub dummy5: gboolean,
pub dummy6: gpointer,
}
impl ::std::default::Default for Struct__GHashTableIter {
fn default() -> Struct__GHashTableIter { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GHmac { }
pub type GHmac = Struct__GHmac;
pub type GHook = Struct__GHook;
pub type GHookList = Struct__GHookList;
pub type GHookCompareFunc =
::std::option::Option<extern "C" fn
(new_hook: *mut GHook, sibling: *mut GHook)
-> gint>;
pub type GHookFindFunc =
::std::option::Option<extern "C" fn(hook: *mut GHook, data: gpointer)
-> gboolean>;
pub type GHookMarshaller =
::std::option::Option<extern "C" fn
(hook: *mut GHook, marshal_data: gpointer)>;
pub type GHookCheckMarshaller =
::std::option::Option<extern "C" fn
(hook: *mut GHook, marshal_data: gpointer)
-> gboolean>;
pub type GHookFunc = ::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GHookCheckFunc =
::std::option::Option<extern "C" fn(data: gpointer) -> gboolean>;
pub type GHookFinalizeFunc =
::std::option::Option<extern "C" fn
(hook_list: *mut GHookList, hook: *mut GHook)>;
pub type Enum_Unnamed52 = ::libc::c_uint;
pub const G_HOOK_FLAG_ACTIVE: ::libc::c_uint = 1;
pub const G_HOOK_FLAG_IN_CALL: ::libc::c_uint = 2;
pub const G_HOOK_FLAG_MASK: ::libc::c_uint = 15;
pub type GHookFlagMask = Enum_Unnamed52;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHookList {
pub seq_id: gulong,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub hooks: *mut GHook,
pub dummy3: gpointer,
pub finalize_hook: GHookFinalizeFunc,
pub dummy: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GHookList {
fn default() -> Struct__GHookList { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHook {
pub data: gpointer,
pub next: *mut GHook,
pub prev: *mut GHook,
pub ref_count: guint,
pub hook_id: gulong,
pub flags: guint,
pub func: gpointer,
pub destroy: GDestroyNotify,
}
impl ::std::default::Default for Struct__GHook {
fn default() -> Struct__GHook { unsafe { ::std::mem::zeroed() } }
}
pub type GPollFD = Struct__GPollFD;
pub type GPollFunc =
::std::option::Option<extern "C" fn
(ufds: *mut GPollFD, nfsd: guint,
timeout_: gint) -> gint>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPollFD {
pub fd: gint,
pub events: gushort,
pub revents: gushort,
}
impl ::std::default::Default for Struct__GPollFD {
fn default() -> Struct__GPollFD { unsafe { ::std::mem::zeroed() } }
}
pub type GSList = Struct__GSList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSList {
pub data: gpointer,
pub next: *mut GSList,
}
impl ::std::default::Default for Struct__GSList {
fn default() -> Struct__GSList { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed53 = ::libc::c_uint;
pub const G_IO_IN: ::libc::c_uint = 1;
pub const G_IO_OUT: ::libc::c_uint = 4;
pub const G_IO_PRI: ::libc::c_uint = 2;
pub const G_IO_ERR: ::libc::c_uint = 8;
pub const G_IO_HUP: ::libc::c_uint = 16;
pub const G_IO_NVAL: ::libc::c_uint = 32;
pub type GIOCondition = Enum_Unnamed53;
pub enum Struct__GMainContext { }
pub type GMainContext = Struct__GMainContext;
pub enum Struct__GMainLoop { }
pub type GMainLoop = Struct__GMainLoop;
pub type GSource = Struct__GSource;
pub enum Struct__GSourcePrivate { }
pub type GSourcePrivate = Struct__GSourcePrivate;
pub type GSourceCallbackFuncs = Struct__GSourceCallbackFuncs;
pub type GSourceFuncs = Struct__GSourceFuncs;
pub type GSourceFunc =
::std::option::Option<extern "C" fn(user_data: gpointer) -> gboolean>;
pub type GChildWatchFunc =
::std::option::Option<extern "C" fn
(pid: GPid, status: gint, user_data: gpointer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSource {
pub callback_data: gpointer,
pub callback_funcs: *mut GSourceCallbackFuncs,
pub source_funcs: *const GSourceFuncs,
pub ref_count: guint,
pub context: *mut GMainContext,
pub priority: gint,
pub flags: guint,
pub source_id: guint,
pub poll_fds: *mut GSList,
pub prev: *mut GSource,
pub next: *mut GSource,
pub name: *mut ::libc::c_char,
pub _priv: *mut GSourcePrivate,
}
impl ::std::default::Default for Struct__GSource {
fn default() -> Struct__GSource { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSourceCallbackFuncs {
pub _ref: ::std::option::Option<extern "C" fn(cb_data: gpointer)>,
pub unref: ::std::option::Option<extern "C" fn(cb_data: gpointer)>,
pub get: ::std::option::Option<extern "C" fn
(cb_data: gpointer,
source: *mut GSource,
func: *mut GSourceFunc,
data: *mut gpointer)>,
}
impl ::std::default::Default for Struct__GSourceCallbackFuncs {
fn default() -> Struct__GSourceCallbackFuncs {
unsafe { ::std::mem::zeroed() }
}
}
pub type GSourceDummyMarshal = ::std::option::Option<extern "C" fn()>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSourceFuncs {
pub prepare: ::std::option::Option<extern "C" fn
(source: *mut GSource,
timeout_: *mut gint) -> gboolean>,
pub check: ::std::option::Option<extern "C" fn(source: *mut GSource)
-> gboolean>,
pub dispatch: ::std::option::Option<extern "C" fn
(source: *mut GSource,
callback: GSourceFunc,
user_data: gpointer)
-> gboolean>,
pub finalize: ::std::option::Option<extern "C" fn(source: *mut GSource)>,
pub closure_callback: GSourceFunc,
pub closure_marshal: GSourceDummyMarshal,
}
impl ::std::default::Default for Struct__GSourceFuncs {
fn default() -> Struct__GSourceFuncs { unsafe { ::std::mem::zeroed() } }
}
pub type gunichar = guint32;
pub type gunichar2 = guint16;
pub type Enum_Unnamed54 = ::libc::c_uint;
pub const G_UNICODE_CONTROL: ::libc::c_uint = 0;
pub const G_UNICODE_FORMAT: ::libc::c_uint = 1;
pub const G_UNICODE_UNASSIGNED: ::libc::c_uint = 2;
pub const G_UNICODE_PRIVATE_USE: ::libc::c_uint = 3;
pub const G_UNICODE_SURROGATE: ::libc::c_uint = 4;
pub const G_UNICODE_LOWERCASE_LETTER: ::libc::c_uint = 5;
pub const G_UNICODE_MODIFIER_LETTER: ::libc::c_uint = 6;
pub const G_UNICODE_OTHER_LETTER: ::libc::c_uint = 7;
pub const G_UNICODE_TITLECASE_LETTER: ::libc::c_uint = 8;
pub const G_UNICODE_UPPERCASE_LETTER: ::libc::c_uint = 9;
pub const G_UNICODE_SPACING_MARK: ::libc::c_uint = 10;
pub const G_UNICODE_ENCLOSING_MARK: ::libc::c_uint = 11;
pub const G_UNICODE_NON_SPACING_MARK: ::libc::c_uint = 12;
pub const G_UNICODE_DECIMAL_NUMBER: ::libc::c_uint = 13;
pub const G_UNICODE_LETTER_NUMBER: ::libc::c_uint = 14;
pub const G_UNICODE_OTHER_NUMBER: ::libc::c_uint = 15;
pub const G_UNICODE_CONNECT_PUNCTUATION: ::libc::c_uint = 16;
pub const G_UNICODE_DASH_PUNCTUATION: ::libc::c_uint = 17;
pub const G_UNICODE_CLOSE_PUNCTUATION: ::libc::c_uint = 18;
pub const G_UNICODE_FINAL_PUNCTUATION: ::libc::c_uint = 19;
pub const G_UNICODE_INITIAL_PUNCTUATION: ::libc::c_uint = 20;
pub const G_UNICODE_OTHER_PUNCTUATION: ::libc::c_uint = 21;
pub const G_UNICODE_OPEN_PUNCTUATION: ::libc::c_uint = 22;
pub const G_UNICODE_CURRENCY_SYMBOL: ::libc::c_uint = 23;
pub const G_UNICODE_MODIFIER_SYMBOL: ::libc::c_uint = 24;
pub const G_UNICODE_MATH_SYMBOL: ::libc::c_uint = 25;
pub const G_UNICODE_OTHER_SYMBOL: ::libc::c_uint = 26;
pub const G_UNICODE_LINE_SEPARATOR: ::libc::c_uint = 27;
pub const G_UNICODE_PARAGRAPH_SEPARATOR: ::libc::c_uint = 28;
pub const G_UNICODE_SPACE_SEPARATOR: ::libc::c_uint = 29;
pub type GUnicodeType = Enum_Unnamed54;
pub type Enum_Unnamed55 = ::libc::c_uint;
pub const G_UNICODE_BREAK_MANDATORY: ::libc::c_uint = 0;
pub const G_UNICODE_BREAK_CARRIAGE_RETURN: ::libc::c_uint = 1;
pub const G_UNICODE_BREAK_LINE_FEED: ::libc::c_uint = 2;
pub const G_UNICODE_BREAK_COMBINING_MARK: ::libc::c_uint = 3;
pub const G_UNICODE_BREAK_SURROGATE: ::libc::c_uint = 4;
pub const G_UNICODE_BREAK_ZERO_WIDTH_SPACE: ::libc::c_uint = 5;
pub const G_UNICODE_BREAK_INSEPARABLE: ::libc::c_uint = 6;
pub const G_UNICODE_BREAK_NON_BREAKING_GLUE: ::libc::c_uint = 7;
pub const G_UNICODE_BREAK_CONTINGENT: ::libc::c_uint = 8;
pub const G_UNICODE_BREAK_SPACE: ::libc::c_uint = 9;
pub const G_UNICODE_BREAK_AFTER: ::libc::c_uint = 10;
pub const G_UNICODE_BREAK_BEFORE: ::libc::c_uint = 11;
pub const G_UNICODE_BREAK_BEFORE_AND_AFTER: ::libc::c_uint = 12;
pub const G_UNICODE_BREAK_HYPHEN: ::libc::c_uint = 13;
pub const G_UNICODE_BREAK_NON_STARTER: ::libc::c_uint = 14;
pub const G_UNICODE_BREAK_OPEN_PUNCTUATION: ::libc::c_uint = 15;
pub const G_UNICODE_BREAK_CLOSE_PUNCTUATION: ::libc::c_uint = 16;
pub const G_UNICODE_BREAK_QUOTATION: ::libc::c_uint = 17;
pub const G_UNICODE_BREAK_EXCLAMATION: ::libc::c_uint = 18;
pub const G_UNICODE_BREAK_IDEOGRAPHIC: ::libc::c_uint = 19;
pub const G_UNICODE_BREAK_NUMERIC: ::libc::c_uint = 20;
pub const G_UNICODE_BREAK_INFIX_SEPARATOR: ::libc::c_uint = 21;
pub const G_UNICODE_BREAK_SYMBOL: ::libc::c_uint = 22;
pub const G_UNICODE_BREAK_ALPHABETIC: ::libc::c_uint = 23;
pub const G_UNICODE_BREAK_PREFIX: ::libc::c_uint = 24;
pub const G_UNICODE_BREAK_POSTFIX: ::libc::c_uint = 25;
pub const G_UNICODE_BREAK_COMPLEX_CONTEXT: ::libc::c_uint = 26;
pub const G_UNICODE_BREAK_AMBIGUOUS: ::libc::c_uint = 27;
pub const G_UNICODE_BREAK_UNKNOWN: ::libc::c_uint = 28;
pub const G_UNICODE_BREAK_NEXT_LINE: ::libc::c_uint = 29;
pub const G_UNICODE_BREAK_WORD_JOINER: ::libc::c_uint = 30;
pub const G_UNICODE_BREAK_HANGUL_L_JAMO: ::libc::c_uint = 31;
pub const G_UNICODE_BREAK_HANGUL_V_JAMO: ::libc::c_uint = 32;
pub const G_UNICODE_BREAK_HANGUL_T_JAMO: ::libc::c_uint = 33;
pub const G_UNICODE_BREAK_HANGUL_LV_SYLLABLE: ::libc::c_uint = 34;
pub const G_UNICODE_BREAK_HANGUL_LVT_SYLLABLE: ::libc::c_uint = 35;
pub const G_UNICODE_BREAK_CLOSE_PARANTHESIS: ::libc::c_uint = 36;
pub const G_UNICODE_BREAK_CONDITIONAL_JAPANESE_STARTER: ::libc::c_uint = 37;
pub const G_UNICODE_BREAK_HEBREW_LETTER: ::libc::c_uint = 38;
pub const G_UNICODE_BREAK_REGIONAL_INDICATOR: ::libc::c_uint = 39;
pub type GUnicodeBreakType = Enum_Unnamed55;
pub type Enum_Unnamed56 = ::libc::c_int;
pub const G_UNICODE_SCRIPT_INVALID_CODE: ::libc::c_int = -1;
pub const G_UNICODE_SCRIPT_COMMON: ::libc::c_int = 0;
pub const G_UNICODE_SCRIPT_INHERITED: ::libc::c_int = 1;
pub const G_UNICODE_SCRIPT_ARABIC: ::libc::c_int = 2;
pub const G_UNICODE_SCRIPT_ARMENIAN: ::libc::c_int = 3;
pub const G_UNICODE_SCRIPT_BENGALI: ::libc::c_int = 4;
pub const G_UNICODE_SCRIPT_BOPOMOFO: ::libc::c_int = 5;
pub const G_UNICODE_SCRIPT_CHEROKEE: ::libc::c_int = 6;
pub const G_UNICODE_SCRIPT_COPTIC: ::libc::c_int = 7;
pub const G_UNICODE_SCRIPT_CYRILLIC: ::libc::c_int = 8;
pub const G_UNICODE_SCRIPT_DESERET: ::libc::c_int = 9;
pub const G_UNICODE_SCRIPT_DEVANAGARI: ::libc::c_int = 10;
pub const G_UNICODE_SCRIPT_ETHIOPIC: ::libc::c_int = 11;
pub const G_UNICODE_SCRIPT_GEORGIAN: ::libc::c_int = 12;
pub const G_UNICODE_SCRIPT_GOTHIC: ::libc::c_int = 13;
pub const G_UNICODE_SCRIPT_GREEK: ::libc::c_int = 14;
pub const G_UNICODE_SCRIPT_GUJARATI: ::libc::c_int = 15;
pub const G_UNICODE_SCRIPT_GURMUKHI: ::libc::c_int = 16;
pub const G_UNICODE_SCRIPT_HAN: ::libc::c_int = 17;
pub const G_UNICODE_SCRIPT_HANGUL: ::libc::c_int = 18;
pub const G_UNICODE_SCRIPT_HEBREW: ::libc::c_int = 19;
pub const G_UNICODE_SCRIPT_HIRAGANA: ::libc::c_int = 20;
pub const G_UNICODE_SCRIPT_KANNADA: ::libc::c_int = 21;
pub const G_UNICODE_SCRIPT_KATAKANA: ::libc::c_int = 22;
pub const G_UNICODE_SCRIPT_KHMER: ::libc::c_int = 23;
pub const G_UNICODE_SCRIPT_LAO: ::libc::c_int = 24;
pub const G_UNICODE_SCRIPT_LATIN: ::libc::c_int = 25;
pub const G_UNICODE_SCRIPT_MALAYALAM: ::libc::c_int = 26;
pub const G_UNICODE_SCRIPT_MONGOLIAN: ::libc::c_int = 27;
pub const G_UNICODE_SCRIPT_MYANMAR: ::libc::c_int = 28;
pub const G_UNICODE_SCRIPT_OGHAM: ::libc::c_int = 29;
pub const G_UNICODE_SCRIPT_OLD_ITALIC: ::libc::c_int = 30;
pub const G_UNICODE_SCRIPT_ORIYA: ::libc::c_int = 31;
pub const G_UNICODE_SCRIPT_RUNIC: ::libc::c_int = 32;
pub const G_UNICODE_SCRIPT_SINHALA: ::libc::c_int = 33;
pub const G_UNICODE_SCRIPT_SYRIAC: ::libc::c_int = 34;
pub const G_UNICODE_SCRIPT_TAMIL: ::libc::c_int = 35;
pub const G_UNICODE_SCRIPT_TELUGU: ::libc::c_int = 36;
pub const G_UNICODE_SCRIPT_THAANA: ::libc::c_int = 37;
pub const G_UNICODE_SCRIPT_THAI: ::libc::c_int = 38;
pub const G_UNICODE_SCRIPT_TIBETAN: ::libc::c_int = 39;
pub const G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL: ::libc::c_int = 40;
pub const G_UNICODE_SCRIPT_YI: ::libc::c_int = 41;
pub const G_UNICODE_SCRIPT_TAGALOG: ::libc::c_int = 42;
pub const G_UNICODE_SCRIPT_HANUNOO: ::libc::c_int = 43;
pub const G_UNICODE_SCRIPT_BUHID: ::libc::c_int = 44;
pub const G_UNICODE_SCRIPT_TAGBANWA: ::libc::c_int = 45;
pub const G_UNICODE_SCRIPT_BRAILLE: ::libc::c_int = 46;
pub const G_UNICODE_SCRIPT_CYPRIOT: ::libc::c_int = 47;
pub const G_UNICODE_SCRIPT_LIMBU: ::libc::c_int = 48;
pub const G_UNICODE_SCRIPT_OSMANYA: ::libc::c_int = 49;
pub const G_UNICODE_SCRIPT_SHAVIAN: ::libc::c_int = 50;
pub const G_UNICODE_SCRIPT_LINEAR_B: ::libc::c_int = 51;
pub const G_UNICODE_SCRIPT_TAI_LE: ::libc::c_int = 52;
pub const G_UNICODE_SCRIPT_UGARITIC: ::libc::c_int = 53;
pub const G_UNICODE_SCRIPT_NEW_TAI_LUE: ::libc::c_int = 54;
pub const G_UNICODE_SCRIPT_BUGINESE: ::libc::c_int = 55;
pub const G_UNICODE_SCRIPT_GLAGOLITIC: ::libc::c_int = 56;
pub const G_UNICODE_SCRIPT_TIFINAGH: ::libc::c_int = 57;
pub const G_UNICODE_SCRIPT_SYLOTI_NAGRI: ::libc::c_int = 58;
pub const G_UNICODE_SCRIPT_OLD_PERSIAN: ::libc::c_int = 59;
pub const G_UNICODE_SCRIPT_KHAROSHTHI: ::libc::c_int = 60;
pub const G_UNICODE_SCRIPT_UNKNOWN: ::libc::c_int = 61;
pub const G_UNICODE_SCRIPT_BALINESE: ::libc::c_int = 62;
pub const G_UNICODE_SCRIPT_CUNEIFORM: ::libc::c_int = 63;
pub const G_UNICODE_SCRIPT_PHOENICIAN: ::libc::c_int = 64;
pub const G_UNICODE_SCRIPT_PHAGS_PA: ::libc::c_int = 65;
pub const G_UNICODE_SCRIPT_NKO: ::libc::c_int = 66;
pub const G_UNICODE_SCRIPT_KAYAH_LI: ::libc::c_int = 67;
pub const G_UNICODE_SCRIPT_LEPCHA: ::libc::c_int = 68;
pub const G_UNICODE_SCRIPT_REJANG: ::libc::c_int = 69;
pub const G_UNICODE_SCRIPT_SUNDANESE: ::libc::c_int = 70;
pub const G_UNICODE_SCRIPT_SAURASHTRA: ::libc::c_int = 71;
pub const G_UNICODE_SCRIPT_CHAM: ::libc::c_int = 72;
pub const G_UNICODE_SCRIPT_OL_CHIKI: ::libc::c_int = 73;
pub const G_UNICODE_SCRIPT_VAI: ::libc::c_int = 74;
pub const G_UNICODE_SCRIPT_CARIAN: ::libc::c_int = 75;
pub const G_UNICODE_SCRIPT_LYCIAN: ::libc::c_int = 76;
pub const G_UNICODE_SCRIPT_LYDIAN: ::libc::c_int = 77;
pub const G_UNICODE_SCRIPT_AVESTAN: ::libc::c_int = 78;
pub const G_UNICODE_SCRIPT_BAMUM: ::libc::c_int = 79;
pub const G_UNICODE_SCRIPT_EGYPTIAN_HIEROGLYPHS: ::libc::c_int = 80;
pub const G_UNICODE_SCRIPT_IMPERIAL_ARAMAIC: ::libc::c_int = 81;
pub const G_UNICODE_SCRIPT_INSCRIPTIONAL_PAHLAVI: ::libc::c_int = 82;
pub const G_UNICODE_SCRIPT_INSCRIPTIONAL_PARTHIAN: ::libc::c_int = 83;
pub const G_UNICODE_SCRIPT_JAVANESE: ::libc::c_int = 84;
pub const G_UNICODE_SCRIPT_KAITHI: ::libc::c_int = 85;
pub const G_UNICODE_SCRIPT_LISU: ::libc::c_int = 86;
pub const G_UNICODE_SCRIPT_MEETEI_MAYEK: ::libc::c_int = 87;
pub const G_UNICODE_SCRIPT_OLD_SOUTH_ARABIAN: ::libc::c_int = 88;
pub const G_UNICODE_SCRIPT_OLD_TURKIC: ::libc::c_int = 89;
pub const G_UNICODE_SCRIPT_SAMARITAN: ::libc::c_int = 90;
pub const G_UNICODE_SCRIPT_TAI_THAM: ::libc::c_int = 91;
pub const G_UNICODE_SCRIPT_TAI_VIET: ::libc::c_int = 92;
pub const G_UNICODE_SCRIPT_BATAK: ::libc::c_int = 93;
pub const G_UNICODE_SCRIPT_BRAHMI: ::libc::c_int = 94;
pub const G_UNICODE_SCRIPT_MANDAIC: ::libc::c_int = 95;
pub const G_UNICODE_SCRIPT_CHAKMA: ::libc::c_int = 96;
pub const G_UNICODE_SCRIPT_MEROITIC_CURSIVE: ::libc::c_int = 97;
pub const G_UNICODE_SCRIPT_MEROITIC_HIEROGLYPHS: ::libc::c_int = 98;
pub const G_UNICODE_SCRIPT_MIAO: ::libc::c_int = 99;
pub const G_UNICODE_SCRIPT_SHARADA: ::libc::c_int = 100;
pub const G_UNICODE_SCRIPT_SORA_SOMPENG: ::libc::c_int = 101;
pub const G_UNICODE_SCRIPT_TAKRI: ::libc::c_int = 102;
pub const G_UNICODE_SCRIPT_BASSA_VAH: ::libc::c_int = 103;
pub const G_UNICODE_SCRIPT_CAUCASIAN_ALBANIAN: ::libc::c_int = 104;
pub const G_UNICODE_SCRIPT_DUPLOYAN: ::libc::c_int = 105;
pub const G_UNICODE_SCRIPT_ELBASAN: ::libc::c_int = 106;
pub const G_UNICODE_SCRIPT_GRANTHA: ::libc::c_int = 107;
pub const G_UNICODE_SCRIPT_KHOJKI: ::libc::c_int = 108;
pub const G_UNICODE_SCRIPT_KHUDAWADI: ::libc::c_int = 109;
pub const G_UNICODE_SCRIPT_LINEAR_A: ::libc::c_int = 110;
pub const G_UNICODE_SCRIPT_MAHAJANI: ::libc::c_int = 111;
pub const G_UNICODE_SCRIPT_MANICHAEAN: ::libc::c_int = 112;
pub const G_UNICODE_SCRIPT_MENDE_KIKAKUI: ::libc::c_int = 113;
pub const G_UNICODE_SCRIPT_MODI: ::libc::c_int = 114;
pub const G_UNICODE_SCRIPT_MRO: ::libc::c_int = 115;
pub const G_UNICODE_SCRIPT_NABATAEAN: ::libc::c_int = 116;
pub const G_UNICODE_SCRIPT_OLD_NORTH_ARABIAN: ::libc::c_int = 117;
pub const G_UNICODE_SCRIPT_OLD_PERMIC: ::libc::c_int = 118;
pub const G_UNICODE_SCRIPT_PAHAWH_HMONG: ::libc::c_int = 119;
pub const G_UNICODE_SCRIPT_PALMYRENE: ::libc::c_int = 120;
pub const G_UNICODE_SCRIPT_PAU_CIN_HAU: ::libc::c_int = 121;
pub const G_UNICODE_SCRIPT_PSALTER_PAHLAVI: ::libc::c_int = 122;
pub const G_UNICODE_SCRIPT_SIDDHAM: ::libc::c_int = 123;
pub const G_UNICODE_SCRIPT_TIRHUTA: ::libc::c_int = 124;
pub const G_UNICODE_SCRIPT_WARANG_CITI: ::libc::c_int = 125;
pub type GUnicodeScript = Enum_Unnamed56;
pub type Enum_Unnamed57 = ::libc::c_uint;
pub const G_NORMALIZE_DEFAULT: ::libc::c_uint = 0;
pub const G_NORMALIZE_NFD: ::libc::c_uint = 0;
pub const G_NORMALIZE_DEFAULT_COMPOSE: ::libc::c_uint = 1;
pub const G_NORMALIZE_NFC: ::libc::c_uint = 1;
pub const G_NORMALIZE_ALL: ::libc::c_uint = 2;
pub const G_NORMALIZE_NFKD: ::libc::c_uint = 2;
pub const G_NORMALIZE_ALL_COMPOSE: ::libc::c_uint = 3;
pub const G_NORMALIZE_NFKC: ::libc::c_uint = 3;
pub type GNormalizeMode = Enum_Unnamed57;
pub type Enum_Unnamed58 = ::libc::c_uint;
pub const G_USER_DIRECTORY_DESKTOP: ::libc::c_uint = 0;
pub const G_USER_DIRECTORY_DOCUMENTS: ::libc::c_uint = 1;
pub const G_USER_DIRECTORY_DOWNLOAD: ::libc::c_uint = 2;
pub const G_USER_DIRECTORY_MUSIC: ::libc::c_uint = 3;
pub const G_USER_DIRECTORY_PICTURES: ::libc::c_uint = 4;
pub const G_USER_DIRECTORY_PUBLIC_SHARE: ::libc::c_uint = 5;
pub const G_USER_DIRECTORY_TEMPLATES: ::libc::c_uint = 6;
pub const G_USER_DIRECTORY_VIDEOS: ::libc::c_uint = 7;
pub const G_USER_N_DIRECTORIES: ::libc::c_uint = 8;
pub type GUserDirectory = Enum_Unnamed58;
pub type GDebugKey = Struct__GDebugKey;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GDebugKey {
pub key: *const gchar,
pub value: guint,
}
impl ::std::default::Default for Struct__GDebugKey {
fn default() -> Struct__GDebugKey { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed59 = ::libc::c_uint;
pub const G_FORMAT_SIZE_DEFAULT: ::libc::c_uint = 0;
pub const G_FORMAT_SIZE_LONG_FORMAT: ::libc::c_uint = 1;
pub const G_FORMAT_SIZE_IEC_UNITS: ::libc::c_uint = 2;
pub type GFormatSizeFlags = Enum_Unnamed59;
pub type GVoidFunc = ::std::option::Option<extern "C" fn()>;
pub type GString = Struct__GString;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GString {
pub _str: *mut gchar,
pub len: gsize,
pub allocated_len: gsize,
}
impl ::std::default::Default for Struct__GString {
fn default() -> Struct__GString { unsafe { ::std::mem::zeroed() } }
}
pub type GIOChannel = Struct__GIOChannel;
pub type GIOFuncs = Struct__GIOFuncs;
pub type Enum_Unnamed60 = ::libc::c_uint;
pub const G_IO_ERROR_NONE: ::libc::c_uint = 0;
pub const G_IO_ERROR_AGAIN: ::libc::c_uint = 1;
pub const G_IO_ERROR_INVAL: ::libc::c_uint = 2;
pub const G_IO_ERROR_UNKNOWN: ::libc::c_uint = 3;
pub type GIOError = Enum_Unnamed60;
pub type Enum_Unnamed61 = ::libc::c_uint;
pub const G_IO_CHANNEL_ERROR_FBIG: ::libc::c_uint = 0;
pub const G_IO_CHANNEL_ERROR_INVAL: ::libc::c_uint = 1;
pub const G_IO_CHANNEL_ERROR_IO: ::libc::c_uint = 2;
pub const G_IO_CHANNEL_ERROR_ISDIR: ::libc::c_uint = 3;
pub const G_IO_CHANNEL_ERROR_NOSPC: ::libc::c_uint = 4;
pub const G_IO_CHANNEL_ERROR_NXIO: ::libc::c_uint = 5;
pub const G_IO_CHANNEL_ERROR_OVERFLOW: ::libc::c_uint = 6;
pub const G_IO_CHANNEL_ERROR_PIPE: ::libc::c_uint = 7;
pub const G_IO_CHANNEL_ERROR_FAILED: ::libc::c_uint = 8;
pub type GIOChannelError = Enum_Unnamed61;
pub type Enum_Unnamed62 = ::libc::c_uint;
pub const G_IO_STATUS_ERROR: ::libc::c_uint = 0;
pub const G_IO_STATUS_NORMAL: ::libc::c_uint = 1;
pub const G_IO_STATUS_EOF: ::libc::c_uint = 2;
pub const G_IO_STATUS_AGAIN: ::libc::c_uint = 3;
pub type GIOStatus = Enum_Unnamed62;
pub type Enum_Unnamed63 = ::libc::c_uint;
pub const G_SEEK_CUR: ::libc::c_uint = 0;
pub const G_SEEK_SET: ::libc::c_uint = 1;
pub const G_SEEK_END: ::libc::c_uint = 2;
pub type GSeekType = Enum_Unnamed63;
pub type Enum_Unnamed64 = ::libc::c_uint;
pub const G_IO_FLAG_APPEND: ::libc::c_uint = 1;
pub const G_IO_FLAG_NONBLOCK: ::libc::c_uint = 2;
pub const G_IO_FLAG_IS_READABLE: ::libc::c_uint = 4;
pub const G_IO_FLAG_IS_WRITABLE: ::libc::c_uint = 8;
pub const G_IO_FLAG_IS_WRITEABLE: ::libc::c_uint = 8;
pub const G_IO_FLAG_IS_SEEKABLE: ::libc::c_uint = 16;
pub const G_IO_FLAG_MASK: ::libc::c_uint = 31;
pub const G_IO_FLAG_GET_MASK: ::libc::c_uint = 31;
pub const G_IO_FLAG_SET_MASK: ::libc::c_uint = 3;
pub type GIOFlags = Enum_Unnamed64;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GIOChannel {
pub ref_count: gint,
pub funcs: *mut GIOFuncs,
pub encoding: *mut gchar,
pub read_cd: GIConv,
pub write_cd: GIConv,
pub line_term: *mut gchar,
pub line_term_len: guint,
pub buf_size: gsize,
pub read_buf: *mut GString,
pub encoded_read_buf: *mut GString,
pub write_buf: *mut GString,
pub partial_write_buf: [gchar; 6u],
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub reserved1: gpointer,
pub reserved2: gpointer,
}
impl ::std::default::Default for Struct__GIOChannel {
fn default() -> Struct__GIOChannel { unsafe { ::std::mem::zeroed() } }
}
pub type GIOFunc =
::std::option::Option<extern "C" fn
(source: *mut GIOChannel,
condition: GIOCondition, data: gpointer)
-> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GIOFuncs {
pub io_read: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
buf: *mut gchar, count: gsize,
bytes_read: *mut gsize,
err: *mut *mut GError)
-> GIOStatus>,
pub io_write: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
buf: *const gchar, count: gsize,
bytes_written: *mut gsize,
err: *mut *mut GError)
-> GIOStatus>,
pub io_seek: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
offset: gint64, _type: GSeekType,
err: *mut *mut GError)
-> GIOStatus>,
pub io_close: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
err: *mut *mut GError)
-> GIOStatus>,
pub io_create_watch: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
condition: GIOCondition)
-> *mut GSource>,
pub io_free: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel)>,
pub io_set_flags: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
flags: GIOFlags,
err: *mut *mut GError)
-> GIOStatus>,
pub io_get_flags: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel)
-> GIOFlags>,
}
impl ::std::default::Default for Struct__GIOFuncs {
fn default() -> Struct__GIOFuncs { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed65 = ::libc::c_uint;
pub const G_KEY_FILE_ERROR_UNKNOWN_ENCODING: ::libc::c_uint = 0;
pub const G_KEY_FILE_ERROR_PARSE: ::libc::c_uint = 1;
pub const G_KEY_FILE_ERROR_NOT_FOUND: ::libc::c_uint = 2;
pub const G_KEY_FILE_ERROR_KEY_NOT_FOUND: ::libc::c_uint = 3;
pub const G_KEY_FILE_ERROR_GROUP_NOT_FOUND: ::libc::c_uint = 4;
pub const G_KEY_FILE_ERROR_INVALID_VALUE: ::libc::c_uint = 5;
pub type GKeyFileError = Enum_Unnamed65;
pub enum Struct__GKeyFile { }
pub type GKeyFile = Struct__GKeyFile;
pub type Enum_Unnamed66 = ::libc::c_uint;
pub const G_KEY_FILE_NONE: ::libc::c_uint = 0;
pub const G_KEY_FILE_KEEP_COMMENTS: ::libc::c_uint = 1;
pub const G_KEY_FILE_KEEP_TRANSLATIONS: ::libc::c_uint = 2;
pub type GKeyFileFlags = Enum_Unnamed66;
pub enum Struct__GMappedFile { }
pub type GMappedFile = Struct__GMappedFile;
pub type Enum_Unnamed67 = ::libc::c_uint;
pub const G_MARKUP_ERROR_BAD_UTF8: ::libc::c_uint = 0;
pub const G_MARKUP_ERROR_EMPTY: ::libc::c_uint = 1;
pub const G_MARKUP_ERROR_PARSE: ::libc::c_uint = 2;
pub const G_MARKUP_ERROR_UNKNOWN_ELEMENT: ::libc::c_uint = 3;
pub const G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE: ::libc::c_uint = 4;
pub const G_MARKUP_ERROR_INVALID_CONTENT: ::libc::c_uint = 5;
pub const G_MARKUP_ERROR_MISSING_ATTRIBUTE: ::libc::c_uint = 6;
pub type GMarkupError = Enum_Unnamed67;
pub type Enum_Unnamed68 = ::libc::c_uint;
pub const G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG: ::libc::c_uint = 1;
pub const G_MARKUP_TREAT_CDATA_AS_TEXT: ::libc::c_uint = 2;
pub const G_MARKUP_PREFIX_ERROR_POSITION: ::libc::c_uint = 4;
pub const G_MARKUP_IGNORE_QUALIFIED: ::libc::c_uint = 8;
pub type GMarkupParseFlags = Enum_Unnamed68;
pub enum Struct__GMarkupParseContext { }
pub type GMarkupParseContext = Struct__GMarkupParseContext;
pub type GMarkupParser = Struct__GMarkupParser;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GMarkupParser {
pub start_element: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
element_name: *const gchar,
attribute_names:
*mut *const gchar,
attribute_values:
*mut *const gchar,
user_data: gpointer,
error: *mut *mut GError)>,
pub end_element: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
element_name: *const gchar,
user_data: gpointer,
error: *mut *mut GError)>,
pub text: ::std::option::Option<extern "C" fn
(context: *mut GMarkupParseContext,
text: *const gchar, text_len: gsize,
user_data: gpointer,
error: *mut *mut GError)>,
pub passthrough: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
passthrough_text:
*const gchar,
text_len: gsize,
user_data: gpointer,
error: *mut *mut GError)>,
pub error: ::std::option::Option<extern "C" fn
(context: *mut GMarkupParseContext,
error: *mut GError,
user_data: gpointer)>,
}
impl ::std::default::Default for Struct__GMarkupParser {
fn default() -> Struct__GMarkupParser { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed69 = ::libc::c_uint;
pub const G_MARKUP_COLLECT_INVALID: ::libc::c_uint = 0;
pub const G_MARKUP_COLLECT_STRING: ::libc::c_uint = 1;
pub const G_MARKUP_COLLECT_STRDUP: ::libc::c_uint = 2;
pub const G_MARKUP_COLLECT_BOOLEAN: ::libc::c_uint = 3;
pub const G_MARKUP_COLLECT_TRISTATE: ::libc::c_uint = 4;
pub const G_MARKUP_COLLECT_OPTIONAL: ::libc::c_uint = 65536;
pub type GMarkupCollectType = Enum_Unnamed69;
pub type Enum_Unnamed70 = ::libc::c_int;
pub const G_LOG_FLAG_RECURSION: ::libc::c_int = 1;
pub const G_LOG_FLAG_FATAL: ::libc::c_int = 2;
pub const G_LOG_LEVEL_ERROR: ::libc::c_int = 4;
pub const G_LOG_LEVEL_CRITICAL: ::libc::c_int = 8;
pub const G_LOG_LEVEL_WARNING: ::libc::c_int = 16;
pub const G_LOG_LEVEL_MESSAGE: ::libc::c_int = 32;
pub const G_LOG_LEVEL_INFO: ::libc::c_int = 64;
pub const G_LOG_LEVEL_DEBUG: ::libc::c_int = 128;
pub const G_LOG_LEVEL_MASK: ::libc::c_int = -4;
pub type GLogLevelFlags = Enum_Unnamed70;
pub type GLogFunc =
::std::option::Option<extern "C" fn
(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar, user_data: gpointer)>;
pub type GPrintFunc =
::std::option::Option<extern "C" fn(string: *const gchar)>;
pub enum Struct__GOptionContext { }
pub type GOptionContext = Struct__GOptionContext;
pub enum Struct__GOptionGroup { }
pub type GOptionGroup = Struct__GOptionGroup;
pub type GOptionEntry = Struct__GOptionEntry;
pub type Enum_Unnamed71 = ::libc::c_uint;
pub const G_OPTION_FLAG_NONE: ::libc::c_uint = 0;
pub const G_OPTION_FLAG_HIDDEN: ::libc::c_uint = 1;
pub const G_OPTION_FLAG_IN_MAIN: ::libc::c_uint = 2;
pub const G_OPTION_FLAG_REVERSE: ::libc::c_uint = 4;
pub const G_OPTION_FLAG_NO_ARG: ::libc::c_uint = 8;
pub const G_OPTION_FLAG_FILENAME: ::libc::c_uint = 16;
pub const G_OPTION_FLAG_OPTIONAL_ARG: ::libc::c_uint = 32;
pub const G_OPTION_FLAG_NOALIAS: ::libc::c_uint = 64;
pub type GOptionFlags = Enum_Unnamed71;
pub type Enum_Unnamed72 = ::libc::c_uint;
pub const G_OPTION_ARG_NONE: ::libc::c_uint = 0;
pub const G_OPTION_ARG_STRING: ::libc::c_uint = 1;
pub const G_OPTION_ARG_INT: ::libc::c_uint = 2;
pub const G_OPTION_ARG_CALLBACK: ::libc::c_uint = 3;
pub const G_OPTION_ARG_FILENAME: ::libc::c_uint = 4;
pub const G_OPTION_ARG_STRING_ARRAY: ::libc::c_uint = 5;
pub const G_OPTION_ARG_FILENAME_ARRAY: ::libc::c_uint = 6;
pub const G_OPTION_ARG_DOUBLE: ::libc::c_uint = 7;
pub const G_OPTION_ARG_INT64: ::libc::c_uint = 8;
pub type GOptionArg = Enum_Unnamed72;
pub type GOptionArgFunc =
::std::option::Option<extern "C" fn
(option_name: *const gchar, value: *const gchar,
data: gpointer, error: *mut *mut GError)
-> gboolean>;
pub type GOptionParseFunc =
::std::option::Option<extern "C" fn
(context: *mut GOptionContext,
group: *mut GOptionGroup, data: gpointer,
error: *mut *mut GError) -> gboolean>;
pub type GOptionErrorFunc =
::std::option::Option<extern "C" fn
(context: *mut GOptionContext,
group: *mut GOptionGroup, data: gpointer,
error: *mut *mut GError)>;
pub type Enum_Unnamed73 = ::libc::c_uint;
pub const G_OPTION_ERROR_UNKNOWN_OPTION: ::libc::c_uint = 0;
pub const G_OPTION_ERROR_BAD_VALUE: ::libc::c_uint = 1;
pub const G_OPTION_ERROR_FAILED: ::libc::c_uint = 2;
pub type GOptionError = Enum_Unnamed73;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GOptionEntry {
pub long_name: *const gchar,
pub short_name: gchar,
pub flags: gint,
pub arg: GOptionArg,
pub arg_data: gpointer,
pub description: *const gchar,
pub arg_description: *const gchar,
}
impl ::std::default::Default for Struct__GOptionEntry {
fn default() -> Struct__GOptionEntry { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GPatternSpec { }
pub type GPatternSpec = Struct__GPatternSpec;
pub type GQueue = Struct__GQueue;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GQueue {
pub head: *mut GList,
pub tail: *mut GList,
pub length: guint,
}
impl ::std::default::Default for Struct__GQueue {
fn default() -> Struct__GQueue { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GRand { }
pub type GRand = Struct__GRand;
pub type Enum_Unnamed74 = ::libc::c_uint;
pub const G_REGEX_ERROR_COMPILE: ::libc::c_uint = 0;
pub const G_REGEX_ERROR_OPTIMIZE: ::libc::c_uint = 1;
pub const G_REGEX_ERROR_REPLACE: ::libc::c_uint = 2;
pub const G_REGEX_ERROR_MATCH: ::libc::c_uint = 3;
pub const G_REGEX_ERROR_INTERNAL: ::libc::c_uint = 4;
pub const G_REGEX_ERROR_STRAY_BACKSLASH: ::libc::c_uint = 101;
pub const G_REGEX_ERROR_MISSING_CONTROL_CHAR: ::libc::c_uint = 102;
pub const G_REGEX_ERROR_UNRECOGNIZED_ESCAPE: ::libc::c_uint = 103;
pub const G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER: ::libc::c_uint = 104;
pub const G_REGEX_ERROR_QUANTIFIER_TOO_BIG: ::libc::c_uint = 105;
pub const G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS: ::libc::c_uint = 106;
pub const G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS: ::libc::c_uint =
107;
pub const G_REGEX_ERROR_RANGE_OUT_OF_ORDER: ::libc::c_uint = 108;
pub const G_REGEX_ERROR_NOTHING_TO_REPEAT: ::libc::c_uint = 109;
pub const G_REGEX_ERROR_UNRECOGNIZED_CHARACTER: ::libc::c_uint = 112;
pub const G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS: ::libc::c_uint = 113;
pub const G_REGEX_ERROR_UNMATCHED_PARENTHESIS: ::libc::c_uint = 114;
pub const G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE: ::libc::c_uint = 115;
pub const G_REGEX_ERROR_UNTERMINATED_COMMENT: ::libc::c_uint = 118;
pub const G_REGEX_ERROR_EXPRESSION_TOO_LARGE: ::libc::c_uint = 120;
pub const G_REGEX_ERROR_MEMORY_ERROR: ::libc::c_uint = 121;
pub const G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND: ::libc::c_uint = 125;
pub const G_REGEX_ERROR_MALFORMED_CONDITION: ::libc::c_uint = 126;
pub const G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES: ::libc::c_uint = 127;
pub const G_REGEX_ERROR_ASSERTION_EXPECTED: ::libc::c_uint = 128;
pub const G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME: ::libc::c_uint = 130;
pub const G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED: ::libc::c_uint
=
131;
pub const G_REGEX_ERROR_HEX_CODE_TOO_LARGE: ::libc::c_uint = 134;
pub const G_REGEX_ERROR_INVALID_CONDITION: ::libc::c_uint = 135;
pub const G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND: ::libc::c_uint = 136;
pub const G_REGEX_ERROR_INFINITE_LOOP: ::libc::c_uint = 140;
pub const G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR: ::libc::c_uint =
142;
pub const G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME: ::libc::c_uint = 143;
pub const G_REGEX_ERROR_MALFORMED_PROPERTY: ::libc::c_uint = 146;
pub const G_REGEX_ERROR_UNKNOWN_PROPERTY: ::libc::c_uint = 147;
pub const G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG: ::libc::c_uint = 148;
pub const G_REGEX_ERROR_TOO_MANY_SUBPATTERNS: ::libc::c_uint = 149;
pub const G_REGEX_ERROR_INVALID_OCTAL_VALUE: ::libc::c_uint = 151;
pub const G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE: ::libc::c_uint = 154;
pub const G_REGEX_ERROR_DEFINE_REPETION: ::libc::c_uint = 155;
pub const G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS: ::libc::c_uint = 156;
pub const G_REGEX_ERROR_MISSING_BACK_REFERENCE: ::libc::c_uint = 157;
pub const G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE: ::libc::c_uint = 158;
pub const G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
::libc::c_uint =
159;
pub const G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB: ::libc::c_uint =
160;
pub const G_REGEX_ERROR_NUMBER_TOO_BIG: ::libc::c_uint = 161;
pub const G_REGEX_ERROR_MISSING_SUBPATTERN_NAME: ::libc::c_uint = 162;
pub const G_REGEX_ERROR_MISSING_DIGIT: ::libc::c_uint = 163;
pub const G_REGEX_ERROR_INVALID_DATA_CHARACTER: ::libc::c_uint = 164;
pub const G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME: ::libc::c_uint = 165;
pub const G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
::libc::c_uint =
166;
pub const G_REGEX_ERROR_INVALID_CONTROL_CHAR: ::libc::c_uint = 168;
pub const G_REGEX_ERROR_MISSING_NAME: ::libc::c_uint = 169;
pub const G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS: ::libc::c_uint = 171;
pub const G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES: ::libc::c_uint = 172;
pub const G_REGEX_ERROR_NAME_TOO_LONG: ::libc::c_uint = 175;
pub const G_REGEX_ERROR_CHARACTER_VALUE_TOO_LARGE: ::libc::c_uint = 176;
pub type GRegexError = Enum_Unnamed74;
pub type Enum_Unnamed75 = ::libc::c_uint;
pub const G_REGEX_CASELESS: ::libc::c_uint = 1;
pub const G_REGEX_MULTILINE: ::libc::c_uint = 2;
pub const G_REGEX_DOTALL: ::libc::c_uint = 4;
pub const G_REGEX_EXTENDED: ::libc::c_uint = 8;
pub const G_REGEX_ANCHORED: ::libc::c_uint = 16;
pub const G_REGEX_DOLLAR_ENDONLY: ::libc::c_uint = 32;
pub const G_REGEX_UNGREEDY: ::libc::c_uint = 512;
pub const G_REGEX_RAW: ::libc::c_uint = 2048;
pub const G_REGEX_NO_AUTO_CAPTURE: ::libc::c_uint = 4096;
pub const G_REGEX_OPTIMIZE: ::libc::c_uint = 8192;
pub const G_REGEX_FIRSTLINE: ::libc::c_uint = 262144;
pub const G_REGEX_DUPNAMES: ::libc::c_uint = 524288;
pub const G_REGEX_NEWLINE_CR: ::libc::c_uint = 1048576;
pub const G_REGEX_NEWLINE_LF: ::libc::c_uint = 2097152;
pub const G_REGEX_NEWLINE_CRLF: ::libc::c_uint = 3145728;
pub const G_REGEX_NEWLINE_ANYCRLF: ::libc::c_uint = 5242880;
pub const G_REGEX_BSR_ANYCRLF: ::libc::c_uint = 8388608;
pub const G_REGEX_JAVASCRIPT_COMPAT: ::libc::c_uint = 33554432;
pub type GRegexCompileFlags = Enum_Unnamed75;
pub type Enum_Unnamed76 = ::libc::c_uint;
pub const G_REGEX_MATCH_ANCHORED: ::libc::c_uint = 16;
pub const G_REGEX_MATCH_NOTBOL: ::libc::c_uint = 128;
pub const G_REGEX_MATCH_NOTEOL: ::libc::c_uint = 256;
pub const G_REGEX_MATCH_NOTEMPTY: ::libc::c_uint = 1024;
pub const G_REGEX_MATCH_PARTIAL: ::libc::c_uint = 32768;
pub const G_REGEX_MATCH_NEWLINE_CR: ::libc::c_uint = 1048576;
pub const G_REGEX_MATCH_NEWLINE_LF: ::libc::c_uint = 2097152;
pub const G_REGEX_MATCH_NEWLINE_CRLF: ::libc::c_uint = 3145728;
pub const G_REGEX_MATCH_NEWLINE_ANY: ::libc::c_uint = 4194304;
pub const G_REGEX_MATCH_NEWLINE_ANYCRLF: ::libc::c_uint = 5242880;
pub const G_REGEX_MATCH_BSR_ANYCRLF: ::libc::c_uint = 8388608;
pub const G_REGEX_MATCH_BSR_ANY: ::libc::c_uint = 16777216;
pub const G_REGEX_MATCH_PARTIAL_SOFT: ::libc::c_uint = 32768;
pub const G_REGEX_MATCH_PARTIAL_HARD: ::libc::c_uint = 134217728;
pub const G_REGEX_MATCH_NOTEMPTY_ATSTART: ::libc::c_uint = 268435456;
pub type GRegexMatchFlags = Enum_Unnamed76;
pub enum Struct__GRegex { }
pub type GRegex = Struct__GRegex;
pub enum Struct__GMatchInfo { }
pub type GMatchInfo = Struct__GMatchInfo;
pub type GRegexEvalCallback =
::std::option::Option<extern "C" fn
(match_info: *const GMatchInfo,
result: *mut GString, user_data: gpointer)
-> gboolean>;
pub type GScanner = Struct__GScanner;
pub type GScannerConfig = Struct__GScannerConfig;
pub type GTokenValue = Union__GTokenValue;
pub type GScannerMsgFunc =
::std::option::Option<extern "C" fn
(scanner: *mut GScanner, message: *mut gchar,
error: gboolean)>;
pub type Enum_Unnamed77 = ::libc::c_uint;
pub const G_ERR_UNKNOWN: ::libc::c_uint = 0;
pub const G_ERR_UNEXP_EOF: ::libc::c_uint = 1;
pub const G_ERR_UNEXP_EOF_IN_STRING: ::libc::c_uint = 2;
pub const G_ERR_UNEXP_EOF_IN_COMMENT: ::libc::c_uint = 3;
pub const G_ERR_NON_DIGIT_IN_CONST: ::libc::c_uint = 4;
pub const G_ERR_DIGIT_RADIX: ::libc::c_uint = 5;
pub const G_ERR_FLOAT_RADIX: ::libc::c_uint = 6;
pub const G_ERR_FLOAT_MALFORMED: ::libc::c_uint = 7;
pub type GErrorType = Enum_Unnamed77;
pub type Enum_Unnamed78 = ::libc::c_uint;
pub const G_TOKEN_EOF: ::libc::c_uint = 0;
pub const G_TOKEN_LEFT_PAREN: ::libc::c_uint = 40;
pub const G_TOKEN_RIGHT_PAREN: ::libc::c_uint = 41;
pub const G_TOKEN_LEFT_CURLY: ::libc::c_uint = 123;
pub const G_TOKEN_RIGHT_CURLY: ::libc::c_uint = 125;
pub const G_TOKEN_LEFT_BRACE: ::libc::c_uint = 91;
pub const G_TOKEN_RIGHT_BRACE: ::libc::c_uint = 93;
pub const G_TOKEN_EQUAL_SIGN: ::libc::c_uint = 61;
pub const G_TOKEN_COMMA: ::libc::c_uint = 44;
pub const G_TOKEN_NONE: ::libc::c_uint = 256;
pub const G_TOKEN_ERROR: ::libc::c_uint = 257;
pub const G_TOKEN_CHAR: ::libc::c_uint = 258;
pub const G_TOKEN_BINARY: ::libc::c_uint = 259;
pub const G_TOKEN_OCTAL: ::libc::c_uint = 260;
pub const G_TOKEN_INT: ::libc::c_uint = 261;
pub const G_TOKEN_HEX: ::libc::c_uint = 262;
pub const G_TOKEN_FLOAT: ::libc::c_uint = 263;
pub const G_TOKEN_STRING: ::libc::c_uint = 264;
pub const G_TOKEN_SYMBOL: ::libc::c_uint = 265;
pub const G_TOKEN_IDENTIFIER: ::libc::c_uint = 266;
pub const G_TOKEN_IDENTIFIER_NULL: ::libc::c_uint = 267;
pub const G_TOKEN_COMMENT_SINGLE: ::libc::c_uint = 268;
pub const G_TOKEN_COMMENT_MULTI: ::libc::c_uint = 269;
pub const G_TOKEN_LAST: ::libc::c_uint = 270;
pub type GTokenType = Enum_Unnamed78;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GTokenValue {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GTokenValue {
pub unsafe fn v_symbol(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_identifier(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_binary(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_octal(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int64(&mut self) -> *mut guint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_float(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_hex(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_string(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_comment(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_char(&mut self) -> *mut guchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_error(&mut self) -> *mut guint {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GTokenValue {
fn default() -> Union__GTokenValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GScannerConfig {
pub cset_skip_characters: *mut gchar,
pub cset_identifier_first: *mut gchar,
pub cset_identifier_nth: *mut gchar,
pub cpair_comment_single: *mut gchar,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub _bindgen_bitfield_7_: guint,
pub _bindgen_bitfield_8_: guint,
pub _bindgen_bitfield_9_: guint,
pub _bindgen_bitfield_10_: guint,
pub _bindgen_bitfield_11_: guint,
pub _bindgen_bitfield_12_: guint,
pub _bindgen_bitfield_13_: guint,
pub _bindgen_bitfield_14_: guint,
pub _bindgen_bitfield_15_: guint,
pub _bindgen_bitfield_16_: guint,
pub _bindgen_bitfield_17_: guint,
pub _bindgen_bitfield_18_: guint,
pub _bindgen_bitfield_19_: guint,
pub _bindgen_bitfield_20_: guint,
pub _bindgen_bitfield_21_: guint,
pub _bindgen_bitfield_22_: guint,
pub padding_dummy: guint,
}
impl ::std::default::Default for Struct__GScannerConfig {
fn default() -> Struct__GScannerConfig { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GScanner {
pub user_data: gpointer,
pub max_parse_errors: guint,
pub parse_errors: guint,
pub input_name: *const gchar,
pub qdata: *mut GData,
pub config: *mut GScannerConfig,
pub token: GTokenType,
pub value: GTokenValue,
pub line: guint,
pub position: guint,
pub next_token: GTokenType,
pub next_value: GTokenValue,
pub next_line: guint,
pub next_position: guint,
pub symbol_table: *mut GHashTable,
pub input_fd: gint,
pub text: *const gchar,
pub text_end: *const gchar,
pub buffer: *mut gchar,
pub scope_id: guint,
pub msg_handler: GScannerMsgFunc,
}
impl ::std::default::Default for Struct__GScanner {
fn default() -> Struct__GScanner { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GSequence { }
pub type GSequence = Struct__GSequence;
pub enum Struct__GSequenceNode { }
pub type GSequenceIter = Struct__GSequenceNode;
pub type GSequenceIterCompareFunc =
::std::option::Option<extern "C" fn
(a: *mut GSequenceIter, b: *mut GSequenceIter,
data: gpointer) -> gint>;
pub type Enum_Unnamed79 = ::libc::c_uint;
pub const G_SHELL_ERROR_BAD_QUOTING: ::libc::c_uint = 0;
pub const G_SHELL_ERROR_EMPTY_STRING: ::libc::c_uint = 1;
pub const G_SHELL_ERROR_FAILED: ::libc::c_uint = 2;
pub type GShellError = Enum_Unnamed79;
pub type Enum_Unnamed80 = ::libc::c_uint;
pub const G_SLICE_CONFIG_ALWAYS_MALLOC: ::libc::c_uint = 1;
pub const G_SLICE_CONFIG_BYPASS_MAGAZINES: ::libc::c_uint = 2;
pub const G_SLICE_CONFIG_WORKING_SET_MSECS: ::libc::c_uint = 3;
pub const G_SLICE_CONFIG_COLOR_INCREMENT: ::libc::c_uint = 4;
pub const G_SLICE_CONFIG_CHUNK_SIZES: ::libc::c_uint = 5;
pub const G_SLICE_CONFIG_CONTENTION_COUNTER: ::libc::c_uint = 6;
pub type GSliceConfig = Enum_Unnamed80;
pub type Enum_Unnamed81 = ::libc::c_uint;
pub const G_SPAWN_ERROR_FORK: ::libc::c_uint = 0;
pub const G_SPAWN_ERROR_READ: ::libc::c_uint = 1;
pub const G_SPAWN_ERROR_CHDIR: ::libc::c_uint = 2;
pub const G_SPAWN_ERROR_ACCES: ::libc::c_uint = 3;
pub const G_SPAWN_ERROR_PERM: ::libc::c_uint = 4;
pub const G_SPAWN_ERROR_TOO_BIG: ::libc::c_uint = 5;
pub const G_SPAWN_ERROR_2BIG: ::libc::c_uint = 5;
pub const G_SPAWN_ERROR_NOEXEC: ::libc::c_uint = 6;
pub const G_SPAWN_ERROR_NAMETOOLONG: ::libc::c_uint = 7;
pub const G_SPAWN_ERROR_NOENT: ::libc::c_uint = 8;
pub const G_SPAWN_ERROR_NOMEM: ::libc::c_uint = 9;
pub const G_SPAWN_ERROR_NOTDIR: ::libc::c_uint = 10;
pub const G_SPAWN_ERROR_LOOP: ::libc::c_uint = 11;
pub const G_SPAWN_ERROR_TXTBUSY: ::libc::c_uint = 12;
pub const G_SPAWN_ERROR_IO: ::libc::c_uint = 13;
pub const G_SPAWN_ERROR_NFILE: ::libc::c_uint = 14;
pub const G_SPAWN_ERROR_MFILE: ::libc::c_uint = 15;
pub const G_SPAWN_ERROR_INVAL: ::libc::c_uint = 16;
pub const G_SPAWN_ERROR_ISDIR: ::libc::c_uint = 17;
pub const G_SPAWN_ERROR_LIBBAD: ::libc::c_uint = 18;
pub const G_SPAWN_ERROR_FAILED: ::libc::c_uint = 19;
pub type GSpawnError = Enum_Unnamed81;
pub type GSpawnChildSetupFunc =
::std::option::Option<extern "C" fn(user_data: gpointer)>;
pub type Enum_Unnamed82 = ::libc::c_uint;
pub const G_SPAWN_DEFAULT: ::libc::c_uint = 0;
pub const G_SPAWN_LEAVE_DESCRIPTORS_OPEN: ::libc::c_uint = 1;
pub const G_SPAWN_DO_NOT_REAP_CHILD: ::libc::c_uint = 2;
pub const G_SPAWN_SEARCH_PATH: ::libc::c_uint = 4;
pub const G_SPAWN_STDOUT_TO_DEV_NULL: ::libc::c_uint = 8;
pub const G_SPAWN_STDERR_TO_DEV_NULL: ::libc::c_uint = 16;
pub const G_SPAWN_CHILD_INHERITS_STDIN: ::libc::c_uint = 32;
pub const G_SPAWN_FILE_AND_ARGV_ZERO: ::libc::c_uint = 64;
pub const G_SPAWN_SEARCH_PATH_FROM_ENVP: ::libc::c_uint = 128;
pub const G_SPAWN_CLOEXEC_PIPES: ::libc::c_uint = 256;
pub type GSpawnFlags = Enum_Unnamed82;
pub type Enum_Unnamed83 = ::libc::c_uint;
pub const G_ASCII_ALNUM: ::libc::c_uint = 1;
pub const G_ASCII_ALPHA: ::libc::c_uint = 2;
pub const G_ASCII_CNTRL: ::libc::c_uint = 4;
pub const G_ASCII_DIGIT: ::libc::c_uint = 8;
pub const G_ASCII_GRAPH: ::libc::c_uint = 16;
pub const G_ASCII_LOWER: ::libc::c_uint = 32;
pub const G_ASCII_PRINT: ::libc::c_uint = 64;
pub const G_ASCII_PUNCT: ::libc::c_uint = 128;
pub const G_ASCII_SPACE: ::libc::c_uint = 256;
pub const G_ASCII_UPPER: ::libc::c_uint = 512;
pub const G_ASCII_XDIGIT: ::libc::c_uint = 1024;
pub type GAsciiType = Enum_Unnamed83;
pub enum Struct__GStringChunk { }
pub type GStringChunk = Struct__GStringChunk;
pub enum Struct_GTestCase { }
pub type GTestCase = Struct_GTestCase;
pub enum Struct_GTestSuite { }
pub type GTestSuite = Struct_GTestSuite;
pub type GTestFunc = ::std::option::Option<extern "C" fn()>;
pub type GTestDataFunc =
::std::option::Option<extern "C" fn(user_data: gconstpointer)>;
pub type GTestFixtureFunc =
::std::option::Option<extern "C" fn
(fixture: gpointer, user_data: gconstpointer)>;
pub type Enum_Unnamed84 = ::libc::c_uint;
pub const G_TEST_TRAP_SILENCE_STDOUT: ::libc::c_uint = 128;
pub const G_TEST_TRAP_SILENCE_STDERR: ::libc::c_uint = 256;
pub const G_TEST_TRAP_INHERIT_STDIN: ::libc::c_uint = 512;
pub type GTestTrapFlags = Enum_Unnamed84;
pub type Enum_Unnamed85 = ::libc::c_uint;
pub const G_TEST_SUBPROCESS_INHERIT_STDIN: ::libc::c_uint = 1;
pub const G_TEST_SUBPROCESS_INHERIT_STDOUT: ::libc::c_uint = 2;
pub const G_TEST_SUBPROCESS_INHERIT_STDERR: ::libc::c_uint = 4;
pub type GTestSubprocessFlags = Enum_Unnamed85;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed86 {
pub test_initialized: gboolean,
pub test_quick: gboolean,
pub test_perf: gboolean,
pub test_verbose: gboolean,
pub test_quiet: gboolean,
pub test_undefined: gboolean,
}
impl ::std::default::Default for Struct_Unnamed86 {
fn default() -> Struct_Unnamed86 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestConfig = Struct_Unnamed86;
pub type Enum_Unnamed87 = ::libc::c_uint;
pub const G_TEST_LOG_NONE: ::libc::c_uint = 0;
pub const G_TEST_LOG_ERROR: ::libc::c_uint = 1;
pub const G_TEST_LOG_START_BINARY: ::libc::c_uint = 2;
pub const G_TEST_LOG_LIST_CASE: ::libc::c_uint = 3;
pub const G_TEST_LOG_SKIP_CASE: ::libc::c_uint = 4;
pub const G_TEST_LOG_START_CASE: ::libc::c_uint = 5;
pub const G_TEST_LOG_STOP_CASE: ::libc::c_uint = 6;
pub const G_TEST_LOG_MIN_RESULT: ::libc::c_uint = 7;
pub const G_TEST_LOG_MAX_RESULT: ::libc::c_uint = 8;
pub const G_TEST_LOG_MESSAGE: ::libc::c_uint = 9;
pub const G_TEST_LOG_START_SUITE: ::libc::c_uint = 10;
pub const G_TEST_LOG_STOP_SUITE: ::libc::c_uint = 11;
pub type GTestLogType = Enum_Unnamed87;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed88 {
pub log_type: GTestLogType,
pub n_strings: guint,
pub strings: *mut *mut gchar,
pub n_nums: guint,
pub nums: *mut ::libc::c_double,
}
impl ::std::default::Default for Struct_Unnamed88 {
fn default() -> Struct_Unnamed88 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestLogMsg = Struct_Unnamed88;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed89 {
pub data: *mut GString,
pub msgs: *mut GSList,
}
impl ::std::default::Default for Struct_Unnamed89 {
fn default() -> Struct_Unnamed89 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestLogBuffer = Struct_Unnamed89;
pub type GTestLogFatalFunc =
::std::option::Option<extern "C" fn
(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed90 = ::libc::c_uint;
pub const G_TEST_DIST: ::libc::c_uint = 0;
pub const G_TEST_BUILT: ::libc::c_uint = 1;
pub type GTestFileType = Enum_Unnamed90;
pub type GThreadPool = Struct__GThreadPool;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThreadPool {
pub func: GFunc,
pub user_data: gpointer,
pub exclusive: gboolean,
}
impl ::std::default::Default for Struct__GThreadPool {
fn default() -> Struct__GThreadPool { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTimer { }
pub type GTimer = Struct__GTimer;
pub type GTrashStack = Struct__GTrashStack;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTrashStack {
pub next: *mut GTrashStack,
}
impl ::std::default::Default for Struct__GTrashStack {
fn default() -> Struct__GTrashStack { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTree { }
pub type GTree = Struct__GTree;
pub type GTraverseFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer, data: gpointer)
-> gboolean>;
pub enum Struct__GVariantType { }
pub type GVariantType = Struct__GVariantType;
pub enum Struct__GVariant { }
pub type GVariant = Struct__GVariant;
pub type Enum_Unnamed91 = ::libc::c_uint;
pub const G_VARIANT_CLASS_BOOLEAN: ::libc::c_uint = 98;
pub const G_VARIANT_CLASS_BYTE: ::libc::c_uint = 121;
pub const G_VARIANT_CLASS_INT16: ::libc::c_uint = 110;
pub const G_VARIANT_CLASS_UINT16: ::libc::c_uint = 113;
pub const G_VARIANT_CLASS_INT32: ::libc::c_uint = 105;
pub const G_VARIANT_CLASS_UINT32: ::libc::c_uint = 117;
pub const G_VARIANT_CLASS_INT64: ::libc::c_uint = 120;
pub const G_VARIANT_CLASS_UINT64: ::libc::c_uint = 116;
pub const G_VARIANT_CLASS_HANDLE: ::libc::c_uint = 104;
pub const G_VARIANT_CLASS_DOUBLE: ::libc::c_uint = 100;
pub const G_VARIANT_CLASS_STRING: ::libc::c_uint = 115;
pub const G_VARIANT_CLASS_OBJECT_PATH: ::libc::c_uint = 111;
pub const G_VARIANT_CLASS_SIGNATURE: ::libc::c_uint = 103;
pub const G_VARIANT_CLASS_VARIANT: ::libc::c_uint = 118;
pub const G_VARIANT_CLASS_MAYBE: ::libc::c_uint = 109;
pub const G_VARIANT_CLASS_ARRAY: ::libc::c_uint = 97;
pub const G_VARIANT_CLASS_TUPLE: ::libc::c_uint = 40;
pub const G_VARIANT_CLASS_DICT_ENTRY: ::libc::c_uint = 123;
pub type GVariantClass = Enum_Unnamed91;
pub type GVariantIter = Struct__GVariantIter;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantIter {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantIter {
fn default() -> Struct__GVariantIter { unsafe { ::std::mem::zeroed() } }
}
pub type GVariantBuilder = Struct__GVariantBuilder;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantBuilder {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantBuilder {
fn default() -> Struct__GVariantBuilder {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed92 = ::libc::c_uint;
pub const G_VARIANT_PARSE_ERROR_FAILED: ::libc::c_uint = 0;
pub const G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED: ::libc::c_uint = 1;
pub const G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE: ::libc::c_uint = 2;
pub const G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED: ::libc::c_uint = 3;
pub const G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END: ::libc::c_uint = 4;
pub const G_VARIANT_PARSE_ERROR_INVALID_CHARACTER: ::libc::c_uint = 5;
pub const G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING: ::libc::c_uint = 6;
pub const G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH: ::libc::c_uint = 7;
pub const G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE: ::libc::c_uint = 8;
pub const G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING: ::libc::c_uint = 9;
pub const G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE: ::libc::c_uint = 10;
pub const G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE: ::libc::c_uint = 11;
pub const G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG: ::libc::c_uint = 12;
pub const G_VARIANT_PARSE_ERROR_TYPE_ERROR: ::libc::c_uint = 13;
pub const G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN: ::libc::c_uint = 14;
pub const G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD: ::libc::c_uint = 15;
pub const G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT: ::libc::c_uint =
16;
pub const G_VARIANT_PARSE_ERROR_VALUE_EXPECTED: ::libc::c_uint = 17;
pub type GVariantParseError = Enum_Unnamed92;
pub type GVariantDict = Struct__GVariantDict;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantDict {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantDict {
fn default() -> Struct__GVariantDict { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GAllocator { }
pub type GAllocator = Struct__GAllocator;
pub enum Struct__GMemChunk { }
pub type GMemChunk = Struct__GMemChunk;
pub enum Struct__GCache { }
pub type GCache = Struct__GCache;
pub type GCacheNewFunc =
::std::option::Option<extern "C" fn(key: gpointer) -> gpointer>;
pub type GCacheDupFunc =
::std::option::Option<extern "C" fn(value: gpointer) -> gpointer>;
pub type GCacheDestroyFunc =
::std::option::Option<extern "C" fn(value: gpointer)>;
pub type GCompletion = Struct__GCompletion;
pub type GCompletionFunc =
::std::option::Option<extern "C" fn(arg1: gpointer) -> *mut gchar>;
pub type GCompletionStrncmpFunc =
::std::option::Option<extern "C" fn
(s1: *const gchar, s2: *const gchar, n: gsize)
-> gint>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCompletion {
pub items: *mut GList,
pub func: GCompletionFunc,
pub prefix: *mut gchar,
pub cache: *mut GList,
pub strncmp_func: GCompletionStrncmpFunc,
}
impl ::std::default::Default for Struct__GCompletion {
fn default() -> Struct__GCompletion { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GRelation { }
pub type GRelation = Struct__GRelation;
pub type GTuples = Struct__GTuples;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTuples {
pub len: guint,
}
impl ::std::default::Default for Struct__GTuples {
fn default() -> Struct__GTuples { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed93 = ::libc::c_uint;
pub const G_THREAD_PRIORITY_LOW: ::libc::c_uint = 0;
pub const G_THREAD_PRIORITY_NORMAL: ::libc::c_uint = 1;
pub const G_THREAD_PRIORITY_HIGH: ::libc::c_uint = 2;
pub const G_THREAD_PRIORITY_URGENT: ::libc::c_uint = 3;
pub type GThreadPriority = Enum_Unnamed93;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThread {
pub func: GThreadFunc,
pub data: gpointer,
pub joinable: gboolean,
pub priority: GThreadPriority,
}
impl ::std::default::Default for Struct__GThread {
fn default() -> Struct__GThread { unsafe { ::std::mem::zeroed() } }
}
pub type GThreadFunctions = Struct__GThreadFunctions;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThreadFunctions {
pub mutex_new: ::std::option::Option<extern "C" fn() -> *mut GMutex>,
pub mutex_lock: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)>,
pub mutex_trylock: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)
-> gboolean>,
pub mutex_unlock: ::std::option::Option<extern "C" fn
(mutex: *mut GMutex)>,
pub mutex_free: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)>,
pub cond_new: ::std::option::Option<extern "C" fn() -> *mut GCond>,
pub cond_signal: ::std::option::Option<extern "C" fn(cond: *mut GCond)>,
pub cond_broadcast: ::std::option::Option<extern "C" fn
(cond: *mut GCond)>,
pub cond_wait: ::std::option::Option<extern "C" fn
(cond: *mut GCond,
mutex: *mut GMutex)>,
pub cond_timed_wait: ::std::option::Option<extern "C" fn
(cond: *mut GCond,
mutex: *mut GMutex,
end_time: *mut GTimeVal)
-> gboolean>,
pub cond_free: ::std::option::Option<extern "C" fn(cond: *mut GCond)>,
pub private_new: ::std::option::Option<extern "C" fn
(destructor: GDestroyNotify)
-> *mut GPrivate>,
pub private_get: ::std::option::Option<extern "C" fn
(private_key: *mut GPrivate)
-> gpointer>,
pub private_set: ::std::option::Option<extern "C" fn
(private_key: *mut GPrivate,
data: gpointer)>,
pub thread_create: ::std::option::Option<extern "C" fn
(func: GThreadFunc,
data: gpointer,
stack_size: gulong,
joinable: gboolean,
bound: gboolean,
priority: GThreadPriority,
thread: gpointer,
error: *mut *mut GError)>,
pub thread_yield: ::std::option::Option<extern "C" fn()>,
pub thread_join: ::std::option::Option<extern "C" fn(thread: gpointer)>,
pub thread_exit: ::std::option::Option<extern "C" fn()>,
pub thread_set_priority: ::std::option::Option<extern "C" fn
(thread: gpointer,
priority:
GThreadPriority)>,
pub thread_self: ::std::option::Option<extern "C" fn(thread: gpointer)>,
pub thread_equal: ::std::option::Option<extern "C" fn
(thread1: gpointer,
thread2: gpointer)
-> gboolean>,
}
impl ::std::default::Default for Struct__GThreadFunctions {
fn default() -> Struct__GThreadFunctions {
unsafe { ::std::mem::zeroed() }
}
}
pub type u_char = __u_char;
pub type u_short = __u_short;
pub type u_int = __u_int;
pub type u_long = __u_long;
pub type quad_t = __quad_t;
pub type u_quad_t = __u_quad_t;
pub type fsid_t = __fsid_t;
pub type loff_t = __loff_t;
pub type ino_t = __ino_t;
pub type dev_t = __dev_t;
pub type gid_t = __gid_t;
pub type mode_t = __mode_t;
pub type nlink_t = __nlink_t;
pub type off_t = __off_t;
pub type id_t = __id_t;
pub type ssize_t = __ssize_t;
pub type daddr_t = __daddr_t;
pub type caddr_t = __caddr_t;
pub type key_t = __key_t;
pub type ulong = ::libc::c_ulong;
pub type ushort = ::libc::c_ushort;
pub type _uint = ::libc::c_uint;
pub type int8_t = ::libc::c_char;
pub type int16_t = ::libc::c_short;
pub type int32_t = ::libc::c_int;
pub type int64_t = ::libc::c_long;
pub type u_int8_t = ::libc::c_uchar;
pub type u_int16_t = ::libc::c_ushort;
pub type u_int32_t = ::libc::c_uint;
pub type u_int64_t = ::libc::c_ulong;
pub type register_t = ::libc::c_long;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_timeval {
pub tv_sec: __time_t,
pub tv_usec: __suseconds_t,
}
impl ::std::default::Default for Struct_timeval {
fn default() -> Struct_timeval { unsafe { ::std::mem::zeroed() } }
}
pub type suseconds_t = __suseconds_t;
pub type __fd_mask = ::libc::c_long;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed94 {
pub __fds_bits: [__fd_mask; 16u],
}
impl ::std::default::Default for Struct_Unnamed94 {
fn default() -> Struct_Unnamed94 { unsafe { ::std::mem::zeroed() } }
}
pub type fd_set = Struct_Unnamed94;
pub type fd_mask = __fd_mask;
pub type blksize_t = __blksize_t;
pub type blkcnt_t = __blkcnt_t;
pub type fsblkcnt_t = __fsblkcnt_t;
pub type fsfilcnt_t = __fsfilcnt_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sched_param {
pub __sched_priority: ::libc::c_int,
}
impl ::std::default::Default for Struct_sched_param {
fn default() -> Struct_sched_param { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___sched_param {
pub __sched_priority: ::libc::c_int,
}
impl ::std::default::Default for Struct___sched_param {
fn default() -> Struct___sched_param { unsafe { ::std::mem::zeroed() } }
}
pub type __cpu_mask = ::libc::c_ulong;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed95 {
pub __bits: [__cpu_mask; 16u],
}
impl ::std::default::Default for Struct_Unnamed95 {
fn default() -> Struct_Unnamed95 { unsafe { ::std::mem::zeroed() } }
}
pub type cpu_set_t = Struct_Unnamed95;
pub type __jmp_buf = [::libc::c_long; 8u];
pub type Enum_Unnamed96 = ::libc::c_uint;
pub const PTHREAD_CREATE_JOINABLE: ::libc::c_uint = 0;
pub const PTHREAD_CREATE_DETACHED: ::libc::c_uint = 1;
pub type Enum_Unnamed97 = ::libc::c_uint;
pub const PTHREAD_MUTEX_TIMED_NP: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_RECURSIVE_NP: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ERRORCHECK_NP: ::libc::c_uint = 2;
pub const PTHREAD_MUTEX_ADAPTIVE_NP: ::libc::c_uint = 3;
pub const PTHREAD_MUTEX_NORMAL: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_RECURSIVE: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ERRORCHECK: ::libc::c_uint = 2;
pub const PTHREAD_MUTEX_DEFAULT: ::libc::c_uint = 0;
pub type Enum_Unnamed98 = ::libc::c_uint;
pub const PTHREAD_MUTEX_STALLED: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_STALLED_NP: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_ROBUST: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ROBUST_NP: ::libc::c_uint = 1;
pub type Enum_Unnamed99 = ::libc::c_uint;
pub const PTHREAD_PRIO_NONE: ::libc::c_uint = 0;
pub const PTHREAD_PRIO_INHERIT: ::libc::c_uint = 1;
pub const PTHREAD_PRIO_PROTECT: ::libc::c_uint = 2;
pub type Enum_Unnamed100 = ::libc::c_uint;
pub const PTHREAD_RWLOCK_PREFER_READER_NP: ::libc::c_uint = 0;
pub const PTHREAD_RWLOCK_PREFER_WRITER_NP: ::libc::c_uint = 1;
pub const PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP: ::libc::c_uint = 2;
pub const PTHREAD_RWLOCK_DEFAULT_NP: ::libc::c_uint = 0;
pub type Enum_Unnamed101 = ::libc::c_uint;
pub const PTHREAD_INHERIT_SCHED: ::libc::c_uint = 0;
pub const PTHREAD_EXPLICIT_SCHED: ::libc::c_uint = 1;
pub type Enum_Unnamed102 = ::libc::c_uint;
pub const PTHREAD_SCOPE_SYSTEM: ::libc::c_uint = 0;
pub const PTHREAD_SCOPE_PROCESS: ::libc::c_uint = 1;
pub type Enum_Unnamed103 = ::libc::c_uint;
pub const PTHREAD_PROCESS_PRIVATE: ::libc::c_uint = 0;
pub const PTHREAD_PROCESS_SHARED: ::libc::c_uint = 1;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__pthread_cleanup_buffer {
pub __routine: ::std::option::Option<extern "C" fn
(arg1: *mut ::libc::c_void)>,
pub __arg: *mut ::libc::c_void,
pub __canceltype: ::libc::c_int,
pub __prev: *mut Struct__pthread_cleanup_buffer,
}
impl ::std::default::Default for Struct__pthread_cleanup_buffer {
fn default() -> Struct__pthread_cleanup_buffer {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed104 = ::libc::c_uint;
pub const PTHREAD_CANCEL_ENABLE: ::libc::c_uint = 0;
pub const PTHREAD_CANCEL_DISABLE: ::libc::c_uint = 1;
pub type Enum_Unnamed105 = ::libc::c_uint;
pub const PTHREAD_CANCEL_DEFERRED: ::libc::c_uint = 0;
pub const PTHREAD_CANCEL_ASYNCHRONOUS: ::libc::c_uint = 1;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed106 {
pub __cancel_jmp_buf: [Struct_Unnamed107; 1u],
pub __pad: [*mut ::libc::c_void; 4u],
}
impl ::std::default::Default for Struct_Unnamed106 {
fn default() -> Struct_Unnamed106 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed107 {
pub __cancel_jmp_buf: __jmp_buf,
pub __mask_was_saved: ::libc::c_int,
}
impl ::std::default::Default for Struct_Unnamed107 {
fn default() -> Struct_Unnamed107 { unsafe { ::std::mem::zeroed() } }
}
pub type __pthread_unwind_buf_t = Struct_Unnamed106;
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_cleanup_frame {
pub __cancel_routine: ::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)>,
pub __cancel_arg: *mut ::libc::c_void,
pub __do_it: ::libc::c_int,
pub __cancel_type: ::libc::c_int,
}
impl ::std::default::Default for Struct___pthread_cleanup_frame {
fn default() -> Struct___pthread_cleanup_frame {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct___jmp_buf_tag { }
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed108 {
pub mutex: *mut GMutex,
pub unused: pthread_mutex_t,
}
impl ::std::default::Default for Struct_Unnamed108 {
fn default() -> Struct_Unnamed108 { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticMutex = Struct_Unnamed108;
pub type GStaticRecMutex = Struct__GStaticRecMutex;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticRecMutex {
pub mutex: GStaticMutex,
pub depth: guint,
pub unused: Union_Unnamed109,
}
impl ::std::default::Default for Struct__GStaticRecMutex {
fn default() -> Struct__GStaticRecMutex {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed109 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed109 {
pub unsafe fn owner(&mut self) -> *mut pthread_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn dummy(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed109 {
fn default() -> Union_Unnamed109 { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticRWLock = Struct__GStaticRWLock;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticRWLock {
pub mutex: GStaticMutex,
pub read_cond: *mut GCond,
pub write_cond: *mut GCond,
pub read_counter: guint,
pub have_writer: gboolean,
pub want_to_read: guint,
pub want_to_write: guint,
}
impl ::std::default::Default for Struct__GStaticRWLock {
fn default() -> Struct__GStaticRWLock { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticPrivate = Struct__GStaticPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticPrivate {
pub index: guint,
}
impl ::std::default::Default for Struct__GStaticPrivate {
fn default() -> Struct__GStaticPrivate { unsafe { ::std::mem::zeroed() } }
}
pub type GType = gsize;
pub type GValue = Struct__GValue;
pub enum Union__GTypeCValue { }
pub type GTypeCValue = Union__GTypeCValue;
pub enum Struct__GTypePlugin { }
pub type GTypePlugin = Struct__GTypePlugin;
pub type GTypeClass = Struct__GTypeClass;
pub type GTypeInterface = Struct__GTypeInterface;
pub type GTypeInstance = Struct__GTypeInstance;
pub type GTypeInfo = Struct__GTypeInfo;
pub type GTypeFundamentalInfo = Struct__GTypeFundamentalInfo;
pub type GInterfaceInfo = Struct__GInterfaceInfo;
pub type GTypeValueTable = Struct__GTypeValueTable;
pub type GTypeQuery = Struct__GTypeQuery;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeClass {
pub g_type: GType,
}
impl ::std::default::Default for Struct__GTypeClass {
fn default() -> Struct__GTypeClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInstance {
pub g_class: *mut GTypeClass,
}
impl ::std::default::Default for Struct__GTypeInstance {
fn default() -> Struct__GTypeInstance { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInterface {
pub g_type: GType,
pub g_instance_type: GType,
}
impl ::std::default::Default for Struct__GTypeInterface {
fn default() -> Struct__GTypeInterface { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeQuery {
pub _type: GType,
pub type_name: *const gchar,
pub class_size: guint,
pub instance_size: guint,
}
impl ::std::default::Default for Struct__GTypeQuery {
fn default() -> Struct__GTypeQuery { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed110 = ::libc::c_uint;
pub const G_TYPE_DEBUG_NONE: ::libc::c_uint = 0;
pub const G_TYPE_DEBUG_OBJECTS: ::libc::c_uint = 1;
pub const G_TYPE_DEBUG_SIGNALS: ::libc::c_uint = 2;
pub const G_TYPE_DEBUG_MASK: ::libc::c_uint = 3;
pub type GTypeDebugFlags = Enum_Unnamed110;
pub type GBaseInitFunc =
::std::option::Option<extern "C" fn(g_class: gpointer)>;
pub type GBaseFinalizeFunc =
::std::option::Option<extern "C" fn(g_class: gpointer)>;
pub type GClassInitFunc =
::std::option::Option<extern "C" fn
(g_class: gpointer, class_data: gpointer)>;
pub type GClassFinalizeFunc =
::std::option::Option<extern "C" fn
(g_class: gpointer, class_data: gpointer)>;
pub type GInstanceInitFunc =
::std::option::Option<extern "C" fn
(instance: *mut GTypeInstance,
g_class: gpointer)>;
pub type GInterfaceInitFunc =
::std::option::Option<extern "C" fn
(g_iface: gpointer, iface_data: gpointer)>;
pub type GInterfaceFinalizeFunc =
::std::option::Option<extern "C" fn
(g_iface: gpointer, iface_data: gpointer)>;
pub type GTypeClassCacheFunc =
::std::option::Option<extern "C" fn
(cache_data: gpointer, g_class: *mut GTypeClass)
-> gboolean>;
pub type GTypeInterfaceCheckFunc =
::std::option::Option<extern "C" fn
(check_data: gpointer, g_iface: gpointer)>;
pub type Enum_Unnamed111 = ::libc::c_uint;
pub const G_TYPE_FLAG_CLASSED: ::libc::c_uint = 1;
pub const G_TYPE_FLAG_INSTANTIATABLE: ::libc::c_uint = 2;
pub const G_TYPE_FLAG_DERIVABLE: ::libc::c_uint = 4;
pub const G_TYPE_FLAG_DEEP_DERIVABLE: ::libc::c_uint = 8;
pub type GTypeFundamentalFlags = Enum_Unnamed111;
pub type Enum_Unnamed112 = ::libc::c_uint;
pub const G_TYPE_FLAG_ABSTRACT: ::libc::c_uint = 16;
pub const G_TYPE_FLAG_VALUE_ABSTRACT: ::libc::c_uint = 32;
pub type GTypeFlags = Enum_Unnamed112;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInfo {
pub class_size: guint16,
pub base_init: GBaseInitFunc,
pub base_finalize: GBaseFinalizeFunc,
pub class_init: GClassInitFunc,
pub class_finalize: GClassFinalizeFunc,
pub class_data: gconstpointer,
pub instance_size: guint16,
pub n_preallocs: guint16,
pub instance_init: GInstanceInitFunc,
pub value_table: *const GTypeValueTable,
}
impl ::std::default::Default for Struct__GTypeInfo {
fn default() -> Struct__GTypeInfo { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeFundamentalInfo {
pub type_flags: GTypeFundamentalFlags,
}
impl ::std::default::Default for Struct__GTypeFundamentalInfo {
fn default() -> Struct__GTypeFundamentalInfo {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GInterfaceInfo {
pub interface_init: GInterfaceInitFunc,
pub interface_finalize: GInterfaceFinalizeFunc,
pub interface_data: gpointer,
}
impl ::std::default::Default for Struct__GInterfaceInfo {
fn default() -> Struct__GInterfaceInfo { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeValueTable {
pub value_init: ::std::option::Option<extern "C" fn(value: *mut GValue)>,
pub value_free: ::std::option::Option<extern "C" fn(value: *mut GValue)>,
pub value_copy: ::std::option::Option<extern "C" fn
(src_value: *const GValue,
dest_value: *mut GValue)>,
pub value_peek_pointer: ::std::option::Option<extern "C" fn
(value: *const GValue)
-> gpointer>,
pub collect_format: *const gchar,
pub collect_value: ::std::option::Option<extern "C" fn
(value: *mut GValue,
n_collect_values: guint,
collect_values:
*mut GTypeCValue,
collect_flags: guint)
-> *mut gchar>,
pub lcopy_format: *const gchar,
pub lcopy_value: ::std::option::Option<extern "C" fn
(value: *const GValue,
n_collect_values: guint,
collect_values:
*mut GTypeCValue,
collect_flags: guint)
-> *mut gchar>,
}
impl ::std::default::Default for Struct__GTypeValueTable {
fn default() -> Struct__GTypeValueTable {
unsafe { ::std::mem::zeroed() }
}
}
pub type GValueTransform =
::std::option::Option<extern "C" fn
(src_value: *const GValue,
dest_value: *mut GValue)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GValue {
pub g_type: GType,
pub data: [Union_Unnamed113; 2u],
}
impl ::std::default::Default for Struct__GValue {
fn default() -> Struct__GValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed113 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed113 {
pub unsafe fn v_int(&mut self) -> *mut gint {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_uint(&mut self) -> *mut guint {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_long(&mut self) -> *mut glong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_ulong(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int64(&mut self) -> *mut gint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_uint64(&mut self) -> *mut guint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_float(&mut self) -> *mut gfloat {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_double(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_pointer(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed113 {
fn default() -> Union_Unnamed113 { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed114 = ::libc::c_int;
pub const G_PARAM_READABLE: ::libc::c_int = 1;
pub const G_PARAM_WRITABLE: ::libc::c_int = 2;
pub const G_PARAM_READWRITE: ::libc::c_int = 3;
pub const G_PARAM_CONSTRUCT: ::libc::c_int = 4;
pub const G_PARAM_CONSTRUCT_ONLY: ::libc::c_int = 8;
pub const G_PARAM_LAX_VALIDATION: ::libc::c_int = 16;
pub const G_PARAM_STATIC_NAME: ::libc::c_int = 32;
pub const G_PARAM_PRIVATE: ::libc::c_int = 32;
pub const G_PARAM_STATIC_NICK: ::libc::c_int = 64;
pub const G_PARAM_STATIC_BLURB: ::libc::c_int = 128;
pub const G_PARAM_EXPLICIT_NOTIFY: ::libc::c_int = 1073741824;
pub const G_PARAM_DEPRECATED: ::libc::c_int = -2147483648;
pub type GParamFlags = Enum_Unnamed114;
pub type GParamSpec = Struct__GParamSpec;
pub type GParamSpecClass = Struct__GParamSpecClass;
pub type GParameter = Struct__GParameter;
pub enum Struct__GParamSpecPool { }
pub type GParamSpecPool = Struct__GParamSpecPool;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpec {
pub g_type_instance: GTypeInstance,
pub name: *const gchar,
pub flags: GParamFlags,
pub value_type: GType,
pub owner_type: GType,
pub _nick: *mut gchar,
pub _blurb: *mut gchar,
pub qdata: *mut GData,
pub ref_count: guint,
pub param_id: guint,
}
impl ::std::default::Default for Struct__GParamSpec {
fn default() -> Struct__GParamSpec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecClass {
pub g_type_class: GTypeClass,
pub value_type: GType,
pub finalize: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_set_default: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)>,
pub value_validate: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)
-> gboolean>,
pub values_cmp: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value1: *const GValue,
value2: *const GValue)
-> gint>,
pub dummy: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GParamSpecClass {
fn default() -> Struct__GParamSpecClass {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParameter {
pub name: *const gchar,
pub value: GValue,
}
impl ::std::default::Default for Struct__GParameter {
fn default() -> Struct__GParameter { unsafe { ::std::mem::zeroed() } }
}
pub type GParamSpecTypeInfo = Struct__GParamSpecTypeInfo;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecTypeInfo {
pub instance_size: guint16,
pub n_preallocs: guint16,
pub instance_init: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_type: GType,
pub finalize: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_set_default: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)>,
pub value_validate: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)
-> gboolean>,
pub values_cmp: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value1: *const GValue,
value2: *const GValue)
-> gint>,
}
impl ::std::default::Default for Struct__GParamSpecTypeInfo {
fn default() -> Struct__GParamSpecTypeInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type GClosure = Struct__GClosure;
pub type GClosureNotifyData = Struct__GClosureNotifyData;
pub type GCallback = ::std::option::Option<extern "C" fn()>;
pub type GClosureNotify =
::std::option::Option<extern "C" fn
(data: gpointer, closure: *mut GClosure)>;
pub type GClosureMarshal =
::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer)>;
pub type GVaClosureMarshal =
::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue, instance: gpointer,
args: va_list, marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType)>;
pub type GCClosure = Struct__GCClosure;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GClosureNotifyData {
pub data: gpointer,
pub notify: GClosureNotify,
}
impl ::std::default::Default for Struct__GClosureNotifyData {
fn default() -> Struct__GClosureNotifyData {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GClosure {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub _bindgen_bitfield_7_: guint,
pub _bindgen_bitfield_8_: guint,
pub _bindgen_bitfield_9_: guint,
pub _bindgen_bitfield_10_: guint,
pub marshal: ::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer)>,
pub data: gpointer,
pub notifiers: *mut GClosureNotifyData,
}
impl ::std::default::Default for Struct__GClosure {
fn default() -> Struct__GClosure { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCClosure {
pub closure: GClosure,
pub callback: gpointer,
}
impl ::std::default::Default for Struct__GCClosure {
fn default() -> Struct__GCClosure { unsafe { ::std::mem::zeroed() } }
}
pub type GSignalQuery = Struct__GSignalQuery;
pub type GSignalInvocationHint = Struct__GSignalInvocationHint;
pub type GSignalCMarshaller = GClosureMarshal;
pub type GSignalCVaMarshaller = GVaClosureMarshal;
pub type GSignalEmissionHook =
::std::option::Option<extern "C" fn
(ihint: *mut GSignalInvocationHint,
n_param_values: guint,
param_values: *const GValue, data: gpointer)
-> gboolean>;
pub type GSignalAccumulator =
::std::option::Option<extern "C" fn
(ihint: *mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue, data: gpointer)
-> gboolean>;
pub type Enum_Unnamed115 = ::libc::c_uint;
pub const G_SIGNAL_RUN_FIRST: ::libc::c_uint = 1;
pub const G_SIGNAL_RUN_LAST: ::libc::c_uint = 2;
pub const G_SIGNAL_RUN_CLEANUP: ::libc::c_uint = 4;
pub const G_SIGNAL_NO_RECURSE: ::libc::c_uint = 8;
pub const G_SIGNAL_DETAILED: ::libc::c_uint = 16;
pub const G_SIGNAL_ACTION: ::libc::c_uint = 32;
pub const G_SIGNAL_NO_HOOKS: ::libc::c_uint = 64;
pub const G_SIGNAL_MUST_COLLECT: ::libc::c_uint = 128;
pub const G_SIGNAL_DEPRECATED: ::libc::c_uint = 256;
pub type GSignalFlags = Enum_Unnamed115;
pub type Enum_Unnamed116 = ::libc::c_uint;
pub const G_CONNECT_AFTER: ::libc::c_uint = 1;
pub const G_CONNECT_SWAPPED: ::libc::c_uint = 2;
pub type GConnectFlags = Enum_Unnamed116;
pub type Enum_Unnamed117 = ::libc::c_uint;
pub const G_SIGNAL_MATCH_ID: ::libc::c_uint = 1;
pub const G_SIGNAL_MATCH_DETAIL: ::libc::c_uint = 2;
pub const G_SIGNAL_MATCH_CLOSURE: ::libc::c_uint = 4;
pub const G_SIGNAL_MATCH_FUNC: ::libc::c_uint = 8;
pub const G_SIGNAL_MATCH_DATA: ::libc::c_uint = 16;
pub const G_SIGNAL_MATCH_UNBLOCKED: ::libc::c_uint = 32;
pub type GSignalMatchType = Enum_Unnamed117;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSignalInvocationHint {
pub signal_id: guint,
pub detail: GQuark,
pub run_type: GSignalFlags,
}
impl ::std::default::Default for Struct__GSignalInvocationHint {
fn default() -> Struct__GSignalInvocationHint {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSignalQuery {
pub signal_id: guint,
pub signal_name: *const gchar,
pub itype: GType,
pub signal_flags: GSignalFlags,
pub return_type: GType,
pub n_params: guint,
pub param_types: *const GType,
}
impl ::std::default::Default for Struct__GSignalQuery {
fn default() -> Struct__GSignalQuery { unsafe { ::std::mem::zeroed() } }
}
pub type GStrv = *mut *mut gchar;
pub type GBoxedCopyFunc =
::std::option::Option<extern "C" fn(boxed: gpointer) -> gpointer>;
pub type GBoxedFreeFunc =
::std::option::Option<extern "C" fn(boxed: gpointer)>;
pub type GObject = Struct__GObject;
pub type GObjectClass = Struct__GObjectClass;
pub type GInitiallyUnowned = Struct__GObject;
pub type GInitiallyUnownedClass = Struct__GObjectClass;
pub type GObjectConstructParam = Struct__GObjectConstructParam;
pub type GObjectGetPropertyFunc =
::std::option::Option<extern "C" fn
(object: *mut GObject, property_id: guint,
value: *mut GValue, pspec: *mut GParamSpec)>;
pub type GObjectSetPropertyFunc =
::std::option::Option<extern "C" fn
(object: *mut GObject, property_id: guint,
value: *const GValue, pspec: *mut GParamSpec)>;
pub type GObjectFinalizeFunc =
::std::option::Option<extern "C" fn(object: *mut GObject)>;
pub type GWeakNotify =
::std::option::Option<extern "C" fn
(data: gpointer,
where_the_object_was: *mut GObject)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObject {
pub g_type_instance: GTypeInstance,
pub ref_count: guint,
pub qdata: *mut GData,
}
impl ::std::default::Default for Struct__GObject {
fn default() -> Struct__GObject { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObjectClass {
pub g_type_class: GTypeClass,
pub construct_properties: *mut GSList,
pub constructor: ::std::option::Option<extern "C" fn
(_type: GType,
n_construct_properties: guint,
construct_properties:
*mut GObjectConstructParam)
-> *mut GObject>,
pub set_property: ::std::option::Option<extern "C" fn
(object: *mut GObject,
property_id: guint,
value: *const GValue,
pspec: *mut GParamSpec)>,
pub get_property: ::std::option::Option<extern "C" fn
(object: *mut GObject,
property_id: guint,
value: *mut GValue,
pspec: *mut GParamSpec)>,
pub dispose: ::std::option::Option<extern "C" fn(object: *mut GObject)>,
pub finalize: ::std::option::Option<extern "C" fn(object: *mut GObject)>,
pub dispatch_properties_changed: ::std::option::Option<extern "C" fn
(object:
*mut GObject,
n_pspecs:
guint,
pspecs:
*mut *mut GParamSpec)>,
pub notify: ::std::option::Option<extern "C" fn
(object: *mut GObject,
pspec: *mut GParamSpec)>,
pub constructed: ::std::option::Option<extern "C" fn
(object: *mut GObject)>,
pub flags: gsize,
pub pdummy: [gpointer; 6u],
}
impl ::std::default::Default for Struct__GObjectClass {
fn default() -> Struct__GObjectClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObjectConstructParam {
pub pspec: *mut GParamSpec,
pub value: *mut GValue,
}
impl ::std::default::Default for Struct__GObjectConstructParam {
fn default() -> Struct__GObjectConstructParam {
unsafe { ::std::mem::zeroed() }
}
}
pub type GToggleNotify =
::std::option::Option<extern "C" fn
(data: gpointer, object: *mut GObject,
is_last_ref: gboolean)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed118 {
pub _priv: Union_Unnamed119,
}
impl ::std::default::Default for Struct_Unnamed118 {
fn default() -> Struct_Unnamed118 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed119 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed119 {
pub unsafe fn p(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed119 {
fn default() -> Union_Unnamed119 { unsafe { ::std::mem::zeroed() } }
}
pub type GWeakRef = Struct_Unnamed118;
pub enum Struct__GBinding { }
pub type GBinding = Struct__GBinding;
pub type GBindingTransformFunc =
::std::option::Option<extern "C" fn
(binding: *mut GBinding,
from_value: *const GValue,
to_value: *mut GValue, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed120 = ::libc::c_uint;
pub const G_BINDING_DEFAULT: ::libc::c_uint = 0;
pub const G_BINDING_BIDIRECTIONAL: ::libc::c_uint = 1;
pub const G_BINDING_SYNC_CREATE: ::libc::c_uint = 2;
pub const G_BINDING_INVERT_BOOLEAN: ::libc::c_uint = 4;
pub type GBindingFlags = Enum_Unnamed120;
pub type GEnumClass = Struct__GEnumClass;
pub type GFlagsClass = Struct__GFlagsClass;
pub type GEnumValue = Struct__GEnumValue;
pub type GFlagsValue = Struct__GFlagsValue;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GEnumClass {
pub g_type_class: GTypeClass,
pub minimum: gint,
pub maximum: gint,
pub n_values: guint,
pub values: *mut GEnumValue,
}
impl ::std::default::Default for Struct__GEnumClass {
fn default() -> Struct__GEnumClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GFlagsClass {
pub g_type_class: GTypeClass,
pub mask: guint,
pub n_values: guint,
pub values: *mut GFlagsValue,
}
impl ::std::default::Default for Struct__GFlagsClass {
fn default() -> Struct__GFlagsClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GEnumValue {
pub value: gint,
pub value_name: *const gchar,
pub value_nick: *const gchar,
}
impl ::std::default::Default for Struct__GEnumValue {
fn default() -> Struct__GEnumValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GFlagsValue {
pub value: guint,
pub value_name: *const gchar,
pub value_nick: *const gchar,
}
impl ::std::default::Default for Struct__GFlagsValue {
fn default() -> Struct__GFlagsValue { unsafe { ::std::mem::zeroed() } }
}
pub type GParamSpecChar = Struct__GParamSpecChar;
pub type GParamSpecUChar = Struct__GParamSpecUChar;
pub type GParamSpecBoolean = Struct__GParamSpecBoolean;
pub type GParamSpecInt = Struct__GParamSpecInt;
pub type GParamSpecUInt = Struct__GParamSpecUInt;
pub type GParamSpecLong = Struct__GParamSpecLong;
pub type GParamSpecULong = Struct__GParamSpecULong;
pub type GParamSpecInt64 = Struct__GParamSpecInt64;
pub type GParamSpecUInt64 = Struct__GParamSpecUInt64;
pub type GParamSpecUnichar = Struct__GParamSpecUnichar;
pub type GParamSpecEnum = Struct__GParamSpecEnum;
pub type GParamSpecFlags = Struct__GParamSpecFlags;
pub type GParamSpecFloat = Struct__GParamSpecFloat;
pub type GParamSpecDouble = Struct__GParamSpecDouble;
pub type GParamSpecString = Struct__GParamSpecString;
pub type GParamSpecParam = Struct__GParamSpecParam;
pub type GParamSpecBoxed = Struct__GParamSpecBoxed;
pub type GParamSpecPointer = Struct__GParamSpecPointer;
pub type GParamSpecValueArray = Struct__GParamSpecValueArray;
pub type GParamSpecObject = Struct__GParamSpecObject;
pub type GParamSpecOverride = Struct__GParamSpecOverride;
pub type GParamSpecGType = Struct__GParamSpecGType;
pub type GParamSpecVariant = Struct__GParamSpecVariant;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecChar {
pub parent_instance: GParamSpec,
pub minimum: gint8,
pub maximum: gint8,
pub default_value: gint8,
}
impl ::std::default::Default for Struct__GParamSpecChar {
fn default() -> Struct__GParamSpecChar { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUChar {
pub parent_instance: GParamSpec,
pub minimum: guint8,
pub maximum: guint8,
pub default_value: guint8,
}
impl ::std::default::Default for Struct__GParamSpecUChar {
fn default() -> Struct__GParamSpecUChar {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecBoolean {
pub parent_instance: GParamSpec,
pub default_value: gboolean,
}
impl ::std::default::Default for Struct__GParamSpecBoolean {
fn default() -> Struct__GParamSpecBoolean {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecInt {
pub parent_instance: GParamSpec,
pub minimum: gint,
pub maximum: gint,
pub default_value: gint,
}
impl ::std::default::Default for Struct__GParamSpecInt {
fn default() -> Struct__GParamSpecInt { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUInt {
pub parent_instance: GParamSpec,
pub minimum: guint,
pub maximum: guint,
pub default_value: guint,
}
impl ::std::default::Default for Struct__GParamSpecUInt {
fn default() -> Struct__GParamSpecUInt { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecLong {
pub parent_instance: GParamSpec,
pub minimum: glong,
pub maximum: glong,
pub default_value: glong,
}
impl ::std::default::Default for Struct__GParamSpecLong {
fn default() -> Struct__GParamSpecLong { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecULong {
pub parent_instance: GParamSpec,
pub minimum: gulong,
pub maximum: gulong,
pub default_value: gulong,
}
impl ::std::default::Default for Struct__GParamSpecULong {
fn default() -> Struct__GParamSpecULong {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecInt64 {
pub parent_instance: GParamSpec,
pub minimum: gint64,
pub maximum: gint64,
pub default_value: gint64,
}
impl ::std::default::Default for Struct__GParamSpecInt64 {
fn default() -> Struct__GParamSpecInt64 {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUInt64 {
pub parent_instance: GParamSpec,
pub minimum: guint64,
pub maximum: guint64,
pub default_value: guint64,
}
impl ::std::default::Default for Struct__GParamSpecUInt64 {
fn default() -> Struct__GParamSpecUInt64 {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUnichar {
pub parent_instance: GParamSpec,
pub default_value: gunichar,
}
impl ::std::default::Default for Struct__GParamSpecUnichar {
fn default() -> Struct__GParamSpecUnichar {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecEnum {
pub parent_instance: GParamSpec,
pub enum_class: *mut GEnumClass,
pub default_value: gint,
}
impl ::std::default::Default for Struct__GParamSpecEnum {
fn default() -> Struct__GParamSpecEnum { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecFlags {
pub parent_instance: GParamSpec,
pub flags_class: *mut GFlagsClass,
pub default_value: guint,
}
impl ::std::default::Default for Struct__GParamSpecFlags {
fn default() -> Struct__GParamSpecFlags {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecFloat {
pub parent_instance: GParamSpec,
pub minimum: gfloat,
pub maximum: gfloat,
pub default_value: gfloat,
pub epsilon: gfloat,
}
impl ::std::default::Default for Struct__GParamSpecFloat {
fn default() -> Struct__GParamSpecFloat {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecDouble {
pub parent_instance: GParamSpec,
pub minimum: gdouble,
pub maximum: gdouble,
pub default_value: gdouble,
pub epsilon: gdouble,
}
impl ::std::default::Default for Struct__GParamSpecDouble {
fn default() -> Struct__GParamSpecDouble {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecString {
pub parent_instance: GParamSpec,
pub default_value: *mut gchar,
pub cset_first: *mut gchar,
pub cset_nth: *mut gchar,
pub substitutor: gchar,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
}
impl ::std::default::Default for Struct__GParamSpecString {
fn default() -> Struct__GParamSpecString {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecParam {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecParam {
fn default() -> Struct__GParamSpecParam {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecBoxed {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecBoxed {
fn default() -> Struct__GParamSpecBoxed {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecPointer {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecPointer {
fn default() -> Struct__GParamSpecPointer {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecValueArray {
pub parent_instance: GParamSpec,
pub element_spec: *mut GParamSpec,
pub fixed_n_elements: guint,
}
impl ::std::default::Default for Struct__GParamSpecValueArray {
fn default() -> Struct__GParamSpecValueArray {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecObject {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecObject {
fn default() -> Struct__GParamSpecObject {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecOverride {
pub parent_instance: GParamSpec,
pub overridden: *mut GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecOverride {
fn default() -> Struct__GParamSpecOverride {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecGType {
pub parent_instance: GParamSpec,
pub is_a_type: GType,
}
impl ::std::default::Default for Struct__GParamSpecGType {
fn default() -> Struct__GParamSpecGType {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecVariant {
pub parent_instance: GParamSpec,
pub _type: *mut GVariantType,
pub default_value: *mut GVariant,
pub padding: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GParamSpecVariant {
fn default() -> Struct__GParamSpecVariant {
unsafe { ::std::mem::zeroed() }
}
}
pub type GTypeModule = Struct__GTypeModule;
pub type GTypeModuleClass = Struct__GTypeModuleClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeModule {
pub parent_instance: GObject,
pub use_count: guint,
pub type_infos: *mut GSList,
pub interface_infos: *mut GSList,
pub name: *mut gchar,
}
impl ::std::default::Default for Struct__GTypeModule {
fn default() -> Struct__GTypeModule { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeModuleClass {
pub parent_class: GObjectClass,
pub load: ::std::option::Option<extern "C" fn(module: *mut GTypeModule)
-> gboolean>,
pub unload: ::std::option::Option<extern "C" fn
(module: *mut GTypeModule)>,
pub reserved1: ::std::option::Option<extern "C" fn()>,
pub reserved2: ::std::option::Option<extern "C" fn()>,
pub reserved3: ::std::option::Option<extern "C" fn()>,
pub reserved4: ::std::option::Option<extern "C" fn()>,
}
impl ::std::default::Default for Struct__GTypeModuleClass {
fn default() -> Struct__GTypeModuleClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GTypePluginClass = Struct__GTypePluginClass;
pub type GTypePluginUse =
::std::option::Option<extern "C" fn(plugin: *mut GTypePlugin)>;
pub type GTypePluginUnuse =
::std::option::Option<extern "C" fn(plugin: *mut GTypePlugin)>;
pub type GTypePluginCompleteTypeInfo =
::std::option::Option<extern "C" fn
(plugin: *mut GTypePlugin, g_type: GType,
info: *mut GTypeInfo,
value_table: *mut GTypeValueTable)>;
pub type GTypePluginCompleteInterfaceInfo =
::std::option::Option<extern "C" fn
(plugin: *mut GTypePlugin, instance_type: GType,
interface_type: GType,
info: *mut GInterfaceInfo)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypePluginClass {
pub base_iface: GTypeInterface,
pub use_plugin: GTypePluginUse,
pub unuse_plugin: GTypePluginUnuse,
pub complete_type_info: GTypePluginCompleteTypeInfo,
pub complete_interface_info: GTypePluginCompleteInterfaceInfo,
}
impl ::std::default::Default for Struct__GTypePluginClass {
fn default() -> Struct__GTypePluginClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GValueArray = Struct__GValueArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GValueArray {
pub n_values: guint,
pub values: *mut GValue,
pub n_prealloced: guint,
}
impl ::std::default::Default for Struct__GValueArray {
fn default() -> Struct__GValueArray { unsafe { ::std::mem::zeroed() } }
}
pub type gchararray = *mut gchar;
pub enum Struct__GstAtomicQueue { }
pub type GstAtomicQueue = Struct__GstAtomicQueue;
pub type GstElement = Struct__GstElement;
pub type GstElementClass = Struct__GstElementClass;
#[repr(C)]
#[derive(Copy,Debug)]
pub enum GstState{
GST_STATE_VOID_PENDING = 0,
GST_STATE_NULL = 1,
GST_STATE_READY = 2,
GST_STATE_PAUSED = 3,
GST_STATE_PLAYING = 4,
}
/*pub type Enum_Unnamed121 = ::libc::c_uint;
pub const GST_STATE_VOID_PENDING: ::libc::c_uint = 0;
pub const GST_STATE_NULL: ::libc::c_uint = 1;
pub const GST_STATE_READY: ::libc::c_uint = 2;
pub const GST_STATE_PAUSED: ::libc::c_uint = 3;
pub const GST_STATE_PLAYING: ::libc::c_uint = 4;
pub type GstState = Enum_Unnamed121;*/
pub type Enum_Unnamed122 = ::libc::c_uint;
pub const GST_OBJECT_FLAG_LAST: ::libc::c_uint = 16;
pub type GstObjectFlags = Enum_Unnamed122;
pub type GstObject = Struct__GstObject;
pub type GstObjectClass = Struct__GstObjectClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstObject {
pub object: GInitiallyUnowned,
pub lock: GMutex,
pub name: *mut gchar,
pub parent: *mut GstObject,
pub flags: guint32,
pub control_bindings: *mut GList,
pub control_rate: guint64,
pub last_sync: guint64,
pub _gst_reserved: gpointer,
}
impl ::std::default::Default for Struct__GstObject {
fn default() -> Struct__GstObject { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstObjectClass {
pub parent_class: GInitiallyUnownedClass,
pub path_string_separator: *const gchar,
pub deep_notify: ::std::option::Option<extern "C" fn
(object: *mut GstObject,
orig: *mut GstObject,
pspec: *mut GParamSpec)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstObjectClass {
fn default() -> Struct__GstObjectClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstClockTime = guint64;
pub type GstClockTimeDiff = gint64;
pub type GstClockID = gpointer;
pub type GstClockEntry = Struct__GstClockEntry;
pub type GstClock = Struct__GstClock;
pub type GstClockClass = Struct__GstClockClass;
pub enum Struct__GstClockPrivate { }
pub type GstClockPrivate = Struct__GstClockPrivate;
pub type GstClockCallback =
::std::option::Option<extern "C" fn
(clock: *mut GstClock, time: GstClockTime,
id: GstClockID, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed123 = ::libc::c_uint;
pub const GST_CLOCK_OK: ::libc::c_uint = 0;
pub const GST_CLOCK_EARLY: ::libc::c_uint = 1;
pub const GST_CLOCK_UNSCHEDULED: ::libc::c_uint = 2;
pub const GST_CLOCK_BUSY: ::libc::c_uint = 3;
pub const GST_CLOCK_BADTIME: ::libc::c_uint = 4;
pub const GST_CLOCK_ERROR: ::libc::c_uint = 5;
pub const GST_CLOCK_UNSUPPORTED: ::libc::c_uint = 6;
pub const GST_CLOCK_DONE: ::libc::c_uint = 7;
pub type GstClockReturn = Enum_Unnamed123;
pub type Enum_Unnamed124 = ::libc::c_uint;
pub const GST_CLOCK_ENTRY_SINGLE: ::libc::c_uint = 0;
pub const GST_CLOCK_ENTRY_PERIODIC: ::libc::c_uint = 1;
pub type GstClockEntryType = Enum_Unnamed124;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClockEntry {
pub refcount: gint,
pub clock: *mut GstClock,
pub _type: GstClockEntryType,
pub time: GstClockTime,
pub interval: GstClockTime,
pub status: GstClockReturn,
pub func: GstClockCallback,
pub user_data: gpointer,
pub destroy_data: GDestroyNotify,
pub unscheduled: gboolean,
pub woken_up: gboolean,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClockEntry {
fn default() -> Struct__GstClockEntry { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed125 = ::libc::c_uint;
pub const GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC: ::libc::c_uint = 16;
pub const GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC: ::libc::c_uint = 32;
pub const GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC: ::libc::c_uint = 64;
pub const GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC: ::libc::c_uint = 128;
pub const GST_CLOCK_FLAG_CAN_SET_RESOLUTION: ::libc::c_uint = 256;
pub const GST_CLOCK_FLAG_CAN_SET_MASTER: ::libc::c_uint = 512;
pub const GST_CLOCK_FLAG_LAST: ::libc::c_uint = 4096;
pub type GstClockFlags = Enum_Unnamed125;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClock {
pub object: GstObject,
pub _priv: *mut GstClockPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClock {
fn default() -> Struct__GstClock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClockClass {
pub parent_class: GstObjectClass,
pub change_resolution: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
old_resolution:
GstClockTime,
new_resolution:
GstClockTime)
-> GstClockTime>,
pub get_resolution: ::std::option::Option<extern "C" fn
(clock: *mut GstClock)
-> GstClockTime>,
pub get_internal_time: ::std::option::Option<extern "C" fn
(clock: *mut GstClock)
-> GstClockTime>,
pub wait: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry,
jitter: *mut GstClockTimeDiff)
-> GstClockReturn>,
pub wait_async: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry)
-> GstClockReturn>,
pub unschedule: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClockClass {
fn default() -> Struct__GstClockClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstControlSource = Struct__GstControlSource;
pub type GstControlSourceClass = Struct__GstControlSourceClass;
pub type GstTimedValue = Struct__GstTimedValue;
pub enum Struct__GstValueArray { }
pub type GstValueArray = Struct__GstValueArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTimedValue {
pub timestamp: GstClockTime,
pub value: gdouble,
}
impl ::std::default::Default for Struct__GstTimedValue {
fn default() -> Struct__GstTimedValue { unsafe { ::std::mem::zeroed() } }
}
pub type GstControlSourceGetValue =
::std::option::Option<extern "C" fn
(_self: *mut GstControlSource,
timestamp: GstClockTime, value: *mut gdouble)
-> gboolean>;
pub type GstControlSourceGetValueArray =
::std::option::Option<extern "C" fn
(_self: *mut GstControlSource,
timestamp: GstClockTime,
interval: GstClockTime, n_values: guint,
values: *mut gdouble) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlSource {
pub parent: GstObject,
pub get_value: GstControlSourceGetValue,
pub get_value_array: GstControlSourceGetValueArray,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlSource {
fn default() -> Struct__GstControlSource {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlSourceClass {
pub parent_class: GstObjectClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlSourceClass {
fn default() -> Struct__GstControlSourceClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstControlBinding = Struct__GstControlBinding;
pub type GstControlBindingClass = Struct__GstControlBindingClass;
pub type GstControlBindingConvert =
::std::option::Option<extern "C" fn
(binding: *mut GstControlBinding,
src_value: gdouble, dest_value: *mut GValue)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlBinding {
pub parent: GstObject,
pub name: *mut gchar,
pub pspec: *mut GParamSpec,
pub object: *mut GstObject,
pub disabled: gboolean,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlBinding {
fn default() -> Struct__GstControlBinding {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlBindingClass {
pub parent_class: GstObjectClass,
pub sync_values: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
object: *mut GstObject,
timestamp: GstClockTime,
last_sync: GstClockTime)
-> gboolean>,
pub get_value: ::std::option::Option<extern "C" fn
(binding: *mut GstControlBinding,
timestamp: GstClockTime)
-> *mut GValue>,
pub get_value_array: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: gpointer)
-> gboolean>,
pub get_g_value_array: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut GValue)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlBindingClass {
fn default() -> Struct__GstControlBindingClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPad = Struct__GstPad;
pub enum Struct__GstPadPrivate { }
pub type GstPadPrivate = Struct__GstPadPrivate;
pub type GstPadClass = Struct__GstPadClass;
pub type GstPadProbeInfo = Struct__GstPadProbeInfo;
pub type Enum_Unnamed126 = ::libc::c_uint;
pub const GST_PAD_UNKNOWN: ::libc::c_uint = 0;
pub const GST_PAD_SRC: ::libc::c_uint = 1;
pub const GST_PAD_SINK: ::libc::c_uint = 2;
pub type GstPadDirection = Enum_Unnamed126;
pub type Enum_Unnamed127 = ::libc::c_uint;
pub const GST_PAD_MODE_NONE: ::libc::c_uint = 0;
pub const GST_PAD_MODE_PUSH: ::libc::c_uint = 1;
pub const GST_PAD_MODE_PULL: ::libc::c_uint = 2;
pub type GstPadMode = Enum_Unnamed127;
pub type GstMiniObject = Struct__GstMiniObject;
pub type GstMiniObjectCopyFunction =
::std::option::Option<extern "C" fn(obj: *const GstMiniObject)
-> *mut GstMiniObject>;
pub type GstMiniObjectDisposeFunction =
::std::option::Option<extern "C" fn(obj: *mut GstMiniObject) -> gboolean>;
pub type GstMiniObjectFreeFunction =
::std::option::Option<extern "C" fn(obj: *mut GstMiniObject)>;
pub type GstMiniObjectNotify =
::std::option::Option<extern "C" fn
(user_data: gpointer, obj: *mut GstMiniObject)>;
pub type Enum_Unnamed128 = ::libc::c_uint;
pub const GST_MINI_OBJECT_FLAG_LOCKABLE: ::libc::c_uint = 1;
pub const GST_MINI_OBJECT_FLAG_LOCK_READONLY: ::libc::c_uint = 2;
pub const GST_MINI_OBJECT_FLAG_LAST: ::libc::c_uint = 16;
pub type GstMiniObjectFlags = Enum_Unnamed128;
pub type Enum_Unnamed129 = ::libc::c_uint;
pub const GST_LOCK_FLAG_READ: ::libc::c_uint = 1;
pub const GST_LOCK_FLAG_WRITE: ::libc::c_uint = 2;
pub const GST_LOCK_FLAG_EXCLUSIVE: ::libc::c_uint = 4;
pub const GST_LOCK_FLAG_LAST: ::libc::c_uint = 256;
pub type GstLockFlags = Enum_Unnamed129;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMiniObject {
pub _type: GType,
pub refcount: gint,
pub lockstate: gint,
pub flags: guint,
pub copy: GstMiniObjectCopyFunction,
pub dispose: GstMiniObjectDisposeFunction,
pub free: GstMiniObjectFreeFunction,
pub n_qdata: guint,
pub qdata: gpointer,
}
impl ::std::default::Default for Struct__GstMiniObject {
fn default() -> Struct__GstMiniObject { unsafe { ::std::mem::zeroed() } }
}
pub type GstMemory = Struct__GstMemory;
pub type GstAllocator = Struct__GstAllocator;
pub type Enum_Unnamed130 = ::libc::c_uint;
pub const GST_MEMORY_FLAG_READONLY: ::libc::c_uint = 2;
pub const GST_MEMORY_FLAG_NO_SHARE: ::libc::c_uint = 16;
pub const GST_MEMORY_FLAG_ZERO_PREFIXED: ::libc::c_uint = 32;
pub const GST_MEMORY_FLAG_ZERO_PADDED: ::libc::c_uint = 64;
pub const GST_MEMORY_FLAG_PHYSICALLY_CONTIGUOUS: ::libc::c_uint = 128;
pub const GST_MEMORY_FLAG_NOT_MAPPABLE: ::libc::c_uint = 256;
pub const GST_MEMORY_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstMemoryFlags = Enum_Unnamed130;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMemory {
pub mini_object: GstMiniObject,
pub allocator: *mut GstAllocator,
pub parent: *mut GstMemory,
pub maxsize: gsize,
pub align: gsize,
pub offset: gsize,
pub size: gsize,
}
impl ::std::default::Default for Struct__GstMemory {
fn default() -> Struct__GstMemory { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed131 = ::libc::c_uint;
pub const GST_MAP_READ: ::libc::c_uint = 1;
pub const GST_MAP_WRITE: ::libc::c_uint = 2;
pub const GST_MAP_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstMapFlags = Enum_Unnamed131;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed132 {
pub memory: *mut GstMemory,
pub flags: GstMapFlags,
pub data: *mut guint8,
pub size: gsize,
pub maxsize: gsize,
pub user_data: [gpointer; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed132 {
fn default() -> Struct_Unnamed132 { unsafe { ::std::mem::zeroed() } }
}
pub type GstMapInfo = Struct_Unnamed132;
pub type GstMemoryMapFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, maxsize: gsize,
flags: GstMapFlags) -> gpointer>;
pub type GstMemoryUnmapFunction =
::std::option::Option<extern "C" fn(mem: *mut GstMemory)>;
pub type GstMemoryCopyFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, offset: gssize,
size: gssize) -> *mut GstMemory>;
pub type GstMemoryShareFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, offset: gssize,
size: gssize) -> *mut GstMemory>;
pub type GstMemoryIsSpanFunction =
::std::option::Option<extern "C" fn
(mem1: *mut GstMemory, mem2: *mut GstMemory,
offset: *mut gsize) -> gboolean>;
pub enum Struct__GstAllocatorPrivate { }
pub type GstAllocatorPrivate = Struct__GstAllocatorPrivate;
pub type GstAllocatorClass = Struct__GstAllocatorClass;
pub type GstAllocationParams = Struct__GstAllocationParams;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocationParams {
pub flags: GstMemoryFlags,
pub align: gsize,
pub prefix: gsize,
pub padding: gsize,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAllocationParams {
fn default() -> Struct__GstAllocationParams {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed133 = ::libc::c_uint;
pub const GST_ALLOCATOR_FLAG_CUSTOM_ALLOC: ::libc::c_uint = 16;
pub const GST_ALLOCATOR_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstAllocatorFlags = Enum_Unnamed133;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocator {
pub object: GstObject,
pub mem_type: *const gchar,
pub mem_map: GstMemoryMapFunction,
pub mem_unmap: GstMemoryUnmapFunction,
pub mem_copy: GstMemoryCopyFunction,
pub mem_share: GstMemoryShareFunction,
pub mem_is_span: GstMemoryIsSpanFunction,
pub _gst_reserved: [gpointer; 4u],
pub _priv: *mut GstAllocatorPrivate,
}
impl ::std::default::Default for Struct__GstAllocator {
fn default() -> Struct__GstAllocator { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocatorClass {
pub object_class: GstObjectClass,
pub alloc: ::std::option::Option<extern "C" fn
(allocator: *mut GstAllocator,
size: gsize,
params: *mut GstAllocationParams)
-> *mut GstMemory>,
pub free: ::std::option::Option<extern "C" fn
(allocator: *mut GstAllocator,
memory: *mut GstMemory)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAllocatorClass {
fn default() -> Struct__GstAllocatorClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstBuffer = Struct__GstBuffer;
pub type GstBufferPool = Struct__GstBufferPool;
pub type Enum_Unnamed134 = ::libc::c_uint;
pub const GST_BUFFER_FLAG_LIVE: ::libc::c_uint = 16;
pub const GST_BUFFER_FLAG_DECODE_ONLY: ::libc::c_uint = 32;
pub const GST_BUFFER_FLAG_DISCONT: ::libc::c_uint = 64;
pub const GST_BUFFER_FLAG_RESYNC: ::libc::c_uint = 128;
pub const GST_BUFFER_FLAG_CORRUPTED: ::libc::c_uint = 256;
pub const GST_BUFFER_FLAG_MARKER: ::libc::c_uint = 512;
pub const GST_BUFFER_FLAG_HEADER: ::libc::c_uint = 1024;
pub const GST_BUFFER_FLAG_GAP: ::libc::c_uint = 2048;
pub const GST_BUFFER_FLAG_DROPPABLE: ::libc::c_uint = 4096;
pub const GST_BUFFER_FLAG_DELTA_UNIT: ::libc::c_uint = 8192;
pub const GST_BUFFER_FLAG_TAG_MEMORY: ::libc::c_uint = 16384;
pub const GST_BUFFER_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstBufferFlags = Enum_Unnamed134;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBuffer {
pub mini_object: GstMiniObject,
pub pool: *mut GstBufferPool,
pub pts: GstClockTime,
pub dts: GstClockTime,
pub duration: GstClockTime,
pub offset: guint64,
pub offset_end: guint64,
}
impl ::std::default::Default for Struct__GstBuffer {
fn default() -> Struct__GstBuffer { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed135 = ::libc::c_uint;
pub const GST_BUFFER_COPY_NONE: ::libc::c_uint = 0;
pub const GST_BUFFER_COPY_FLAGS: ::libc::c_uint = 1;
pub const GST_BUFFER_COPY_TIMESTAMPS: ::libc::c_uint = 2;
pub const GST_BUFFER_COPY_META: ::libc::c_uint = 4;
pub const GST_BUFFER_COPY_MEMORY: ::libc::c_uint = 8;
pub const GST_BUFFER_COPY_MERGE: ::libc::c_uint = 16;
pub const GST_BUFFER_COPY_DEEP: ::libc::c_uint = 32;
pub type GstBufferCopyFlags = Enum_Unnamed135;
pub type GstMeta = Struct__GstMeta;
pub type GstMetaInfo = Struct__GstMetaInfo;
pub type Enum_Unnamed136 = ::libc::c_uint;
pub const GST_META_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_META_FLAG_READONLY: ::libc::c_uint = 1;
pub const GST_META_FLAG_POOLED: ::libc::c_uint = 2;
pub const GST_META_FLAG_LOCKED: ::libc::c_uint = 4;
pub const GST_META_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstMetaFlags = Enum_Unnamed136;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMeta {
pub flags: GstMetaFlags,
pub info: *const GstMetaInfo,
}
impl ::std::default::Default for Struct__GstMeta {
fn default() -> Struct__GstMeta { unsafe { ::std::mem::zeroed() } }
}
pub type GstMetaInitFunction =
::std::option::Option<extern "C" fn
(meta: *mut GstMeta, params: gpointer,
buffer: *mut GstBuffer) -> gboolean>;
pub type GstMetaFreeFunction =
::std::option::Option<extern "C" fn
(meta: *mut GstMeta, buffer: *mut GstBuffer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed137 {
pub region: gboolean,
pub offset: gsize,
pub size: gsize,
}
impl ::std::default::Default for Struct_Unnamed137 {
fn default() -> Struct_Unnamed137 { unsafe { ::std::mem::zeroed() } }
}
pub type GstMetaTransformCopy = Struct_Unnamed137;
pub type GstMetaTransformFunction =
::std::option::Option<extern "C" fn
(transbuf: *mut GstBuffer, meta: *mut GstMeta,
buffer: *mut GstBuffer, _type: GQuark,
data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMetaInfo {
pub api: GType,
pub _type: GType,
pub size: gsize,
pub init_func: GstMetaInitFunction,
pub free_func: GstMetaFreeFunction,
pub transform_func: GstMetaTransformFunction,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstMetaInfo {
fn default() -> Struct__GstMetaInfo { unsafe { ::std::mem::zeroed() } }
}
pub type GstBufferForeachMetaFunc =
::std::option::Option<extern "C" fn
(buffer: *mut GstBuffer,
meta: *mut *mut GstMeta, user_data: gpointer)
-> gboolean>;
pub enum Struct__GstBufferList { }
pub type GstBufferList = Struct__GstBufferList;
pub type GstBufferListFunc =
::std::option::Option<extern "C" fn
(buffer: *mut *mut GstBuffer, idx: guint,
user_data: gpointer) -> gboolean>;
pub enum Struct__GstDateTime { }
pub type GstDateTime = Struct__GstDateTime;
pub type GstStructure = Struct__GstStructure;
pub type GstStructureForeachFunc =
::std::option::Option<extern "C" fn
(field_id: GQuark, value: *const GValue,
user_data: gpointer) -> gboolean>;
pub type GstStructureMapFunc =
::std::option::Option<extern "C" fn
(field_id: GQuark, value: *mut GValue,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStructure {
pub _type: GType,
pub name: GQuark,
}
impl ::std::default::Default for Struct__GstStructure {
fn default() -> Struct__GstStructure { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstCapsFeatures { }
pub type GstCapsFeatures = Struct__GstCapsFeatures;
pub type Enum_Unnamed138 = ::libc::c_uint;
pub const GST_CAPS_FLAG_ANY: ::libc::c_uint = 16;
pub type GstCapsFlags = Enum_Unnamed138;
pub type Enum_Unnamed139 = ::libc::c_uint;
pub const GST_CAPS_INTERSECT_ZIG_ZAG: ::libc::c_uint = 0;
pub const GST_CAPS_INTERSECT_FIRST: ::libc::c_uint = 1;
pub type GstCapsIntersectMode = Enum_Unnamed139;
pub type GstCaps = Struct__GstCaps;
pub type GstStaticCaps = Struct__GstStaticCaps;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstCaps {
pub mini_object: GstMiniObject,
}
impl ::std::default::Default for Struct__GstCaps {
fn default() -> Struct__GstCaps { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStaticCaps {
pub caps: *mut GstCaps,
pub string: *const ::libc::c_char,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstStaticCaps {
fn default() -> Struct__GstStaticCaps { unsafe { ::std::mem::zeroed() } }
}
pub type GstPadTemplate = Struct__GstPadTemplate;
pub type GstPadTemplateClass = Struct__GstPadTemplateClass;
pub type GstStaticPadTemplate = Struct__GstStaticPadTemplate;
pub type GstEvent = Struct__GstEvent;
pub type Enum_Unnamed140 = ::libc::c_uint;
pub const GST_EVENT_TYPE_UPSTREAM: ::libc::c_uint = 1;
pub const GST_EVENT_TYPE_DOWNSTREAM: ::libc::c_uint = 2;
pub const GST_EVENT_TYPE_SERIALIZED: ::libc::c_uint = 4;
pub const GST_EVENT_TYPE_STICKY: ::libc::c_uint = 8;
pub const GST_EVENT_TYPE_STICKY_MULTI: ::libc::c_uint = 16;
pub type GstEventTypeFlags = Enum_Unnamed140;
pub type Enum_Unnamed141 = ::libc::c_uint;
pub const GST_EVENT_UNKNOWN: ::libc::c_uint = 0;
pub const GST_EVENT_FLUSH_START: ::libc::c_uint = 2563;
pub const GST_EVENT_FLUSH_STOP: ::libc::c_uint = 5127;
pub const GST_EVENT_STREAM_START: ::libc::c_uint = 10254;
pub const GST_EVENT_CAPS: ::libc::c_uint = 12814;
pub const GST_EVENT_SEGMENT: ::libc::c_uint = 17934;
pub const GST_EVENT_TAG: ::libc::c_uint = 20510;
pub const GST_EVENT_BUFFERSIZE: ::libc::c_uint = 23054;
pub const GST_EVENT_SINK_MESSAGE: ::libc::c_uint = 25630;
pub const GST_EVENT_EOS: ::libc::c_uint = 28174;
pub const GST_EVENT_TOC: ::libc::c_uint = 30750;
pub const GST_EVENT_SEGMENT_DONE: ::libc::c_uint = 38406;
pub const GST_EVENT_GAP: ::libc::c_uint = 40966;
pub const GST_EVENT_QOS: ::libc::c_uint = 48641;
pub const GST_EVENT_SEEK: ::libc::c_uint = 51201;
pub const GST_EVENT_NAVIGATION: ::libc::c_uint = 53761;
pub const GST_EVENT_LATENCY: ::libc::c_uint = 56321;
pub const GST_EVENT_STEP: ::libc::c_uint = 58881;
pub const GST_EVENT_RECONFIGURE: ::libc::c_uint = 61441;
pub const GST_EVENT_TOC_SELECT: ::libc::c_uint = 64001;
pub const GST_EVENT_CUSTOM_UPSTREAM: ::libc::c_uint = 69121;
pub const GST_EVENT_CUSTOM_DOWNSTREAM: ::libc::c_uint = 71686;
pub const GST_EVENT_CUSTOM_DOWNSTREAM_OOB: ::libc::c_uint = 74242;
pub const GST_EVENT_CUSTOM_DOWNSTREAM_STICKY: ::libc::c_uint = 76830;
pub const GST_EVENT_CUSTOM_BOTH: ::libc::c_uint = 79367;
pub const GST_EVENT_CUSTOM_BOTH_OOB: ::libc::c_uint = 81923;
pub type GstEventType = Enum_Unnamed141;
pub type Enum_Unnamed142 = ::libc::c_uint;
pub const GST_ITERATOR_DONE: ::libc::c_uint = 0;
pub const GST_ITERATOR_OK: ::libc::c_uint = 1;
pub const GST_ITERATOR_RESYNC: ::libc::c_uint = 2;
pub const GST_ITERATOR_ERROR: ::libc::c_uint = 3;
pub type GstIteratorResult = Enum_Unnamed142;
pub type GstIterator = Struct__GstIterator;
pub type Enum_Unnamed143 = ::libc::c_uint;
pub const GST_ITERATOR_ITEM_SKIP: ::libc::c_uint = 0;
pub const GST_ITERATOR_ITEM_PASS: ::libc::c_uint = 1;
pub const GST_ITERATOR_ITEM_END: ::libc::c_uint = 2;
pub type GstIteratorItem = Enum_Unnamed143;
pub type GstIteratorCopyFunction =
::std::option::Option<extern "C" fn
(it: *const GstIterator,
copy: *mut GstIterator)>;
pub type GstIteratorItemFunction =
::std::option::Option<extern "C" fn
(it: *mut GstIterator, item: *const GValue)
-> GstIteratorItem>;
pub type GstIteratorNextFunction =
::std::option::Option<extern "C" fn
(it: *mut GstIterator, result: *mut GValue)
-> GstIteratorResult>;
pub type GstIteratorResyncFunction =
::std::option::Option<extern "C" fn(it: *mut GstIterator)>;
pub type GstIteratorFreeFunction =
::std::option::Option<extern "C" fn(it: *mut GstIterator)>;
pub type GstIteratorForeachFunction =
::std::option::Option<extern "C" fn
(item: *const GValue, user_data: gpointer)>;
pub type GstIteratorFoldFunction =
::std::option::Option<extern "C" fn
(item: *const GValue, ret: *mut GValue,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstIterator {
pub copy: GstIteratorCopyFunction,
pub next: GstIteratorNextFunction,
pub item: GstIteratorItemFunction,
pub resync: GstIteratorResyncFunction,
pub free: GstIteratorFreeFunction,
pub pushed: *mut GstIterator,
pub _type: GType,
pub lock: *mut GMutex,
pub cookie: guint32,
pub master_cookie: *mut guint32,
pub size: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstIterator {
fn default() -> Struct__GstIterator { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed144 = ::libc::c_uint;
pub const GST_FORMAT_UNDEFINED: ::libc::c_uint = 0;
pub const GST_FORMAT_DEFAULT: ::libc::c_uint = 1;
pub const GST_FORMAT_BYTES: ::libc::c_uint = 2;
pub const GST_FORMAT_TIME: ::libc::c_uint = 3;
pub const GST_FORMAT_BUFFERS: ::libc::c_uint = 4;
pub const GST_FORMAT_PERCENT: ::libc::c_uint = 5;
pub type GstFormat = Enum_Unnamed144;
pub type GstFormatDefinition = Struct__GstFormatDefinition;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstFormatDefinition {
pub value: GstFormat,
pub nick: *const gchar,
pub description: *const gchar,
pub quark: GQuark,
}
impl ::std::default::Default for Struct__GstFormatDefinition {
fn default() -> Struct__GstFormatDefinition {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstSegment = Struct__GstSegment;
pub type Enum_Unnamed145 = ::libc::c_uint;
pub const GST_SEEK_TYPE_NONE: ::libc::c_uint = 0;
pub const GST_SEEK_TYPE_SET: ::libc::c_uint = 1;
pub const GST_SEEK_TYPE_END: ::libc::c_uint = 2;
pub type GstSeekType = Enum_Unnamed145;
pub type Enum_Unnamed146 = ::libc::c_uint;
pub const GST_SEEK_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_SEEK_FLAG_FLUSH: ::libc::c_uint = 1;
pub const GST_SEEK_FLAG_ACCURATE: ::libc::c_uint = 2;
pub const GST_SEEK_FLAG_KEY_UNIT: ::libc::c_uint = 4;
pub const GST_SEEK_FLAG_SEGMENT: ::libc::c_uint = 8;
pub const GST_SEEK_FLAG_SKIP: ::libc::c_uint = 16;
pub const GST_SEEK_FLAG_SNAP_BEFORE: ::libc::c_uint = 32;
pub const GST_SEEK_FLAG_SNAP_AFTER: ::libc::c_uint = 64;
pub const GST_SEEK_FLAG_SNAP_NEAREST: ::libc::c_uint = 96;
pub type GstSeekFlags = Enum_Unnamed146;
pub type Enum_Unnamed147 = ::libc::c_uint;
pub const GST_SEGMENT_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_SEGMENT_FLAG_RESET: ::libc::c_uint = 1;
pub const GST_SEGMENT_FLAG_SKIP: ::libc::c_uint = 16;
pub const GST_SEGMENT_FLAG_SEGMENT: ::libc::c_uint = 8;
pub type GstSegmentFlags = Enum_Unnamed147;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSegment {
pub flags: GstSegmentFlags,
pub rate: gdouble,
pub applied_rate: gdouble,
pub format: GstFormat,
pub base: guint64,
pub offset: guint64,
pub start: guint64,
pub stop: guint64,
pub time: guint64,
pub position: guint64,
pub duration: guint64,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSegment {
fn default() -> Struct__GstSegment { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstSample { }
pub type GstSample = Struct__GstSample;
pub type Enum_Unnamed148 = ::libc::c_uint;
pub const GST_TAG_MERGE_UNDEFINED: ::libc::c_uint = 0;
pub const GST_TAG_MERGE_REPLACE_ALL: ::libc::c_uint = 1;
pub const GST_TAG_MERGE_REPLACE: ::libc::c_uint = 2;
pub const GST_TAG_MERGE_APPEND: ::libc::c_uint = 3;
pub const GST_TAG_MERGE_PREPEND: ::libc::c_uint = 4;
pub const GST_TAG_MERGE_KEEP: ::libc::c_uint = 5;
pub const GST_TAG_MERGE_KEEP_ALL: ::libc::c_uint = 6;
pub const GST_TAG_MERGE_COUNT: ::libc::c_uint = 7;
pub type GstTagMergeMode = Enum_Unnamed148;
pub type Enum_Unnamed149 = ::libc::c_uint;
pub const GST_TAG_FLAG_UNDEFINED: ::libc::c_uint = 0;
pub const GST_TAG_FLAG_META: ::libc::c_uint = 1;
pub const GST_TAG_FLAG_ENCODED: ::libc::c_uint = 2;
pub const GST_TAG_FLAG_DECODED: ::libc::c_uint = 3;
pub const GST_TAG_FLAG_COUNT: ::libc::c_uint = 4;
pub type GstTagFlag = Enum_Unnamed149;
pub type GstTagList = Struct__GstTagList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTagList {
pub mini_object: GstMiniObject,
}
impl ::std::default::Default for Struct__GstTagList {
fn default() -> Struct__GstTagList { unsafe { ::std::mem::zeroed() } }
}
pub type GstTagForeachFunc =
::std::option::Option<extern "C" fn
(list: *const GstTagList, tag: *const gchar,
user_data: gpointer)>;
pub type GstTagMergeFunc =
::std::option::Option<extern "C" fn
(dest: *mut GValue, src: *const GValue)>;
pub type Enum_Unnamed150 = ::libc::c_uint;
pub const GST_TAG_SCOPE_STREAM: ::libc::c_uint = 0;
pub const GST_TAG_SCOPE_GLOBAL: ::libc::c_uint = 1;
pub type GstTagScope = Enum_Unnamed150;
pub type GstMessage = Struct__GstMessage;
pub type Enum_Unnamed151 = ::libc::c_int;
pub const GST_MESSAGE_UNKNOWN: ::libc::c_int = 0;
pub const GST_MESSAGE_EOS: ::libc::c_int = 1;
pub const GST_MESSAGE_ERROR: ::libc::c_int = 2;
pub const GST_MESSAGE_WARNING: ::libc::c_int = 4;
pub const GST_MESSAGE_INFO: ::libc::c_int = 8;
pub const GST_MESSAGE_TAG: ::libc::c_int = 16;
pub const GST_MESSAGE_BUFFERING: ::libc::c_int = 32;
pub const GST_MESSAGE_STATE_CHANGED: ::libc::c_int = 64;
pub const GST_MESSAGE_STATE_DIRTY: ::libc::c_int = 128;
pub const GST_MESSAGE_STEP_DONE: ::libc::c_int = 256;
pub const GST_MESSAGE_CLOCK_PROVIDE: ::libc::c_int = 512;
pub const GST_MESSAGE_CLOCK_LOST: ::libc::c_int = 1024;
pub const GST_MESSAGE_NEW_CLOCK: ::libc::c_int = 2048;
pub const GST_MESSAGE_STRUCTURE_CHANGE: ::libc::c_int = 4096;
pub const GST_MESSAGE_STREAM_STATUS: ::libc::c_int = 8192;
pub const GST_MESSAGE_APPLICATION: ::libc::c_int = 16384;
pub const GST_MESSAGE_ELEMENT: ::libc::c_int = 32768;
pub const GST_MESSAGE_SEGMENT_START: ::libc::c_int = 65536;
pub const GST_MESSAGE_SEGMENT_DONE: ::libc::c_int = 131072;
pub const GST_MESSAGE_DURATION_CHANGED: ::libc::c_int = 262144;
pub const GST_MESSAGE_LATENCY: ::libc::c_int = 524288;
pub const GST_MESSAGE_ASYNC_START: ::libc::c_int = 1048576;
pub const GST_MESSAGE_ASYNC_DONE: ::libc::c_int = 2097152;
pub const GST_MESSAGE_REQUEST_STATE: ::libc::c_int = 4194304;
pub const GST_MESSAGE_STEP_START: ::libc::c_int = 8388608;
pub const GST_MESSAGE_QOS: ::libc::c_int = 16777216;
pub const GST_MESSAGE_PROGRESS: ::libc::c_int = 33554432;
pub const GST_MESSAGE_TOC: ::libc::c_int = 67108864;
pub const GST_MESSAGE_RESET_TIME: ::libc::c_int = 134217728;
pub const GST_MESSAGE_STREAM_START: ::libc::c_int = 268435456;
pub const GST_MESSAGE_NEED_CONTEXT: ::libc::c_int = 536870912;
pub const GST_MESSAGE_HAVE_CONTEXT: ::libc::c_int = 1073741824;
pub const GST_MESSAGE_EXTENDED: ::libc::c_int = -2147483648;
pub const GST_MESSAGE_DEVICE_ADDED: ::libc::c_int = -2147483647;
pub const GST_MESSAGE_DEVICE_REMOVED: ::libc::c_int = -2147483646;
pub const GST_MESSAGE_ANY: ::libc::c_int = -1;
pub type GstMessageType = Enum_Unnamed151;
pub enum Struct__GstTocEntry { }
pub type GstTocEntry = Struct__GstTocEntry;
pub enum Struct__GstToc { }
pub type GstToc = Struct__GstToc;
pub type Enum_Unnamed152 = ::libc::c_uint;
pub const GST_TOC_SCOPE_GLOBAL: ::libc::c_uint = 1;
pub const GST_TOC_SCOPE_CURRENT: ::libc::c_uint = 2;
pub type GstTocScope = Enum_Unnamed152;
pub type Enum_Unnamed153 = ::libc::c_int;
pub const GST_TOC_ENTRY_TYPE_ANGLE: ::libc::c_int = -3;
pub const GST_TOC_ENTRY_TYPE_VERSION: ::libc::c_int = -2;
pub const GST_TOC_ENTRY_TYPE_EDITION: ::libc::c_int = -1;
pub const GST_TOC_ENTRY_TYPE_INVALID: ::libc::c_int = 0;
pub const GST_TOC_ENTRY_TYPE_TITLE: ::libc::c_int = 1;
pub const GST_TOC_ENTRY_TYPE_TRACK: ::libc::c_int = 2;
pub const GST_TOC_ENTRY_TYPE_CHAPTER: ::libc::c_int = 3;
pub type GstTocEntryType = Enum_Unnamed153;
pub type Enum_Unnamed154 = ::libc::c_uint;
pub const GST_TOC_LOOP_NONE: ::libc::c_uint = 0;
pub const GST_TOC_LOOP_FORWARD: ::libc::c_uint = 1;
pub const GST_TOC_LOOP_REVERSE: ::libc::c_uint = 2;
pub const GST_TOC_LOOP_PING_PONG: ::libc::c_uint = 3;
pub type GstTocLoopType = Enum_Unnamed154;
pub enum Struct__GstContext { }
pub type GstContext = Struct__GstContext;
pub type GstQuery = Struct__GstQuery;
pub type Enum_Unnamed155 = ::libc::c_uint;
pub const GST_QUERY_TYPE_UPSTREAM: ::libc::c_uint = 1;
pub const GST_QUERY_TYPE_DOWNSTREAM: ::libc::c_uint = 2;
pub const GST_QUERY_TYPE_SERIALIZED: ::libc::c_uint = 4;
pub type GstQueryTypeFlags = Enum_Unnamed155;
pub type Enum_Unnamed156 = ::libc::c_uint;
pub const GST_QUERY_UNKNOWN: ::libc::c_uint = 0;
pub const GST_QUERY_POSITION: ::libc::c_uint = 2563;
pub const GST_QUERY_DURATION: ::libc::c_uint = 5123;
pub const GST_QUERY_LATENCY: ::libc::c_uint = 7683;
pub const GST_QUERY_JITTER: ::libc::c_uint = 10243;
pub const GST_QUERY_RATE: ::libc::c_uint = 12803;
pub const GST_QUERY_SEEKING: ::libc::c_uint = 15363;
pub const GST_QUERY_SEGMENT: ::libc::c_uint = 17923;
pub const GST_QUERY_CONVERT: ::libc::c_uint = 20483;
pub const GST_QUERY_FORMATS: ::libc::c_uint = 23043;
pub const GST_QUERY_BUFFERING: ::libc::c_uint = 28163;
pub const GST_QUERY_CUSTOM: ::libc::c_uint = 30723;
pub const GST_QUERY_URI: ::libc::c_uint = 33283;
pub const GST_QUERY_ALLOCATION: ::libc::c_uint = 35846;
pub const GST_QUERY_SCHEDULING: ::libc::c_uint = 38401;
pub const GST_QUERY_ACCEPT_CAPS: ::libc::c_uint = 40963;
pub const GST_QUERY_CAPS: ::libc::c_uint = 43523;
pub const GST_QUERY_DRAIN: ::libc::c_uint = 46086;
pub const GST_QUERY_CONTEXT: ::libc::c_uint = 48643;
pub type GstQueryType = Enum_Unnamed156;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstQuery {
pub mini_object: GstMiniObject,
pub _type: GstQueryType,
}
impl ::std::default::Default for Struct__GstQuery {
fn default() -> Struct__GstQuery { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed157 = ::libc::c_uint;
pub const GST_BUFFERING_STREAM: ::libc::c_uint = 0;
pub const GST_BUFFERING_DOWNLOAD: ::libc::c_uint = 1;
pub const GST_BUFFERING_TIMESHIFT: ::libc::c_uint = 2;
pub const GST_BUFFERING_LIVE: ::libc::c_uint = 3;
pub type GstBufferingMode = Enum_Unnamed157;
pub type Enum_Unnamed158 = ::libc::c_uint;
pub const GST_SCHEDULING_FLAG_SEEKABLE: ::libc::c_uint = 1;
pub const GST_SCHEDULING_FLAG_SEQUENTIAL: ::libc::c_uint = 2;
pub const GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED: ::libc::c_uint = 4;
pub type GstSchedulingFlags = Enum_Unnamed158;
pub type GstDevice = Struct__GstDevice;
pub type GstDeviceClass = Struct__GstDeviceClass;
pub enum Struct__GstDevicePrivate { }
pub type GstDevicePrivate = Struct__GstDevicePrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDevice {
pub parent: GstObject,
pub _priv: *mut GstDevicePrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDevice {
fn default() -> Struct__GstDevice { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceClass {
pub parent_class: GstObjectClass,
pub create_element: ::std::option::Option<extern "C" fn
(device: *mut GstDevice,
name: *const gchar)
-> *mut GstElement>,
pub reconfigure_element: ::std::option::Option<extern "C" fn
(device:
*mut GstDevice,
element:
*mut GstElement)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceClass {
fn default() -> Struct__GstDeviceClass { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed159 = ::libc::c_uint;
pub const GST_STRUCTURE_CHANGE_TYPE_PAD_LINK: ::libc::c_uint = 0;
pub const GST_STRUCTURE_CHANGE_TYPE_PAD_UNLINK: ::libc::c_uint = 1;
pub type GstStructureChangeType = Enum_Unnamed159;
pub type Enum_Unnamed160 = ::libc::c_uint;
pub const GST_STREAM_STATUS_TYPE_CREATE: ::libc::c_uint = 0;
pub const GST_STREAM_STATUS_TYPE_ENTER: ::libc::c_uint = 1;
pub const GST_STREAM_STATUS_TYPE_LEAVE: ::libc::c_uint = 2;
pub const GST_STREAM_STATUS_TYPE_DESTROY: ::libc::c_uint = 3;
pub const GST_STREAM_STATUS_TYPE_START: ::libc::c_uint = 8;
pub const GST_STREAM_STATUS_TYPE_PAUSE: ::libc::c_uint = 9;
pub const GST_STREAM_STATUS_TYPE_STOP: ::libc::c_uint = 10;
pub type GstStreamStatusType = Enum_Unnamed160;
pub type Enum_Unnamed161 = ::libc::c_uint;
pub const GST_PROGRESS_TYPE_START: ::libc::c_uint = 0;
pub const GST_PROGRESS_TYPE_CONTINUE: ::libc::c_uint = 1;
pub const GST_PROGRESS_TYPE_COMPLETE: ::libc::c_uint = 2;
pub const GST_PROGRESS_TYPE_CANCELED: ::libc::c_uint = 3;
pub const GST_PROGRESS_TYPE_ERROR: ::libc::c_uint = 4;
pub type GstProgressType = Enum_Unnamed161;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMessage {
pub mini_object: GstMiniObject,
pub _type: GstMessageType,
pub timestamp: guint64,
pub src: *mut GstObject,
pub seqnum: guint32,
pub lock: GMutex,
pub cond: GCond,
}
impl ::std::default::Default for Struct__GstMessage {
fn default() -> Struct__GstMessage { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed162 = ::libc::c_uint;
pub const GST_QOS_TYPE_OVERFLOW: ::libc::c_uint = 0;
pub const GST_QOS_TYPE_UNDERFLOW: ::libc::c_uint = 1;
pub const GST_QOS_TYPE_THROTTLE: ::libc::c_uint = 2;
pub type GstQOSType = Enum_Unnamed162;
pub type Enum_Unnamed163 = ::libc::c_uint;
pub const GST_STREAM_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_STREAM_FLAG_SPARSE: ::libc::c_uint = 1;
pub const GST_STREAM_FLAG_SELECT: ::libc::c_uint = 2;
pub const GST_STREAM_FLAG_UNSELECT: ::libc::c_uint = 4;
pub type GstStreamFlags = Enum_Unnamed163;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstEvent {
pub mini_object: GstMiniObject,
pub _type: GstEventType,
pub timestamp: guint64,
pub seqnum: guint32,
}
impl ::std::default::Default for Struct__GstEvent {
fn default() -> Struct__GstEvent { unsafe { ::std::mem::zeroed() } }
}
pub type GstTaskPool = Struct__GstTaskPool;
pub type GstTaskPoolClass = Struct__GstTaskPoolClass;
pub type GstTaskPoolFunction =
::std::option::Option<extern "C" fn(user_data: *mut ::libc::c_void)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskPool {
pub object: GstObject,
pub pool: *mut GThreadPool,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskPool {
fn default() -> Struct__GstTaskPool { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskPoolClass {
pub parent_class: GstObjectClass,
pub prepare: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
error: *mut *mut GError)>,
pub cleanup: ::std::option::Option<extern "C" fn(pool: *mut GstTaskPool)>,
pub push: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
func: GstTaskPoolFunction,
user_data: gpointer,
error: *mut *mut GError)
-> gpointer>,
pub join: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
id: gpointer)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskPoolClass {
fn default() -> Struct__GstTaskPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstTaskFunction =
::std::option::Option<extern "C" fn(user_data: gpointer)>;
pub type GstTask = Struct__GstTask;
pub type GstTaskClass = Struct__GstTaskClass;
pub enum Struct__GstTaskPrivate { }
pub type GstTaskPrivate = Struct__GstTaskPrivate;
pub type Enum_Unnamed164 = ::libc::c_uint;
pub const GST_TASK_STARTED: ::libc::c_uint = 0;
pub const GST_TASK_STOPPED: ::libc::c_uint = 1;
pub const GST_TASK_PAUSED: ::libc::c_uint = 2;
pub type GstTaskState = Enum_Unnamed164;
pub type GstTaskThreadFunc =
::std::option::Option<extern "C" fn
(task: *mut GstTask, thread: *mut GThread,
user_data: gpointer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTask {
pub object: GstObject,
pub state: GstTaskState,
pub cond: GCond,
pub lock: *mut GRecMutex,
pub func: GstTaskFunction,
pub user_data: gpointer,
pub notify: GDestroyNotify,
pub running: gboolean,
pub thread: *mut GThread,
pub _priv: *mut GstTaskPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTask {
fn default() -> Struct__GstTask { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskClass {
pub parent_class: GstObjectClass,
pub pool: *mut GstTaskPool,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskClass {
fn default() -> Struct__GstTaskClass { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed165 = ::libc::c_uint;
pub const GST_PAD_ALWAYS: ::libc::c_uint = 0;
pub const GST_PAD_SOMETIMES: ::libc::c_uint = 1;
pub const GST_PAD_REQUEST: ::libc::c_uint = 2;
pub type GstPadPresence = Enum_Unnamed165;
pub type Enum_Unnamed166 = ::libc::c_uint;
pub const GST_PAD_TEMPLATE_FLAG_LAST: ::libc::c_uint = 256;
pub type GstPadTemplateFlags = Enum_Unnamed166;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadTemplate {
pub object: GstObject,
pub name_template: *mut gchar,
pub direction: GstPadDirection,
pub presence: GstPadPresence,
pub caps: *mut GstCaps,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadTemplate {
fn default() -> Struct__GstPadTemplate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadTemplateClass {
pub parent_class: GstObjectClass,
pub pad_created: ::std::option::Option<extern "C" fn
(templ: *mut GstPadTemplate,
pad: *mut GstPad)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadTemplateClass {
fn default() -> Struct__GstPadTemplateClass {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStaticPadTemplate {
pub name_template: *const gchar,
pub direction: GstPadDirection,
pub presence: GstPadPresence,
pub static_caps: GstStaticCaps,
}
impl ::std::default::Default for Struct__GstStaticPadTemplate {
fn default() -> Struct__GstStaticPadTemplate {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed167 = ::libc::c_int;
pub const GST_PAD_LINK_OK: ::libc::c_int = 0;
pub const GST_PAD_LINK_WRONG_HIERARCHY: ::libc::c_int = -1;
pub const GST_PAD_LINK_WAS_LINKED: ::libc::c_int = -2;
pub const GST_PAD_LINK_WRONG_DIRECTION: ::libc::c_int = -3;
pub const GST_PAD_LINK_NOFORMAT: ::libc::c_int = -4;
pub const GST_PAD_LINK_NOSCHED: ::libc::c_int = -5;
pub const GST_PAD_LINK_REFUSED: ::libc::c_int = -6;
pub type GstPadLinkReturn = Enum_Unnamed167;
pub type Enum_Unnamed168 = ::libc::c_int;
pub const GST_FLOW_CUSTOM_SUCCESS_2: ::libc::c_int = 102;
pub const GST_FLOW_CUSTOM_SUCCESS_1: ::libc::c_int = 101;
pub const GST_FLOW_CUSTOM_SUCCESS: ::libc::c_int = 100;
pub const GST_FLOW_OK: ::libc::c_int = 0;
pub const GST_FLOW_NOT_LINKED: ::libc::c_int = -1;
pub const GST_FLOW_FLUSHING: ::libc::c_int = -2;
pub const GST_FLOW_EOS: ::libc::c_int = -3;
pub const GST_FLOW_NOT_NEGOTIATED: ::libc::c_int = -4;
pub const GST_FLOW_ERROR: ::libc::c_int = -5;
pub const GST_FLOW_NOT_SUPPORTED: ::libc::c_int = -6;
pub const GST_FLOW_CUSTOM_ERROR: ::libc::c_int = -100;
pub const GST_FLOW_CUSTOM_ERROR_1: ::libc::c_int = -101;
pub const GST_FLOW_CUSTOM_ERROR_2: ::libc::c_int = -102;
pub type GstFlowReturn = Enum_Unnamed168;
pub type Enum_Unnamed169 = ::libc::c_uint;
pub const GST_PAD_LINK_CHECK_NOTHING: ::libc::c_uint = 0;
pub const GST_PAD_LINK_CHECK_HIERARCHY: ::libc::c_uint = 1;
pub const GST_PAD_LINK_CHECK_TEMPLATE_CAPS: ::libc::c_uint = 2;
pub const GST_PAD_LINK_CHECK_CAPS: ::libc::c_uint = 4;
pub const GST_PAD_LINK_CHECK_DEFAULT: ::libc::c_uint = 5;
pub type GstPadLinkCheck = Enum_Unnamed169;
pub type GstPadActivateFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)
-> gboolean>;
pub type GstPadActivateModeFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
mode: GstPadMode, active: gboolean)
-> gboolean>;
pub type GstPadChainFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
buffer: *mut GstBuffer) -> GstFlowReturn>;
pub type GstPadChainListFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
list: *mut GstBufferList) -> GstFlowReturn>;
pub type GstPadGetRangeFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
offset: guint64, length: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn>;
pub type GstPadEventFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
event: *mut GstEvent) -> gboolean>;
pub type GstPadIterIntLinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)
-> *mut GstIterator>;
pub type GstPadQueryFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
query: *mut GstQuery) -> gboolean>;
pub type GstPadLinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
peer: *mut GstPad) -> GstPadLinkReturn>;
pub type GstPadUnlinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)>;
pub type GstPadForwardFunction =
::std::option::Option<extern "C" fn(pad: *mut GstPad, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed170 = ::libc::c_uint;
pub const GST_PAD_PROBE_TYPE_INVALID: ::libc::c_uint = 0;
pub const GST_PAD_PROBE_TYPE_IDLE: ::libc::c_uint = 1;
pub const GST_PAD_PROBE_TYPE_BLOCK: ::libc::c_uint = 2;
pub const GST_PAD_PROBE_TYPE_BUFFER: ::libc::c_uint = 16;
pub const GST_PAD_PROBE_TYPE_BUFFER_LIST: ::libc::c_uint = 32;
pub const GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM: ::libc::c_uint = 64;
pub const GST_PAD_PROBE_TYPE_EVENT_UPSTREAM: ::libc::c_uint = 128;
pub const GST_PAD_PROBE_TYPE_EVENT_FLUSH: ::libc::c_uint = 256;
pub const GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM: ::libc::c_uint = 512;
pub const GST_PAD_PROBE_TYPE_QUERY_UPSTREAM: ::libc::c_uint = 1024;
pub const GST_PAD_PROBE_TYPE_PUSH: ::libc::c_uint = 4096;
pub const GST_PAD_PROBE_TYPE_PULL: ::libc::c_uint = 8192;
pub const GST_PAD_PROBE_TYPE_BLOCKING: ::libc::c_uint = 3;
pub const GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM: ::libc::c_uint = 112;
pub const GST_PAD_PROBE_TYPE_DATA_UPSTREAM: ::libc::c_uint = 128;
pub const GST_PAD_PROBE_TYPE_DATA_BOTH: ::libc::c_uint = 240;
pub const GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM: ::libc::c_uint = 114;
pub const GST_PAD_PROBE_TYPE_BLOCK_UPSTREAM: ::libc::c_uint = 130;
pub const GST_PAD_PROBE_TYPE_EVENT_BOTH: ::libc::c_uint = 192;
pub const GST_PAD_PROBE_TYPE_QUERY_BOTH: ::libc::c_uint = 1536;
pub const GST_PAD_PROBE_TYPE_ALL_BOTH: ::libc::c_uint = 1776;
pub const GST_PAD_PROBE_TYPE_SCHEDULING: ::libc::c_uint = 12288;
pub type GstPadProbeType = Enum_Unnamed170;
pub type Enum_Unnamed171 = ::libc::c_uint;
pub const GST_PAD_PROBE_DROP: ::libc::c_uint = 0;
pub const GST_PAD_PROBE_OK: ::libc::c_uint = 1;
pub const GST_PAD_PROBE_REMOVE: ::libc::c_uint = 2;
pub const GST_PAD_PROBE_PASS: ::libc::c_uint = 3;
pub type GstPadProbeReturn = Enum_Unnamed171;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadProbeInfo {
pub _type: GstPadProbeType,
pub id: gulong,
pub data: gpointer,
pub offset: guint64,
pub size: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadProbeInfo {
fn default() -> Struct__GstPadProbeInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPadProbeCallback =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, info: *mut GstPadProbeInfo,
user_data: gpointer) -> GstPadProbeReturn>;
pub type GstPadStickyEventsForeachFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, event: *mut *mut GstEvent,
user_data: gpointer) -> gboolean>;
pub type Enum_Unnamed172 = ::libc::c_uint;
pub const GST_PAD_FLAG_BLOCKED: ::libc::c_uint = 16;
pub const GST_PAD_FLAG_FLUSHING: ::libc::c_uint = 32;
pub const GST_PAD_FLAG_EOS: ::libc::c_uint = 64;
pub const GST_PAD_FLAG_BLOCKING: ::libc::c_uint = 128;
pub const GST_PAD_FLAG_NEED_PARENT: ::libc::c_uint = 256;
pub const GST_PAD_FLAG_NEED_RECONFIGURE: ::libc::c_uint = 512;
pub const GST_PAD_FLAG_PENDING_EVENTS: ::libc::c_uint = 1024;
pub const GST_PAD_FLAG_FIXED_CAPS: ::libc::c_uint = 2048;
pub const GST_PAD_FLAG_PROXY_CAPS: ::libc::c_uint = 4096;
pub const GST_PAD_FLAG_PROXY_ALLOCATION: ::libc::c_uint = 8192;
pub const GST_PAD_FLAG_PROXY_SCHEDULING: ::libc::c_uint = 16384;
pub const GST_PAD_FLAG_ACCEPT_INTERSECT: ::libc::c_uint = 32768;
pub const GST_PAD_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstPadFlags = Enum_Unnamed172;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPad {
pub object: GstObject,
pub element_private: gpointer,
pub padtemplate: *mut GstPadTemplate,
pub direction: GstPadDirection,
pub stream_rec_lock: GRecMutex,
pub task: *mut GstTask,
pub block_cond: GCond,
pub probes: GHookList,
pub mode: GstPadMode,
pub activatefunc: GstPadActivateFunction,
pub activatedata: gpointer,
pub activatenotify: GDestroyNotify,
pub activatemodefunc: GstPadActivateModeFunction,
pub activatemodedata: gpointer,
pub activatemodenotify: GDestroyNotify,
pub peer: *mut GstPad,
pub linkfunc: GstPadLinkFunction,
pub linkdata: gpointer,
pub linknotify: GDestroyNotify,
pub unlinkfunc: GstPadUnlinkFunction,
pub unlinkdata: gpointer,
pub unlinknotify: GDestroyNotify,
pub chainfunc: GstPadChainFunction,
pub chaindata: gpointer,
pub chainnotify: GDestroyNotify,
pub chainlistfunc: GstPadChainListFunction,
pub chainlistdata: gpointer,
pub chainlistnotify: GDestroyNotify,
pub getrangefunc: GstPadGetRangeFunction,
pub getrangedata: gpointer,
pub getrangenotify: GDestroyNotify,
pub eventfunc: GstPadEventFunction,
pub eventdata: gpointer,
pub eventnotify: GDestroyNotify,
pub offset: gint64,
pub queryfunc: GstPadQueryFunction,
pub querydata: gpointer,
pub querynotify: GDestroyNotify,
pub iterintlinkfunc: GstPadIterIntLinkFunction,
pub iterintlinkdata: gpointer,
pub iterintlinknotify: GDestroyNotify,
pub num_probes: gint,
pub num_blocked: gint,
pub _priv: *mut GstPadPrivate,
pub ABI: Union_Unnamed173,
}
impl ::std::default::Default for Struct__GstPad {
fn default() -> Struct__GstPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed173 {
pub _bindgen_data_: [u64; 4u],
}
impl Union_Unnamed173 {
pub unsafe fn _gst_reserved(&mut self) -> *mut [gpointer; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn abi(&mut self) -> *mut Struct_Unnamed174 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed173 {
fn default() -> Union_Unnamed173 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed174 {
pub last_flowret: GstFlowReturn,
}
impl ::std::default::Default for Struct_Unnamed174 {
fn default() -> Struct_Unnamed174 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadClass {
pub parent_class: GstObjectClass,
pub linked: ::std::option::Option<extern "C" fn
(pad: *mut GstPad,
peer: *mut GstPad)>,
pub unlinked: ::std::option::Option<extern "C" fn
(pad: *mut GstPad,
peer: *mut GstPad)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadClass {
fn default() -> Struct__GstPadClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstBus = Struct__GstBus;
pub enum Struct__GstBusPrivate { }
pub type GstBusPrivate = Struct__GstBusPrivate;
pub type GstBusClass = Struct__GstBusClass;
pub type Enum_Unnamed175 = ::libc::c_uint;
pub const GST_BUS_FLUSHING: ::libc::c_uint = 16;
pub const GST_BUS_FLAG_LAST: ::libc::c_uint = 32;
pub type GstBusFlags = Enum_Unnamed175;
pub type Enum_Unnamed176 = ::libc::c_uint;
pub const GST_BUS_DROP: ::libc::c_uint = 0;
pub const GST_BUS_PASS: ::libc::c_uint = 1;
pub const GST_BUS_ASYNC: ::libc::c_uint = 2;
pub type GstBusSyncReply = Enum_Unnamed176;
pub type GstBusSyncHandler =
::std::option::Option<extern "C" fn
(bus: *mut GstBus, message: *mut GstMessage,
user_data: gpointer) -> GstBusSyncReply>;
pub type GstBusFunc =
::std::option::Option<extern "C" fn
(bus: *mut GstBus, message: *mut GstMessage,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBus {
pub object: GstObject,
pub _priv: *mut GstBusPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBus {
fn default() -> Struct__GstBus { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBusClass {
pub parent_class: GstObjectClass,
pub message: ::std::option::Option<extern "C" fn
(bus: *mut GstBus,
message: *mut GstMessage)>,
pub sync_message: ::std::option::Option<extern "C" fn
(bus: *mut GstBus,
message: *mut GstMessage)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBusClass {
fn default() -> Struct__GstBusClass { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstElementFactory { }
pub type GstElementFactory = Struct__GstElementFactory;
pub enum Struct__GstElementFactoryClass { }
pub type GstElementFactoryClass = Struct__GstElementFactoryClass;
pub enum Struct__GstPlugin { }
pub type GstPlugin = Struct__GstPlugin;
pub enum Struct__GstPluginClass { }
pub type GstPluginClass = Struct__GstPluginClass;
pub type GstPluginDesc = Struct__GstPluginDesc;
pub type Enum_Unnamed177 = ::libc::c_uint;
pub const GST_PLUGIN_ERROR_MODULE: ::libc::c_uint = 0;
pub const GST_PLUGIN_ERROR_DEPENDENCIES: ::libc::c_uint = 1;
pub const GST_PLUGIN_ERROR_NAME_MISMATCH: ::libc::c_uint = 2;
pub type GstPluginError = Enum_Unnamed177;
pub type Enum_Unnamed178 = ::libc::c_uint;
pub const GST_PLUGIN_FLAG_CACHED: ::libc::c_uint = 16;
pub const GST_PLUGIN_FLAG_BLACKLISTED: ::libc::c_uint = 32;
pub type GstPluginFlags = Enum_Unnamed178;
pub type Enum_Unnamed179 = ::libc::c_uint;
pub const GST_PLUGIN_DEPENDENCY_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_PLUGIN_DEPENDENCY_FLAG_RECURSE: ::libc::c_uint = 1;
pub const GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY: ::libc::c_uint =
2;
pub const GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX: ::libc::c_uint = 4;
pub type GstPluginDependencyFlags = Enum_Unnamed179;
pub type GstPluginInitFunc =
::std::option::Option<extern "C" fn(plugin: *mut GstPlugin) -> gboolean>;
pub type GstPluginInitFullFunc =
::std::option::Option<extern "C" fn
(plugin: *mut GstPlugin, user_data: gpointer)
-> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPluginDesc {
pub major_version: gint,
pub minor_version: gint,
pub name: *const gchar,
pub description: *const gchar,
pub plugin_init: GstPluginInitFunc,
pub version: *const gchar,
pub license: *const gchar,
pub source: *const gchar,
pub package: *const gchar,
pub origin: *const gchar,
pub release_datetime: *const gchar,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPluginDesc {
fn default() -> Struct__GstPluginDesc { unsafe { ::std::mem::zeroed() } }
}
pub type GstPluginFilter =
::std::option::Option<extern "C" fn
(plugin: *mut GstPlugin, user_data: gpointer)
-> gboolean>;
pub enum Struct__GstPluginFeature { }
pub type GstPluginFeature = Struct__GstPluginFeature;
pub enum Struct__GstPluginFeatureClass { }
pub type GstPluginFeatureClass = Struct__GstPluginFeatureClass;
pub type Enum_Unnamed180 = ::libc::c_uint;
pub const GST_RANK_NONE: ::libc::c_uint = 0;
pub const GST_RANK_MARGINAL: ::libc::c_uint = 64;
pub const GST_RANK_SECONDARY: ::libc::c_uint = 128;
pub const GST_RANK_PRIMARY: ::libc::c_uint = 256;
pub type GstRank = Enum_Unnamed180;
pub type GstPluginFeatureFilter =
::std::option::Option<extern "C" fn
(feature: *mut GstPluginFeature,
user_data: gpointer) -> gboolean>;
pub type Enum_Unnamed181 = ::libc::c_uint;
pub const GST_URI_ERROR_UNSUPPORTED_PROTOCOL: ::libc::c_uint = 0;
pub const GST_URI_ERROR_BAD_URI: ::libc::c_uint = 1;
pub const GST_URI_ERROR_BAD_STATE: ::libc::c_uint = 2;
pub const GST_URI_ERROR_BAD_REFERENCE: ::libc::c_uint = 3;
pub type GstURIError = Enum_Unnamed181;
pub type Enum_Unnamed182 = ::libc::c_uint;
pub const GST_URI_UNKNOWN: ::libc::c_uint = 0;
pub const GST_URI_SINK: ::libc::c_uint = 1;
pub const GST_URI_SRC: ::libc::c_uint = 2;
pub type GstURIType = Enum_Unnamed182;
pub enum Struct__GstURIHandler { }
pub type GstURIHandler = Struct__GstURIHandler;
pub type GstURIHandlerInterface = Struct__GstURIHandlerInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstURIHandlerInterface {
pub parent: GTypeInterface,
pub get_type: ::std::option::Option<extern "C" fn(_type: GType)
-> GstURIType>,
pub get_protocols: ::std::option::Option<extern "C" fn(_type: GType)
-> *const *const gchar>,
pub get_uri: ::std::option::Option<extern "C" fn
(handler: *mut GstURIHandler)
-> *mut gchar>,
pub set_uri: ::std::option::Option<extern "C" fn
(handler: *mut GstURIHandler,
uri: *const gchar,
error: *mut *mut GError)
-> gboolean>,
}
impl ::std::default::Default for Struct__GstURIHandlerInterface {
fn default() -> Struct__GstURIHandlerInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstElementFactoryListType = guint64;
pub type Enum_Unnamed183 = ::libc::c_uint;
pub const GST_STATE_CHANGE_FAILURE: ::libc::c_uint = 0;
pub const GST_STATE_CHANGE_SUCCESS: ::libc::c_uint = 1;
pub const GST_STATE_CHANGE_ASYNC: ::libc::c_uint = 2;
pub const GST_STATE_CHANGE_NO_PREROLL: ::libc::c_uint = 3;
pub type GstStateChangeReturn = Enum_Unnamed183;
pub type Enum_Unnamed184 = ::libc::c_uint;
pub const GST_STATE_CHANGE_NULL_TO_READY: ::libc::c_uint = 10;
pub const GST_STATE_CHANGE_READY_TO_PAUSED: ::libc::c_uint = 19;
pub const GST_STATE_CHANGE_PAUSED_TO_PLAYING: ::libc::c_uint = 28;
pub const GST_STATE_CHANGE_PLAYING_TO_PAUSED: ::libc::c_uint = 35;
pub const GST_STATE_CHANGE_PAUSED_TO_READY: ::libc::c_uint = 26;
pub const GST_STATE_CHANGE_READY_TO_NULL: ::libc::c_uint = 17;
pub type GstStateChange = Enum_Unnamed184;
pub type Enum_Unnamed185 = ::libc::c_uint;
pub const GST_ELEMENT_FLAG_LOCKED_STATE: ::libc::c_uint = 16;
pub const GST_ELEMENT_FLAG_SINK: ::libc::c_uint = 32;
pub const GST_ELEMENT_FLAG_SOURCE: ::libc::c_uint = 64;
pub const GST_ELEMENT_FLAG_PROVIDE_CLOCK: ::libc::c_uint = 128;
pub const GST_ELEMENT_FLAG_REQUIRE_CLOCK: ::libc::c_uint = 256;
pub const GST_ELEMENT_FLAG_INDEXABLE: ::libc::c_uint = 512;
pub const GST_ELEMENT_FLAG_LAST: ::libc::c_uint = 16384;
pub type GstElementFlags = Enum_Unnamed185;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstElement {
pub object: GstObject,
pub state_lock: GRecMutex,
pub state_cond: GCond,
pub state_cookie: guint32,
pub target_state: GstState,
pub current_state: GstState,
pub next_state: GstState,
pub pending_state: GstState,
pub last_return: GstStateChangeReturn,
pub bus: *mut GstBus,
pub clock: *mut GstClock,
pub base_time: GstClockTimeDiff,
pub start_time: GstClockTime,
pub numpads: guint16,
pub pads: *mut GList,
pub numsrcpads: guint16,
pub srcpads: *mut GList,
pub numsinkpads: guint16,
pub sinkpads: *mut GList,
pub pads_cookie: guint32,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstElement {
fn default() -> Struct__GstElement { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstElementClass {
pub parent_class: GstObjectClass,
pub metadata: gpointer,
pub elementfactory: *mut GstElementFactory,
pub padtemplates: *mut GList,
pub numpadtemplates: gint,
pub pad_templ_cookie: guint32,
pub pad_added: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub pad_removed: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub no_more_pads: ::std::option::Option<extern "C" fn
(element: *mut GstElement)>,
pub request_new_pad: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
templ:
*mut GstPadTemplate,
name: *const gchar,
caps: *const GstCaps)
-> *mut GstPad>,
pub release_pad: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub get_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
state: *mut GstState,
pending: *mut GstState,
timeout: GstClockTime)
-> GstStateChangeReturn>,
pub set_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
state: GstState)
-> GstStateChangeReturn>,
pub change_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
transition: GstStateChange)
-> GstStateChangeReturn>,
pub state_changed: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
oldstate: GstState,
newstate: GstState,
pending: GstState)>,
pub set_bus: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
bus: *mut GstBus)>,
pub provide_clock: ::std::option::Option<extern "C" fn
(element: *mut GstElement)
-> *mut GstClock>,
pub set_clock: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
clock: *mut GstClock)
-> gboolean>,
pub send_event: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
event: *mut GstEvent)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
query: *mut GstQuery) -> gboolean>,
pub post_message: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
message: *mut GstMessage)
-> gboolean>,
pub set_context: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
context: *mut GstContext)>,
pub _gst_reserved: [gpointer; 18u],
}
impl ::std::default::Default for Struct__GstElementClass {
fn default() -> Struct__GstElementClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed186 = ::libc::c_uint;
pub const GST_BIN_FLAG_NO_RESYNC: ::libc::c_uint = 16384;
pub const GST_BIN_FLAG_LAST: ::libc::c_uint = 524288;
pub type GstBinFlags = Enum_Unnamed186;
pub type GstBin = Struct__GstBin;
pub type GstBinClass = Struct__GstBinClass;
pub enum Struct__GstBinPrivate { }
pub type GstBinPrivate = Struct__GstBinPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBin {
pub element: GstElement,
pub numchildren: gint,
pub children: *mut GList,
pub children_cookie: guint32,
pub child_bus: *mut GstBus,
pub messages: *mut GList,
pub polling: gboolean,
pub state_dirty: gboolean,
pub clock_dirty: gboolean,
pub provided_clock: *mut GstClock,
pub clock_provider: *mut GstElement,
pub _priv: *mut GstBinPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBin {
fn default() -> Struct__GstBin { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBinClass {
pub parent_class: GstElementClass,
pub pool: *mut GThreadPool,
pub element_added: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
child: *mut GstElement)>,
pub element_removed: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
child: *mut GstElement)>,
pub add_element: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
element: *mut GstElement)
-> gboolean>,
pub remove_element: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
element: *mut GstElement)
-> gboolean>,
pub handle_message: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
message: *mut GstMessage)>,
pub do_latency: ::std::option::Option<extern "C" fn(bin: *mut GstBin)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBinClass {
fn default() -> Struct__GstBinClass { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstBufferPoolPrivate { }
pub type GstBufferPoolPrivate = Struct__GstBufferPoolPrivate;
pub type GstBufferPoolClass = Struct__GstBufferPoolClass;
pub type Enum_Unnamed187 = ::libc::c_uint;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_KEY_UNIT: ::libc::c_uint = 1;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT: ::libc::c_uint = 2;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_DISCONT: ::libc::c_uint = 4;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstBufferPoolAcquireFlags = Enum_Unnamed187;
pub type GstBufferPoolAcquireParams = Struct__GstBufferPoolAcquireParams;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPoolAcquireParams {
pub format: GstFormat,
pub start: gint64,
pub stop: gint64,
pub flags: GstBufferPoolAcquireFlags,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBufferPoolAcquireParams {
fn default() -> Struct__GstBufferPoolAcquireParams {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPool {
pub object: GstObject,
pub flushing: gint,
pub _priv: *mut GstBufferPoolPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBufferPool {
fn default() -> Struct__GstBufferPool { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPoolClass {
pub object_class: GstObjectClass,
pub get_options: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)
-> *mut *const gchar>,
pub set_config: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
config: *mut GstStructure)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(pool: *mut GstBufferPool)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(pool: *mut GstBufferPool)
-> gboolean>,
pub acquire_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer:
*mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn>,
pub alloc_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn>,
pub reset_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub release_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub free_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub flush_start: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)>,
pub flush_stop: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)>,
pub _gst_reserved: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GstBufferPoolClass {
fn default() -> Struct__GstBufferPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstChildProxy { }
pub type GstChildProxy = Struct__GstChildProxy;
pub type GstChildProxyInterface = Struct__GstChildProxyInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstChildProxyInterface {
pub parent: GTypeInterface,
pub get_child_by_name: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy,
name: *const gchar)
-> *mut GObject>,
pub get_child_by_index: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy,
index: guint)
-> *mut GObject>,
pub get_children_count: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy)
-> guint>,
pub child_added: ::std::option::Option<extern "C" fn
(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar)>,
pub child_removed: ::std::option::Option<extern "C" fn
(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstChildProxyInterface {
fn default() -> Struct__GstChildProxyInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed188 = ::libc::c_uint;
pub const GST_DEBUG_GRAPH_SHOW_MEDIA_TYPE: ::libc::c_uint = 1;
pub const GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS: ::libc::c_uint = 2;
pub const GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS: ::libc::c_uint = 4;
pub const GST_DEBUG_GRAPH_SHOW_STATES: ::libc::c_uint = 8;
pub const GST_DEBUG_GRAPH_SHOW_ALL: ::libc::c_uint = 15;
pub type GstDebugGraphDetails = Enum_Unnamed188;
pub enum Struct__GstDeviceProviderFactory { }
pub type GstDeviceProviderFactory = Struct__GstDeviceProviderFactory;
pub enum Struct__GstDeviceProviderFactoryClass { }
pub type GstDeviceProviderFactoryClass =
Struct__GstDeviceProviderFactoryClass;
pub type GstDeviceProvider = Struct__GstDeviceProvider;
pub type GstDeviceProviderClass = Struct__GstDeviceProviderClass;
pub enum Struct__GstDeviceProviderPrivate { }
pub type GstDeviceProviderPrivate = Struct__GstDeviceProviderPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceProvider {
pub parent: GstObject,
pub devices: *mut GList,
pub _priv: *mut GstDeviceProviderPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceProvider {
fn default() -> Struct__GstDeviceProvider {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceProviderClass {
pub parent_class: GstObjectClass,
pub factory: *mut GstDeviceProviderFactory,
pub probe: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)
-> *mut GList>,
pub start: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)>,
pub metadata: gpointer,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceProviderClass {
fn default() -> Struct__GstDeviceProviderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed189 = ::libc::c_uint;
pub const GST_CORE_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_CORE_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_CORE_ERROR_NOT_IMPLEMENTED: ::libc::c_uint = 3;
pub const GST_CORE_ERROR_STATE_CHANGE: ::libc::c_uint = 4;
pub const GST_CORE_ERROR_PAD: ::libc::c_uint = 5;
pub const GST_CORE_ERROR_THREAD: ::libc::c_uint = 6;
pub const GST_CORE_ERROR_NEGOTIATION: ::libc::c_uint = 7;
pub const GST_CORE_ERROR_EVENT: ::libc::c_uint = 8;
pub const GST_CORE_ERROR_SEEK: ::libc::c_uint = 9;
pub const GST_CORE_ERROR_CAPS: ::libc::c_uint = 10;
pub const GST_CORE_ERROR_TAG: ::libc::c_uint = 11;
pub const GST_CORE_ERROR_MISSING_PLUGIN: ::libc::c_uint = 12;
pub const GST_CORE_ERROR_CLOCK: ::libc::c_uint = 13;
pub const GST_CORE_ERROR_DISABLED: ::libc::c_uint = 14;
pub const GST_CORE_ERROR_NUM_ERRORS: ::libc::c_uint = 15;
pub type GstCoreError = Enum_Unnamed189;
pub type Enum_Unnamed190 = ::libc::c_uint;
pub const GST_LIBRARY_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_LIBRARY_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_LIBRARY_ERROR_INIT: ::libc::c_uint = 3;
pub const GST_LIBRARY_ERROR_SHUTDOWN: ::libc::c_uint = 4;
pub const GST_LIBRARY_ERROR_SETTINGS: ::libc::c_uint = 5;
pub const GST_LIBRARY_ERROR_ENCODE: ::libc::c_uint = 6;
pub const GST_LIBRARY_ERROR_NUM_ERRORS: ::libc::c_uint = 7;
pub type GstLibraryError = Enum_Unnamed190;
pub type Enum_Unnamed191 = ::libc::c_uint;
pub const GST_RESOURCE_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_RESOURCE_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_RESOURCE_ERROR_NOT_FOUND: ::libc::c_uint = 3;
pub const GST_RESOURCE_ERROR_BUSY: ::libc::c_uint = 4;
pub const GST_RESOURCE_ERROR_OPEN_READ: ::libc::c_uint = 5;
pub const GST_RESOURCE_ERROR_OPEN_WRITE: ::libc::c_uint = 6;
pub const GST_RESOURCE_ERROR_OPEN_READ_WRITE: ::libc::c_uint = 7;
pub const GST_RESOURCE_ERROR_CLOSE: ::libc::c_uint = 8;
pub const GST_RESOURCE_ERROR_READ: ::libc::c_uint = 9;
pub const GST_RESOURCE_ERROR_WRITE: ::libc::c_uint = 10;
pub const GST_RESOURCE_ERROR_SEEK: ::libc::c_uint = 11;
pub const GST_RESOURCE_ERROR_SYNC: ::libc::c_uint = 12;
pub const GST_RESOURCE_ERROR_SETTINGS: ::libc::c_uint = 13;
pub const GST_RESOURCE_ERROR_NO_SPACE_LEFT: ::libc::c_uint = 14;
pub const GST_RESOURCE_ERROR_NOT_AUTHORIZED: ::libc::c_uint = 15;
pub const GST_RESOURCE_ERROR_NUM_ERRORS: ::libc::c_uint = 16;
pub type GstResourceError = Enum_Unnamed191;
pub type Enum_Unnamed192 = ::libc::c_uint;
pub const GST_STREAM_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_STREAM_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_STREAM_ERROR_NOT_IMPLEMENTED: ::libc::c_uint = 3;
pub const GST_STREAM_ERROR_TYPE_NOT_FOUND: ::libc::c_uint = 4;
pub const GST_STREAM_ERROR_WRONG_TYPE: ::libc::c_uint = 5;
pub const GST_STREAM_ERROR_CODEC_NOT_FOUND: ::libc::c_uint = 6;
pub const GST_STREAM_ERROR_DECODE: ::libc::c_uint = 7;
pub const GST_STREAM_ERROR_ENCODE: ::libc::c_uint = 8;
pub const GST_STREAM_ERROR_DEMUX: ::libc::c_uint = 9;
pub const GST_STREAM_ERROR_MUX: ::libc::c_uint = 10;
pub const GST_STREAM_ERROR_FORMAT: ::libc::c_uint = 11;
pub const GST_STREAM_ERROR_DECRYPT: ::libc::c_uint = 12;
pub const GST_STREAM_ERROR_DECRYPT_NOKEY: ::libc::c_uint = 13;
pub const GST_STREAM_ERROR_NUM_ERRORS: ::libc::c_uint = 14;
pub type GstStreamError = Enum_Unnamed192;
pub type GstProxyPad = Struct__GstProxyPad;
pub enum Struct__GstProxyPadPrivate { }
pub type GstProxyPadPrivate = Struct__GstProxyPadPrivate;
pub type GstProxyPadClass = Struct__GstProxyPadClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstProxyPad {
pub pad: GstPad,
pub _priv: *mut GstProxyPadPrivate,
}
impl ::std::default::Default for Struct__GstProxyPad {
fn default() -> Struct__GstProxyPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstProxyPadClass {
pub parent_class: GstPadClass,
pub _gst_reserved: [gpointer; 1u],
}
impl ::std::default::Default for Struct__GstProxyPadClass {
fn default() -> Struct__GstProxyPadClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstGhostPad = Struct__GstGhostPad;
pub enum Struct__GstGhostPadPrivate { }
pub type GstGhostPadPrivate = Struct__GstGhostPadPrivate;
pub type GstGhostPadClass = Struct__GstGhostPadClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstGhostPad {
pub pad: GstProxyPad,
pub _priv: *mut GstGhostPadPrivate,
}
impl ::std::default::Default for Struct__GstGhostPad {
fn default() -> Struct__GstGhostPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstGhostPadClass {
pub parent_class: GstProxyPadClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstGhostPadClass {
fn default() -> Struct__GstGhostPadClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstDeviceMonitor = Struct__GstDeviceMonitor;
pub enum Struct__GstDeviceMonitorPrivate { }
pub type GstDeviceMonitorPrivate = Struct__GstDeviceMonitorPrivate;
pub type GstDeviceMonitorClass = Struct__GstDeviceMonitorClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceMonitor {
pub parent: GstObject,
pub _priv: *mut GstDeviceMonitorPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceMonitor {
fn default() -> Struct__GstDeviceMonitor {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceMonitorClass {
pub parent_class: GstObjectClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceMonitorClass {
fn default() -> Struct__GstDeviceMonitorClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed193 = ::libc::c_uint;
pub const GST_LEVEL_NONE: ::libc::c_uint = 0;
pub const GST_LEVEL_ERROR: ::libc::c_uint = 1;
pub const GST_LEVEL_WARNING: ::libc::c_uint = 2;
pub const GST_LEVEL_FIXME: ::libc::c_uint = 3;
pub const GST_LEVEL_INFO: ::libc::c_uint = 4;
pub const GST_LEVEL_DEBUG: ::libc::c_uint = 5;
pub const GST_LEVEL_LOG: ::libc::c_uint = 6;
pub const GST_LEVEL_TRACE: ::libc::c_uint = 7;
pub const GST_LEVEL_MEMDUMP: ::libc::c_uint = 9;
pub const GST_LEVEL_COUNT: ::libc::c_uint = 10;
pub type GstDebugLevel = Enum_Unnamed193;
pub type Enum_Unnamed194 = ::libc::c_uint;
pub const GST_DEBUG_FG_BLACK: ::libc::c_uint = 0;
pub const GST_DEBUG_FG_RED: ::libc::c_uint = 1;
pub const GST_DEBUG_FG_GREEN: ::libc::c_uint = 2;
pub const GST_DEBUG_FG_YELLOW: ::libc::c_uint = 3;
pub const GST_DEBUG_FG_BLUE: ::libc::c_uint = 4;
pub const GST_DEBUG_FG_MAGENTA: ::libc::c_uint = 5;
pub const GST_DEBUG_FG_CYAN: ::libc::c_uint = 6;
pub const GST_DEBUG_FG_WHITE: ::libc::c_uint = 7;
pub const GST_DEBUG_BG_BLACK: ::libc::c_uint = 0;
pub const GST_DEBUG_BG_RED: ::libc::c_uint = 16;
pub const GST_DEBUG_BG_GREEN: ::libc::c_uint = 32;
pub const GST_DEBUG_BG_YELLOW: ::libc::c_uint = 48;
pub const GST_DEBUG_BG_BLUE: ::libc::c_uint = 64;
pub const GST_DEBUG_BG_MAGENTA: ::libc::c_uint = 80;
pub const GST_DEBUG_BG_CYAN: ::libc::c_uint = 96;
pub const GST_DEBUG_BG_WHITE: ::libc::c_uint = 112;
pub const GST_DEBUG_BOLD: ::libc::c_uint = 256;
pub const GST_DEBUG_UNDERLINE: ::libc::c_uint = 512;
pub type GstDebugColorFlags = Enum_Unnamed194;
pub type Enum_Unnamed195 = ::libc::c_uint;
pub const GST_DEBUG_COLOR_MODE_OFF: ::libc::c_uint = 0;
pub const GST_DEBUG_COLOR_MODE_ON: ::libc::c_uint = 1;
pub const GST_DEBUG_COLOR_MODE_UNIX: ::libc::c_uint = 2;
pub type GstDebugColorMode = Enum_Unnamed195;
pub type GstDebugCategory = Struct__GstDebugCategory;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDebugCategory {
pub threshold: gint,
pub color: guint,
pub name: *const gchar,
pub description: *const gchar,
}
impl ::std::default::Default for Struct__GstDebugCategory {
fn default() -> Struct__GstDebugCategory {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstDebugMessage { }
pub type GstDebugMessage = Struct__GstDebugMessage;
pub type GstLogFunction =
::std::option::Option<extern "C" fn
(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject,
message: *mut GstDebugMessage,
user_data: gpointer)>;
pub type GstDebugFuncPtr = ::std::option::Option<extern "C" fn()>;
pub type GstValueCompareFunc =
::std::option::Option<extern "C" fn
(value1: *const GValue, value2: *const GValue)
-> gint>;
pub type GstValueSerializeFunc =
::std::option::Option<extern "C" fn(value1: *const GValue) -> *mut gchar>;
pub type GstValueDeserializeFunc =
::std::option::Option<extern "C" fn(dest: *mut GValue, s: *const gchar)
-> gboolean>;
pub type GstValueTable = Struct__GstValueTable;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstValueTable {
pub _type: GType,
pub compare: GstValueCompareFunc,
pub serialize: GstValueSerializeFunc,
pub deserialize: GstValueDeserializeFunc,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstValueTable {
fn default() -> Struct__GstValueTable { unsafe { ::std::mem::zeroed() } }
}
pub type GstParamSpecFraction = Struct__GstParamSpecFraction;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstParamSpecFraction {
pub parent_instance: GParamSpec,
pub min_num: gint,
pub min_den: gint,
pub max_num: gint,
pub max_den: gint,
pub def_num: gint,
pub def_den: gint,
}
impl ::std::default::Default for Struct__GstParamSpecFraction {
fn default() -> Struct__GstParamSpecFraction {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPipeline = Struct__GstPipeline;
pub type GstPipelineClass = Struct__GstPipelineClass;
pub enum Struct__GstPipelinePrivate { }
pub type GstPipelinePrivate = Struct__GstPipelinePrivate;
pub type Enum_Unnamed196 = ::libc::c_uint;
pub const GST_PIPELINE_FLAG_FIXED_CLOCK: ::libc::c_uint = 524288;
pub const GST_PIPELINE_FLAG_LAST: ::libc::c_uint = 8388608;
pub type GstPipelineFlags = Enum_Unnamed196;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPipeline {
pub bin: GstBin,
pub fixed_clock: *mut GstClock,
pub stream_time: GstClockTime,
pub delay: GstClockTime,
pub _priv: *mut GstPipelinePrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPipeline {
fn default() -> Struct__GstPipeline { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPipelineClass {
pub parent_class: GstBinClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPipelineClass {
fn default() -> Struct__GstPipelineClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstPoll { }
pub type GstPoll = Struct__GstPoll;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed197 {
pub fd: ::libc::c_int,
pub idx: gint,
}
impl ::std::default::Default for Struct_Unnamed197 {
fn default() -> Struct_Unnamed197 { unsafe { ::std::mem::zeroed() } }
}
pub type GstPollFD = Struct_Unnamed197;
pub enum Struct__GstPreset { }
pub type GstPreset = Struct__GstPreset;
pub type GstPresetInterface = Struct__GstPresetInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPresetInterface {
pub parent: GTypeInterface,
pub get_preset_names: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset)
-> *mut *mut gchar>,
pub get_property_names: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset)
-> *mut *mut gchar>,
pub load_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub save_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub rename_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
old_name: *const gchar,
new_name: *const gchar)
-> gboolean>,
pub delete_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub set_meta: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar,
tag: *const gchar,
value: *const gchar)
-> gboolean>,
pub get_meta: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar,
tag: *const gchar,
value: *mut *mut gchar)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPresetInterface {
fn default() -> Struct__GstPresetInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstRegistry = Struct__GstRegistry;
pub type GstRegistryClass = Struct__GstRegistryClass;
pub enum Struct__GstRegistryPrivate { }
pub type GstRegistryPrivate = Struct__GstRegistryPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstRegistry {
pub object: GstObject,
pub _priv: *mut GstRegistryPrivate,
}
impl ::std::default::Default for Struct__GstRegistry {
fn default() -> Struct__GstRegistry { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstRegistryClass {
pub parent_class: GstObjectClass,
}
impl ::std::default::Default for Struct__GstRegistryClass {
fn default() -> Struct__GstRegistryClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstSystemClock = Struct__GstSystemClock;
pub type GstSystemClockClass = Struct__GstSystemClockClass;
pub enum Struct__GstSystemClockPrivate { }
pub type GstSystemClockPrivate = Struct__GstSystemClockPrivate;
pub type Enum_Unnamed198 = ::libc::c_uint;
pub const GST_CLOCK_TYPE_REALTIME: ::libc::c_uint = 0;
pub const GST_CLOCK_TYPE_MONOTONIC: ::libc::c_uint = 1;
pub const GST_CLOCK_TYPE_OTHER: ::libc::c_uint = 2;
pub type GstClockType = Enum_Unnamed198;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSystemClock {
pub clock: GstClock,
pub _priv: *mut GstSystemClockPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSystemClock {
fn default() -> Struct__GstSystemClock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSystemClockClass {
pub parent_class: GstClockClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSystemClockClass {
fn default() -> Struct__GstSystemClockClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstTagSetter { }
pub type GstTagSetter = Struct__GstTagSetter;
pub type GstTagSetterInterface = Struct__GstTagSetterInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTagSetterInterface {
pub g_iface: GTypeInterface,
}
impl ::std::default::Default for Struct__GstTagSetterInterface {
fn default() -> Struct__GstTagSetterInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstTocSetter { }
pub type GstTocSetter = Struct__GstTocSetter;
pub type GstTocSetterInterface = Struct__GstTocSetterInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTocSetterInterface {
pub g_iface: GTypeInterface,
}
impl ::std::default::Default for Struct__GstTocSetterInterface {
fn default() -> Struct__GstTocSetterInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstTypeFind = Struct__GstTypeFind;
pub type GstTypeFindFunction =
::std::option::Option<extern "C" fn
(find: *mut GstTypeFind, user_data: gpointer)>;
pub type Enum_Unnamed199 = ::libc::c_uint;
pub const GST_TYPE_FIND_NONE: ::libc::c_uint = 0;
pub const GST_TYPE_FIND_MINIMUM: ::libc::c_uint = 1;
pub const GST_TYPE_FIND_POSSIBLE: ::libc::c_uint = 50;
pub const GST_TYPE_FIND_LIKELY: ::libc::c_uint = 80;
pub const GST_TYPE_FIND_NEARLY_CERTAIN: ::libc::c_uint = 99;
pub const GST_TYPE_FIND_MAXIMUM: ::libc::c_uint = 100;
pub type GstTypeFindProbability = Enum_Unnamed199;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTypeFind {
pub peek: ::std::option::Option<extern "C" fn
(data: gpointer, offset: gint64,
size: guint) -> *const guint8>,
pub suggest: ::std::option::Option<extern "C" fn
(data: gpointer,
probability: guint,
caps: *mut GstCaps)>,
pub data: gpointer,
pub get_length: ::std::option::Option<extern "C" fn(data: gpointer)
-> guint64>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTypeFind {
fn default() -> Struct__GstTypeFind { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstTypeFindFactory { }
pub type GstTypeFindFactory = Struct__GstTypeFindFactory;
pub enum Struct__GstTypeFindFactoryClass { }
pub type GstTypeFindFactoryClass = Struct__GstTypeFindFactoryClass;
pub type Enum_Unnamed200 = ::libc::c_uint;
pub const GST_PARSE_ERROR_SYNTAX: ::libc::c_uint = 0;
pub const GST_PARSE_ERROR_NO_SUCH_ELEMENT: ::libc::c_uint = 1;
pub const GST_PARSE_ERROR_NO_SUCH_PROPERTY: ::libc::c_uint = 2;
pub const GST_PARSE_ERROR_LINK: ::libc::c_uint = 3;
pub const GST_PARSE_ERROR_COULD_NOT_SET_PROPERTY: ::libc::c_uint = 4;
pub const GST_PARSE_ERROR_EMPTY_BIN: ::libc::c_uint = 5;
pub const GST_PARSE_ERROR_EMPTY: ::libc::c_uint = 6;
pub type GstParseError = Enum_Unnamed200;
pub type Enum_Unnamed201 = ::libc::c_uint;
pub const GST_PARSE_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_PARSE_FLAG_FATAL_ERRORS: ::libc::c_uint = 1;
pub const GST_PARSE_FLAG_NO_SINGLE_ELEMENT_BINS: ::libc::c_uint = 2;
pub type GstParseFlags = Enum_Unnamed201;
pub enum Struct__GstParseContext { }
pub type GstParseContext = Struct__GstParseContext;
pub type Enum_Unnamed202 = ::libc::c_uint;
pub const GST_SEARCH_MODE_EXACT: ::libc::c_uint = 0;
pub const GST_SEARCH_MODE_BEFORE: ::libc::c_uint = 1;
pub const GST_SEARCH_MODE_AFTER: ::libc::c_uint = 2;
pub type GstSearchMode = Enum_Unnamed202;
pub type GstBaseSink = Struct__GstBaseSink;
pub type GstBaseSinkClass = Struct__GstBaseSinkClass;
pub enum Struct__GstBaseSinkPrivate { }
pub type GstBaseSinkPrivate = Struct__GstBaseSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSink {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub pad_mode: GstPadMode,
pub offset: guint64,
pub can_activate_pull: gboolean,
pub can_activate_push: gboolean,
pub preroll_lock: GMutex,
pub preroll_cond: GCond,
pub eos: gboolean,
pub need_preroll: gboolean,
pub have_preroll: gboolean,
pub playing_async: gboolean,
pub have_newsegment: gboolean,
pub segment: GstSegment,
pub clock_id: GstClockID,
pub sync: gboolean,
pub flushing: gboolean,
pub running: gboolean,
pub max_lateness: gint64,
pub _priv: *mut GstBaseSinkPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSink {
fn default() -> Struct__GstBaseSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSinkClass {
pub parent_class: GstElementClass,
pub get_caps: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub set_caps: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
caps: *mut GstCaps) -> gboolean>,
pub fixate: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
caps: *mut GstCaps)
-> *mut GstCaps>,
pub activate_pull: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
active: gboolean)
-> gboolean>,
pub get_times: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer,
start: *mut GstClockTime,
end: *mut GstClockTime)>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
query: *mut GstQuery)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub unlock: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub unlock_stop: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
query: *mut GstQuery) -> gboolean>,
pub event: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
event: *mut GstEvent) -> gboolean>,
pub wait_event: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
event: *mut GstEvent)
-> GstFlowReturn>,
pub prepare: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub prepare_list: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer_list:
*mut GstBufferList)
-> GstFlowReturn>,
pub preroll: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub render: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub render_list: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer_list:
*mut GstBufferList)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSinkClass {
fn default() -> Struct__GstBaseSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstAppSink = Struct__GstAppSink;
pub type GstAppSinkClass = Struct__GstAppSinkClass;
pub enum Struct__GstAppSinkPrivate { }
pub type GstAppSinkPrivate = Struct__GstAppSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed203 {
pub eos: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)>,
pub new_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)
-> GstFlowReturn>,
pub new_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed203 {
fn default() -> Struct_Unnamed203 { unsafe { ::std::mem::zeroed() } }
}
pub type GstAppSinkCallbacks = Struct_Unnamed203;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSink {
pub basesink: GstBaseSink,
pub _priv: *mut GstAppSinkPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSink {
fn default() -> Struct__GstAppSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSinkClass {
pub basesink_class: GstBaseSinkClass,
pub eos: ::std::option::Option<extern "C" fn(appsink: *mut GstAppSink)>,
pub new_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> GstFlowReturn>,
pub new_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> GstFlowReturn>,
pub pull_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> *mut GstSample>,
pub pull_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> *mut GstSample>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSinkClass {
fn default() -> Struct__GstAppSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed204 = ::libc::c_uint;
pub const GST_BASE_SRC_FLAG_STARTING: ::libc::c_uint = 16384;
pub const GST_BASE_SRC_FLAG_STARTED: ::libc::c_uint = 32768;
pub const GST_BASE_SRC_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstBaseSrcFlags = Enum_Unnamed204;
pub type GstBaseSrc = Struct__GstBaseSrc;
pub type GstBaseSrcClass = Struct__GstBaseSrcClass;
pub enum Struct__GstBaseSrcPrivate { }
pub type GstBaseSrcPrivate = Struct__GstBaseSrcPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSrc {
pub element: GstElement,
pub srcpad: *mut GstPad,
pub live_lock: GMutex,
pub live_cond: GCond,
pub is_live: gboolean,
pub live_running: gboolean,
pub blocksize: guint,
pub can_activate_push: gboolean,
pub random_access: gboolean,
pub clock_id: GstClockID,
pub segment: GstSegment,
pub need_newsegment: gboolean,
pub num_buffers: gint,
pub num_buffers_left: gint,
pub typefind: gboolean,
pub running: gboolean,
pub pending_seek: *mut GstEvent,
pub _priv: *mut GstBaseSrcPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSrc {
fn default() -> Struct__GstBaseSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSrcClass {
pub parent_class: GstElementClass,
pub get_caps: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub negotiate: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub fixate: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
caps: *mut GstCaps)
-> *mut GstCaps>,
pub set_caps: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
caps: *mut GstCaps) -> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
query: *mut GstQuery)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub get_times: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
buffer: *mut GstBuffer,
start: *mut GstClockTime,
end: *mut GstClockTime)>,
pub get_size: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
size: *mut guint64) -> gboolean>,
pub is_seekable: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub prepare_seek_segment: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
seek: *mut GstEvent,
segment:
*mut GstSegment)
-> gboolean>,
pub do_seek: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
segment: *mut GstSegment)
-> gboolean>,
pub unlock: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub unlock_stop: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
query: *mut GstQuery) -> gboolean>,
pub event: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
event: *mut GstEvent) -> gboolean>,
pub create: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub alloc: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub fill: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSrcClass {
fn default() -> Struct__GstBaseSrcClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPushSrc = Struct__GstPushSrc;
pub type GstPushSrcClass = Struct__GstPushSrcClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPushSrc {
pub parent: GstBaseSrc,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPushSrc {
fn default() -> Struct__GstPushSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPushSrcClass {
pub parent_class: GstBaseSrcClass,
pub create: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub alloc: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub fill: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPushSrcClass {
fn default() -> Struct__GstPushSrcClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstAppSrc = Struct__GstAppSrc;
pub type GstAppSrcClass = Struct__GstAppSrcClass;
pub enum Struct__GstAppSrcPrivate { }
pub type GstAppSrcPrivate = Struct__GstAppSrcPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed205 {
pub need_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
length: guint,
user_data: gpointer)>,
pub enough_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
user_data: gpointer)>,
pub seek_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
offset: guint64,
user_data: gpointer)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed205 {
fn default() -> Struct_Unnamed205 { unsafe { ::std::mem::zeroed() } }
}
pub type GstAppSrcCallbacks = Struct_Unnamed205;
pub type Enum_Unnamed206 = ::libc::c_uint;
pub const GST_APP_STREAM_TYPE_STREAM: ::libc::c_uint = 0;
pub const GST_APP_STREAM_TYPE_SEEKABLE: ::libc::c_uint = 1;
pub const GST_APP_STREAM_TYPE_RANDOM_ACCESS: ::libc::c_uint = 2;
pub type GstAppStreamType = Enum_Unnamed206;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSrc {
pub basesrc: GstBaseSrc,
pub _priv: *mut GstAppSrcPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSrc {
fn default() -> Struct__GstAppSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSrcClass {
pub basesrc_class: GstBaseSrcClass,
pub need_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
length: guint)>,
pub enough_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc)>,
pub seek_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
offset: guint64) -> gboolean>,
pub push_buffer: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub end_of_stream: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSrcClass {
fn default() -> Struct__GstAppSrcClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoAlignment = Struct__GstVideoAlignment;
pub type Enum_Unnamed207 = ::libc::c_uint;
pub const GST_VIDEO_TILE_TYPE_INDEXED: ::libc::c_uint = 0;
pub type GstVideoTileType = Enum_Unnamed207;
pub type Enum_Unnamed208 = ::libc::c_uint;
pub const GST_VIDEO_TILE_MODE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_TILE_MODE_ZFLIPZ_2X2: ::libc::c_uint = 65536;
pub type GstVideoTileMode = Enum_Unnamed208;
pub type Enum_Unnamed209 = ::libc::c_uint;
pub const GST_VIDEO_FORMAT_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_FORMAT_ENCODED: ::libc::c_uint = 1;
pub const GST_VIDEO_FORMAT_I420: ::libc::c_uint = 2;
pub const GST_VIDEO_FORMAT_YV12: ::libc::c_uint = 3;
pub const GST_VIDEO_FORMAT_YUY2: ::libc::c_uint = 4;
pub const GST_VIDEO_FORMAT_UYVY: ::libc::c_uint = 5;
pub const GST_VIDEO_FORMAT_AYUV: ::libc::c_uint = 6;
pub const GST_VIDEO_FORMAT_RGBx: ::libc::c_uint = 7;
pub const GST_VIDEO_FORMAT_BGRx: ::libc::c_uint = 8;
pub const GST_VIDEO_FORMAT_xRGB: ::libc::c_uint = 9;
pub const GST_VIDEO_FORMAT_xBGR: ::libc::c_uint = 10;
pub const GST_VIDEO_FORMAT_RGBA: ::libc::c_uint = 11;
pub const GST_VIDEO_FORMAT_BGRA: ::libc::c_uint = 12;
pub const GST_VIDEO_FORMAT_ARGB: ::libc::c_uint = 13;
pub const GST_VIDEO_FORMAT_ABGR: ::libc::c_uint = 14;
pub const GST_VIDEO_FORMAT_RGB: ::libc::c_uint = 15;
pub const GST_VIDEO_FORMAT_BGR: ::libc::c_uint = 16;
pub const GST_VIDEO_FORMAT_Y41B: ::libc::c_uint = 17;
pub const GST_VIDEO_FORMAT_Y42B: ::libc::c_uint = 18;
pub const GST_VIDEO_FORMAT_YVYU: ::libc::c_uint = 19;
pub const GST_VIDEO_FORMAT_Y444: ::libc::c_uint = 20;
pub const GST_VIDEO_FORMAT_v210: ::libc::c_uint = 21;
pub const GST_VIDEO_FORMAT_v216: ::libc::c_uint = 22;
pub const GST_VIDEO_FORMAT_NV12: ::libc::c_uint = 23;
pub const GST_VIDEO_FORMAT_NV21: ::libc::c_uint = 24;
pub const GST_VIDEO_FORMAT_GRAY8: ::libc::c_uint = 25;
pub const GST_VIDEO_FORMAT_GRAY16_BE: ::libc::c_uint = 26;
pub const GST_VIDEO_FORMAT_GRAY16_LE: ::libc::c_uint = 27;
pub const GST_VIDEO_FORMAT_v308: ::libc::c_uint = 28;
pub const GST_VIDEO_FORMAT_RGB16: ::libc::c_uint = 29;
pub const GST_VIDEO_FORMAT_BGR16: ::libc::c_uint = 30;
pub const GST_VIDEO_FORMAT_RGB15: ::libc::c_uint = 31;
pub const GST_VIDEO_FORMAT_BGR15: ::libc::c_uint = 32;
pub const GST_VIDEO_FORMAT_UYVP: ::libc::c_uint = 33;
pub const GST_VIDEO_FORMAT_A420: ::libc::c_uint = 34;
pub const GST_VIDEO_FORMAT_RGB8P: ::libc::c_uint = 35;
pub const GST_VIDEO_FORMAT_YUV9: ::libc::c_uint = 36;
pub const GST_VIDEO_FORMAT_YVU9: ::libc::c_uint = 37;
pub const GST_VIDEO_FORMAT_IYU1: ::libc::c_uint = 38;
pub const GST_VIDEO_FORMAT_ARGB64: ::libc::c_uint = 39;
pub const GST_VIDEO_FORMAT_AYUV64: ::libc::c_uint = 40;
pub const GST_VIDEO_FORMAT_r210: ::libc::c_uint = 41;
pub const GST_VIDEO_FORMAT_I420_10BE: ::libc::c_uint = 42;
pub const GST_VIDEO_FORMAT_I420_10LE: ::libc::c_uint = 43;
pub const GST_VIDEO_FORMAT_I422_10BE: ::libc::c_uint = 44;
pub const GST_VIDEO_FORMAT_I422_10LE: ::libc::c_uint = 45;
pub const GST_VIDEO_FORMAT_Y444_10BE: ::libc::c_uint = 46;
pub const GST_VIDEO_FORMAT_Y444_10LE: ::libc::c_uint = 47;
pub const GST_VIDEO_FORMAT_GBR: ::libc::c_uint = 48;
pub const GST_VIDEO_FORMAT_GBR_10BE: ::libc::c_uint = 49;
pub const GST_VIDEO_FORMAT_GBR_10LE: ::libc::c_uint = 50;
pub const GST_VIDEO_FORMAT_NV16: ::libc::c_uint = 51;
pub const GST_VIDEO_FORMAT_NV24: ::libc::c_uint = 52;
pub const GST_VIDEO_FORMAT_NV12_64Z32: ::libc::c_uint = 53;
pub type GstVideoFormat = Enum_Unnamed209;
pub type GstVideoFormatInfo = Struct__GstVideoFormatInfo;
pub type Enum_Unnamed210 = ::libc::c_uint;
pub const GST_VIDEO_FORMAT_FLAG_YUV: ::libc::c_uint = 1;
pub const GST_VIDEO_FORMAT_FLAG_RGB: ::libc::c_uint = 2;
pub const GST_VIDEO_FORMAT_FLAG_GRAY: ::libc::c_uint = 4;
pub const GST_VIDEO_FORMAT_FLAG_ALPHA: ::libc::c_uint = 8;
pub const GST_VIDEO_FORMAT_FLAG_LE: ::libc::c_uint = 16;
pub const GST_VIDEO_FORMAT_FLAG_PALETTE: ::libc::c_uint = 32;
pub const GST_VIDEO_FORMAT_FLAG_COMPLEX: ::libc::c_uint = 64;
pub const GST_VIDEO_FORMAT_FLAG_UNPACK: ::libc::c_uint = 128;
pub const GST_VIDEO_FORMAT_FLAG_TILED: ::libc::c_uint = 256;
pub type GstVideoFormatFlags = Enum_Unnamed210;
pub type Enum_Unnamed211 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_SITE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_SITE_NONE: ::libc::c_uint = 1;
pub const GST_VIDEO_CHROMA_SITE_H_COSITED: ::libc::c_uint = 2;
pub const GST_VIDEO_CHROMA_SITE_V_COSITED: ::libc::c_uint = 4;
pub const GST_VIDEO_CHROMA_SITE_ALT_LINE: ::libc::c_uint = 8;
pub const GST_VIDEO_CHROMA_SITE_COSITED: ::libc::c_uint = 6;
pub const GST_VIDEO_CHROMA_SITE_JPEG: ::libc::c_uint = 1;
pub const GST_VIDEO_CHROMA_SITE_MPEG2: ::libc::c_uint = 2;
pub const GST_VIDEO_CHROMA_SITE_DV: ::libc::c_uint = 14;
pub type GstVideoChromaSite = Enum_Unnamed211;
pub type Enum_Unnamed212 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_METHOD_NEAREST: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_METHOD_LINEAR: ::libc::c_uint = 1;
pub type GstVideoChromaMethod = Enum_Unnamed212;
pub type Enum_Unnamed213 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_FLAG_INTERLACED: ::libc::c_uint = 1;
pub type GstVideoChromaFlags = Enum_Unnamed213;
pub enum Struct__GstVideoChromaResample { }
pub type GstVideoChromaResample = Struct__GstVideoChromaResample;
pub type Enum_Unnamed214 = ::libc::c_uint;
pub const GST_VIDEO_PACK_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_PACK_FLAG_TRUNCATE_RANGE: ::libc::c_uint = 1;
pub const GST_VIDEO_PACK_FLAG_INTERLACED: ::libc::c_uint = 2;
pub type GstVideoPackFlags = Enum_Unnamed214;
pub type GstVideoFormatUnpack =
::std::option::Option<extern "C" fn
(info: *const GstVideoFormatInfo,
flags: GstVideoPackFlags, dest: gpointer,
data: *mut gpointer, stride: *mut gint,
x: gint, y: gint, width: gint)>;
pub type GstVideoFormatPack =
::std::option::Option<extern "C" fn
(info: *const GstVideoFormatInfo,
flags: GstVideoPackFlags, src: gpointer,
sstride: gint, data: *mut gpointer,
stride: *mut gint,
chroma_site: GstVideoChromaSite, y: gint,
width: gint)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFormatInfo {
pub format: GstVideoFormat,
pub name: *const gchar,
pub description: *const gchar,
pub flags: GstVideoFormatFlags,
pub bits: guint,
pub n_components: guint,
pub shift: [guint; 4u],
pub depth: [guint; 4u],
pub pixel_stride: [gint; 4u],
pub n_planes: guint,
pub plane: [guint; 4u],
pub poffset: [guint; 4u],
pub w_sub: [guint; 4u],
pub h_sub: [guint; 4u],
pub unpack_format: GstVideoFormat,
pub unpack_func: GstVideoFormatUnpack,
pub pack_lines: gint,
pub pack_func: GstVideoFormatPack,
pub tile_mode: GstVideoTileMode,
pub tile_ws: guint,
pub tile_hs: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFormatInfo {
fn default() -> Struct__GstVideoFormatInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed215 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_RANGE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_RANGE_0_255: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_RANGE_16_235: ::libc::c_uint = 2;
pub type GstVideoColorRange = Enum_Unnamed215;
pub type Enum_Unnamed216 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_MATRIX_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_MATRIX_RGB: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_MATRIX_FCC: ::libc::c_uint = 2;
pub const GST_VIDEO_COLOR_MATRIX_BT709: ::libc::c_uint = 3;
pub const GST_VIDEO_COLOR_MATRIX_BT601: ::libc::c_uint = 4;
pub const GST_VIDEO_COLOR_MATRIX_SMPTE240M: ::libc::c_uint = 5;
pub type GstVideoColorMatrix = Enum_Unnamed216;
pub type Enum_Unnamed217 = ::libc::c_uint;
pub const GST_VIDEO_TRANSFER_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_TRANSFER_GAMMA10: ::libc::c_uint = 1;
pub const GST_VIDEO_TRANSFER_GAMMA18: ::libc::c_uint = 2;
pub const GST_VIDEO_TRANSFER_GAMMA20: ::libc::c_uint = 3;
pub const GST_VIDEO_TRANSFER_GAMMA22: ::libc::c_uint = 4;
pub const GST_VIDEO_TRANSFER_BT709: ::libc::c_uint = 5;
pub const GST_VIDEO_TRANSFER_SMPTE240M: ::libc::c_uint = 6;
pub const GST_VIDEO_TRANSFER_SRGB: ::libc::c_uint = 7;
pub const GST_VIDEO_TRANSFER_GAMMA28: ::libc::c_uint = 8;
pub const GST_VIDEO_TRANSFER_LOG100: ::libc::c_uint = 9;
pub const GST_VIDEO_TRANSFER_LOG316: ::libc::c_uint = 10;
pub type GstVideoTransferFunction = Enum_Unnamed217;
pub type Enum_Unnamed218 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_PRIMARIES_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_PRIMARIES_BT709: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_PRIMARIES_BT470M: ::libc::c_uint = 2;
pub const GST_VIDEO_COLOR_PRIMARIES_BT470BG: ::libc::c_uint = 3;
pub const GST_VIDEO_COLOR_PRIMARIES_SMPTE170M: ::libc::c_uint = 4;
pub const GST_VIDEO_COLOR_PRIMARIES_SMPTE240M: ::libc::c_uint = 5;
pub const GST_VIDEO_COLOR_PRIMARIES_FILM: ::libc::c_uint = 6;
pub type GstVideoColorPrimaries = Enum_Unnamed218;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed219 {
pub range: GstVideoColorRange,
pub matrix: GstVideoColorMatrix,
pub transfer: GstVideoTransferFunction,
pub primaries: GstVideoColorPrimaries,
}
impl ::std::default::Default for Struct_Unnamed219 {
fn default() -> Struct_Unnamed219 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoColorimetry = Struct_Unnamed219;
pub type GstVideoInfo = Struct__GstVideoInfo;
pub type Enum_Unnamed220 = ::libc::c_uint;
pub const GST_VIDEO_INTERLACE_MODE_PROGRESSIVE: ::libc::c_uint = 0;
pub const GST_VIDEO_INTERLACE_MODE_INTERLEAVED: ::libc::c_uint = 1;
pub const GST_VIDEO_INTERLACE_MODE_MIXED: ::libc::c_uint = 2;
pub const GST_VIDEO_INTERLACE_MODE_FIELDS: ::libc::c_uint = 3;
pub type GstVideoInterlaceMode = Enum_Unnamed220;
pub type Enum_Unnamed221 = ::libc::c_uint;
pub const GST_VIDEO_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_FLAG_VARIABLE_FPS: ::libc::c_uint = 1;
pub const GST_VIDEO_FLAG_PREMULTIPLIED_ALPHA: ::libc::c_uint = 2;
pub type GstVideoFlags = Enum_Unnamed221;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoInfo {
pub finfo: *const GstVideoFormatInfo,
pub interlace_mode: GstVideoInterlaceMode,
pub flags: GstVideoFlags,
pub width: gint,
pub height: gint,
pub size: gsize,
pub views: gint,
pub chroma_site: GstVideoChromaSite,
pub colorimetry: GstVideoColorimetry,
pub par_n: gint,
pub par_d: gint,
pub fps_n: gint,
pub fps_d: gint,
pub offset: [gsize; 4u],
pub stride: [gint; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoInfo {
fn default() -> Struct__GstVideoInfo { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoFrame = Struct__GstVideoFrame;
pub type Enum_Unnamed222 = ::libc::c_uint;
pub const GST_VIDEO_FRAME_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_FRAME_FLAG_INTERLACED: ::libc::c_uint = 1;
pub const GST_VIDEO_FRAME_FLAG_TFF: ::libc::c_uint = 2;
pub const GST_VIDEO_FRAME_FLAG_RFF: ::libc::c_uint = 4;
pub const GST_VIDEO_FRAME_FLAG_ONEFIELD: ::libc::c_uint = 8;
pub type GstVideoFrameFlags = Enum_Unnamed222;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFrame {
pub info: GstVideoInfo,
pub flags: GstVideoFrameFlags,
pub buffer: *mut GstBuffer,
pub meta: gpointer,
pub id: gint,
pub data: [gpointer; 4u],
pub map: [GstMapInfo; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFrame {
fn default() -> Struct__GstVideoFrame { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed223 = ::libc::c_uint;
pub const GST_VIDEO_BUFFER_FLAG_INTERLACED: ::libc::c_uint = 1048576;
pub const GST_VIDEO_BUFFER_FLAG_TFF: ::libc::c_uint = 2097152;
pub const GST_VIDEO_BUFFER_FLAG_RFF: ::libc::c_uint = 4194304;
pub const GST_VIDEO_BUFFER_FLAG_ONEFIELD: ::libc::c_uint = 8388608;
pub const GST_VIDEO_BUFFER_FLAG_LAST: ::libc::c_uint = 268435456;
pub type GstVideoBufferFlags = Enum_Unnamed223;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoAlignment {
pub padding_top: guint,
pub padding_bottom: guint,
pub padding_left: guint,
pub padding_right: guint,
pub stride_align: [guint; 4u],
}
impl ::std::default::Default for Struct__GstVideoAlignment {
fn default() -> Struct__GstVideoAlignment {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoConvertSampleCallback =
::std::option::Option<extern "C" fn
(sample: *mut GstSample, error: *mut GError,
user_data: gpointer)>;
pub type GstColorBalanceChannel = Struct__GstColorBalanceChannel;
pub type GstColorBalanceChannelClass = Struct__GstColorBalanceChannelClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceChannel {
pub parent: GObject,
pub label: *mut gchar,
pub min_value: gint,
pub max_value: gint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceChannel {
fn default() -> Struct__GstColorBalanceChannel {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceChannelClass {
pub parent: GObjectClass,
pub value_changed: ::std::option::Option<extern "C" fn
(channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceChannelClass {
fn default() -> Struct__GstColorBalanceChannelClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstColorBalance { }
pub type GstColorBalance = Struct__GstColorBalance;
pub type GstColorBalanceInterface = Struct__GstColorBalanceInterface;
pub type Enum_Unnamed224 = ::libc::c_uint;
pub const GST_COLOR_BALANCE_HARDWARE: ::libc::c_uint = 0;
pub const GST_COLOR_BALANCE_SOFTWARE: ::libc::c_uint = 1;
pub type GstColorBalanceType = Enum_Unnamed224;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceInterface {
pub iface: GTypeInterface,
pub list_channels: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance)
-> *const GList>,
pub set_value: ::std::option::Option<extern "C" fn
(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub get_value: ::std::option::Option<extern "C" fn
(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel)
-> gint>,
pub get_balance_type: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance)
-> GstColorBalanceType>,
pub value_changed: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceInterface {
fn default() -> Struct__GstColorBalanceInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstAdapter { }
pub type GstAdapter = Struct__GstAdapter;
pub enum Struct__GstAdapterClass { }
pub type GstAdapterClass = Struct__GstAdapterClass;
pub type GstVideoCodecState = Struct__GstVideoCodecState;
pub type GstVideoCodecFrame = Struct__GstVideoCodecFrame;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCodecState {
pub ref_count: gint,
pub info: GstVideoInfo,
pub caps: *mut GstCaps,
pub codec_data: *mut GstBuffer,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoCodecState {
fn default() -> Struct__GstVideoCodecState {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed225 = ::libc::c_uint;
pub const GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY: ::libc::c_uint = 1;
pub const GST_VIDEO_CODEC_FRAME_FLAG_SYNC_POINT: ::libc::c_uint = 2;
pub const GST_VIDEO_CODEC_FRAME_FLAG_FORCE_KEYFRAME: ::libc::c_uint = 4;
pub const GST_VIDEO_CODEC_FRAME_FLAG_FORCE_KEYFRAME_HEADERS: ::libc::c_uint =
8;
pub type GstVideoCodecFrameFlags = Enum_Unnamed225;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCodecFrame {
pub ref_count: gint,
pub flags: guint32,
pub system_frame_number: guint32,
pub decode_frame_number: guint32,
pub presentation_frame_number: guint32,
pub dts: GstClockTime,
pub pts: GstClockTime,
pub duration: GstClockTime,
pub distance_from_sync: ::libc::c_int,
pub input_buffer: *mut GstBuffer,
pub output_buffer: *mut GstBuffer,
pub deadline: GstClockTime,
pub events: *mut GList,
pub user_data: gpointer,
pub user_data_destroy_notify: GDestroyNotify,
pub abidata: Union_Unnamed226,
}
impl ::std::default::Default for Struct__GstVideoCodecFrame {
fn default() -> Struct__GstVideoCodecFrame {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed226 {
pub _bindgen_data_: [u64; 20u],
}
impl Union_Unnamed226 {
pub unsafe fn ABI(&mut self) -> *mut Struct_Unnamed227 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn padding(&mut self) -> *mut [*mut ::libc::c_void; 20u] {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed226 {
fn default() -> Union_Unnamed226 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed227 {
pub ts: GstClockTime,
pub ts2: GstClockTime,
}
impl ::std::default::Default for Struct_Unnamed227 {
fn default() -> Struct_Unnamed227 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoDecoder = Struct__GstVideoDecoder;
pub type GstVideoDecoderClass = Struct__GstVideoDecoderClass;
pub enum Struct__GstVideoDecoderPrivate { }
pub type GstVideoDecoderPrivate = Struct__GstVideoDecoderPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoDecoder {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub stream_lock: GRecMutex,
pub input_segment: GstSegment,
pub output_segment: GstSegment,
pub _priv: *mut GstVideoDecoderPrivate,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoDecoder {
fn default() -> Struct__GstVideoDecoder {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoDecoderClass {
pub element_class: GstElementClass,
pub open: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub close: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub parse: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame,
adapter: *mut GstAdapter,
at_eos: gboolean) -> GstFlowReturn>,
pub set_format: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
state: *mut GstVideoCodecState)
-> gboolean>,
pub reset: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
hard: gboolean) -> gboolean>,
pub finish: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> GstFlowReturn>,
pub handle_frame: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub sink_event: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
event: *mut GstEvent)
-> gboolean>,
pub negotiate: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub flush: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub sink_query: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub src_query: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub padding: [*mut ::libc::c_void; 17u],
}
impl ::std::default::Default for Struct__GstVideoDecoderClass {
fn default() -> Struct__GstVideoDecoderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoEncoder = Struct__GstVideoEncoder;
pub enum Struct__GstVideoEncoderPrivate { }
pub type GstVideoEncoderPrivate = Struct__GstVideoEncoderPrivate;
pub type GstVideoEncoderClass = Struct__GstVideoEncoderClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoEncoder {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub stream_lock: GRecMutex,
pub input_segment: GstSegment,
pub output_segment: GstSegment,
pub _priv: *mut GstVideoEncoderPrivate,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoEncoder {
fn default() -> Struct__GstVideoEncoder {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoEncoderClass {
pub element_class: GstElementClass,
pub open: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub close: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub set_format: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
state: *mut GstVideoCodecState)
-> gboolean>,
pub handle_frame: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub reset: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
hard: gboolean) -> gboolean>,
pub finish: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> GstFlowReturn>,
pub pre_push: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub getcaps: ::std::option::Option<extern "C" fn
(enc: *mut GstVideoEncoder,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub sink_event: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
event: *mut GstEvent)
-> gboolean>,
pub negotiate: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub flush: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub sink_query: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub src_query: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub _gst_reserved: [gpointer; 17u],
}
impl ::std::default::Default for Struct__GstVideoEncoderClass {
fn default() -> Struct__GstVideoEncoderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstBaseTransform = Struct__GstBaseTransform;
pub type GstBaseTransformClass = Struct__GstBaseTransformClass;
pub enum Struct__GstBaseTransformPrivate { }
pub type GstBaseTransformPrivate = Struct__GstBaseTransformPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseTransform {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub have_segment: gboolean,
pub segment: GstSegment,
pub _priv: *mut GstBaseTransformPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseTransform {
fn default() -> Struct__GstBaseTransform {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseTransformClass {
pub parent_class: GstElementClass,
pub passthrough_on_same_caps: gboolean,
pub transform_ip_on_passthrough: gboolean,
pub transform_caps: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub fixate_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
othercaps: *mut GstCaps)
-> *mut GstCaps>,
pub accept_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps)
-> gboolean>,
pub set_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
incaps: *mut GstCaps,
outcaps: *mut GstCaps)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
query: *mut GstQuery) -> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
query: *mut GstQuery)
-> gboolean>,
pub filter_meta: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
query: *mut GstQuery,
api: GType,
params: *const GstStructure)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
decide_query:
*mut GstQuery,
query: *mut GstQuery)
-> gboolean>,
pub transform_size: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
size: gsize,
othercaps: *mut GstCaps,
othersize: *mut gsize)
-> gboolean>,
pub get_unit_size: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
caps: *mut GstCaps,
size: *mut gsize)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform)
-> gboolean>,
pub sink_event: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
event: *mut GstEvent)
-> gboolean>,
pub prepare_output_buffer: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
input:
*mut GstBuffer,
outbuf:
*mut *mut GstBuffer)
-> GstFlowReturn>,
pub copy_metadata: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
input: *mut GstBuffer,
outbuf: *mut GstBuffer)
-> gboolean>,
pub transform_meta: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
outbuf: *mut GstBuffer,
meta: *mut GstMeta,
inbuf: *mut GstBuffer)
-> gboolean>,
pub before_transform: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
buffer: *mut GstBuffer)>,
pub transform: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
inbuf: *mut GstBuffer,
outbuf: *mut GstBuffer)
-> GstFlowReturn>,
pub transform_ip: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseTransformClass {
fn default() -> Struct__GstBaseTransformClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoFilter = Struct__GstVideoFilter;
pub type GstVideoFilterClass = Struct__GstVideoFilterClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFilter {
pub element: GstBaseTransform,
pub negotiated: gboolean,
pub in_info: GstVideoInfo,
pub out_info: GstVideoInfo,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFilter {
fn default() -> Struct__GstVideoFilter { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFilterClass {
pub parent_class: GstBaseTransformClass,
pub set_info: ::std::option::Option<extern "C" fn
(filter: *mut GstVideoFilter,
incaps: *mut GstCaps,
in_info: *mut GstVideoInfo,
outcaps: *mut GstCaps,
out_info: *mut GstVideoInfo)
-> gboolean>,
pub transform_frame: ::std::option::Option<extern "C" fn
(filter:
*mut GstVideoFilter,
inframe:
*mut GstVideoFrame,
outframe:
*mut GstVideoFrame)
-> GstFlowReturn>,
pub transform_frame_ip: ::std::option::Option<extern "C" fn
(trans:
*mut GstVideoFilter,
frame:
*mut GstVideoFrame)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFilterClass {
fn default() -> Struct__GstVideoFilterClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoMeta = Struct__GstVideoMeta;
pub type GstVideoCropMeta = Struct__GstVideoCropMeta;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoMeta {
pub meta: GstMeta,
pub buffer: *mut GstBuffer,
pub flags: GstVideoFrameFlags,
pub format: GstVideoFormat,
pub id: gint,
pub width: guint,
pub height: guint,
pub n_planes: guint,
pub offset: [gsize; 4u],
pub stride: [gint; 4u],
pub map: ::std::option::Option<extern "C" fn
(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo,
data: *mut gpointer,
stride: *mut gint, flags: GstMapFlags)
-> gboolean>,
pub unmap: ::std::option::Option<extern "C" fn
(meta: *mut GstVideoMeta,
plane: guint, info: *mut GstMapInfo)
-> gboolean>,
}
impl ::std::default::Default for Struct__GstVideoMeta {
fn default() -> Struct__GstVideoMeta { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCropMeta {
pub meta: GstMeta,
pub x: guint,
pub y: guint,
pub width: guint,
pub height: guint,
}
impl ::std::default::Default for Struct__GstVideoCropMeta {
fn default() -> Struct__GstVideoCropMeta {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed228 {
pub in_info: *mut GstVideoInfo,
pub out_info: *mut GstVideoInfo,
}
impl ::std::default::Default for Struct_Unnamed228 {
fn default() -> Struct_Unnamed228 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoMetaTransform = Struct_Unnamed228;
pub type Enum_Unnamed229 = ::libc::c_uint;
pub const GST_VIDEO_GL_TEXTURE_TYPE_LUMINANCE: ::libc::c_uint = 0;
pub const GST_VIDEO_GL_TEXTURE_TYPE_LUMINANCE_ALPHA: ::libc::c_uint = 1;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGB16: ::libc::c_uint = 2;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGB: ::libc::c_uint = 3;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGBA: ::libc::c_uint = 4;
pub const GST_VIDEO_GL_TEXTURE_TYPE_R: ::libc::c_uint = 5;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RG: ::libc::c_uint = 6;
pub type GstVideoGLTextureType = Enum_Unnamed229;
pub type Enum_Unnamed230 = ::libc::c_uint;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_NORMAL_Y_NORMAL: ::libc::c_uint =
0;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_NORMAL_Y_FLIP: ::libc::c_uint =
1;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_FLIP_Y_NORMAL: ::libc::c_uint =
2;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_FLIP_Y_FLIP: ::libc::c_uint = 3;
pub type GstVideoGLTextureOrientation = Enum_Unnamed230;
pub type GstVideoGLTextureUploadMeta = Struct__GstVideoGLTextureUploadMeta;
pub type GstVideoGLTextureUpload =
::std::option::Option<extern "C" fn
(meta: *mut GstVideoGLTextureUploadMeta,
texture_id: *mut guint) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoGLTextureUploadMeta {
pub meta: GstMeta,
pub texture_orientation: GstVideoGLTextureOrientation,
pub n_textures: guint,
pub texture_type: [GstVideoGLTextureType; 4u],
pub buffer: *mut GstBuffer,
pub upload: GstVideoGLTextureUpload,
pub user_data: gpointer,
pub user_data_copy: GBoxedCopyFunc,
pub user_data_free: GBoxedFreeFunc,
}
impl ::std::default::Default for Struct__GstVideoGLTextureUploadMeta {
fn default() -> Struct__GstVideoGLTextureUploadMeta {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed231 {
pub meta: GstMeta,
pub roi_type: GQuark,
pub id: gint,
pub parent_id: gint,
pub x: guint,
pub y: guint,
pub w: guint,
pub h: guint,
}
impl ::std::default::Default for Struct_Unnamed231 {
fn default() -> Struct_Unnamed231 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoRegionOfInterestMeta = Struct_Unnamed231;
pub type GstVideoBufferPool = Struct__GstVideoBufferPool;
pub type GstVideoBufferPoolClass = Struct__GstVideoBufferPoolClass;
pub enum Struct__GstVideoBufferPoolPrivate { }
pub type GstVideoBufferPoolPrivate = Struct__GstVideoBufferPoolPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoBufferPool {
pub bufferpool: GstBufferPool,
pub _priv: *mut GstVideoBufferPoolPrivate,
}
impl ::std::default::Default for Struct__GstVideoBufferPool {
fn default() -> Struct__GstVideoBufferPool {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoBufferPoolClass {
pub parent_class: GstBufferPoolClass,
}
impl ::std::default::Default for Struct__GstVideoBufferPoolClass {
fn default() -> Struct__GstVideoBufferPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoSink = Struct__GstVideoSink;
pub type GstVideoSinkClass = Struct__GstVideoSinkClass;
pub type GstVideoRectangle = Struct__GstVideoRectangle;
pub enum Struct__GstVideoSinkPrivate { }
pub type GstVideoSinkPrivate = Struct__GstVideoSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoRectangle {
pub x: gint,
pub y: gint,
pub w: gint,
pub h: gint,
}
impl ::std::default::Default for Struct__GstVideoRectangle {
fn default() -> Struct__GstVideoRectangle {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoSink {
pub element: GstBaseSink,
pub width: gint,
pub height: gint,
pub _priv: *mut GstVideoSinkPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoSink {
fn default() -> Struct__GstVideoSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoSinkClass {
pub parent_class: GstBaseSinkClass,
pub show_frame: ::std::option::Option<extern "C" fn
(video_sink: *mut GstVideoSink,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoSinkClass {
fn default() -> Struct__GstVideoSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstNavigation { }
pub type GstNavigation = Struct__GstNavigation;
pub type GstNavigationInterface = Struct__GstNavigationInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstNavigationInterface {
pub iface: GTypeInterface,
pub send_event: ::std::option::Option<extern "C" fn
(navigation: *mut GstNavigation,
structure: *mut GstStructure)>,
}
impl ::std::default::Default for Struct__GstNavigationInterface {
fn default() -> Struct__GstNavigationInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed232 = ::libc::c_uint;
pub const GST_NAVIGATION_COMMAND_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_COMMAND_MENU1: ::libc::c_uint = 1;
pub const GST_NAVIGATION_COMMAND_MENU2: ::libc::c_uint = 2;
pub const GST_NAVIGATION_COMMAND_MENU3: ::libc::c_uint = 3;
pub const GST_NAVIGATION_COMMAND_MENU4: ::libc::c_uint = 4;
pub const GST_NAVIGATION_COMMAND_MENU5: ::libc::c_uint = 5;
pub const GST_NAVIGATION_COMMAND_MENU6: ::libc::c_uint = 6;
pub const GST_NAVIGATION_COMMAND_MENU7: ::libc::c_uint = 7;
pub const GST_NAVIGATION_COMMAND_LEFT: ::libc::c_uint = 20;
pub const GST_NAVIGATION_COMMAND_RIGHT: ::libc::c_uint = 21;
pub const GST_NAVIGATION_COMMAND_UP: ::libc::c_uint = 22;
pub const GST_NAVIGATION_COMMAND_DOWN: ::libc::c_uint = 23;
pub const GST_NAVIGATION_COMMAND_ACTIVATE: ::libc::c_uint = 24;
pub const GST_NAVIGATION_COMMAND_PREV_ANGLE: ::libc::c_uint = 30;
pub const GST_NAVIGATION_COMMAND_NEXT_ANGLE: ::libc::c_uint = 31;
pub type GstNavigationCommand = Enum_Unnamed232;
pub type Enum_Unnamed233 = ::libc::c_uint;
pub const GST_NAVIGATION_QUERY_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_QUERY_COMMANDS: ::libc::c_uint = 1;
pub const GST_NAVIGATION_QUERY_ANGLES: ::libc::c_uint = 2;
pub type GstNavigationQueryType = Enum_Unnamed233;
pub type Enum_Unnamed234 = ::libc::c_uint;
pub const GST_NAVIGATION_MESSAGE_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_MESSAGE_MOUSE_OVER: ::libc::c_uint = 1;
pub const GST_NAVIGATION_MESSAGE_COMMANDS_CHANGED: ::libc::c_uint = 2;
pub const GST_NAVIGATION_MESSAGE_ANGLES_CHANGED: ::libc::c_uint = 3;
pub type GstNavigationMessageType = Enum_Unnamed234;
pub type Enum_Unnamed235 = ::libc::c_uint;
pub const GST_NAVIGATION_EVENT_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_EVENT_KEY_PRESS: ::libc::c_uint = 1;
pub const GST_NAVIGATION_EVENT_KEY_RELEASE: ::libc::c_uint = 2;
pub const GST_NAVIGATION_EVENT_MOUSE_BUTTON_PRESS: ::libc::c_uint = 3;
pub const GST_NAVIGATION_EVENT_MOUSE_BUTTON_RELEASE: ::libc::c_uint = 4;
pub const GST_NAVIGATION_EVENT_MOUSE_MOVE: ::libc::c_uint = 5;
pub const GST_NAVIGATION_EVENT_COMMAND: ::libc::c_uint = 6;
pub type GstNavigationEventType = Enum_Unnamed235;
pub enum Struct__GstVideoOrientation { }
pub type GstVideoOrientation = Struct__GstVideoOrientation;
pub type GstVideoOrientationInterface = Struct__GstVideoOrientationInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOrientationInterface {
pub iface: GTypeInterface,
pub get_hflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean)
-> gboolean>,
pub get_vflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean)
-> gboolean>,
pub get_hcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: *mut gint)
-> gboolean>,
pub get_vcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: *mut gint)
-> gboolean>,
pub set_hflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean>,
pub set_vflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean>,
pub set_hcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean>,
pub set_vcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean>,
}
impl ::std::default::Default for Struct__GstVideoOrientationInterface {
fn default() -> Struct__GstVideoOrientationInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstVideoOverlayRectangle { }
pub type GstVideoOverlayRectangle = Struct__GstVideoOverlayRectangle;
pub type Enum_Unnamed236 = ::libc::c_uint;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_PREMULTIPLIED_ALPHA: ::libc::c_uint =
1;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_GLOBAL_ALPHA: ::libc::c_uint = 2;
pub type GstVideoOverlayFormatFlags = Enum_Unnamed236;
pub enum Struct__GstVideoOverlayComposition { }
pub type GstVideoOverlayComposition = Struct__GstVideoOverlayComposition;
pub type GstVideoOverlayCompositionMeta =
Struct__GstVideoOverlayCompositionMeta;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOverlayCompositionMeta {
pub meta: GstMeta,
pub overlay: *mut GstVideoOverlayComposition,
}
impl ::std::default::Default for Struct__GstVideoOverlayCompositionMeta {
fn default() -> Struct__GstVideoOverlayCompositionMeta {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstVideoOverlay { }
pub type GstVideoOverlay = Struct__GstVideoOverlay;
pub type GstVideoOverlayInterface = Struct__GstVideoOverlayInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOverlayInterface {
pub iface: GTypeInterface,
pub expose: ::std::option::Option<extern "C" fn
(overlay: *mut GstVideoOverlay)>,
pub handle_events: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
handle_events: gboolean)>,
pub set_render_rectangle: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
x: gint, y: gint,
width: gint,
height: gint)>,
pub set_window_handle: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
handle: guintptr)>,
}
impl ::std::default::Default for Struct__GstVideoOverlayInterface {
fn default() -> Struct__GstVideoOverlayInterface {
unsafe { ::std::mem::zeroed() }
}
}
extern "C" {
pub static mut __tzname: [*mut ::libc::c_char; 2u];
pub static mut __daylight: ::libc::c_int;
pub static mut __timezone: ::libc::c_long;
pub static mut tzname: [*mut ::libc::c_char; 2u];
pub static mut daylight: ::libc::c_int;
pub static mut timezone: ::libc::c_long;
pub static mut _sys_siglist: [*const ::libc::c_char; 65u];
pub static mut sys_siglist: [*const ::libc::c_char; 65u];
pub static mut g_mem_gc_friendly: gboolean;
pub static mut glib_mem_profiler_table: *mut GMemVTable;
pub static mut g_timeout_funcs: GSourceFuncs;
pub static mut g_child_watch_funcs: GSourceFuncs;
pub static mut g_idle_funcs: GSourceFuncs;
pub static mut g_unix_signal_funcs: GSourceFuncs;
pub static mut g_unix_fd_source_funcs: GSourceFuncs;
pub static g_utf8_skip: *const gchar;
pub static mut g_io_watch_funcs: GSourceFuncs;
pub static g_ascii_table: *const guint16;
pub static g_test_config_vars: *const GTestConfig;
pub static glib_major_version: guint;
pub static glib_minor_version: guint;
pub static glib_micro_version: guint;
pub static glib_interface_age: guint;
pub static glib_binary_age: guint;
pub static mut g_thread_functions_for_glib_use: GThreadFunctions;
pub static mut g_thread_use_default_impl: gboolean;
pub static mut g_thread_gettime:
::std::option::Option<extern "C" fn() -> guint64>;
pub static mut g_threads_got_initialized: gboolean;
pub static mut g_param_spec_types: *mut GType;
pub static mut _gst_memory_type: GType;
pub static mut gst_memory_alignment: gsize;
pub static mut _gst_buffer_type: GType;
pub static mut _gst_meta_transform_copy: GQuark;
pub static mut _gst_meta_tag_memory: GQuark;
pub static mut _gst_buffer_list_type: GType;
pub static mut _gst_date_time_type: GType;
pub static mut _gst_structure_type: GType;
pub static mut _gst_caps_features_type: GType;
pub static mut _gst_caps_features_any: *mut GstCapsFeatures;
pub static mut _gst_caps_features_memory_system_memory:
*mut GstCapsFeatures;
pub static mut _gst_caps_type: GType;
pub static mut _gst_caps_any: *mut GstCaps;
pub static mut _gst_caps_none: *mut GstCaps;
pub static mut _gst_sample_type: GType;
pub static mut _gst_tag_list_type: GType;
pub static mut _gst_toc_type: GType;
pub static mut _gst_toc_entry_type: GType;
pub static mut _gst_context_type: GType;
pub static mut _gst_query_type: GType;
pub static mut _gst_message_type: GType;
pub static mut _gst_event_type: GType;
pub static mut GST_CAT_DEFAULT: *mut GstDebugCategory;
pub static mut _gst_debug_enabled: gboolean;
pub static mut _gst_debug_min: GstDebugLevel;
pub static mut _gst_int_range_type: GType;
pub static mut _gst_int64_range_type: GType;
pub static mut _gst_double_range_type: GType;
pub static mut _gst_fraction_range_type: GType;
pub static mut _gst_value_list_type: GType;
pub static mut _gst_value_array_type: GType;
pub static mut _gst_fraction_type: GType;
pub static mut _gst_bitmask_type: GType;
}
extern "C" {
pub fn clock() -> clock_t;
pub fn time(__timer: *mut time_t) -> time_t;
pub fn difftime(__time1: time_t, __time0: time_t) -> ::libc::c_double;
pub fn mktime(__tp: *mut Struct_tm) -> time_t;
pub fn strftime(__s: *mut ::libc::c_char, __maxsize: size_t,
__format: *const ::libc::c_char, __tp: *const Struct_tm)
-> size_t;
pub fn strftime_l(__s: *mut ::libc::c_char, __maxsize: size_t,
__format: *const ::libc::c_char, __tp: *const Struct_tm,
__loc: __locale_t) -> size_t;
pub fn gmtime(__timer: *const time_t) -> *mut Struct_tm;
pub fn localtime(__timer: *const time_t) -> *mut Struct_tm;
pub fn gmtime_r(__timer: *const time_t, __tp: *mut Struct_tm)
-> *mut Struct_tm;
pub fn localtime_r(__timer: *const time_t, __tp: *mut Struct_tm)
-> *mut Struct_tm;
pub fn asctime(__tp: *const Struct_tm) -> *mut ::libc::c_char;
pub fn ctime(__timer: *const time_t) -> *mut ::libc::c_char;
pub fn asctime_r(__tp: *const Struct_tm, __buf: *mut ::libc::c_char)
-> *mut ::libc::c_char;
pub fn ctime_r(__timer: *const time_t, __buf: *mut ::libc::c_char)
-> *mut ::libc::c_char;
pub fn tzset();
pub fn stime(__when: *const time_t) -> ::libc::c_int;
pub fn timegm(__tp: *mut Struct_tm) -> time_t;
pub fn timelocal(__tp: *mut Struct_tm) -> time_t;
pub fn dysize(__year: ::libc::c_int) -> ::libc::c_int;
pub fn nanosleep(__requested_time: *const Struct_timespec,
__remaining: *mut Struct_timespec) -> ::libc::c_int;
pub fn clock_getres(__clock_id: clockid_t, __res: *mut Struct_timespec)
-> ::libc::c_int;
pub fn clock_gettime(__clock_id: clockid_t, __tp: *mut Struct_timespec)
-> ::libc::c_int;
pub fn clock_settime(__clock_id: clockid_t, __tp: *const Struct_timespec)
-> ::libc::c_int;
pub fn clock_nanosleep(__clock_id: clockid_t, __flags: ::libc::c_int,
__req: *const Struct_timespec,
__rem: *mut Struct_timespec) -> ::libc::c_int;
pub fn clock_getcpuclockid(__pid: pid_t, __clock_id: *mut clockid_t)
-> ::libc::c_int;
pub fn timer_create(__clock_id: clockid_t, __evp: *mut Struct_sigevent,
__timerid: *mut timer_t) -> ::libc::c_int;
pub fn timer_delete(__timerid: timer_t) -> ::libc::c_int;
pub fn timer_settime(__timerid: timer_t, __flags: ::libc::c_int,
__value: *const Struct_itimerspec,
__ovalue: *mut Struct_itimerspec) -> ::libc::c_int;
pub fn timer_gettime(__timerid: timer_t, __value: *mut Struct_itimerspec)
-> ::libc::c_int;
pub fn timer_getoverrun(__timerid: timer_t) -> ::libc::c_int;
pub fn g_array_new(zero_terminated: gboolean, clear_: gboolean,
element_size: guint) -> *mut GArray;
pub fn g_array_sized_new(zero_terminated: gboolean, clear_: gboolean,
element_size: guint, reserved_size: guint)
-> *mut GArray;
pub fn g_array_free(array: *mut GArray, free_segment: gboolean)
-> *mut gchar;
pub fn g_array_ref(array: *mut GArray) -> *mut GArray;
pub fn g_array_unref(array: *mut GArray);
pub fn g_array_get_element_size(array: *mut GArray) -> guint;
pub fn g_array_append_vals(array: *mut GArray, data: gconstpointer,
len: guint) -> *mut GArray;
pub fn g_array_prepend_vals(array: *mut GArray, data: gconstpointer,
len: guint) -> *mut GArray;
pub fn g_array_insert_vals(array: *mut GArray, index_: guint,
data: gconstpointer, len: guint)
-> *mut GArray;
pub fn g_array_set_size(array: *mut GArray, length: guint) -> *mut GArray;
pub fn g_array_remove_index(array: *mut GArray, index_: guint)
-> *mut GArray;
pub fn g_array_remove_index_fast(array: *mut GArray, index_: guint)
-> *mut GArray;
pub fn g_array_remove_range(array: *mut GArray, index_: guint,
length: guint) -> *mut GArray;
pub fn g_array_sort(array: *mut GArray, compare_func: GCompareFunc);
pub fn g_array_sort_with_data(array: *mut GArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_array_set_clear_func(array: *mut GArray,
clear_func: GDestroyNotify);
pub fn g_ptr_array_new() -> *mut GPtrArray;
pub fn g_ptr_array_new_with_free_func(element_free_func: GDestroyNotify)
-> *mut GPtrArray;
pub fn g_ptr_array_sized_new(reserved_size: guint) -> *mut GPtrArray;
pub fn g_ptr_array_new_full(reserved_size: guint,
element_free_func: GDestroyNotify)
-> *mut GPtrArray;
pub fn g_ptr_array_free(array: *mut GPtrArray, free_seg: gboolean)
-> *mut gpointer;
pub fn g_ptr_array_ref(array: *mut GPtrArray) -> *mut GPtrArray;
pub fn g_ptr_array_unref(array: *mut GPtrArray);
pub fn g_ptr_array_set_free_func(array: *mut GPtrArray,
element_free_func: GDestroyNotify);
pub fn g_ptr_array_set_size(array: *mut GPtrArray, length: gint);
pub fn g_ptr_array_remove_index(array: *mut GPtrArray, index_: guint)
-> gpointer;
pub fn g_ptr_array_remove_index_fast(array: *mut GPtrArray, index_: guint)
-> gpointer;
pub fn g_ptr_array_remove(array: *mut GPtrArray, data: gpointer)
-> gboolean;
pub fn g_ptr_array_remove_fast(array: *mut GPtrArray, data: gpointer)
-> gboolean;
pub fn g_ptr_array_remove_range(array: *mut GPtrArray, index_: guint,
length: guint) -> *mut GPtrArray;
pub fn g_ptr_array_add(array: *mut GPtrArray, data: gpointer);
pub fn g_ptr_array_insert(array: *mut GPtrArray, index_: gint,
data: gpointer);
pub fn g_ptr_array_sort(array: *mut GPtrArray,
compare_func: GCompareFunc);
pub fn g_ptr_array_sort_with_data(array: *mut GPtrArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_ptr_array_foreach(array: *mut GPtrArray, func: GFunc,
user_data: gpointer);
pub fn g_byte_array_new() -> *mut GByteArray;
pub fn g_byte_array_new_take(data: *mut guint8, len: gsize)
-> *mut GByteArray;
pub fn g_byte_array_sized_new(reserved_size: guint) -> *mut GByteArray;
pub fn g_byte_array_free(array: *mut GByteArray, free_segment: gboolean)
-> *mut guint8;
pub fn g_byte_array_free_to_bytes(array: *mut GByteArray) -> *mut GBytes;
pub fn g_byte_array_ref(array: *mut GByteArray) -> *mut GByteArray;
pub fn g_byte_array_unref(array: *mut GByteArray);
pub fn g_byte_array_append(array: *mut GByteArray, data: *const guint8,
len: guint) -> *mut GByteArray;
pub fn g_byte_array_prepend(array: *mut GByteArray, data: *const guint8,
len: guint) -> *mut GByteArray;
pub fn g_byte_array_set_size(array: *mut GByteArray, length: guint)
-> *mut GByteArray;
pub fn g_byte_array_remove_index(array: *mut GByteArray, index_: guint)
-> *mut GByteArray;
pub fn g_byte_array_remove_index_fast(array: *mut GByteArray,
index_: guint) -> *mut GByteArray;
pub fn g_byte_array_remove_range(array: *mut GByteArray, index_: guint,
length: guint) -> *mut GByteArray;
pub fn g_byte_array_sort(array: *mut GByteArray,
compare_func: GCompareFunc);
pub fn g_byte_array_sort_with_data(array: *mut GByteArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_atomic_int_get(atomic: *const gint) -> gint;
pub fn g_atomic_int_set(atomic: *mut gint, newval: gint);
pub fn g_atomic_int_inc(atomic: *mut gint);
pub fn g_atomic_int_dec_and_test(atomic: *mut gint) -> gboolean;
pub fn g_atomic_int_compare_and_exchange(atomic: *mut gint, oldval: gint,
newval: gint) -> gboolean;
pub fn g_atomic_int_add(atomic: *mut gint, val: gint) -> gint;
pub fn g_atomic_int_and(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_int_or(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_int_xor(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_pointer_get(atomic: *const ::libc::c_void) -> gpointer;
pub fn g_atomic_pointer_set(atomic: *mut ::libc::c_void,
newval: gpointer);
pub fn g_atomic_pointer_compare_and_exchange(atomic: *mut ::libc::c_void,
oldval: gpointer,
newval: gpointer)
-> gboolean;
pub fn g_atomic_pointer_add(atomic: *mut ::libc::c_void, val: gssize)
-> gssize;
pub fn g_atomic_pointer_and(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_pointer_or(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_pointer_xor(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_int_exchange_and_add(atomic: *mut gint, val: gint)
-> gint;
pub fn g_quark_try_string(string: *const gchar) -> GQuark;
pub fn g_quark_from_static_string(string: *const gchar) -> GQuark;
pub fn g_quark_from_string(string: *const gchar) -> GQuark;
pub fn g_quark_to_string(quark: GQuark) -> *const gchar;
pub fn g_intern_string(string: *const gchar) -> *const gchar;
pub fn g_intern_static_string(string: *const gchar) -> *const gchar;
pub fn g_error_new(domain: GQuark, code: gint, format: *const gchar, ...)
-> *mut GError;
pub fn g_error_new_literal(domain: GQuark, code: gint,
message: *const gchar) -> *mut GError;
pub fn g_error_new_valist(domain: GQuark, code: gint,
format: *const gchar, args: va_list)
-> *mut GError;
pub fn g_error_free(error: *mut GError);
pub fn g_error_copy(error: *const GError) -> *mut GError;
pub fn g_error_matches(error: *const GError, domain: GQuark, code: gint)
-> gboolean;
pub fn g_set_error(err: *mut *mut GError, domain: GQuark, code: gint,
format: *const gchar, ...);
pub fn g_set_error_literal(err: *mut *mut GError, domain: GQuark,
code: gint, message: *const gchar);
pub fn g_propagate_error(dest: *mut *mut GError, src: *mut GError);
pub fn g_clear_error(err: *mut *mut GError);
pub fn g_prefix_error(err: *mut *mut GError, format: *const gchar, ...);
pub fn g_propagate_prefixed_error(dest: *mut *mut GError,
src: *mut GError,
format: *const gchar, ...);
pub fn g_thread_error_quark() -> GQuark;
pub fn g_thread_ref(thread: *mut GThread) -> *mut GThread;
pub fn g_thread_unref(thread: *mut GThread);
pub fn g_thread_new(name: *const gchar, func: GThreadFunc, data: gpointer)
-> *mut GThread;
pub fn g_thread_try_new(name: *const gchar, func: GThreadFunc,
data: gpointer, error: *mut *mut GError)
-> *mut GThread;
pub fn g_thread_self() -> *mut GThread;
pub fn g_thread_exit(retval: gpointer);
pub fn g_thread_join(thread: *mut GThread) -> gpointer;
pub fn g_thread_yield();
pub fn g_mutex_init(mutex: *mut GMutex);
pub fn g_mutex_clear(mutex: *mut GMutex);
pub fn g_mutex_lock(mutex: *mut GMutex);
pub fn g_mutex_trylock(mutex: *mut GMutex) -> gboolean;
pub fn g_mutex_unlock(mutex: *mut GMutex);
pub fn g_rw_lock_init(rw_lock: *mut GRWLock);
pub fn g_rw_lock_clear(rw_lock: *mut GRWLock);
pub fn g_rw_lock_writer_lock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_writer_trylock(rw_lock: *mut GRWLock) -> gboolean;
pub fn g_rw_lock_writer_unlock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_reader_lock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_reader_trylock(rw_lock: *mut GRWLock) -> gboolean;
pub fn g_rw_lock_reader_unlock(rw_lock: *mut GRWLock);
pub fn g_rec_mutex_init(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_clear(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_lock(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_trylock(rec_mutex: *mut GRecMutex) -> gboolean;
pub fn g_rec_mutex_unlock(rec_mutex: *mut GRecMutex);
pub fn g_cond_init(cond: *mut GCond);
pub fn g_cond_clear(cond: *mut GCond);
pub fn g_cond_wait(cond: *mut GCond, mutex: *mut GMutex);
pub fn g_cond_signal(cond: *mut GCond);
pub fn g_cond_broadcast(cond: *mut GCond);
pub fn g_cond_wait_until(cond: *mut GCond, mutex: *mut GMutex,
end_time: gint64) -> gboolean;
pub fn g_private_get(key: *mut GPrivate) -> gpointer;
pub fn g_private_set(key: *mut GPrivate, value: gpointer);
pub fn g_private_replace(key: *mut GPrivate, value: gpointer);
pub fn g_once_impl(once: *mut GOnce, func: GThreadFunc, arg: gpointer)
-> gpointer;
pub fn g_once_init_enter(location: *mut ::libc::c_void) -> gboolean;
pub fn g_once_init_leave(location: *mut ::libc::c_void, result: gsize);
pub fn g_get_num_processors() -> guint;
pub fn g_async_queue_new() -> *mut GAsyncQueue;
pub fn g_async_queue_new_full(item_free_func: GDestroyNotify)
-> *mut GAsyncQueue;
pub fn g_async_queue_lock(queue: *mut GAsyncQueue);
pub fn g_async_queue_unlock(queue: *mut GAsyncQueue);
pub fn g_async_queue_ref(queue: *mut GAsyncQueue) -> *mut GAsyncQueue;
pub fn g_async_queue_unref(queue: *mut GAsyncQueue);
pub fn g_async_queue_ref_unlocked(queue: *mut GAsyncQueue);
pub fn g_async_queue_unref_and_unlock(queue: *mut GAsyncQueue);
pub fn g_async_queue_push(queue: *mut GAsyncQueue, data: gpointer);
pub fn g_async_queue_push_unlocked(queue: *mut GAsyncQueue,
data: gpointer);
pub fn g_async_queue_push_sorted(queue: *mut GAsyncQueue, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_push_sorted_unlocked(queue: *mut GAsyncQueue,
data: gpointer,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_pop(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_pop_unlocked(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_try_pop(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_try_pop_unlocked(queue: *mut GAsyncQueue)
-> gpointer;
pub fn g_async_queue_timeout_pop(queue: *mut GAsyncQueue,
timeout: guint64) -> gpointer;
pub fn g_async_queue_timeout_pop_unlocked(queue: *mut GAsyncQueue,
timeout: guint64) -> gpointer;
pub fn g_async_queue_length(queue: *mut GAsyncQueue) -> gint;
pub fn g_async_queue_length_unlocked(queue: *mut GAsyncQueue) -> gint;
pub fn g_async_queue_sort(queue: *mut GAsyncQueue, func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_sort_unlocked(queue: *mut GAsyncQueue,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_timed_pop(queue: *mut GAsyncQueue,
end_time: *mut GTimeVal) -> gpointer;
pub fn g_async_queue_timed_pop_unlocked(queue: *mut GAsyncQueue,
end_time: *mut GTimeVal)
-> gpointer;
pub fn __sigismember(arg1: *const __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sigaddset(arg1: *mut __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sigdelset(arg1: *mut __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sysv_signal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn signal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn kill(__pid: __pid_t, __sig: ::libc::c_int) -> ::libc::c_int;
pub fn killpg(__pgrp: __pid_t, __sig: ::libc::c_int) -> ::libc::c_int;
pub fn raise(__sig: ::libc::c_int) -> ::libc::c_int;
pub fn ssignal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn gsignal(__sig: ::libc::c_int) -> ::libc::c_int;
pub fn psignal(__sig: ::libc::c_int, __s: *const ::libc::c_char);
pub fn psiginfo(__pinfo: *const siginfo_t, __s: *const ::libc::c_char);
pub fn __sigpause(__sig_or_mask: ::libc::c_int, __is_sig: ::libc::c_int)
-> ::libc::c_int;
pub fn sigblock(__mask: ::libc::c_int) -> ::libc::c_int;
pub fn sigsetmask(__mask: ::libc::c_int) -> ::libc::c_int;
pub fn siggetmask() -> ::libc::c_int;
pub fn sigemptyset(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigfillset(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigaddset(__set: *mut sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigdelset(__set: *mut sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigismember(__set: *const sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigprocmask(__how: ::libc::c_int, __set: *const sigset_t,
__oset: *mut sigset_t) -> ::libc::c_int;
pub fn sigsuspend(__set: *const sigset_t) -> ::libc::c_int;
pub fn sigaction(__sig: ::libc::c_int, __act: *const Struct_sigaction,
__oact: *mut Struct_sigaction) -> ::libc::c_int;
pub fn sigpending(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigwait(__set: *const sigset_t, __sig: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn sigwaitinfo(__set: *const sigset_t, __info: *mut siginfo_t)
-> ::libc::c_int;
pub fn sigtimedwait(__set: *const sigset_t, __info: *mut siginfo_t,
__timeout: *const Struct_timespec) -> ::libc::c_int;
pub fn sigqueue(__pid: __pid_t, __sig: ::libc::c_int, __val: Union_sigval)
-> ::libc::c_int;
pub fn sigvec(__sig: ::libc::c_int, __vec: *const Struct_sigvec,
__ovec: *mut Struct_sigvec) -> ::libc::c_int;
pub fn sigreturn(__scp: *mut Struct_sigcontext) -> ::libc::c_int;
pub fn siginterrupt(__sig: ::libc::c_int, __interrupt: ::libc::c_int)
-> ::libc::c_int;
pub fn sigstack(__ss: *mut Struct_sigstack, __oss: *mut Struct_sigstack)
-> ::libc::c_int;
pub fn sigaltstack(__ss: *const Struct_sigaltstack,
__oss: *mut Struct_sigaltstack) -> ::libc::c_int;
pub fn pthread_sigmask(__how: ::libc::c_int, __newmask: *const __sigset_t,
__oldmask: *mut __sigset_t) -> ::libc::c_int;
pub fn pthread_kill(__threadid: pthread_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn __libc_current_sigrtmin() -> ::libc::c_int;
pub fn __libc_current_sigrtmax() -> ::libc::c_int;
pub fn g_on_error_query(prg_name: *const gchar);
pub fn g_on_error_stack_trace(prg_name: *const gchar);
pub fn g_base64_encode_step(_in: *const guchar, len: gsize,
break_lines: gboolean, out: *mut gchar,
state: *mut gint, save: *mut gint) -> gsize;
pub fn g_base64_encode_close(break_lines: gboolean, out: *mut gchar,
state: *mut gint, save: *mut gint) -> gsize;
pub fn g_base64_encode(data: *const guchar, len: gsize) -> *mut gchar;
pub fn g_base64_decode_step(_in: *const gchar, len: gsize,
out: *mut guchar, state: *mut gint,
save: *mut guint) -> gsize;
pub fn g_base64_decode(text: *const gchar, out_len: *mut gsize)
-> *mut guchar;
pub fn g_base64_decode_inplace(text: *mut gchar, out_len: *mut gsize)
-> *mut guchar;
pub fn g_bit_lock(address: *mut gint, lock_bit: gint);
pub fn g_bit_trylock(address: *mut gint, lock_bit: gint) -> gboolean;
pub fn g_bit_unlock(address: *mut gint, lock_bit: gint);
pub fn g_pointer_bit_lock(address: *mut ::libc::c_void, lock_bit: gint);
pub fn g_pointer_bit_trylock(address: *mut ::libc::c_void, lock_bit: gint)
-> gboolean;
pub fn g_pointer_bit_unlock(address: *mut ::libc::c_void, lock_bit: gint);
pub fn g_bookmark_file_error_quark() -> GQuark;
pub fn g_bookmark_file_new() -> *mut GBookmarkFile;
pub fn g_bookmark_file_free(bookmark: *mut GBookmarkFile);
pub fn g_bookmark_file_load_from_file(bookmark: *mut GBookmarkFile,
filename: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_load_from_data(bookmark: *mut GBookmarkFile,
data: *const gchar, length: gsize,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_load_from_data_dirs(bookmark: *mut GBookmarkFile,
file: *const gchar,
full_path: *mut *mut gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_to_data(bookmark: *mut GBookmarkFile,
length: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_bookmark_file_to_file(bookmark: *mut GBookmarkFile,
filename: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_title(bookmark: *mut GBookmarkFile,
uri: *const gchar, title: *const gchar);
pub fn g_bookmark_file_get_title(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_bookmark_file_set_description(bookmark: *mut GBookmarkFile,
uri: *const gchar,
description: *const gchar);
pub fn g_bookmark_file_get_description(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_bookmark_file_set_mime_type(bookmark: *mut GBookmarkFile,
uri: *const gchar,
mime_type: *const gchar);
pub fn g_bookmark_file_get_mime_type(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_bookmark_file_set_groups(bookmark: *mut GBookmarkFile,
uri: *const gchar,
groups: *mut *const gchar,
length: gsize);
pub fn g_bookmark_file_add_group(bookmark: *mut GBookmarkFile,
uri: *const gchar, group: *const gchar);
pub fn g_bookmark_file_has_group(bookmark: *mut GBookmarkFile,
uri: *const gchar, group: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_get_groups(bookmark: *mut GBookmarkFile,
uri: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_bookmark_file_add_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
exec: *const gchar);
pub fn g_bookmark_file_has_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_get_applications(bookmark: *mut GBookmarkFile,
uri: *const gchar,
length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_bookmark_file_set_app_info(bookmark: *mut GBookmarkFile,
uri: *const gchar, name: *const gchar,
exec: *const gchar, count: gint,
stamp: time_t,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_get_app_info(bookmark: *mut GBookmarkFile,
uri: *const gchar, name: *const gchar,
exec: *mut *mut gchar,
count: *mut guint, stamp: *mut time_t,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_is_private(bookmark: *mut GBookmarkFile,
uri: *const gchar,
is_private: gboolean);
pub fn g_bookmark_file_get_is_private(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_set_icon(bookmark: *mut GBookmarkFile,
uri: *const gchar, href: *const gchar,
mime_type: *const gchar);
pub fn g_bookmark_file_get_icon(bookmark: *mut GBookmarkFile,
uri: *const gchar, href: *mut *mut gchar,
mime_type: *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_added(bookmark: *mut GBookmarkFile,
uri: *const gchar, added: time_t);
pub fn g_bookmark_file_get_added(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_set_modified(bookmark: *mut GBookmarkFile,
uri: *const gchar, modified: time_t);
pub fn g_bookmark_file_get_modified(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_set_visited(bookmark: *mut GBookmarkFile,
uri: *const gchar, visited: time_t);
pub fn g_bookmark_file_get_visited(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_has_item(bookmark: *mut GBookmarkFile,
uri: *const gchar) -> gboolean;
pub fn g_bookmark_file_get_size(bookmark: *mut GBookmarkFile) -> gint;
pub fn g_bookmark_file_get_uris(bookmark: *mut GBookmarkFile,
length: *mut gsize) -> *mut *mut gchar;
pub fn g_bookmark_file_remove_group(bookmark: *mut GBookmarkFile,
uri: *const gchar,
group: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_remove_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_remove_item(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_move_item(bookmark: *mut GBookmarkFile,
old_uri: *const gchar,
new_uri: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bytes_new(data: gconstpointer, size: gsize) -> *mut GBytes;
pub fn g_bytes_new_take(data: gpointer, size: gsize) -> *mut GBytes;
pub fn g_bytes_new_static(data: gconstpointer, size: gsize)
-> *mut GBytes;
pub fn g_bytes_new_with_free_func(data: gconstpointer, size: gsize,
free_func: GDestroyNotify,
user_data: gpointer) -> *mut GBytes;
pub fn g_bytes_new_from_bytes(bytes: *mut GBytes, offset: gsize,
length: gsize) -> *mut GBytes;
pub fn g_bytes_get_data(bytes: *mut GBytes, size: *mut gsize)
-> gconstpointer;
pub fn g_bytes_get_size(bytes: *mut GBytes) -> gsize;
pub fn g_bytes_ref(bytes: *mut GBytes) -> *mut GBytes;
pub fn g_bytes_unref(bytes: *mut GBytes);
pub fn g_bytes_unref_to_data(bytes: *mut GBytes, size: *mut gsize)
-> gpointer;
pub fn g_bytes_unref_to_array(bytes: *mut GBytes) -> *mut GByteArray;
pub fn g_bytes_hash(bytes: gconstpointer) -> guint;
pub fn g_bytes_equal(bytes1: gconstpointer, bytes2: gconstpointer)
-> gboolean;
pub fn g_bytes_compare(bytes1: gconstpointer, bytes2: gconstpointer)
-> gint;
pub fn g_get_charset(charset: *mut *const ::libc::c_char) -> gboolean;
pub fn g_get_codeset() -> *mut gchar;
pub fn g_get_language_names() -> *const *const gchar;
pub fn g_get_locale_variants(locale: *const gchar) -> *mut *mut gchar;
pub fn g_checksum_type_get_length(checksum_type: GChecksumType) -> gssize;
pub fn g_checksum_new(checksum_type: GChecksumType) -> *mut GChecksum;
pub fn g_checksum_reset(checksum: *mut GChecksum);
pub fn g_checksum_copy(checksum: *const GChecksum) -> *mut GChecksum;
pub fn g_checksum_free(checksum: *mut GChecksum);
pub fn g_checksum_update(checksum: *mut GChecksum, data: *const guchar,
length: gssize);
pub fn g_checksum_get_string(checksum: *mut GChecksum) -> *const gchar;
pub fn g_checksum_get_digest(checksum: *mut GChecksum,
buffer: *mut guint8, digest_len: *mut gsize);
pub fn g_compute_checksum_for_data(checksum_type: GChecksumType,
data: *const guchar, length: gsize)
-> *mut gchar;
pub fn g_compute_checksum_for_string(checksum_type: GChecksumType,
str: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_compute_checksum_for_bytes(checksum_type: GChecksumType,
data: *mut GBytes) -> *mut gchar;
pub fn g_convert_error_quark() -> GQuark;
pub fn g_iconv_open(to_codeset: *const gchar, from_codeset: *const gchar)
-> GIConv;
pub fn g_iconv(converter: GIConv, inbuf: *mut *mut gchar,
inbytes_left: *mut gsize, outbuf: *mut *mut gchar,
outbytes_left: *mut gsize) -> gsize;
pub fn g_iconv_close(converter: GIConv) -> gint;
pub fn g_convert(str: *const gchar, len: gssize, to_codeset: *const gchar,
from_codeset: *const gchar, bytes_read: *mut gsize,
bytes_written: *mut gsize, error: *mut *mut GError)
-> *mut gchar;
pub fn g_convert_with_iconv(str: *const gchar, len: gssize,
converter: GIConv, bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_convert_with_fallback(str: *const gchar, len: gssize,
to_codeset: *const gchar,
from_codeset: *const gchar,
fallback: *const gchar,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_locale_to_utf8(opsysstring: *const gchar, len: gssize,
bytes_read: *mut gsize, bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_locale_from_utf8(utf8string: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_to_utf8(opsysstring: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_from_utf8(utf8string: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_from_uri(uri: *const gchar, hostname: *mut *mut gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_to_uri(filename: *const gchar, hostname: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_display_name(filename: *const gchar) -> *mut gchar;
pub fn g_get_filename_charsets(charsets: *mut *mut *const gchar)
-> gboolean;
pub fn g_filename_display_basename(filename: *const gchar) -> *mut gchar;
pub fn g_uri_list_extract_uris(uri_list: *const gchar) -> *mut *mut gchar;
pub fn g_datalist_init(datalist: *mut *mut GData);
pub fn g_datalist_clear(datalist: *mut *mut GData);
pub fn g_datalist_id_get_data(datalist: *mut *mut GData, key_id: GQuark)
-> gpointer;
pub fn g_datalist_id_set_data_full(datalist: *mut *mut GData,
key_id: GQuark, data: gpointer,
destroy_func: GDestroyNotify);
pub fn g_datalist_id_dup_data(datalist: *mut *mut GData, key_id: GQuark,
dup_func: GDuplicateFunc,
user_data: gpointer) -> gpointer;
pub fn g_datalist_id_replace_data(datalist: *mut *mut GData,
key_id: GQuark, oldval: gpointer,
newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_datalist_id_remove_no_notify(datalist: *mut *mut GData,
key_id: GQuark) -> gpointer;
pub fn g_datalist_foreach(datalist: *mut *mut GData,
func: GDataForeachFunc, user_data: gpointer);
pub fn g_datalist_set_flags(datalist: *mut *mut GData, flags: guint);
pub fn g_datalist_unset_flags(datalist: *mut *mut GData, flags: guint);
pub fn g_datalist_get_flags(datalist: *mut *mut GData) -> guint;
pub fn g_dataset_destroy(dataset_location: gconstpointer);
pub fn g_dataset_id_get_data(dataset_location: gconstpointer,
key_id: GQuark) -> gpointer;
pub fn g_datalist_get_data(datalist: *mut *mut GData, key: *const gchar)
-> gpointer;
pub fn g_dataset_id_set_data_full(dataset_location: gconstpointer,
key_id: GQuark, data: gpointer,
destroy_func: GDestroyNotify);
pub fn g_dataset_id_remove_no_notify(dataset_location: gconstpointer,
key_id: GQuark) -> gpointer;
pub fn g_dataset_foreach(dataset_location: gconstpointer,
func: GDataForeachFunc, user_data: gpointer);
pub fn g_date_new() -> *mut GDate;
pub fn g_date_new_dmy(day: GDateDay, month: GDateMonth, year: GDateYear)
-> *mut GDate;
pub fn g_date_new_julian(julian_day: guint32) -> *mut GDate;
pub fn g_date_free(date: *mut GDate);
pub fn g_date_valid(date: *const GDate) -> gboolean;
pub fn g_date_valid_day(day: GDateDay) -> gboolean;
pub fn g_date_valid_month(month: GDateMonth) -> gboolean;
pub fn g_date_valid_year(year: GDateYear) -> gboolean;
pub fn g_date_valid_weekday(weekday: GDateWeekday) -> gboolean;
pub fn g_date_valid_julian(julian_date: guint32) -> gboolean;
pub fn g_date_valid_dmy(day: GDateDay, month: GDateMonth, year: GDateYear)
-> gboolean;
pub fn g_date_get_weekday(date: *const GDate) -> GDateWeekday;
pub fn g_date_get_month(date: *const GDate) -> GDateMonth;
pub fn g_date_get_year(date: *const GDate) -> GDateYear;
pub fn g_date_get_day(date: *const GDate) -> GDateDay;
pub fn g_date_get_julian(date: *const GDate) -> guint32;
pub fn g_date_get_day_of_year(date: *const GDate) -> guint;
pub fn g_date_get_monday_week_of_year(date: *const GDate) -> guint;
pub fn g_date_get_sunday_week_of_year(date: *const GDate) -> guint;
pub fn g_date_get_iso8601_week_of_year(date: *const GDate) -> guint;
pub fn g_date_clear(date: *mut GDate, n_dates: guint);
pub fn g_date_set_parse(date: *mut GDate, str: *const gchar);
pub fn g_date_set_time_t(date: *mut GDate, timet: time_t);
pub fn g_date_set_time_val(date: *mut GDate, timeval: *mut GTimeVal);
pub fn g_date_set_time(date: *mut GDate, time_: GTime);
pub fn g_date_set_month(date: *mut GDate, month: GDateMonth);
pub fn g_date_set_day(date: *mut GDate, day: GDateDay);
pub fn g_date_set_year(date: *mut GDate, year: GDateYear);
pub fn g_date_set_dmy(date: *mut GDate, day: GDateDay, month: GDateMonth,
y: GDateYear);
pub fn g_date_set_julian(date: *mut GDate, julian_date: guint32);
pub fn g_date_is_first_of_month(date: *const GDate) -> gboolean;
pub fn g_date_is_last_of_month(date: *const GDate) -> gboolean;
pub fn g_date_add_days(date: *mut GDate, n_days: guint);
pub fn g_date_subtract_days(date: *mut GDate, n_days: guint);
pub fn g_date_add_months(date: *mut GDate, n_months: guint);
pub fn g_date_subtract_months(date: *mut GDate, n_months: guint);
pub fn g_date_add_years(date: *mut GDate, n_years: guint);
pub fn g_date_subtract_years(date: *mut GDate, n_years: guint);
pub fn g_date_is_leap_year(year: GDateYear) -> gboolean;
pub fn g_date_get_days_in_month(month: GDateMonth, year: GDateYear)
-> guint8;
pub fn g_date_get_monday_weeks_in_year(year: GDateYear) -> guint8;
pub fn g_date_get_sunday_weeks_in_year(year: GDateYear) -> guint8;
pub fn g_date_days_between(date1: *const GDate, date2: *const GDate)
-> gint;
pub fn g_date_compare(lhs: *const GDate, rhs: *const GDate) -> gint;
pub fn g_date_to_struct_tm(date: *const GDate, tm: *mut Struct_tm);
pub fn g_date_clamp(date: *mut GDate, min_date: *const GDate,
max_date: *const GDate);
pub fn g_date_order(date1: *mut GDate, date2: *mut GDate);
pub fn g_date_strftime(s: *mut gchar, slen: gsize, format: *const gchar,
date: *const GDate) -> gsize;
pub fn g_time_zone_new(identifier: *const gchar) -> *mut GTimeZone;
pub fn g_time_zone_new_utc() -> *mut GTimeZone;
pub fn g_time_zone_new_local() -> *mut GTimeZone;
pub fn g_time_zone_ref(tz: *mut GTimeZone) -> *mut GTimeZone;
pub fn g_time_zone_unref(tz: *mut GTimeZone);
pub fn g_time_zone_find_interval(tz: *mut GTimeZone, _type: GTimeType,
time_: gint64) -> gint;
pub fn g_time_zone_adjust_time(tz: *mut GTimeZone, _type: GTimeType,
time_: *mut gint64) -> gint;
pub fn g_time_zone_get_abbreviation(tz: *mut GTimeZone, interval: gint)
-> *const gchar;
pub fn g_time_zone_get_offset(tz: *mut GTimeZone, interval: gint)
-> gint32;
pub fn g_time_zone_is_dst(tz: *mut GTimeZone, interval: gint) -> gboolean;
pub fn g_date_time_unref(datetime: *mut GDateTime);
pub fn g_date_time_ref(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_new_now(tz: *mut GTimeZone) -> *mut GDateTime;
pub fn g_date_time_new_now_local() -> *mut GDateTime;
pub fn g_date_time_new_now_utc() -> *mut GDateTime;
pub fn g_date_time_new_from_unix_local(t: gint64) -> *mut GDateTime;
pub fn g_date_time_new_from_unix_utc(t: gint64) -> *mut GDateTime;
pub fn g_date_time_new_from_timeval_local(tv: *const GTimeVal)
-> *mut GDateTime;
pub fn g_date_time_new_from_timeval_utc(tv: *const GTimeVal)
-> *mut GDateTime;
pub fn g_date_time_new(tz: *mut GTimeZone, year: gint, month: gint,
day: gint, hour: gint, minute: gint,
seconds: gdouble) -> *mut GDateTime;
pub fn g_date_time_new_local(year: gint, month: gint, day: gint,
hour: gint, minute: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_new_utc(year: gint, month: gint, day: gint, hour: gint,
minute: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_add(datetime: *mut GDateTime, timespan: GTimeSpan)
-> *mut GDateTime;
pub fn g_date_time_add_years(datetime: *mut GDateTime, years: gint)
-> *mut GDateTime;
pub fn g_date_time_add_months(datetime: *mut GDateTime, months: gint)
-> *mut GDateTime;
pub fn g_date_time_add_weeks(datetime: *mut GDateTime, weeks: gint)
-> *mut GDateTime;
pub fn g_date_time_add_days(datetime: *mut GDateTime, days: gint)
-> *mut GDateTime;
pub fn g_date_time_add_hours(datetime: *mut GDateTime, hours: gint)
-> *mut GDateTime;
pub fn g_date_time_add_minutes(datetime: *mut GDateTime, minutes: gint)
-> *mut GDateTime;
pub fn g_date_time_add_seconds(datetime: *mut GDateTime, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_add_full(datetime: *mut GDateTime, years: gint,
months: gint, days: gint, hours: gint,
minutes: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_compare(dt1: gconstpointer, dt2: gconstpointer)
-> gint;
pub fn g_date_time_difference(end: *mut GDateTime, begin: *mut GDateTime)
-> GTimeSpan;
pub fn g_date_time_hash(datetime: gconstpointer) -> guint;
pub fn g_date_time_equal(dt1: gconstpointer, dt2: gconstpointer)
-> gboolean;
pub fn g_date_time_get_ymd(datetime: *mut GDateTime, year: *mut gint,
month: *mut gint, day: *mut gint);
pub fn g_date_time_get_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_month(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_month(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_week_numbering_year(datetime: *mut GDateTime)
-> gint;
pub fn g_date_time_get_week_of_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_week(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_hour(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_minute(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_second(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_microsecond(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_seconds(datetime: *mut GDateTime) -> gdouble;
pub fn g_date_time_to_unix(datetime: *mut GDateTime) -> gint64;
pub fn g_date_time_to_timeval(datetime: *mut GDateTime, tv: *mut GTimeVal)
-> gboolean;
pub fn g_date_time_get_utc_offset(datetime: *mut GDateTime) -> GTimeSpan;
pub fn g_date_time_get_timezone_abbreviation(datetime: *mut GDateTime)
-> *const gchar;
pub fn g_date_time_is_daylight_savings(datetime: *mut GDateTime)
-> gboolean;
pub fn g_date_time_to_timezone(datetime: *mut GDateTime,
tz: *mut GTimeZone) -> *mut GDateTime;
pub fn g_date_time_to_local(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_to_utc(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_format(datetime: *mut GDateTime, format: *const gchar)
-> *mut gchar;
pub fn opendir(__name: *const ::libc::c_char) -> *mut DIR;
pub fn fdopendir(__fd: ::libc::c_int) -> *mut DIR;
pub fn closedir(__dirp: *mut DIR) -> ::libc::c_int;
pub fn readdir(__dirp: *mut DIR) -> *mut Struct_dirent;
pub fn readdir_r(__dirp: *mut DIR, __entry: *mut Struct_dirent,
__result: *mut *mut Struct_dirent) -> ::libc::c_int;
pub fn rewinddir(__dirp: *mut DIR);
pub fn seekdir(__dirp: *mut DIR, __pos: ::libc::c_long);
pub fn telldir(__dirp: *mut DIR) -> ::libc::c_long;
pub fn dirfd(__dirp: *mut DIR) -> ::libc::c_int;
pub fn scandir(__dir: *const ::libc::c_char,
__namelist: *mut *mut *mut Struct_dirent,
__selector:
::std::option::Option<extern "C" fn
(arg1: *const Struct_dirent)
-> ::libc::c_int>,
__cmp:
::std::option::Option<extern "C" fn
(arg1:
*mut *const Struct_dirent,
arg2:
*mut *const Struct_dirent)
-> ::libc::c_int>)
-> ::libc::c_int;
pub fn alphasort(__e1: *mut *const Struct_dirent,
__e2: *mut *const Struct_dirent) -> ::libc::c_int;
pub fn getdirentries(__fd: ::libc::c_int, __buf: *mut ::libc::c_char,
__nbytes: size_t, __basep: *mut __off_t)
-> __ssize_t;
pub fn g_dir_open(path: *const gchar, flags: guint,
error: *mut *mut GError) -> *mut GDir;
pub fn g_dir_read_name(dir: *mut GDir) -> *const gchar;
pub fn g_dir_rewind(dir: *mut GDir);
pub fn g_dir_close(dir: *mut GDir);
pub fn g_getenv(variable: *const gchar) -> *const gchar;
pub fn g_setenv(variable: *const gchar, value: *const gchar,
overwrite: gboolean) -> gboolean;
pub fn g_unsetenv(variable: *const gchar);
pub fn g_listenv() -> *mut *mut gchar;
pub fn g_get_environ() -> *mut *mut gchar;
pub fn g_environ_getenv(envp: *mut *mut gchar, variable: *const gchar)
-> *const gchar;
pub fn g_environ_setenv(envp: *mut *mut gchar, variable: *const gchar,
value: *const gchar, overwrite: gboolean)
-> *mut *mut gchar;
pub fn g_environ_unsetenv(envp: *mut *mut gchar, variable: *const gchar)
-> *mut *mut gchar;
pub fn g_file_error_quark() -> GQuark;
pub fn g_file_error_from_errno(err_no: gint) -> GFileError;
pub fn g_file_test(filename: *const gchar, test: GFileTest) -> gboolean;
pub fn g_file_get_contents(filename: *const gchar,
contents: *mut *mut gchar, length: *mut gsize,
error: *mut *mut GError) -> gboolean;
pub fn g_file_set_contents(filename: *const gchar, contents: *const gchar,
length: gssize, error: *mut *mut GError)
-> gboolean;
pub fn g_file_read_link(filename: *const gchar, error: *mut *mut GError)
-> *mut gchar;
pub fn g_mkdtemp(tmpl: *mut gchar) -> *mut gchar;
pub fn g_mkdtemp_full(tmpl: *mut gchar, mode: gint) -> *mut gchar;
pub fn g_mkstemp(tmpl: *mut gchar) -> gint;
pub fn g_mkstemp_full(tmpl: *mut gchar, flags: gint, mode: gint) -> gint;
pub fn g_file_open_tmp(tmpl: *const gchar, name_used: *mut *mut gchar,
error: *mut *mut GError) -> gint;
pub fn g_dir_make_tmp(tmpl: *const gchar, error: *mut *mut GError)
-> *mut gchar;
pub fn g_build_path(separator: *const gchar,
first_element: *const gchar, ...) -> *mut gchar;
pub fn g_build_pathv(separator: *const gchar, args: *mut *mut gchar)
-> *mut gchar;
pub fn g_build_filename(first_element: *const gchar, ...) -> *mut gchar;
pub fn g_build_filenamev(args: *mut *mut gchar) -> *mut gchar;
pub fn g_mkdir_with_parents(pathname: *const gchar, mode: gint) -> gint;
pub fn g_path_is_absolute(file_name: *const gchar) -> gboolean;
pub fn g_path_skip_root(file_name: *const gchar) -> *const gchar;
pub fn g_basename(file_name: *const gchar) -> *const gchar;
pub fn g_get_current_dir() -> *mut gchar;
pub fn g_path_get_basename(file_name: *const gchar) -> *mut gchar;
pub fn g_path_get_dirname(file_name: *const gchar) -> *mut gchar;
pub fn g_strip_context(msgid: *const gchar, msgval: *const gchar)
-> *const gchar;
pub fn g_dgettext(domain: *const gchar, msgid: *const gchar)
-> *const gchar;
pub fn g_dcgettext(domain: *const gchar, msgid: *const gchar,
category: gint) -> *const gchar;
pub fn g_dngettext(domain: *const gchar, msgid: *const gchar,
msgid_plural: *const gchar, n: gulong) -> *const gchar;
pub fn g_dpgettext(domain: *const gchar, msgctxtid: *const gchar,
msgidoffset: gsize) -> *const gchar;
pub fn g_dpgettext2(domain: *const gchar, context: *const gchar,
msgid: *const gchar) -> *const gchar;
pub fn g_free(mem: gpointer);
pub fn g_clear_pointer(pp: *mut gpointer, destroy: GDestroyNotify);
pub fn g_malloc(n_bytes: gsize) -> gpointer;
pub fn g_malloc0(n_bytes: gsize) -> gpointer;
pub fn g_realloc(mem: gpointer, n_bytes: gsize) -> gpointer;
pub fn g_try_malloc(n_bytes: gsize) -> gpointer;
pub fn g_try_malloc0(n_bytes: gsize) -> gpointer;
pub fn g_try_realloc(mem: gpointer, n_bytes: gsize) -> gpointer;
pub fn g_malloc_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_malloc0_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_realloc_n(mem: gpointer, n_blocks: gsize, n_block_bytes: gsize)
-> gpointer;
pub fn g_try_malloc_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_try_malloc0_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_try_realloc_n(mem: gpointer, n_blocks: gsize,
n_block_bytes: gsize) -> gpointer;
pub fn g_mem_set_vtable(vtable: *mut GMemVTable);
pub fn g_mem_is_system_malloc() -> gboolean;
pub fn g_mem_profile();
pub fn g_node_new(data: gpointer) -> *mut GNode;
pub fn g_node_destroy(root: *mut GNode);
pub fn g_node_unlink(node: *mut GNode);
pub fn g_node_copy_deep(node: *mut GNode, copy_func: GCopyFunc,
data: gpointer) -> *mut GNode;
pub fn g_node_copy(node: *mut GNode) -> *mut GNode;
pub fn g_node_insert(parent: *mut GNode, position: gint, node: *mut GNode)
-> *mut GNode;
pub fn g_node_insert_before(parent: *mut GNode, sibling: *mut GNode,
node: *mut GNode) -> *mut GNode;
pub fn g_node_insert_after(parent: *mut GNode, sibling: *mut GNode,
node: *mut GNode) -> *mut GNode;
pub fn g_node_prepend(parent: *mut GNode, node: *mut GNode) -> *mut GNode;
pub fn g_node_n_nodes(root: *mut GNode, flags: GTraverseFlags) -> guint;
pub fn g_node_get_root(node: *mut GNode) -> *mut GNode;
pub fn g_node_is_ancestor(node: *mut GNode, descendant: *mut GNode)
-> gboolean;
pub fn g_node_depth(node: *mut GNode) -> guint;
pub fn g_node_find(root: *mut GNode, order: GTraverseType,
flags: GTraverseFlags, data: gpointer) -> *mut GNode;
pub fn g_node_traverse(root: *mut GNode, order: GTraverseType,
flags: GTraverseFlags, max_depth: gint,
func: GNodeTraverseFunc, data: gpointer);
pub fn g_node_max_height(root: *mut GNode) -> guint;
pub fn g_node_children_foreach(node: *mut GNode, flags: GTraverseFlags,
func: GNodeForeachFunc, data: gpointer);
pub fn g_node_reverse_children(node: *mut GNode);
pub fn g_node_n_children(node: *mut GNode) -> guint;
pub fn g_node_nth_child(node: *mut GNode, n: guint) -> *mut GNode;
pub fn g_node_last_child(node: *mut GNode) -> *mut GNode;
pub fn g_node_find_child(node: *mut GNode, flags: GTraverseFlags,
data: gpointer) -> *mut GNode;
pub fn g_node_child_position(node: *mut GNode, child: *mut GNode) -> gint;
pub fn g_node_child_index(node: *mut GNode, data: gpointer) -> gint;
pub fn g_node_first_sibling(node: *mut GNode) -> *mut GNode;
pub fn g_node_last_sibling(node: *mut GNode) -> *mut GNode;
pub fn g_list_alloc() -> *mut GList;
pub fn g_list_free(list: *mut GList);
pub fn g_list_free_1(list: *mut GList);
pub fn g_list_free_full(list: *mut GList, free_func: GDestroyNotify);
pub fn g_list_append(list: *mut GList, data: gpointer) -> *mut GList;
pub fn g_list_prepend(list: *mut GList, data: gpointer) -> *mut GList;
pub fn g_list_insert(list: *mut GList, data: gpointer, position: gint)
-> *mut GList;
pub fn g_list_insert_sorted(list: *mut GList, data: gpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_list_insert_sorted_with_data(list: *mut GList, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_insert_before(list: *mut GList, sibling: *mut GList,
data: gpointer) -> *mut GList;
pub fn g_list_concat(list1: *mut GList, list2: *mut GList) -> *mut GList;
pub fn g_list_remove(list: *mut GList, data: gconstpointer) -> *mut GList;
pub fn g_list_remove_all(list: *mut GList, data: gconstpointer)
-> *mut GList;
pub fn g_list_remove_link(list: *mut GList, llink: *mut GList)
-> *mut GList;
pub fn g_list_delete_link(list: *mut GList, link_: *mut GList)
-> *mut GList;
pub fn g_list_reverse(list: *mut GList) -> *mut GList;
pub fn g_list_copy(list: *mut GList) -> *mut GList;
pub fn g_list_copy_deep(list: *mut GList, func: GCopyFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_nth(list: *mut GList, n: guint) -> *mut GList;
pub fn g_list_nth_prev(list: *mut GList, n: guint) -> *mut GList;
pub fn g_list_find(list: *mut GList, data: gconstpointer) -> *mut GList;
pub fn g_list_find_custom(list: *mut GList, data: gconstpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_list_position(list: *mut GList, llink: *mut GList) -> gint;
pub fn g_list_index(list: *mut GList, data: gconstpointer) -> gint;
pub fn g_list_last(list: *mut GList) -> *mut GList;
pub fn g_list_first(list: *mut GList) -> *mut GList;
pub fn g_list_length(list: *mut GList) -> guint;
pub fn g_list_foreach(list: *mut GList, func: GFunc, user_data: gpointer);
pub fn g_list_sort(list: *mut GList, compare_func: GCompareFunc)
-> *mut GList;
pub fn g_list_sort_with_data(list: *mut GList,
compare_func: GCompareDataFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_nth_data(list: *mut GList, n: guint) -> gpointer;
pub fn g_hash_table_new(hash_func: GHashFunc, key_equal_func: GEqualFunc)
-> *mut GHashTable;
pub fn g_hash_table_new_full(hash_func: GHashFunc,
key_equal_func: GEqualFunc,
key_destroy_func: GDestroyNotify,
value_destroy_func: GDestroyNotify)
-> *mut GHashTable;
pub fn g_hash_table_destroy(hash_table: *mut GHashTable);
pub fn g_hash_table_insert(hash_table: *mut GHashTable, key: gpointer,
value: gpointer) -> gboolean;
pub fn g_hash_table_replace(hash_table: *mut GHashTable, key: gpointer,
value: gpointer) -> gboolean;
pub fn g_hash_table_add(hash_table: *mut GHashTable, key: gpointer)
-> gboolean;
pub fn g_hash_table_remove(hash_table: *mut GHashTable,
key: gconstpointer) -> gboolean;
pub fn g_hash_table_remove_all(hash_table: *mut GHashTable);
pub fn g_hash_table_steal(hash_table: *mut GHashTable, key: gconstpointer)
-> gboolean;
pub fn g_hash_table_steal_all(hash_table: *mut GHashTable);
pub fn g_hash_table_lookup(hash_table: *mut GHashTable,
key: gconstpointer) -> gpointer;
pub fn g_hash_table_contains(hash_table: *mut GHashTable,
key: gconstpointer) -> gboolean;
pub fn g_hash_table_lookup_extended(hash_table: *mut GHashTable,
lookup_key: gconstpointer,
orig_key: *mut gpointer,
value: *mut gpointer) -> gboolean;
pub fn g_hash_table_foreach(hash_table: *mut GHashTable, func: GHFunc,
user_data: gpointer);
pub fn g_hash_table_find(hash_table: *mut GHashTable, predicate: GHRFunc,
user_data: gpointer) -> gpointer;
pub fn g_hash_table_foreach_remove(hash_table: *mut GHashTable,
func: GHRFunc, user_data: gpointer)
-> guint;
pub fn g_hash_table_foreach_steal(hash_table: *mut GHashTable,
func: GHRFunc, user_data: gpointer)
-> guint;
pub fn g_hash_table_size(hash_table: *mut GHashTable) -> guint;
pub fn g_hash_table_get_keys(hash_table: *mut GHashTable) -> *mut GList;
pub fn g_hash_table_get_values(hash_table: *mut GHashTable) -> *mut GList;
pub fn g_hash_table_get_keys_as_array(hash_table: *mut GHashTable,
length: *mut guint)
-> *mut gpointer;
pub fn g_hash_table_iter_init(iter: *mut GHashTableIter,
hash_table: *mut GHashTable);
pub fn g_hash_table_iter_next(iter: *mut GHashTableIter,
key: *mut gpointer, value: *mut gpointer)
-> gboolean;
pub fn g_hash_table_iter_get_hash_table(iter: *mut GHashTableIter)
-> *mut GHashTable;
pub fn g_hash_table_iter_remove(iter: *mut GHashTableIter);
pub fn g_hash_table_iter_replace(iter: *mut GHashTableIter,
value: gpointer);
pub fn g_hash_table_iter_steal(iter: *mut GHashTableIter);
pub fn g_hash_table_ref(hash_table: *mut GHashTable) -> *mut GHashTable;
pub fn g_hash_table_unref(hash_table: *mut GHashTable);
pub fn g_str_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_str_hash(v: gconstpointer) -> guint;
pub fn g_int_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_int_hash(v: gconstpointer) -> guint;
pub fn g_int64_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_int64_hash(v: gconstpointer) -> guint;
pub fn g_double_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_double_hash(v: gconstpointer) -> guint;
pub fn g_direct_hash(v: gconstpointer) -> guint;
pub fn g_direct_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_hmac_new(digest_type: GChecksumType, key: *const guchar,
key_len: gsize) -> *mut GHmac;
pub fn g_hmac_copy(hmac: *const GHmac) -> *mut GHmac;
pub fn g_hmac_ref(hmac: *mut GHmac) -> *mut GHmac;
pub fn g_hmac_unref(hmac: *mut GHmac);
pub fn g_hmac_update(hmac: *mut GHmac, data: *const guchar,
length: gssize);
pub fn g_hmac_get_string(hmac: *mut GHmac) -> *const gchar;
pub fn g_hmac_get_digest(hmac: *mut GHmac, buffer: *mut guint8,
digest_len: *mut gsize);
pub fn g_compute_hmac_for_data(digest_type: GChecksumType,
key: *const guchar, key_len: gsize,
data: *const guchar, length: gsize)
-> *mut gchar;
pub fn g_compute_hmac_for_string(digest_type: GChecksumType,
key: *const guchar, key_len: gsize,
str: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_hook_list_init(hook_list: *mut GHookList, hook_size: guint);
pub fn g_hook_list_clear(hook_list: *mut GHookList);
pub fn g_hook_alloc(hook_list: *mut GHookList) -> *mut GHook;
pub fn g_hook_free(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_ref(hook_list: *mut GHookList, hook: *mut GHook)
-> *mut GHook;
pub fn g_hook_unref(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_destroy(hook_list: *mut GHookList, hook_id: gulong)
-> gboolean;
pub fn g_hook_destroy_link(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_prepend(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_insert_before(hook_list: *mut GHookList,
sibling: *mut GHook, hook: *mut GHook);
pub fn g_hook_insert_sorted(hook_list: *mut GHookList, hook: *mut GHook,
func: GHookCompareFunc);
pub fn g_hook_get(hook_list: *mut GHookList, hook_id: gulong)
-> *mut GHook;
pub fn g_hook_find(hook_list: *mut GHookList, need_valids: gboolean,
func: GHookFindFunc, data: gpointer) -> *mut GHook;
pub fn g_hook_find_data(hook_list: *mut GHookList, need_valids: gboolean,
data: gpointer) -> *mut GHook;
pub fn g_hook_find_func(hook_list: *mut GHookList, need_valids: gboolean,
func: gpointer) -> *mut GHook;
pub fn g_hook_find_func_data(hook_list: *mut GHookList,
need_valids: gboolean, func: gpointer,
data: gpointer) -> *mut GHook;
pub fn g_hook_first_valid(hook_list: *mut GHookList,
may_be_in_call: gboolean) -> *mut GHook;
pub fn g_hook_next_valid(hook_list: *mut GHookList, hook: *mut GHook,
may_be_in_call: gboolean) -> *mut GHook;
pub fn g_hook_compare_ids(new_hook: *mut GHook, sibling: *mut GHook)
-> gint;
pub fn g_hook_list_invoke(hook_list: *mut GHookList,
may_recurse: gboolean);
pub fn g_hook_list_invoke_check(hook_list: *mut GHookList,
may_recurse: gboolean);
pub fn g_hook_list_marshal(hook_list: *mut GHookList,
may_recurse: gboolean,
marshaller: GHookMarshaller,
marshal_data: gpointer);
pub fn g_hook_list_marshal_check(hook_list: *mut GHookList,
may_recurse: gboolean,
marshaller: GHookCheckMarshaller,
marshal_data: gpointer);
pub fn g_hostname_is_non_ascii(hostname: *const gchar) -> gboolean;
pub fn g_hostname_is_ascii_encoded(hostname: *const gchar) -> gboolean;
pub fn g_hostname_is_ip_address(hostname: *const gchar) -> gboolean;
pub fn g_hostname_to_ascii(hostname: *const gchar) -> *mut gchar;
pub fn g_hostname_to_unicode(hostname: *const gchar) -> *mut gchar;
pub fn g_poll(fds: *mut GPollFD, nfds: guint, timeout: gint) -> gint;
pub fn g_slist_alloc() -> *mut GSList;
pub fn g_slist_free(list: *mut GSList);
pub fn g_slist_free_1(list: *mut GSList);
pub fn g_slist_free_full(list: *mut GSList, free_func: GDestroyNotify);
pub fn g_slist_append(list: *mut GSList, data: gpointer) -> *mut GSList;
pub fn g_slist_prepend(list: *mut GSList, data: gpointer) -> *mut GSList;
pub fn g_slist_insert(list: *mut GSList, data: gpointer, position: gint)
-> *mut GSList;
pub fn g_slist_insert_sorted(list: *mut GSList, data: gpointer,
func: GCompareFunc) -> *mut GSList;
pub fn g_slist_insert_sorted_with_data(list: *mut GSList, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer)
-> *mut GSList;
pub fn g_slist_insert_before(slist: *mut GSList, sibling: *mut GSList,
data: gpointer) -> *mut GSList;
pub fn g_slist_concat(list1: *mut GSList, list2: *mut GSList)
-> *mut GSList;
pub fn g_slist_remove(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_remove_all(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_remove_link(list: *mut GSList, link_: *mut GSList)
-> *mut GSList;
pub fn g_slist_delete_link(list: *mut GSList, link_: *mut GSList)
-> *mut GSList;
pub fn g_slist_reverse(list: *mut GSList) -> *mut GSList;
pub fn g_slist_copy(list: *mut GSList) -> *mut GSList;
pub fn g_slist_copy_deep(list: *mut GSList, func: GCopyFunc,
user_data: gpointer) -> *mut GSList;
pub fn g_slist_nth(list: *mut GSList, n: guint) -> *mut GSList;
pub fn g_slist_find(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_find_custom(list: *mut GSList, data: gconstpointer,
func: GCompareFunc) -> *mut GSList;
pub fn g_slist_position(list: *mut GSList, llink: *mut GSList) -> gint;
pub fn g_slist_index(list: *mut GSList, data: gconstpointer) -> gint;
pub fn g_slist_last(list: *mut GSList) -> *mut GSList;
pub fn g_slist_length(list: *mut GSList) -> guint;
pub fn g_slist_foreach(list: *mut GSList, func: GFunc,
user_data: gpointer);
pub fn g_slist_sort(list: *mut GSList, compare_func: GCompareFunc)
-> *mut GSList;
pub fn g_slist_sort_with_data(list: *mut GSList,
compare_func: GCompareDataFunc,
user_data: gpointer) -> *mut GSList;
pub fn g_slist_nth_data(list: *mut GSList, n: guint) -> gpointer;
pub fn g_main_context_new() -> *mut GMainContext;
pub fn g_main_context_ref(context: *mut GMainContext)
-> *mut GMainContext;
pub fn g_main_context_unref(context: *mut GMainContext);
pub fn g_main_context_default() -> *mut GMainContext;
pub fn g_main_context_iteration(context: *mut GMainContext,
may_block: gboolean) -> gboolean;
pub fn g_main_context_pending(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_find_source_by_id(context: *mut GMainContext,
source_id: guint) -> *mut GSource;
pub fn g_main_context_find_source_by_user_data(context: *mut GMainContext,
user_data: gpointer)
-> *mut GSource;
pub fn g_main_context_find_source_by_funcs_user_data(context:
*mut GMainContext,
funcs:
*mut GSourceFuncs,
user_data: gpointer)
-> *mut GSource;
pub fn g_main_context_wakeup(context: *mut GMainContext);
pub fn g_main_context_acquire(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_release(context: *mut GMainContext);
pub fn g_main_context_is_owner(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_wait(context: *mut GMainContext, cond: *mut GCond,
mutex: *mut GMutex) -> gboolean;
pub fn g_main_context_prepare(context: *mut GMainContext,
priority: *mut gint) -> gboolean;
pub fn g_main_context_query(context: *mut GMainContext,
max_priority: gint, timeout_: *mut gint,
fds: *mut GPollFD, n_fds: gint) -> gint;
pub fn g_main_context_check(context: *mut GMainContext,
max_priority: gint, fds: *mut GPollFD,
n_fds: gint) -> gint;
pub fn g_main_context_dispatch(context: *mut GMainContext);
pub fn g_main_context_set_poll_func(context: *mut GMainContext,
func: GPollFunc);
pub fn g_main_context_get_poll_func(context: *mut GMainContext)
-> GPollFunc;
pub fn g_main_context_add_poll(context: *mut GMainContext,
fd: *mut GPollFD, priority: gint);
pub fn g_main_context_remove_poll(context: *mut GMainContext,
fd: *mut GPollFD);
pub fn g_main_depth() -> gint;
pub fn g_main_current_source() -> *mut GSource;
pub fn g_main_context_push_thread_default(context: *mut GMainContext);
pub fn g_main_context_pop_thread_default(context: *mut GMainContext);
pub fn g_main_context_get_thread_default() -> *mut GMainContext;
pub fn g_main_context_ref_thread_default() -> *mut GMainContext;
pub fn g_main_loop_new(context: *mut GMainContext, is_running: gboolean)
-> *mut GMainLoop;
pub fn g_main_loop_run(_loop: *mut GMainLoop);
pub fn g_main_loop_quit(_loop: *mut GMainLoop);
pub fn g_main_loop_ref(_loop: *mut GMainLoop) -> *mut GMainLoop;
pub fn g_main_loop_unref(_loop: *mut GMainLoop);
pub fn g_main_loop_is_running(_loop: *mut GMainLoop) -> gboolean;
pub fn g_main_loop_get_context(_loop: *mut GMainLoop)
-> *mut GMainContext;
pub fn g_source_new(source_funcs: *mut GSourceFuncs, struct_size: guint)
-> *mut GSource;
pub fn g_source_ref(source: *mut GSource) -> *mut GSource;
pub fn g_source_unref(source: *mut GSource);
pub fn g_source_attach(source: *mut GSource, context: *mut GMainContext)
-> guint;
pub fn g_source_destroy(source: *mut GSource);
pub fn g_source_set_priority(source: *mut GSource, priority: gint);
pub fn g_source_get_priority(source: *mut GSource) -> gint;
pub fn g_source_set_can_recurse(source: *mut GSource,
can_recurse: gboolean);
pub fn g_source_get_can_recurse(source: *mut GSource) -> gboolean;
pub fn g_source_get_id(source: *mut GSource) -> guint;
pub fn g_source_get_context(source: *mut GSource) -> *mut GMainContext;
pub fn g_source_set_callback(source: *mut GSource, func: GSourceFunc,
data: gpointer, notify: GDestroyNotify);
pub fn g_source_set_funcs(source: *mut GSource, funcs: *mut GSourceFuncs);
pub fn g_source_is_destroyed(source: *mut GSource) -> gboolean;
pub fn g_source_set_name(source: *mut GSource,
name: *const ::libc::c_char);
pub fn g_source_get_name(source: *mut GSource) -> *const ::libc::c_char;
pub fn g_source_set_name_by_id(tag: guint, name: *const ::libc::c_char);
pub fn g_source_set_ready_time(source: *mut GSource, ready_time: gint64);
pub fn g_source_get_ready_time(source: *mut GSource) -> gint64;
pub fn g_source_add_unix_fd(source: *mut GSource, fd: gint,
events: GIOCondition) -> gpointer;
pub fn g_source_modify_unix_fd(source: *mut GSource, tag: gpointer,
new_events: GIOCondition);
pub fn g_source_remove_unix_fd(source: *mut GSource, tag: gpointer);
pub fn g_source_query_unix_fd(source: *mut GSource, tag: gpointer)
-> GIOCondition;
pub fn g_source_set_callback_indirect(source: *mut GSource,
callback_data: gpointer,
callback_funcs:
*mut GSourceCallbackFuncs);
pub fn g_source_add_poll(source: *mut GSource, fd: *mut GPollFD);
pub fn g_source_remove_poll(source: *mut GSource, fd: *mut GPollFD);
pub fn g_source_add_child_source(source: *mut GSource,
child_source: *mut GSource);
pub fn g_source_remove_child_source(source: *mut GSource,
child_source: *mut GSource);
pub fn g_source_get_current_time(source: *mut GSource,
timeval: *mut GTimeVal);
pub fn g_source_get_time(source: *mut GSource) -> gint64;
pub fn g_idle_source_new() -> *mut GSource;
pub fn g_child_watch_source_new(pid: GPid) -> *mut GSource;
pub fn g_timeout_source_new(interval: guint) -> *mut GSource;
pub fn g_timeout_source_new_seconds(interval: guint) -> *mut GSource;
pub fn g_get_current_time(result: *mut GTimeVal);
pub fn g_get_monotonic_time() -> gint64;
pub fn g_get_real_time() -> gint64;
pub fn g_source_remove(tag: guint) -> gboolean;
pub fn g_source_remove_by_user_data(user_data: gpointer) -> gboolean;
pub fn g_source_remove_by_funcs_user_data(funcs: *mut GSourceFuncs,
user_data: gpointer)
-> gboolean;
pub fn g_timeout_add_full(priority: gint, interval: guint,
function: GSourceFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_timeout_add(interval: guint, function: GSourceFunc,
data: gpointer) -> guint;
pub fn g_timeout_add_seconds_full(priority: gint, interval: guint,
function: GSourceFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_timeout_add_seconds(interval: guint, function: GSourceFunc,
data: gpointer) -> guint;
pub fn g_child_watch_add_full(priority: gint, pid: GPid,
function: GChildWatchFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_child_watch_add(pid: GPid, function: GChildWatchFunc,
data: gpointer) -> guint;
pub fn g_idle_add(function: GSourceFunc, data: gpointer) -> guint;
pub fn g_idle_add_full(priority: gint, function: GSourceFunc,
data: gpointer, notify: GDestroyNotify) -> guint;
pub fn g_idle_remove_by_data(data: gpointer) -> gboolean;
pub fn g_main_context_invoke_full(context: *mut GMainContext,
priority: gint, function: GSourceFunc,
data: gpointer, notify: GDestroyNotify);
pub fn g_main_context_invoke(context: *mut GMainContext,
function: GSourceFunc, data: gpointer);
pub fn g_unicode_script_to_iso15924(script: GUnicodeScript) -> guint32;
pub fn g_unicode_script_from_iso15924(iso15924: guint32)
-> GUnicodeScript;
pub fn g_unichar_isalnum(c: gunichar) -> gboolean;
pub fn g_unichar_isalpha(c: gunichar) -> gboolean;
pub fn g_unichar_iscntrl(c: gunichar) -> gboolean;
pub fn g_unichar_isdigit(c: gunichar) -> gboolean;
pub fn g_unichar_isgraph(c: gunichar) -> gboolean;
pub fn g_unichar_islower(c: gunichar) -> gboolean;
pub fn g_unichar_isprint(c: gunichar) -> gboolean;
pub fn g_unichar_ispunct(c: gunichar) -> gboolean;
pub fn g_unichar_isspace(c: gunichar) -> gboolean;
pub fn g_unichar_isupper(c: gunichar) -> gboolean;
pub fn g_unichar_isxdigit(c: gunichar) -> gboolean;
pub fn g_unichar_istitle(c: gunichar) -> gboolean;
pub fn g_unichar_isdefined(c: gunichar) -> gboolean;
pub fn g_unichar_iswide(c: gunichar) -> gboolean;
pub fn g_unichar_iswide_cjk(c: gunichar) -> gboolean;
pub fn g_unichar_iszerowidth(c: gunichar) -> gboolean;
pub fn g_unichar_ismark(c: gunichar) -> gboolean;
pub fn g_unichar_toupper(c: gunichar) -> gunichar;
pub fn g_unichar_tolower(c: gunichar) -> gunichar;
pub fn g_unichar_totitle(c: gunichar) -> gunichar;
pub fn g_unichar_digit_value(c: gunichar) -> gint;
pub fn g_unichar_xdigit_value(c: gunichar) -> gint;
pub fn g_unichar_type(c: gunichar) -> GUnicodeType;
pub fn g_unichar_break_type(c: gunichar) -> GUnicodeBreakType;
pub fn g_unichar_combining_class(uc: gunichar) -> gint;
pub fn g_unichar_get_mirror_char(ch: gunichar, mirrored_ch: *mut gunichar)
-> gboolean;
pub fn g_unichar_get_script(ch: gunichar) -> GUnicodeScript;
pub fn g_unichar_validate(ch: gunichar) -> gboolean;
pub fn g_unichar_compose(a: gunichar, b: gunichar, ch: *mut gunichar)
-> gboolean;
pub fn g_unichar_decompose(ch: gunichar, a: *mut gunichar,
b: *mut gunichar) -> gboolean;
pub fn g_unichar_fully_decompose(ch: gunichar, compat: gboolean,
result: *mut gunichar, result_len: gsize)
-> gsize;
pub fn g_unicode_canonical_ordering(string: *mut gunichar, len: gsize);
pub fn g_unicode_canonical_decomposition(ch: gunichar,
result_len: *mut gsize)
-> *mut gunichar;
pub fn g_utf8_get_char(p: *const gchar) -> gunichar;
pub fn g_utf8_get_char_validated(p: *const gchar, max_len: gssize)
-> gunichar;
pub fn g_utf8_offset_to_pointer(str: *const gchar, offset: glong)
-> *mut gchar;
pub fn g_utf8_pointer_to_offset(str: *const gchar, pos: *const gchar)
-> glong;
pub fn g_utf8_prev_char(p: *const gchar) -> *mut gchar;
pub fn g_utf8_find_next_char(p: *const gchar, end: *const gchar)
-> *mut gchar;
pub fn g_utf8_find_prev_char(str: *const gchar, p: *const gchar)
-> *mut gchar;
pub fn g_utf8_strlen(p: *const gchar, max: gssize) -> glong;
pub fn g_utf8_substring(str: *const gchar, start_pos: glong,
end_pos: glong) -> *mut gchar;
pub fn g_utf8_strncpy(dest: *mut gchar, src: *const gchar, n: gsize)
-> *mut gchar;
pub fn g_utf8_strchr(p: *const gchar, len: gssize, c: gunichar)
-> *mut gchar;
pub fn g_utf8_strrchr(p: *const gchar, len: gssize, c: gunichar)
-> *mut gchar;
pub fn g_utf8_strreverse(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_to_utf16(str: *const gchar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar2;
pub fn g_utf8_to_ucs4(str: *const gchar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar;
pub fn g_utf8_to_ucs4_fast(str: *const gchar, len: glong,
items_written: *mut glong) -> *mut gunichar;
pub fn g_utf16_to_ucs4(str: *const gunichar2, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar;
pub fn g_utf16_to_utf8(str: *const gunichar2, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gchar;
pub fn g_ucs4_to_utf16(str: *const gunichar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar2;
pub fn g_ucs4_to_utf8(str: *const gunichar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gchar;
pub fn g_unichar_to_utf8(c: gunichar, outbuf: *mut gchar) -> gint;
pub fn g_utf8_validate(str: *const gchar, max_len: gssize,
end: *mut *const gchar) -> gboolean;
pub fn g_utf8_strup(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_strdown(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_casefold(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_normalize(str: *const gchar, len: gssize,
mode: GNormalizeMode) -> *mut gchar;
pub fn g_utf8_collate(str1: *const gchar, str2: *const gchar) -> gint;
pub fn g_utf8_collate_key(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_collate_key_for_filename(str: *const gchar, len: gssize)
-> *mut gchar;
pub fn _g_utf8_make_valid(name: *const gchar) -> *mut gchar;
pub fn g_get_user_name() -> *const gchar;
pub fn g_get_real_name() -> *const gchar;
pub fn g_get_home_dir() -> *const gchar;
pub fn g_get_tmp_dir() -> *const gchar;
pub fn g_get_host_name() -> *const gchar;
pub fn g_get_prgname() -> *const gchar;
pub fn g_set_prgname(prgname: *const gchar);
pub fn g_get_application_name() -> *const gchar;
pub fn g_set_application_name(application_name: *const gchar);
pub fn g_reload_user_special_dirs_cache();
pub fn g_get_user_data_dir() -> *const gchar;
pub fn g_get_user_config_dir() -> *const gchar;
pub fn g_get_user_cache_dir() -> *const gchar;
pub fn g_get_system_data_dirs() -> *const *const gchar;
pub fn g_get_system_config_dirs() -> *const *const gchar;
pub fn g_get_user_runtime_dir() -> *const gchar;
pub fn g_get_user_special_dir(directory: GUserDirectory) -> *const gchar;
pub fn g_parse_debug_string(string: *const gchar, keys: *const GDebugKey,
nkeys: guint) -> guint;
pub fn g_snprintf(string: *mut gchar, n: gulong,
format: *const gchar, ...) -> gint;
pub fn g_vsnprintf(string: *mut gchar, n: gulong, format: *const gchar,
args: va_list) -> gint;
pub fn g_nullify_pointer(nullify_location: *mut gpointer);
pub fn g_format_size_full(size: guint64, flags: GFormatSizeFlags)
-> *mut gchar;
pub fn g_format_size(size: guint64) -> *mut gchar;
pub fn g_format_size_for_display(size: goffset) -> *mut gchar;
pub fn g_atexit(func: GVoidFunc);
pub fn g_find_program_in_path(program: *const gchar) -> *mut gchar;
pub fn g_string_new(init: *const gchar) -> *mut GString;
pub fn g_string_new_len(init: *const gchar, len: gssize) -> *mut GString;
pub fn g_string_sized_new(dfl_size: gsize) -> *mut GString;
pub fn g_string_free(string: *mut GString, free_segment: gboolean)
-> *mut gchar;
pub fn g_string_free_to_bytes(string: *mut GString) -> *mut GBytes;
pub fn g_string_equal(v: *const GString, v2: *const GString) -> gboolean;
pub fn g_string_hash(str: *const GString) -> guint;
pub fn g_string_assign(string: *mut GString, rval: *const gchar)
-> *mut GString;
pub fn g_string_truncate(string: *mut GString, len: gsize)
-> *mut GString;
pub fn g_string_set_size(string: *mut GString, len: gsize)
-> *mut GString;
pub fn g_string_insert_len(string: *mut GString, pos: gssize,
val: *const gchar, len: gssize)
-> *mut GString;
pub fn g_string_append(string: *mut GString, val: *const gchar)
-> *mut GString;
pub fn g_string_append_len(string: *mut GString, val: *const gchar,
len: gssize) -> *mut GString;
pub fn g_string_append_c(string: *mut GString, c: gchar) -> *mut GString;
pub fn g_string_append_unichar(string: *mut GString, wc: gunichar)
-> *mut GString;
pub fn g_string_prepend(string: *mut GString, val: *const gchar)
-> *mut GString;
pub fn g_string_prepend_c(string: *mut GString, c: gchar) -> *mut GString;
pub fn g_string_prepend_unichar(string: *mut GString, wc: gunichar)
-> *mut GString;
pub fn g_string_prepend_len(string: *mut GString, val: *const gchar,
len: gssize) -> *mut GString;
pub fn g_string_insert(string: *mut GString, pos: gssize,
val: *const gchar) -> *mut GString;
pub fn g_string_insert_c(string: *mut GString, pos: gssize, c: gchar)
-> *mut GString;
pub fn g_string_insert_unichar(string: *mut GString, pos: gssize,
wc: gunichar) -> *mut GString;
pub fn g_string_overwrite(string: *mut GString, pos: gsize,
val: *const gchar) -> *mut GString;
pub fn g_string_overwrite_len(string: *mut GString, pos: gsize,
val: *const gchar, len: gssize)
-> *mut GString;
pub fn g_string_erase(string: *mut GString, pos: gssize, len: gssize)
-> *mut GString;
pub fn g_string_ascii_down(string: *mut GString) -> *mut GString;
pub fn g_string_ascii_up(string: *mut GString) -> *mut GString;
pub fn g_string_vprintf(string: *mut GString, format: *const gchar,
args: va_list);
pub fn g_string_printf(string: *mut GString, format: *const gchar, ...);
pub fn g_string_append_vprintf(string: *mut GString, format: *const gchar,
args: va_list);
pub fn g_string_append_printf(string: *mut GString,
format: *const gchar, ...);
pub fn g_string_append_uri_escaped(string: *mut GString,
unescaped: *const gchar,
reserved_chars_allowed: *const gchar,
allow_utf8: gboolean) -> *mut GString;
pub fn g_string_down(string: *mut GString) -> *mut GString;
pub fn g_string_up(string: *mut GString) -> *mut GString;
pub fn g_io_channel_init(channel: *mut GIOChannel);
pub fn g_io_channel_ref(channel: *mut GIOChannel) -> *mut GIOChannel;
pub fn g_io_channel_unref(channel: *mut GIOChannel);
pub fn g_io_channel_read(channel: *mut GIOChannel, buf: *mut gchar,
count: gsize, bytes_read: *mut gsize)
-> GIOError;
pub fn g_io_channel_write(channel: *mut GIOChannel, buf: *const gchar,
count: gsize, bytes_written: *mut gsize)
-> GIOError;
pub fn g_io_channel_seek(channel: *mut GIOChannel, offset: gint64,
_type: GSeekType) -> GIOError;
pub fn g_io_channel_close(channel: *mut GIOChannel);
pub fn g_io_channel_shutdown(channel: *mut GIOChannel, flush: gboolean,
err: *mut *mut GError) -> GIOStatus;
pub fn g_io_add_watch_full(channel: *mut GIOChannel, priority: gint,
condition: GIOCondition, func: GIOFunc,
user_data: gpointer, notify: GDestroyNotify)
-> guint;
pub fn g_io_create_watch(channel: *mut GIOChannel,
condition: GIOCondition) -> *mut GSource;
pub fn g_io_add_watch(channel: *mut GIOChannel, condition: GIOCondition,
func: GIOFunc, user_data: gpointer) -> guint;
pub fn g_io_channel_set_buffer_size(channel: *mut GIOChannel,
size: gsize);
pub fn g_io_channel_get_buffer_size(channel: *mut GIOChannel) -> gsize;
pub fn g_io_channel_get_buffer_condition(channel: *mut GIOChannel)
-> GIOCondition;
pub fn g_io_channel_set_flags(channel: *mut GIOChannel, flags: GIOFlags,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_get_flags(channel: *mut GIOChannel) -> GIOFlags;
pub fn g_io_channel_set_line_term(channel: *mut GIOChannel,
line_term: *const gchar, length: gint);
pub fn g_io_channel_get_line_term(channel: *mut GIOChannel,
length: *mut gint) -> *const gchar;
pub fn g_io_channel_set_buffered(channel: *mut GIOChannel,
buffered: gboolean);
pub fn g_io_channel_get_buffered(channel: *mut GIOChannel) -> gboolean;
pub fn g_io_channel_set_encoding(channel: *mut GIOChannel,
encoding: *const gchar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_get_encoding(channel: *mut GIOChannel)
-> *const gchar;
pub fn g_io_channel_set_close_on_unref(channel: *mut GIOChannel,
do_close: gboolean);
pub fn g_io_channel_get_close_on_unref(channel: *mut GIOChannel)
-> gboolean;
pub fn g_io_channel_flush(channel: *mut GIOChannel,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_line(channel: *mut GIOChannel,
str_return: *mut *mut gchar,
length: *mut gsize,
terminator_pos: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_line_string(channel: *mut GIOChannel,
buffer: *mut GString,
terminator_pos: *mut gsize,
error: *mut *mut GError)
-> GIOStatus;
pub fn g_io_channel_read_to_end(channel: *mut GIOChannel,
str_return: *mut *mut gchar,
length: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_chars(channel: *mut GIOChannel, buf: *mut gchar,
count: gsize, bytes_read: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_unichar(channel: *mut GIOChannel,
thechar: *mut gunichar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_write_chars(channel: *mut GIOChannel,
buf: *const gchar, count: gssize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_write_unichar(channel: *mut GIOChannel,
thechar: gunichar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_seek_position(channel: *mut GIOChannel,
offset: gint64, _type: GSeekType,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_new_file(filename: *const gchar, mode: *const gchar,
error: *mut *mut GError) -> *mut GIOChannel;
pub fn g_io_channel_error_quark() -> GQuark;
pub fn g_io_channel_error_from_errno(en: gint) -> GIOChannelError;
pub fn g_io_channel_unix_new(fd: ::libc::c_int) -> *mut GIOChannel;
pub fn g_io_channel_unix_get_fd(channel: *mut GIOChannel) -> gint;
pub fn g_key_file_error_quark() -> GQuark;
pub fn g_key_file_new() -> *mut GKeyFile;
pub fn g_key_file_ref(key_file: *mut GKeyFile) -> *mut GKeyFile;
pub fn g_key_file_unref(key_file: *mut GKeyFile);
pub fn g_key_file_free(key_file: *mut GKeyFile);
pub fn g_key_file_set_list_separator(key_file: *mut GKeyFile,
separator: gchar);
pub fn g_key_file_load_from_file(key_file: *mut GKeyFile,
file: *const gchar, flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_data(key_file: *mut GKeyFile,
data: *const gchar, length: gsize,
flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_dirs(key_file: *mut GKeyFile,
file: *const gchar,
search_dirs: *mut *const gchar,
full_path: *mut *mut gchar,
flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_data_dirs(key_file: *mut GKeyFile,
file: *const gchar,
full_path: *mut *mut gchar,
flags: GKeyFileFlags,
error: *mut *mut GError)
-> gboolean;
pub fn g_key_file_to_data(key_file: *mut GKeyFile, length: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_save_to_file(key_file: *mut GKeyFile,
filename: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_start_group(key_file: *mut GKeyFile) -> *mut gchar;
pub fn g_key_file_get_groups(key_file: *mut GKeyFile, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_key_file_get_keys(key_file: *mut GKeyFile,
group_name: *const gchar, length: *mut gsize,
error: *mut *mut GError) -> *mut *mut gchar;
pub fn g_key_file_has_group(key_file: *mut GKeyFile,
group_name: *const gchar) -> gboolean;
pub fn g_key_file_has_key(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_value(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_set_value(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: *const gchar);
pub fn g_key_file_get_string(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_set_string(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
string: *const gchar);
pub fn g_key_file_get_locale_string(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_key_file_set_locale_string(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
string: *const gchar);
pub fn g_key_file_get_boolean(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_set_boolean(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gboolean);
pub fn g_key_file_get_integer(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gint;
pub fn g_key_file_set_integer(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gint);
pub fn g_key_file_get_int64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gint64;
pub fn g_key_file_set_int64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gint64);
pub fn g_key_file_get_uint64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> guint64;
pub fn g_key_file_set_uint64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: guint64);
pub fn g_key_file_get_double(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gdouble;
pub fn g_key_file_set_double(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gdouble);
pub fn g_key_file_get_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_key_file_set_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
list: *const *const gchar,
length: gsize);
pub fn g_key_file_get_locale_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_key_file_set_locale_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
list: *const *const gchar,
length: gsize);
pub fn g_key_file_get_boolean_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut gboolean;
pub fn g_key_file_set_boolean_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gboolean,
length: gsize);
pub fn g_key_file_get_integer_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError) -> *mut gint;
pub fn g_key_file_set_double_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gdouble,
length: gsize);
pub fn g_key_file_get_double_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut gdouble;
pub fn g_key_file_set_integer_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gint,
length: gsize);
pub fn g_key_file_set_comment(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
comment: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_comment(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_remove_comment(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_remove_key(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_remove_group(key_file: *mut GKeyFile,
group_name: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_mapped_file_new(filename: *const gchar, writable: gboolean,
error: *mut *mut GError) -> *mut GMappedFile;
pub fn g_mapped_file_new_from_fd(fd: gint, writable: gboolean,
error: *mut *mut GError)
-> *mut GMappedFile;
pub fn g_mapped_file_get_length(file: *mut GMappedFile) -> gsize;
pub fn g_mapped_file_get_contents(file: *mut GMappedFile) -> *mut gchar;
pub fn g_mapped_file_get_bytes(file: *mut GMappedFile) -> *mut GBytes;
pub fn g_mapped_file_ref(file: *mut GMappedFile) -> *mut GMappedFile;
pub fn g_mapped_file_unref(file: *mut GMappedFile);
pub fn g_mapped_file_free(file: *mut GMappedFile);
pub fn g_markup_error_quark() -> GQuark;
pub fn g_markup_parse_context_new(parser: *const GMarkupParser,
flags: GMarkupParseFlags,
user_data: gpointer,
user_data_dnotify: GDestroyNotify)
-> *mut GMarkupParseContext;
pub fn g_markup_parse_context_ref(context: *mut GMarkupParseContext)
-> *mut GMarkupParseContext;
pub fn g_markup_parse_context_unref(context: *mut GMarkupParseContext);
pub fn g_markup_parse_context_free(context: *mut GMarkupParseContext);
pub fn g_markup_parse_context_parse(context: *mut GMarkupParseContext,
text: *const gchar, text_len: gssize,
error: *mut *mut GError) -> gboolean;
pub fn g_markup_parse_context_push(context: *mut GMarkupParseContext,
parser: *const GMarkupParser,
user_data: gpointer);
pub fn g_markup_parse_context_pop(context: *mut GMarkupParseContext)
-> gpointer;
pub fn g_markup_parse_context_end_parse(context: *mut GMarkupParseContext,
error: *mut *mut GError)
-> gboolean;
pub fn g_markup_parse_context_get_element(context:
*mut GMarkupParseContext)
-> *const gchar;
pub fn g_markup_parse_context_get_element_stack(context:
*mut GMarkupParseContext)
-> *const GSList;
pub fn g_markup_parse_context_get_position(context:
*mut GMarkupParseContext,
line_number: *mut gint,
char_number: *mut gint);
pub fn g_markup_parse_context_get_user_data(context:
*mut GMarkupParseContext)
-> gpointer;
pub fn g_markup_escape_text(text: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_markup_printf_escaped(format: *const ::libc::c_char, ...)
-> *mut gchar;
pub fn g_markup_vprintf_escaped(format: *const ::libc::c_char,
args: va_list) -> *mut gchar;
pub fn g_markup_collect_attributes(element_name: *const gchar,
attribute_names: *mut *const gchar,
attribute_values: *mut *const gchar,
error: *mut *mut GError,
first_type: GMarkupCollectType,
first_attr: *const gchar, ...)
-> gboolean;
pub fn g_printf_string_upper_bound(format: *const gchar, args: va_list)
-> gsize;
pub fn g_log_set_handler(log_domain: *const gchar,
log_levels: GLogLevelFlags, log_func: GLogFunc,
user_data: gpointer) -> guint;
pub fn g_log_remove_handler(log_domain: *const gchar, handler_id: guint);
pub fn g_log_default_handler(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar,
unused_data: gpointer);
pub fn g_log_set_default_handler(log_func: GLogFunc, user_data: gpointer)
-> GLogFunc;
pub fn g_log(log_domain: *const gchar, log_level: GLogLevelFlags,
format: *const gchar, ...);
pub fn g_logv(log_domain: *const gchar, log_level: GLogLevelFlags,
format: *const gchar, args: va_list);
pub fn g_log_set_fatal_mask(log_domain: *const gchar,
fatal_mask: GLogLevelFlags) -> GLogLevelFlags;
pub fn g_log_set_always_fatal(fatal_mask: GLogLevelFlags)
-> GLogLevelFlags;
pub fn _g_log_fallback_handler(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar,
unused_data: gpointer);
pub fn g_return_if_fail_warning(log_domain: *const ::libc::c_char,
pretty_function: *const ::libc::c_char,
expression: *const ::libc::c_char);
pub fn g_warn_message(domain: *const ::libc::c_char,
file: *const ::libc::c_char, line: ::libc::c_int,
func: *const ::libc::c_char,
warnexpr: *const ::libc::c_char);
pub fn g_assert_warning(log_domain: *const ::libc::c_char,
file: *const ::libc::c_char, line: ::libc::c_int,
pretty_function: *const ::libc::c_char,
expression: *const ::libc::c_char);
pub fn g_print(format: *const gchar, ...);
pub fn g_set_print_handler(func: GPrintFunc) -> GPrintFunc;
pub fn g_printerr(format: *const gchar, ...);
pub fn g_set_printerr_handler(func: GPrintFunc) -> GPrintFunc;
pub fn g_option_error_quark() -> GQuark;
pub fn g_option_context_new(parameter_string: *const gchar)
-> *mut GOptionContext;
pub fn g_option_context_set_summary(context: *mut GOptionContext,
summary: *const gchar);
pub fn g_option_context_get_summary(context: *mut GOptionContext)
-> *const gchar;
pub fn g_option_context_set_description(context: *mut GOptionContext,
description: *const gchar);
pub fn g_option_context_get_description(context: *mut GOptionContext)
-> *const gchar;
pub fn g_option_context_free(context: *mut GOptionContext);
pub fn g_option_context_set_help_enabled(context: *mut GOptionContext,
help_enabled: gboolean);
pub fn g_option_context_get_help_enabled(context: *mut GOptionContext)
-> gboolean;
pub fn g_option_context_set_ignore_unknown_options(context:
*mut GOptionContext,
ignore_unknown:
gboolean);
pub fn g_option_context_get_ignore_unknown_options(context:
*mut GOptionContext)
-> gboolean;
pub fn g_option_context_add_main_entries(context: *mut GOptionContext,
entries: *const GOptionEntry,
translation_domain:
*const gchar);
pub fn g_option_context_parse(context: *mut GOptionContext,
argc: *mut gint, argv: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_option_context_parse_strv(context: *mut GOptionContext,
arguments: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_option_context_set_translate_func(context: *mut GOptionContext,
func: GTranslateFunc,
data: gpointer,
destroy_notify:
GDestroyNotify);
pub fn g_option_context_set_translation_domain(context:
*mut GOptionContext,
domain: *const gchar);
pub fn g_option_context_add_group(context: *mut GOptionContext,
group: *mut GOptionGroup);
pub fn g_option_context_set_main_group(context: *mut GOptionContext,
group: *mut GOptionGroup);
pub fn g_option_context_get_main_group(context: *mut GOptionContext)
-> *mut GOptionGroup;
pub fn g_option_context_get_help(context: *mut GOptionContext,
main_help: gboolean,
group: *mut GOptionGroup) -> *mut gchar;
pub fn g_option_group_new(name: *const gchar, description: *const gchar,
help_description: *const gchar,
user_data: gpointer, destroy: GDestroyNotify)
-> *mut GOptionGroup;
pub fn g_option_group_set_parse_hooks(group: *mut GOptionGroup,
pre_parse_func: GOptionParseFunc,
post_parse_func: GOptionParseFunc);
pub fn g_option_group_set_error_hook(group: *mut GOptionGroup,
error_func: GOptionErrorFunc);
pub fn g_option_group_free(group: *mut GOptionGroup);
pub fn g_option_group_add_entries(group: *mut GOptionGroup,
entries: *const GOptionEntry);
pub fn g_option_group_set_translate_func(group: *mut GOptionGroup,
func: GTranslateFunc,
data: gpointer,
destroy_notify: GDestroyNotify);
pub fn g_option_group_set_translation_domain(group: *mut GOptionGroup,
domain: *const gchar);
pub fn g_pattern_spec_new(pattern: *const gchar) -> *mut GPatternSpec;
pub fn g_pattern_spec_free(pspec: *mut GPatternSpec);
pub fn g_pattern_spec_equal(pspec1: *mut GPatternSpec,
pspec2: *mut GPatternSpec) -> gboolean;
pub fn g_pattern_match(pspec: *mut GPatternSpec, string_length: guint,
string: *const gchar,
string_reversed: *const gchar) -> gboolean;
pub fn g_pattern_match_string(pspec: *mut GPatternSpec,
string: *const gchar) -> gboolean;
pub fn g_pattern_match_simple(pattern: *const gchar, string: *const gchar)
-> gboolean;
pub fn g_spaced_primes_closest(num: guint) -> guint;
pub fn g_qsort_with_data(pbase: gconstpointer, total_elems: gint,
size: gsize, compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_queue_new() -> *mut GQueue;
pub fn g_queue_free(queue: *mut GQueue);
pub fn g_queue_free_full(queue: *mut GQueue, free_func: GDestroyNotify);
pub fn g_queue_init(queue: *mut GQueue);
pub fn g_queue_clear(queue: *mut GQueue);
pub fn g_queue_is_empty(queue: *mut GQueue) -> gboolean;
pub fn g_queue_get_length(queue: *mut GQueue) -> guint;
pub fn g_queue_reverse(queue: *mut GQueue);
pub fn g_queue_copy(queue: *mut GQueue) -> *mut GQueue;
pub fn g_queue_foreach(queue: *mut GQueue, func: GFunc,
user_data: gpointer);
pub fn g_queue_find(queue: *mut GQueue, data: gconstpointer)
-> *mut GList;
pub fn g_queue_find_custom(queue: *mut GQueue, data: gconstpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_queue_sort(queue: *mut GQueue, compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_queue_push_head(queue: *mut GQueue, data: gpointer);
pub fn g_queue_push_tail(queue: *mut GQueue, data: gpointer);
pub fn g_queue_push_nth(queue: *mut GQueue, data: gpointer, n: gint);
pub fn g_queue_pop_head(queue: *mut GQueue) -> gpointer;
pub fn g_queue_pop_tail(queue: *mut GQueue) -> gpointer;
pub fn g_queue_pop_nth(queue: *mut GQueue, n: guint) -> gpointer;
pub fn g_queue_peek_head(queue: *mut GQueue) -> gpointer;
pub fn g_queue_peek_tail(queue: *mut GQueue) -> gpointer;
pub fn g_queue_peek_nth(queue: *mut GQueue, n: guint) -> gpointer;
pub fn g_queue_index(queue: *mut GQueue, data: gconstpointer) -> gint;
pub fn g_queue_remove(queue: *mut GQueue, data: gconstpointer)
-> gboolean;
pub fn g_queue_remove_all(queue: *mut GQueue, data: gconstpointer)
-> guint;
pub fn g_queue_insert_before(queue: *mut GQueue, sibling: *mut GList,
data: gpointer);
pub fn g_queue_insert_after(queue: *mut GQueue, sibling: *mut GList,
data: gpointer);
pub fn g_queue_insert_sorted(queue: *mut GQueue, data: gpointer,
func: GCompareDataFunc, user_data: gpointer);
pub fn g_queue_push_head_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_push_tail_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_push_nth_link(queue: *mut GQueue, n: gint,
link_: *mut GList);
pub fn g_queue_pop_head_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_pop_tail_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_pop_nth_link(queue: *mut GQueue, n: guint) -> *mut GList;
pub fn g_queue_peek_head_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_peek_tail_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_peek_nth_link(queue: *mut GQueue, n: guint) -> *mut GList;
pub fn g_queue_link_index(queue: *mut GQueue, link_: *mut GList) -> gint;
pub fn g_queue_unlink(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_delete_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_rand_new_with_seed(seed: guint32) -> *mut GRand;
pub fn g_rand_new_with_seed_array(seed: *const guint32,
seed_length: guint) -> *mut GRand;
pub fn g_rand_new() -> *mut GRand;
pub fn g_rand_free(rand_: *mut GRand);
pub fn g_rand_copy(rand_: *mut GRand) -> *mut GRand;
pub fn g_rand_set_seed(rand_: *mut GRand, seed: guint32);
pub fn g_rand_set_seed_array(rand_: *mut GRand, seed: *const guint32,
seed_length: guint);
pub fn g_rand_int(rand_: *mut GRand) -> guint32;
pub fn g_rand_int_range(rand_: *mut GRand, begin: gint32, end: gint32)
-> gint32;
pub fn g_rand_double(rand_: *mut GRand) -> gdouble;
pub fn g_rand_double_range(rand_: *mut GRand, begin: gdouble,
end: gdouble) -> gdouble;
pub fn g_random_set_seed(seed: guint32);
pub fn g_random_int() -> guint32;
pub fn g_random_int_range(begin: gint32, end: gint32) -> gint32;
pub fn g_random_double() -> gdouble;
pub fn g_random_double_range(begin: gdouble, end: gdouble) -> gdouble;
pub fn g_regex_error_quark() -> GQuark;
pub fn g_regex_new(pattern: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut GRegex;
pub fn g_regex_ref(regex: *mut GRegex) -> *mut GRegex;
pub fn g_regex_unref(regex: *mut GRegex);
pub fn g_regex_get_pattern(regex: *const GRegex) -> *const gchar;
pub fn g_regex_get_max_backref(regex: *const GRegex) -> gint;
pub fn g_regex_get_capture_count(regex: *const GRegex) -> gint;
pub fn g_regex_get_has_cr_or_lf(regex: *const GRegex) -> gboolean;
pub fn g_regex_get_max_lookbehind(regex: *const GRegex) -> gint;
pub fn g_regex_get_string_number(regex: *const GRegex, name: *const gchar)
-> gint;
pub fn g_regex_escape_string(string: *const gchar, length: gint)
-> *mut gchar;
pub fn g_regex_escape_nul(string: *const gchar, length: gint)
-> *mut gchar;
pub fn g_regex_get_compile_flags(regex: *const GRegex)
-> GRegexCompileFlags;
pub fn g_regex_get_match_flags(regex: *const GRegex) -> GRegexMatchFlags;
pub fn g_regex_match_simple(pattern: *const gchar, string: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags) -> gboolean;
pub fn g_regex_match(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo) -> gboolean;
pub fn g_regex_match_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_regex_match_all(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo) -> gboolean;
pub fn g_regex_match_all_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_regex_split_simple(pattern: *const gchar, string: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags)
-> *mut *mut gchar;
pub fn g_regex_split(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags) -> *mut *mut gchar;
pub fn g_regex_split_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
max_tokens: gint, error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_regex_replace(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
replacement: *const gchar,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_replace_literal(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
replacement: *const gchar,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_replace_eval(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
eval: GRegexEvalCallback, user_data: gpointer,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_check_replacement(replacement: *const gchar,
has_references: *mut gboolean,
error: *mut *mut GError) -> gboolean;
pub fn g_match_info_get_regex(match_info: *const GMatchInfo)
-> *mut GRegex;
pub fn g_match_info_get_string(match_info: *const GMatchInfo)
-> *const gchar;
pub fn g_match_info_ref(match_info: *mut GMatchInfo) -> *mut GMatchInfo;
pub fn g_match_info_unref(match_info: *mut GMatchInfo);
pub fn g_match_info_free(match_info: *mut GMatchInfo);
pub fn g_match_info_next(match_info: *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_match_info_matches(match_info: *const GMatchInfo) -> gboolean;
pub fn g_match_info_get_match_count(match_info: *const GMatchInfo)
-> gint;
pub fn g_match_info_is_partial_match(match_info: *const GMatchInfo)
-> gboolean;
pub fn g_match_info_expand_references(match_info: *const GMatchInfo,
string_to_expand: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_match_info_fetch(match_info: *const GMatchInfo, match_num: gint)
-> *mut gchar;
pub fn g_match_info_fetch_pos(match_info: *const GMatchInfo,
match_num: gint, start_pos: *mut gint,
end_pos: *mut gint) -> gboolean;
pub fn g_match_info_fetch_named(match_info: *const GMatchInfo,
name: *const gchar) -> *mut gchar;
pub fn g_match_info_fetch_named_pos(match_info: *const GMatchInfo,
name: *const gchar,
start_pos: *mut gint,
end_pos: *mut gint) -> gboolean;
pub fn g_match_info_fetch_all(match_info: *const GMatchInfo)
-> *mut *mut gchar;
pub fn g_scanner_new(config_templ: *const GScannerConfig)
-> *mut GScanner;
pub fn g_scanner_destroy(scanner: *mut GScanner);
pub fn g_scanner_input_file(scanner: *mut GScanner, input_fd: gint);
pub fn g_scanner_sync_file_offset(scanner: *mut GScanner);
pub fn g_scanner_input_text(scanner: *mut GScanner, text: *const gchar,
text_len: guint);
pub fn g_scanner_get_next_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_peek_next_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_cur_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_cur_value(scanner: *mut GScanner) -> GTokenValue;
pub fn g_scanner_cur_line(scanner: *mut GScanner) -> guint;
pub fn g_scanner_cur_position(scanner: *mut GScanner) -> guint;
pub fn g_scanner_eof(scanner: *mut GScanner) -> gboolean;
pub fn g_scanner_set_scope(scanner: *mut GScanner, scope_id: guint)
-> guint;
pub fn g_scanner_scope_add_symbol(scanner: *mut GScanner, scope_id: guint,
symbol: *const gchar, value: gpointer);
pub fn g_scanner_scope_remove_symbol(scanner: *mut GScanner,
scope_id: guint,
symbol: *const gchar);
pub fn g_scanner_scope_lookup_symbol(scanner: *mut GScanner,
scope_id: guint,
symbol: *const gchar) -> gpointer;
pub fn g_scanner_scope_foreach_symbol(scanner: *mut GScanner,
scope_id: guint, func: GHFunc,
user_data: gpointer);
pub fn g_scanner_lookup_symbol(scanner: *mut GScanner,
symbol: *const gchar) -> gpointer;
pub fn g_scanner_unexp_token(scanner: *mut GScanner,
expected_token: GTokenType,
identifier_spec: *const gchar,
symbol_spec: *const gchar,
symbol_name: *const gchar,
message: *const gchar, is_error: gint);
pub fn g_scanner_error(scanner: *mut GScanner, format: *const gchar, ...);
pub fn g_scanner_warn(scanner: *mut GScanner, format: *const gchar, ...);
pub fn g_sequence_new(data_destroy: GDestroyNotify) -> *mut GSequence;
pub fn g_sequence_free(seq: *mut GSequence);
pub fn g_sequence_get_length(seq: *mut GSequence) -> gint;
pub fn g_sequence_foreach(seq: *mut GSequence, func: GFunc,
user_data: gpointer);
pub fn g_sequence_foreach_range(begin: *mut GSequenceIter,
end: *mut GSequenceIter, func: GFunc,
user_data: gpointer);
pub fn g_sequence_sort(seq: *mut GSequence, cmp_func: GCompareDataFunc,
cmp_data: gpointer);
pub fn g_sequence_sort_iter(seq: *mut GSequence,
cmp_func: GSequenceIterCompareFunc,
cmp_data: gpointer);
pub fn g_sequence_get_begin_iter(seq: *mut GSequence)
-> *mut GSequenceIter;
pub fn g_sequence_get_end_iter(seq: *mut GSequence) -> *mut GSequenceIter;
pub fn g_sequence_get_iter_at_pos(seq: *mut GSequence, pos: gint)
-> *mut GSequenceIter;
pub fn g_sequence_append(seq: *mut GSequence, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_prepend(seq: *mut GSequence, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_insert_before(iter: *mut GSequenceIter, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_move(src: *mut GSequenceIter, dest: *mut GSequenceIter);
pub fn g_sequence_swap(a: *mut GSequenceIter, b: *mut GSequenceIter);
pub fn g_sequence_insert_sorted(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_insert_sorted_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_sort_changed(iter: *mut GSequenceIter,
cmp_func: GCompareDataFunc,
cmp_data: gpointer);
pub fn g_sequence_sort_changed_iter(iter: *mut GSequenceIter,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer);
pub fn g_sequence_remove(iter: *mut GSequenceIter);
pub fn g_sequence_remove_range(begin: *mut GSequenceIter,
end: *mut GSequenceIter);
pub fn g_sequence_move_range(dest: *mut GSequenceIter,
begin: *mut GSequenceIter,
end: *mut GSequenceIter);
pub fn g_sequence_search(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc, cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_search_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_lookup(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc, cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_lookup_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_get(iter: *mut GSequenceIter) -> gpointer;
pub fn g_sequence_set(iter: *mut GSequenceIter, data: gpointer);
pub fn g_sequence_iter_is_begin(iter: *mut GSequenceIter) -> gboolean;
pub fn g_sequence_iter_is_end(iter: *mut GSequenceIter) -> gboolean;
pub fn g_sequence_iter_next(iter: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_sequence_iter_prev(iter: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_sequence_iter_get_position(iter: *mut GSequenceIter) -> gint;
pub fn g_sequence_iter_move(iter: *mut GSequenceIter, delta: gint)
-> *mut GSequenceIter;
pub fn g_sequence_iter_get_sequence(iter: *mut GSequenceIter)
-> *mut GSequence;
pub fn g_sequence_iter_compare(a: *mut GSequenceIter,
b: *mut GSequenceIter) -> gint;
pub fn g_sequence_range_get_midpoint(begin: *mut GSequenceIter,
end: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_shell_error_quark() -> GQuark;
pub fn g_shell_quote(unquoted_string: *const gchar) -> *mut gchar;
pub fn g_shell_unquote(quoted_string: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_shell_parse_argv(command_line: *const gchar, argcp: *mut gint,
argvp: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_slice_alloc(block_size: gsize) -> gpointer;
pub fn g_slice_alloc0(block_size: gsize) -> gpointer;
pub fn g_slice_copy(block_size: gsize, mem_block: gconstpointer)
-> gpointer;
pub fn g_slice_free1(block_size: gsize, mem_block: gpointer);
pub fn g_slice_free_chain_with_offset(block_size: gsize,
mem_chain: gpointer,
next_offset: gsize);
pub fn g_slice_set_config(ckey: GSliceConfig, value: gint64);
pub fn g_slice_get_config(ckey: GSliceConfig) -> gint64;
pub fn g_slice_get_config_state(ckey: GSliceConfig, address: gint64,
n_values: *mut guint) -> *mut gint64;
pub fn g_spawn_error_quark() -> GQuark;
pub fn g_spawn_exit_error_quark() -> GQuark;
pub fn g_spawn_async(working_directory: *const gchar,
argv: *mut *mut gchar, envp: *mut *mut gchar,
flags: GSpawnFlags,
child_setup: GSpawnChildSetupFunc,
user_data: gpointer, child_pid: *mut GPid,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_async_with_pipes(working_directory: *const gchar,
argv: *mut *mut gchar,
envp: *mut *mut gchar, flags: GSpawnFlags,
child_setup: GSpawnChildSetupFunc,
user_data: gpointer, child_pid: *mut GPid,
standard_input: *mut gint,
standard_output: *mut gint,
standard_error: *mut gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_sync(working_directory: *const gchar,
argv: *mut *mut gchar, envp: *mut *mut gchar,
flags: GSpawnFlags, child_setup: GSpawnChildSetupFunc,
user_data: gpointer, standard_output: *mut *mut gchar,
standard_error: *mut *mut gchar,
exit_status: *mut gint, error: *mut *mut GError)
-> gboolean;
pub fn g_spawn_command_line_sync(command_line: *const gchar,
standard_output: *mut *mut gchar,
standard_error: *mut *mut gchar,
exit_status: *mut gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_command_line_async(command_line: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_check_exit_status(exit_status: gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_close_pid(pid: GPid);
pub fn g_ascii_tolower(c: gchar) -> gchar;
pub fn g_ascii_toupper(c: gchar) -> gchar;
pub fn g_ascii_digit_value(c: gchar) -> gint;
pub fn g_ascii_xdigit_value(c: gchar) -> gint;
pub fn g_strdelimit(string: *mut gchar, delimiters: *const gchar,
new_delimiter: gchar) -> *mut gchar;
pub fn g_strcanon(string: *mut gchar, valid_chars: *const gchar,
substitutor: gchar) -> *mut gchar;
pub fn g_strerror(errnum: gint) -> *const gchar;
pub fn g_strsignal(signum: gint) -> *const gchar;
pub fn g_strreverse(string: *mut gchar) -> *mut gchar;
pub fn g_strlcpy(dest: *mut gchar, src: *const gchar, dest_size: gsize)
-> gsize;
pub fn g_strlcat(dest: *mut gchar, src: *const gchar, dest_size: gsize)
-> gsize;
pub fn g_strstr_len(haystack: *const gchar, haystack_len: gssize,
needle: *const gchar) -> *mut gchar;
pub fn g_strrstr(haystack: *const gchar, needle: *const gchar)
-> *mut gchar;
pub fn g_strrstr_len(haystack: *const gchar, haystack_len: gssize,
needle: *const gchar) -> *mut gchar;
pub fn g_str_has_suffix(str: *const gchar, suffix: *const gchar)
-> gboolean;
pub fn g_str_has_prefix(str: *const gchar, prefix: *const gchar)
-> gboolean;
pub fn g_strtod(nptr: *const gchar, endptr: *mut *mut gchar) -> gdouble;
pub fn g_ascii_strtod(nptr: *const gchar, endptr: *mut *mut gchar)
-> gdouble;
pub fn g_ascii_strtoull(nptr: *const gchar, endptr: *mut *mut gchar,
base: guint) -> guint64;
pub fn g_ascii_strtoll(nptr: *const gchar, endptr: *mut *mut gchar,
base: guint) -> gint64;
pub fn g_ascii_dtostr(buffer: *mut gchar, buf_len: gint, d: gdouble)
-> *mut gchar;
pub fn g_ascii_formatd(buffer: *mut gchar, buf_len: gint,
format: *const gchar, d: gdouble) -> *mut gchar;
pub fn g_strchug(string: *mut gchar) -> *mut gchar;
pub fn g_strchomp(string: *mut gchar) -> *mut gchar;
pub fn g_ascii_strcasecmp(s1: *const gchar, s2: *const gchar) -> gint;
pub fn g_ascii_strncasecmp(s1: *const gchar, s2: *const gchar, n: gsize)
-> gint;
pub fn g_ascii_strdown(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_ascii_strup(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_str_is_ascii(str: *const gchar) -> gboolean;
pub fn g_strcasecmp(s1: *const gchar, s2: *const gchar) -> gint;
pub fn g_strncasecmp(s1: *const gchar, s2: *const gchar, n: guint)
-> gint;
pub fn g_strdown(string: *mut gchar) -> *mut gchar;
pub fn g_strup(string: *mut gchar) -> *mut gchar;
pub fn g_strdup(str: *const gchar) -> *mut gchar;
pub fn g_strdup_printf(format: *const gchar, ...) -> *mut gchar;
pub fn g_strdup_vprintf(format: *const gchar, args: va_list)
-> *mut gchar;
pub fn g_strndup(str: *const gchar, n: gsize) -> *mut gchar;
pub fn g_strnfill(length: gsize, fill_char: gchar) -> *mut gchar;
pub fn g_strconcat(string1: *const gchar, ...) -> *mut gchar;
pub fn g_strjoin(separator: *const gchar, ...) -> *mut gchar;
pub fn g_strcompress(source: *const gchar) -> *mut gchar;
pub fn g_strescape(source: *const gchar, exceptions: *const gchar)
-> *mut gchar;
pub fn g_memdup(mem: gconstpointer, byte_size: guint) -> gpointer;
pub fn g_strsplit(string: *const gchar, delimiter: *const gchar,
max_tokens: gint) -> *mut *mut gchar;
pub fn g_strsplit_set(string: *const gchar, delimiters: *const gchar,
max_tokens: gint) -> *mut *mut gchar;
pub fn g_strjoinv(separator: *const gchar, str_array: *mut *mut gchar)
-> *mut gchar;
pub fn g_strfreev(str_array: *mut *mut gchar);
pub fn g_strdupv(str_array: *mut *mut gchar) -> *mut *mut gchar;
pub fn g_strv_length(str_array: *mut *mut gchar) -> guint;
pub fn g_stpcpy(dest: *mut gchar, src: *const ::libc::c_char)
-> *mut gchar;
pub fn g_str_to_ascii(str: *const gchar, from_locale: *const gchar)
-> *mut gchar;
pub fn g_str_tokenize_and_fold(string: *const gchar,
translit_locale: *const gchar,
ascii_alternates: *mut *mut *mut gchar)
-> *mut *mut gchar;
pub fn g_str_match_string(search_term: *const gchar,
potential_hit: *const gchar,
accept_alternates: gboolean) -> gboolean;
pub fn g_string_chunk_new(size: gsize) -> *mut GStringChunk;
pub fn g_string_chunk_free(chunk: *mut GStringChunk);
pub fn g_string_chunk_clear(chunk: *mut GStringChunk);
pub fn g_string_chunk_insert(chunk: *mut GStringChunk,
string: *const gchar) -> *mut gchar;
pub fn g_string_chunk_insert_len(chunk: *mut GStringChunk,
string: *const gchar, len: gssize)
-> *mut gchar;
pub fn g_string_chunk_insert_const(chunk: *mut GStringChunk,
string: *const gchar) -> *mut gchar;
pub fn g_strcmp0(str1: *const ::libc::c_char, str2: *const ::libc::c_char)
-> ::libc::c_int;
pub fn g_test_minimized_result(minimized_quantity: ::libc::c_double,
format: *const ::libc::c_char, ...);
pub fn g_test_maximized_result(maximized_quantity: ::libc::c_double,
format: *const ::libc::c_char, ...);
pub fn g_test_init(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char, ...);
pub fn g_test_subprocess() -> gboolean;
pub fn g_test_run() -> ::libc::c_int;
pub fn g_test_add_func(testpath: *const ::libc::c_char,
test_func: GTestFunc);
pub fn g_test_add_data_func(testpath: *const ::libc::c_char,
test_data: gconstpointer,
test_func: GTestDataFunc);
pub fn g_test_add_data_func_full(testpath: *const ::libc::c_char,
test_data: gpointer,
test_func: GTestDataFunc,
data_free_func: GDestroyNotify);
pub fn g_test_fail();
pub fn g_test_incomplete(msg: *const gchar);
pub fn g_test_skip(msg: *const gchar);
pub fn g_test_failed() -> gboolean;
pub fn g_test_set_nonfatal_assertions();
pub fn g_test_message(format: *const ::libc::c_char, ...);
pub fn g_test_bug_base(uri_pattern: *const ::libc::c_char);
pub fn g_test_bug(bug_uri_snippet: *const ::libc::c_char);
pub fn g_test_timer_start();
pub fn g_test_timer_elapsed() -> ::libc::c_double;
pub fn g_test_timer_last() -> ::libc::c_double;
pub fn g_test_queue_free(gfree_pointer: gpointer);
pub fn g_test_queue_destroy(destroy_func: GDestroyNotify,
destroy_data: gpointer);
pub fn g_test_trap_fork(usec_timeout: guint64,
test_trap_flags: GTestTrapFlags) -> gboolean;
pub fn g_test_trap_subprocess(test_path: *const ::libc::c_char,
usec_timeout: guint64,
test_flags: GTestSubprocessFlags);
pub fn g_test_trap_has_passed() -> gboolean;
pub fn g_test_trap_reached_timeout() -> gboolean;
pub fn g_test_rand_int() -> gint32;
pub fn g_test_rand_int_range(begin: gint32, end: gint32) -> gint32;
pub fn g_test_rand_double() -> ::libc::c_double;
pub fn g_test_rand_double_range(range_start: ::libc::c_double,
range_end: ::libc::c_double)
-> ::libc::c_double;
pub fn g_test_create_case(test_name: *const ::libc::c_char,
data_size: gsize, test_data: gconstpointer,
data_setup: GTestFixtureFunc,
data_test: GTestFixtureFunc,
data_teardown: GTestFixtureFunc)
-> *mut GTestCase;
pub fn g_test_create_suite(suite_name: *const ::libc::c_char)
-> *mut GTestSuite;
pub fn g_test_get_root() -> *mut GTestSuite;
pub fn g_test_suite_add(suite: *mut GTestSuite,
test_case: *mut GTestCase);
pub fn g_test_suite_add_suite(suite: *mut GTestSuite,
nestedsuite: *mut GTestSuite);
pub fn g_test_run_suite(suite: *mut GTestSuite) -> ::libc::c_int;
pub fn g_test_trap_assertions(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
assertion_flags: guint64,
pattern: *const ::libc::c_char);
pub fn g_assertion_message(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
message: *const ::libc::c_char);
pub fn g_assertion_message_expr(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char);
pub fn g_assertion_message_cmpstr(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
arg1: *const ::libc::c_char,
cmp: *const ::libc::c_char,
arg2: *const ::libc::c_char);
pub fn g_assertion_message_cmpnum(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
arg1: ::libc::c_double,
cmp: *const ::libc::c_char,
arg2: ::libc::c_double,
numtype: ::libc::c_char);
pub fn g_assertion_message_error(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
error: *const GError,
error_domain: GQuark,
error_code: ::libc::c_int);
pub fn g_test_add_vtable(testpath: *const ::libc::c_char,
data_size: gsize, test_data: gconstpointer,
data_setup: GTestFixtureFunc,
data_test: GTestFixtureFunc,
data_teardown: GTestFixtureFunc);
pub fn g_test_log_type_name(log_type: GTestLogType)
-> *const ::libc::c_char;
pub fn g_test_log_buffer_new() -> *mut GTestLogBuffer;
pub fn g_test_log_buffer_free(tbuffer: *mut GTestLogBuffer);
pub fn g_test_log_buffer_push(tbuffer: *mut GTestLogBuffer,
n_bytes: guint, bytes: *const guint8);
pub fn g_test_log_buffer_pop(tbuffer: *mut GTestLogBuffer)
-> *mut GTestLogMsg;
pub fn g_test_log_msg_free(tmsg: *mut GTestLogMsg);
pub fn g_test_log_set_fatal_handler(log_func: GTestLogFatalFunc,
user_data: gpointer);
pub fn g_test_expect_message(log_domain: *const gchar,
log_level: GLogLevelFlags,
pattern: *const gchar);
pub fn g_test_assert_expected_messages_internal(domain:
*const ::libc::c_char,
file:
*const ::libc::c_char,
line: ::libc::c_int,
func:
*const ::libc::c_char);
pub fn g_test_build_filename(file_type: GTestFileType,
first_path: *const gchar, ...) -> *mut gchar;
pub fn g_test_get_dir(file_type: GTestFileType) -> *const gchar;
pub fn g_test_get_filename(file_type: GTestFileType,
first_path: *const gchar, ...) -> *const gchar;
pub fn g_thread_pool_new(func: GFunc, user_data: gpointer,
max_threads: gint, exclusive: gboolean,
error: *mut *mut GError) -> *mut GThreadPool;
pub fn g_thread_pool_free(pool: *mut GThreadPool, immediate: gboolean,
wait_: gboolean);
pub fn g_thread_pool_push(pool: *mut GThreadPool, data: gpointer,
error: *mut *mut GError) -> gboolean;
pub fn g_thread_pool_unprocessed(pool: *mut GThreadPool) -> guint;
pub fn g_thread_pool_set_sort_function(pool: *mut GThreadPool,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_thread_pool_set_max_threads(pool: *mut GThreadPool,
max_threads: gint,
error: *mut *mut GError) -> gboolean;
pub fn g_thread_pool_get_max_threads(pool: *mut GThreadPool) -> gint;
pub fn g_thread_pool_get_num_threads(pool: *mut GThreadPool) -> guint;
pub fn g_thread_pool_set_max_unused_threads(max_threads: gint);
pub fn g_thread_pool_get_max_unused_threads() -> gint;
pub fn g_thread_pool_get_num_unused_threads() -> guint;
pub fn g_thread_pool_stop_unused_threads();
pub fn g_thread_pool_set_max_idle_time(interval: guint);
pub fn g_thread_pool_get_max_idle_time() -> guint;
pub fn g_timer_new() -> *mut GTimer;
pub fn g_timer_destroy(timer: *mut GTimer);
pub fn g_timer_start(timer: *mut GTimer);
pub fn g_timer_stop(timer: *mut GTimer);
pub fn g_timer_reset(timer: *mut GTimer);
pub fn g_timer_continue(timer: *mut GTimer);
pub fn g_timer_elapsed(timer: *mut GTimer, microseconds: *mut gulong)
-> gdouble;
pub fn g_usleep(microseconds: gulong);
pub fn g_time_val_add(time_: *mut GTimeVal, microseconds: glong);
pub fn g_time_val_from_iso8601(iso_date: *const gchar,
time_: *mut GTimeVal) -> gboolean;
pub fn g_time_val_to_iso8601(time_: *mut GTimeVal) -> *mut gchar;
pub fn g_tree_new(key_compare_func: GCompareFunc) -> *mut GTree;
pub fn g_tree_new_with_data(key_compare_func: GCompareDataFunc,
key_compare_data: gpointer) -> *mut GTree;
pub fn g_tree_new_full(key_compare_func: GCompareDataFunc,
key_compare_data: gpointer,
key_destroy_func: GDestroyNotify,
value_destroy_func: GDestroyNotify) -> *mut GTree;
pub fn g_tree_ref(tree: *mut GTree) -> *mut GTree;
pub fn g_tree_unref(tree: *mut GTree);
pub fn g_tree_destroy(tree: *mut GTree);
pub fn g_tree_insert(tree: *mut GTree, key: gpointer, value: gpointer);
pub fn g_tree_replace(tree: *mut GTree, key: gpointer, value: gpointer);
pub fn g_tree_remove(tree: *mut GTree, key: gconstpointer) -> gboolean;
pub fn g_tree_steal(tree: *mut GTree, key: gconstpointer) -> gboolean;
pub fn g_tree_lookup(tree: *mut GTree, key: gconstpointer) -> gpointer;
pub fn g_tree_lookup_extended(tree: *mut GTree, lookup_key: gconstpointer,
orig_key: *mut gpointer,
value: *mut gpointer) -> gboolean;
pub fn g_tree_foreach(tree: *mut GTree, func: GTraverseFunc,
user_data: gpointer);
pub fn g_tree_traverse(tree: *mut GTree, traverse_func: GTraverseFunc,
traverse_type: GTraverseType, user_data: gpointer);
pub fn g_tree_search(tree: *mut GTree, search_func: GCompareFunc,
user_data: gconstpointer) -> gpointer;
pub fn g_tree_height(tree: *mut GTree) -> gint;
pub fn g_tree_nnodes(tree: *mut GTree) -> gint;
pub fn g_uri_unescape_string(escaped_string: *const ::libc::c_char,
illegal_characters: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_unescape_segment(escaped_string: *const ::libc::c_char,
escaped_string_end: *const ::libc::c_char,
illegal_characters: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_parse_scheme(uri: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_escape_string(unescaped: *const ::libc::c_char,
reserved_chars_allowed: *const ::libc::c_char,
allow_utf8: gboolean) -> *mut ::libc::c_char;
pub fn g_variant_type_string_is_valid(type_string: *const gchar)
-> gboolean;
pub fn g_variant_type_string_scan(string: *const gchar,
limit: *const gchar,
endptr: *mut *const gchar) -> gboolean;
pub fn g_variant_type_free(_type: *mut GVariantType);
pub fn g_variant_type_copy(_type: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new(type_string: *const gchar) -> *mut GVariantType;
pub fn g_variant_type_get_string_length(_type: *const GVariantType)
-> gsize;
pub fn g_variant_type_peek_string(_type: *const GVariantType)
-> *const gchar;
pub fn g_variant_type_dup_string(_type: *const GVariantType)
-> *mut gchar;
pub fn g_variant_type_is_definite(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_container(_type: *const GVariantType)
-> gboolean;
pub fn g_variant_type_is_basic(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_maybe(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_array(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_tuple(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_dict_entry(_type: *const GVariantType)
-> gboolean;
pub fn g_variant_type_is_variant(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_hash(_type: gconstpointer) -> guint;
pub fn g_variant_type_equal(type1: gconstpointer, type2: gconstpointer)
-> gboolean;
pub fn g_variant_type_is_subtype_of(_type: *const GVariantType,
supertype: *const GVariantType)
-> gboolean;
pub fn g_variant_type_element(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_first(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_next(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_n_items(_type: *const GVariantType) -> gsize;
pub fn g_variant_type_key(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_value(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_new_array(element: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new_maybe(element: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new_tuple(items: *const *const GVariantType,
length: gint) -> *mut GVariantType;
pub fn g_variant_type_new_dict_entry(key: *const GVariantType,
value: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_checked_(arg1: *const gchar) -> *const GVariantType;
pub fn g_variant_unref(value: *mut GVariant);
pub fn g_variant_ref(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_ref_sink(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_is_floating(value: *mut GVariant) -> gboolean;
pub fn g_variant_take_ref(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_get_type(value: *mut GVariant) -> *const GVariantType;
pub fn g_variant_get_type_string(value: *mut GVariant) -> *const gchar;
pub fn g_variant_is_of_type(value: *mut GVariant,
_type: *const GVariantType) -> gboolean;
pub fn g_variant_is_container(value: *mut GVariant) -> gboolean;
pub fn g_variant_classify(value: *mut GVariant) -> GVariantClass;
pub fn g_variant_new_boolean(value: gboolean) -> *mut GVariant;
pub fn g_variant_new_byte(value: guchar) -> *mut GVariant;
pub fn g_variant_new_int16(value: gint16) -> *mut GVariant;
pub fn g_variant_new_uint16(value: guint16) -> *mut GVariant;
pub fn g_variant_new_int32(value: gint32) -> *mut GVariant;
pub fn g_variant_new_uint32(value: guint32) -> *mut GVariant;
pub fn g_variant_new_int64(value: gint64) -> *mut GVariant;
pub fn g_variant_new_uint64(value: guint64) -> *mut GVariant;
pub fn g_variant_new_handle(value: gint32) -> *mut GVariant;
pub fn g_variant_new_double(value: gdouble) -> *mut GVariant;
pub fn g_variant_new_string(string: *const gchar) -> *mut GVariant;
pub fn g_variant_new_take_string(string: *mut gchar) -> *mut GVariant;
pub fn g_variant_new_printf(format_string: *const gchar, ...)
-> *mut GVariant;
pub fn g_variant_new_object_path(object_path: *const gchar)
-> *mut GVariant;
pub fn g_variant_is_object_path(string: *const gchar) -> gboolean;
pub fn g_variant_new_signature(signature: *const gchar) -> *mut GVariant;
pub fn g_variant_is_signature(string: *const gchar) -> gboolean;
pub fn g_variant_new_variant(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_strv(strv: *const *const gchar, length: gssize)
-> *mut GVariant;
pub fn g_variant_new_objv(strv: *const *const gchar, length: gssize)
-> *mut GVariant;
pub fn g_variant_new_bytestring(string: *const gchar) -> *mut GVariant;
pub fn g_variant_new_bytestring_array(strv: *const *const gchar,
length: gssize) -> *mut GVariant;
pub fn g_variant_new_fixed_array(element_type: *const GVariantType,
elements: gconstpointer,
n_elements: gsize, element_size: gsize)
-> *mut GVariant;
pub fn g_variant_get_boolean(value: *mut GVariant) -> gboolean;
pub fn g_variant_get_byte(value: *mut GVariant) -> guchar;
pub fn g_variant_get_int16(value: *mut GVariant) -> gint16;
pub fn g_variant_get_uint16(value: *mut GVariant) -> guint16;
pub fn g_variant_get_int32(value: *mut GVariant) -> gint32;
pub fn g_variant_get_uint32(value: *mut GVariant) -> guint32;
pub fn g_variant_get_int64(value: *mut GVariant) -> gint64;
pub fn g_variant_get_uint64(value: *mut GVariant) -> guint64;
pub fn g_variant_get_handle(value: *mut GVariant) -> gint32;
pub fn g_variant_get_double(value: *mut GVariant) -> gdouble;
pub fn g_variant_get_variant(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_get_string(value: *mut GVariant, length: *mut gsize)
-> *const gchar;
pub fn g_variant_dup_string(value: *mut GVariant, length: *mut gsize)
-> *mut gchar;
pub fn g_variant_get_strv(value: *mut GVariant, length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_strv(value: *mut GVariant, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_get_objv(value: *mut GVariant, length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_objv(value: *mut GVariant, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_get_bytestring(value: *mut GVariant) -> *const gchar;
pub fn g_variant_dup_bytestring(value: *mut GVariant, length: *mut gsize)
-> *mut gchar;
pub fn g_variant_get_bytestring_array(value: *mut GVariant,
length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_bytestring_array(value: *mut GVariant,
length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_new_maybe(child_type: *const GVariantType,
child: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_array(child_type: *const GVariantType,
children: *const *mut GVariant,
n_children: gsize) -> *mut GVariant;
pub fn g_variant_new_tuple(children: *const *mut GVariant,
n_children: gsize) -> *mut GVariant;
pub fn g_variant_new_dict_entry(key: *mut GVariant, value: *mut GVariant)
-> *mut GVariant;
pub fn g_variant_get_maybe(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_n_children(value: *mut GVariant) -> gsize;
pub fn g_variant_get_child(value: *mut GVariant, index_: gsize,
format_string: *const gchar, ...);
pub fn g_variant_get_child_value(value: *mut GVariant, index_: gsize)
-> *mut GVariant;
pub fn g_variant_lookup(dictionary: *mut GVariant, key: *const gchar,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_lookup_value(dictionary: *mut GVariant,
key: *const gchar,
expected_type: *const GVariantType)
-> *mut GVariant;
pub fn g_variant_get_fixed_array(value: *mut GVariant,
n_elements: *mut gsize,
element_size: gsize) -> gconstpointer;
pub fn g_variant_get_size(value: *mut GVariant) -> gsize;
pub fn g_variant_get_data(value: *mut GVariant) -> gconstpointer;
pub fn g_variant_get_data_as_bytes(value: *mut GVariant) -> *mut GBytes;
pub fn g_variant_store(value: *mut GVariant, data: gpointer);
pub fn g_variant_print(value: *mut GVariant, type_annotate: gboolean)
-> *mut gchar;
pub fn g_variant_print_string(value: *mut GVariant, string: *mut GString,
type_annotate: gboolean) -> *mut GString;
pub fn g_variant_hash(value: gconstpointer) -> guint;
pub fn g_variant_equal(one: gconstpointer, two: gconstpointer)
-> gboolean;
pub fn g_variant_get_normal_form(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_is_normal_form(value: *mut GVariant) -> gboolean;
pub fn g_variant_byteswap(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_from_bytes(_type: *const GVariantType,
bytes: *mut GBytes, trusted: gboolean)
-> *mut GVariant;
pub fn g_variant_new_from_data(_type: *const GVariantType,
data: gconstpointer, size: gsize,
trusted: gboolean, notify: GDestroyNotify,
user_data: gpointer) -> *mut GVariant;
pub fn g_variant_iter_new(value: *mut GVariant) -> *mut GVariantIter;
pub fn g_variant_iter_init(iter: *mut GVariantIter, value: *mut GVariant)
-> gsize;
pub fn g_variant_iter_copy(iter: *mut GVariantIter) -> *mut GVariantIter;
pub fn g_variant_iter_n_children(iter: *mut GVariantIter) -> gsize;
pub fn g_variant_iter_free(iter: *mut GVariantIter);
pub fn g_variant_iter_next_value(iter: *mut GVariantIter)
-> *mut GVariant;
pub fn g_variant_iter_next(iter: *mut GVariantIter,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_iter_loop(iter: *mut GVariantIter,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_parser_get_error_quark() -> GQuark;
pub fn g_variant_parse_error_quark() -> GQuark;
pub fn g_variant_builder_new(_type: *const GVariantType)
-> *mut GVariantBuilder;
pub fn g_variant_builder_unref(builder: *mut GVariantBuilder);
pub fn g_variant_builder_ref(builder: *mut GVariantBuilder)
-> *mut GVariantBuilder;
pub fn g_variant_builder_init(builder: *mut GVariantBuilder,
_type: *const GVariantType);
pub fn g_variant_builder_end(builder: *mut GVariantBuilder)
-> *mut GVariant;
pub fn g_variant_builder_clear(builder: *mut GVariantBuilder);
pub fn g_variant_builder_open(builder: *mut GVariantBuilder,
_type: *const GVariantType);
pub fn g_variant_builder_close(builder: *mut GVariantBuilder);
pub fn g_variant_builder_add_value(builder: *mut GVariantBuilder,
value: *mut GVariant);
pub fn g_variant_builder_add(builder: *mut GVariantBuilder,
format_string: *const gchar, ...);
pub fn g_variant_builder_add_parsed(builder: *mut GVariantBuilder,
format: *const gchar, ...);
pub fn g_variant_new(format_string: *const gchar, ...) -> *mut GVariant;
pub fn g_variant_get(value: *mut GVariant,
format_string: *const gchar, ...);
pub fn g_variant_new_va(format_string: *const gchar,
endptr: *mut *const gchar, app: *mut va_list)
-> *mut GVariant;
pub fn g_variant_get_va(value: *mut GVariant, format_string: *const gchar,
endptr: *mut *const gchar, app: *mut va_list);
pub fn g_variant_check_format_string(value: *mut GVariant,
format_string: *const gchar,
copy_only: gboolean) -> gboolean;
pub fn g_variant_parse(_type: *const GVariantType, text: *const gchar,
limit: *const gchar, endptr: *mut *const gchar,
error: *mut *mut GError) -> *mut GVariant;
pub fn g_variant_new_parsed(format: *const gchar, ...) -> *mut GVariant;
pub fn g_variant_new_parsed_va(format: *const gchar, app: *mut va_list)
-> *mut GVariant;
pub fn g_variant_parse_error_print_context(error: *mut GError,
source_str: *const gchar)
-> *mut gchar;
pub fn g_variant_compare(one: gconstpointer, two: gconstpointer) -> gint;
pub fn g_variant_dict_new(from_asv: *mut GVariant) -> *mut GVariantDict;
pub fn g_variant_dict_init(dict: *mut GVariantDict,
from_asv: *mut GVariant);
pub fn g_variant_dict_lookup(dict: *mut GVariantDict, key: *const gchar,
format_string: *const gchar, ...)
-> gboolean;
pub fn g_variant_dict_lookup_value(dict: *mut GVariantDict,
key: *const gchar,
expected_type: *const GVariantType)
-> *mut GVariant;
pub fn g_variant_dict_contains(dict: *mut GVariantDict, key: *const gchar)
-> gboolean;
pub fn g_variant_dict_insert(dict: *mut GVariantDict, key: *const gchar,
format_string: *const gchar, ...);
pub fn g_variant_dict_insert_value(dict: *mut GVariantDict,
key: *const gchar,
value: *mut GVariant);
pub fn g_variant_dict_remove(dict: *mut GVariantDict, key: *const gchar)
-> gboolean;
pub fn g_variant_dict_clear(dict: *mut GVariantDict);
pub fn g_variant_dict_end(dict: *mut GVariantDict) -> *mut GVariant;
pub fn g_variant_dict_ref(dict: *mut GVariantDict) -> *mut GVariantDict;
pub fn g_variant_dict_unref(dict: *mut GVariantDict);
pub fn glib_check_version(required_major: guint, required_minor: guint,
required_micro: guint) -> *const gchar;
pub fn g_mem_chunk_new(name: *const gchar, atom_size: gint,
area_size: gsize, _type: gint) -> *mut GMemChunk;
pub fn g_mem_chunk_destroy(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_alloc(mem_chunk: *mut GMemChunk) -> gpointer;
pub fn g_mem_chunk_alloc0(mem_chunk: *mut GMemChunk) -> gpointer;
pub fn g_mem_chunk_free(mem_chunk: *mut GMemChunk, mem: gpointer);
pub fn g_mem_chunk_clean(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_reset(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_print(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_info();
pub fn g_blow_chunks();
pub fn g_allocator_new(name: *const gchar, n_preallocs: guint)
-> *mut GAllocator;
pub fn g_allocator_free(allocator: *mut GAllocator);
pub fn g_list_push_allocator(allocator: *mut GAllocator);
pub fn g_list_pop_allocator();
pub fn g_slist_push_allocator(allocator: *mut GAllocator);
pub fn g_slist_pop_allocator();
pub fn g_node_push_allocator(allocator: *mut GAllocator);
pub fn g_node_pop_allocator();
pub fn g_cache_new(value_new_func: GCacheNewFunc,
value_destroy_func: GCacheDestroyFunc,
key_dup_func: GCacheDupFunc,
key_destroy_func: GCacheDestroyFunc,
hash_key_func: GHashFunc, hash_value_func: GHashFunc,
key_equal_func: GEqualFunc) -> *mut GCache;
pub fn g_cache_destroy(cache: *mut GCache);
pub fn g_cache_insert(cache: *mut GCache, key: gpointer) -> gpointer;
pub fn g_cache_remove(cache: *mut GCache, value: gconstpointer);
pub fn g_cache_key_foreach(cache: *mut GCache, func: GHFunc,
user_data: gpointer);
pub fn g_cache_value_foreach(cache: *mut GCache, func: GHFunc,
user_data: gpointer);
pub fn g_completion_new(func: GCompletionFunc) -> *mut GCompletion;
pub fn g_completion_add_items(cmp: *mut GCompletion, items: *mut GList);
pub fn g_completion_remove_items(cmp: *mut GCompletion,
items: *mut GList);
pub fn g_completion_clear_items(cmp: *mut GCompletion);
pub fn g_completion_complete(cmp: *mut GCompletion, prefix: *const gchar,
new_prefix: *mut *mut gchar) -> *mut GList;
pub fn g_completion_complete_utf8(cmp: *mut GCompletion,
prefix: *const gchar,
new_prefix: *mut *mut gchar)
-> *mut GList;
pub fn g_completion_set_compare(cmp: *mut GCompletion,
strncmp_func: GCompletionStrncmpFunc);
pub fn g_completion_free(cmp: *mut GCompletion);
pub fn g_relation_new(fields: gint) -> *mut GRelation;
pub fn g_relation_destroy(relation: *mut GRelation);
pub fn g_relation_index(relation: *mut GRelation, field: gint,
hash_func: GHashFunc, key_equal_func: GEqualFunc);
pub fn g_relation_insert(relation: *mut GRelation, ...);
pub fn g_relation_delete(relation: *mut GRelation, key: gconstpointer,
field: gint) -> gint;
pub fn g_relation_select(relation: *mut GRelation, key: gconstpointer,
field: gint) -> *mut GTuples;
pub fn g_relation_count(relation: *mut GRelation, key: gconstpointer,
field: gint) -> gint;
pub fn g_relation_exists(relation: *mut GRelation, ...) -> gboolean;
pub fn g_relation_print(relation: *mut GRelation);
pub fn g_tuples_destroy(tuples: *mut GTuples);
pub fn g_tuples_index(tuples: *mut GTuples, index_: gint, field: gint)
-> gpointer;
pub fn g_thread_create(func: GThreadFunc, data: gpointer,
joinable: gboolean, error: *mut *mut GError)
-> *mut GThread;
pub fn g_thread_create_full(func: GThreadFunc, data: gpointer,
stack_size: gulong, joinable: gboolean,
bound: gboolean, priority: GThreadPriority,
error: *mut *mut GError) -> *mut GThread;
pub fn g_thread_set_priority(thread: *mut GThread,
priority: GThreadPriority);
pub fn g_thread_foreach(thread_func: GFunc, user_data: gpointer);
pub fn select(__nfds: ::libc::c_int, __readfds: *mut fd_set,
__writefds: *mut fd_set, __exceptfds: *mut fd_set,
__timeout: *mut Struct_timeval) -> ::libc::c_int;
pub fn pselect(__nfds: ::libc::c_int, __readfds: *mut fd_set,
__writefds: *mut fd_set, __exceptfds: *mut fd_set,
__timeout: *const Struct_timespec,
__sigmask: *const __sigset_t) -> ::libc::c_int;
pub fn gnu_dev_major(__dev: ::libc::c_ulonglong) -> ::libc::c_uint;
pub fn gnu_dev_minor(__dev: ::libc::c_ulonglong) -> ::libc::c_uint;
pub fn gnu_dev_makedev(__major: ::libc::c_uint, __minor: ::libc::c_uint)
-> ::libc::c_ulonglong;
pub fn __sched_cpucount(__setsize: size_t, __setp: *const cpu_set_t)
-> ::libc::c_int;
pub fn __sched_cpualloc(__count: size_t) -> *mut cpu_set_t;
pub fn __sched_cpufree(__set: *mut cpu_set_t);
pub fn sched_setparam(__pid: __pid_t, __param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn sched_getparam(__pid: __pid_t, __param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn sched_setscheduler(__pid: __pid_t, __policy: ::libc::c_int,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn sched_getscheduler(__pid: __pid_t) -> ::libc::c_int;
pub fn sched_yield() -> ::libc::c_int;
pub fn sched_get_priority_max(__algorithm: ::libc::c_int)
-> ::libc::c_int;
pub fn sched_get_priority_min(__algorithm: ::libc::c_int)
-> ::libc::c_int;
pub fn sched_rr_get_interval(__pid: __pid_t, __t: *mut Struct_timespec)
-> ::libc::c_int;
pub fn pthread_create(__newthread: *mut pthread_t,
__attr: *const pthread_attr_t,
__start_routine:
::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)
->
*mut ::libc::c_void>,
__arg: *mut ::libc::c_void) -> ::libc::c_int;
pub fn pthread_exit(__retval: *mut ::libc::c_void);
pub fn pthread_join(__th: pthread_t,
__thread_return: *mut *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_detach(__th: pthread_t) -> ::libc::c_int;
pub fn pthread_self() -> pthread_t;
pub fn pthread_equal(__thread1: pthread_t, __thread2: pthread_t)
-> ::libc::c_int;
pub fn pthread_attr_init(__attr: *mut pthread_attr_t) -> ::libc::c_int;
pub fn pthread_attr_destroy(__attr: *mut pthread_attr_t) -> ::libc::c_int;
pub fn pthread_attr_getdetachstate(__attr: *const pthread_attr_t,
__detachstate: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setdetachstate(__attr: *mut pthread_attr_t,
__detachstate: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getguardsize(__attr: *const pthread_attr_t,
__guardsize: *mut size_t)
-> ::libc::c_int;
pub fn pthread_attr_setguardsize(__attr: *mut pthread_attr_t,
__guardsize: size_t) -> ::libc::c_int;
pub fn pthread_attr_getschedparam(__attr: *const pthread_attr_t,
__param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_attr_setschedparam(__attr: *mut pthread_attr_t,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_attr_getschedpolicy(__attr: *const pthread_attr_t,
__policy: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setschedpolicy(__attr: *mut pthread_attr_t,
__policy: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getinheritsched(__attr: *const pthread_attr_t,
__inherit: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setinheritsched(__attr: *mut pthread_attr_t,
__inherit: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getscope(__attr: *const pthread_attr_t,
__scope: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setscope(__attr: *mut pthread_attr_t,
__scope: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_attr_getstackaddr(__attr: *const pthread_attr_t,
__stackaddr: *mut *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_attr_setstackaddr(__attr: *mut pthread_attr_t,
__stackaddr: *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_attr_getstacksize(__attr: *const pthread_attr_t,
__stacksize: *mut size_t)
-> ::libc::c_int;
pub fn pthread_attr_setstacksize(__attr: *mut pthread_attr_t,
__stacksize: size_t) -> ::libc::c_int;
pub fn pthread_attr_getstack(__attr: *const pthread_attr_t,
__stackaddr: *mut *mut ::libc::c_void,
__stacksize: *mut size_t) -> ::libc::c_int;
pub fn pthread_attr_setstack(__attr: *mut pthread_attr_t,
__stackaddr: *mut ::libc::c_void,
__stacksize: size_t) -> ::libc::c_int;
pub fn pthread_setschedparam(__target_thread: pthread_t,
__policy: ::libc::c_int,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_getschedparam(__target_thread: pthread_t,
__policy: *mut ::libc::c_int,
__param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_setschedprio(__target_thread: pthread_t,
__prio: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_once(__once_control: *mut pthread_once_t,
__init_routine:
::std::option::Option<extern "C" fn()>)
-> ::libc::c_int;
pub fn pthread_setcancelstate(__state: ::libc::c_int,
__oldstate: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_setcanceltype(__type: ::libc::c_int,
__oldtype: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_cancel(__th: pthread_t) -> ::libc::c_int;
pub fn pthread_testcancel();
pub fn __pthread_register_cancel(__buf: *mut __pthread_unwind_buf_t);
pub fn __pthread_unregister_cancel(__buf: *mut __pthread_unwind_buf_t);
pub fn __pthread_unwind_next(__buf: *mut __pthread_unwind_buf_t);
pub fn __sigsetjmp(__env: *mut Struct___jmp_buf_tag,
__savemask: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_mutex_init(__mutex: *mut pthread_mutex_t,
__mutexattr: *const pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutex_destroy(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_trylock(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_lock(__mutex: *mut pthread_mutex_t) -> ::libc::c_int;
pub fn pthread_mutex_timedlock(__mutex: *mut pthread_mutex_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_mutex_unlock(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_getprioceiling(__mutex: *const pthread_mutex_t,
__prioceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutex_setprioceiling(__mutex: *mut pthread_mutex_t,
__prioceiling: ::libc::c_int,
__old_ceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutex_consistent(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_init(__attr: *mut pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_destroy(__attr: *mut pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_getpshared(__attr: *const pthread_mutexattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setpshared(__attr: *mut pthread_mutexattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_gettype(__attr: *const pthread_mutexattr_t,
__kind: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_settype(__attr: *mut pthread_mutexattr_t,
__kind: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_mutexattr_getprotocol(__attr: *const pthread_mutexattr_t,
__protocol: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setprotocol(__attr: *mut pthread_mutexattr_t,
__protocol: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_getprioceiling(__attr:
*const pthread_mutexattr_t,
__prioceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setprioceiling(__attr: *mut pthread_mutexattr_t,
__prioceiling: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_getrobust(__attr: *const pthread_mutexattr_t,
__robustness: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setrobust(__attr: *mut pthread_mutexattr_t,
__robustness: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlock_init(__rwlock: *mut pthread_rwlock_t,
__attr: *const pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlock_destroy(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_rdlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_tryrdlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_timedrdlock(__rwlock: *mut pthread_rwlock_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_rwlock_wrlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_trywrlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_timedwrlock(__rwlock: *mut pthread_rwlock_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_rwlock_unlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_init(__attr: *mut pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_destroy(__attr: *mut pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_getpshared(__attr: *const pthread_rwlockattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_setpshared(__attr: *mut pthread_rwlockattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_getkind_np(__attr: *const pthread_rwlockattr_t,
__pref: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_setkind_np(__attr: *mut pthread_rwlockattr_t,
__pref: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_cond_init(__cond: *mut pthread_cond_t,
__cond_attr: *const pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_cond_destroy(__cond: *mut pthread_cond_t) -> ::libc::c_int;
pub fn pthread_cond_signal(__cond: *mut pthread_cond_t) -> ::libc::c_int;
pub fn pthread_cond_broadcast(__cond: *mut pthread_cond_t)
-> ::libc::c_int;
pub fn pthread_cond_wait(__cond: *mut pthread_cond_t,
__mutex: *mut pthread_mutex_t) -> ::libc::c_int;
pub fn pthread_cond_timedwait(__cond: *mut pthread_cond_t,
__mutex: *mut pthread_mutex_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_condattr_init(__attr: *mut pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_condattr_destroy(__attr: *mut pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_condattr_getpshared(__attr: *const pthread_condattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_condattr_setpshared(__attr: *mut pthread_condattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_condattr_getclock(__attr: *const pthread_condattr_t,
__clock_id: *mut __clockid_t)
-> ::libc::c_int;
pub fn pthread_condattr_setclock(__attr: *mut pthread_condattr_t,
__clock_id: __clockid_t)
-> ::libc::c_int;
pub fn pthread_spin_init(__lock: *mut pthread_spinlock_t,
__pshared: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_spin_destroy(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_lock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_trylock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_unlock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_barrier_init(__barrier: *mut pthread_barrier_t,
__attr: *const pthread_barrierattr_t,
__count: ::libc::c_uint) -> ::libc::c_int;
pub fn pthread_barrier_destroy(__barrier: *mut pthread_barrier_t)
-> ::libc::c_int;
pub fn pthread_barrier_wait(__barrier: *mut pthread_barrier_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_init(__attr: *mut pthread_barrierattr_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_destroy(__attr: *mut pthread_barrierattr_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_getpshared(__attr:
*const pthread_barrierattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_barrierattr_setpshared(__attr: *mut pthread_barrierattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_key_create(__key: *mut pthread_key_t,
__destr_function:
::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)>)
-> ::libc::c_int;
pub fn pthread_key_delete(__key: pthread_key_t) -> ::libc::c_int;
pub fn pthread_getspecific(__key: pthread_key_t) -> *mut ::libc::c_void;
pub fn pthread_setspecific(__key: pthread_key_t,
__pointer: *const ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_getcpuclockid(__thread_id: pthread_t,
__clock_id: *mut __clockid_t)
-> ::libc::c_int;
pub fn pthread_atfork(__prepare: ::std::option::Option<extern "C" fn()>,
__parent: ::std::option::Option<extern "C" fn()>,
__child: ::std::option::Option<extern "C" fn()>)
-> ::libc::c_int;
pub fn g_static_mutex_init(mutex: *mut GStaticMutex);
pub fn g_static_mutex_free(mutex: *mut GStaticMutex);
pub fn g_static_mutex_get_mutex_impl(mutex: *mut GStaticMutex)
-> *mut GMutex;
pub fn g_static_rec_mutex_init(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_lock(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_trylock(mutex: *mut GStaticRecMutex)
-> gboolean;
pub fn g_static_rec_mutex_unlock(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_lock_full(mutex: *mut GStaticRecMutex,
depth: guint);
pub fn g_static_rec_mutex_unlock_full(mutex: *mut GStaticRecMutex)
-> guint;
pub fn g_static_rec_mutex_free(mutex: *mut GStaticRecMutex);
pub fn g_static_rw_lock_init(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_reader_lock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_reader_trylock(lock: *mut GStaticRWLock)
-> gboolean;
pub fn g_static_rw_lock_reader_unlock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_writer_lock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_writer_trylock(lock: *mut GStaticRWLock)
-> gboolean;
pub fn g_static_rw_lock_writer_unlock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_free(lock: *mut GStaticRWLock);
pub fn g_private_new(notify: GDestroyNotify) -> *mut GPrivate;
pub fn g_static_private_init(private_key: *mut GStaticPrivate);
pub fn g_static_private_get(private_key: *mut GStaticPrivate) -> gpointer;
pub fn g_static_private_set(private_key: *mut GStaticPrivate,
data: gpointer, notify: GDestroyNotify);
pub fn g_static_private_free(private_key: *mut GStaticPrivate);
pub fn g_once_init_enter_impl(location: *mut gsize) -> gboolean;
pub fn g_thread_init(vtable: gpointer);
pub fn g_thread_init_with_errorcheck_mutexes(vtable: gpointer);
pub fn g_thread_get_initialized() -> gboolean;
pub fn g_mutex_new() -> *mut GMutex;
pub fn g_mutex_free(mutex: *mut GMutex);
pub fn g_cond_new() -> *mut GCond;
pub fn g_cond_free(cond: *mut GCond);
pub fn g_cond_timed_wait(cond: *mut GCond, mutex: *mut GMutex,
timeval: *mut GTimeVal) -> gboolean;
pub fn g_type_init();
pub fn g_type_init_with_debug_flags(debug_flags: GTypeDebugFlags);
pub fn g_type_name(_type: GType) -> *const gchar;
pub fn g_type_qname(_type: GType) -> GQuark;
pub fn g_type_from_name(name: *const gchar) -> GType;
pub fn g_type_parent(_type: GType) -> GType;
pub fn g_type_depth(_type: GType) -> guint;
pub fn g_type_next_base(leaf_type: GType, root_type: GType) -> GType;
pub fn g_type_is_a(_type: GType, is_a_type: GType) -> gboolean;
pub fn g_type_class_ref(_type: GType) -> gpointer;
pub fn g_type_class_peek(_type: GType) -> gpointer;
pub fn g_type_class_peek_static(_type: GType) -> gpointer;
pub fn g_type_class_unref(g_class: gpointer);
pub fn g_type_class_peek_parent(g_class: gpointer) -> gpointer;
pub fn g_type_interface_peek(instance_class: gpointer, iface_type: GType)
-> gpointer;
pub fn g_type_interface_peek_parent(g_iface: gpointer) -> gpointer;
pub fn g_type_default_interface_ref(g_type: GType) -> gpointer;
pub fn g_type_default_interface_peek(g_type: GType) -> gpointer;
pub fn g_type_default_interface_unref(g_iface: gpointer);
pub fn g_type_children(_type: GType, n_children: *mut guint)
-> *mut GType;
pub fn g_type_interfaces(_type: GType, n_interfaces: *mut guint)
-> *mut GType;
pub fn g_type_set_qdata(_type: GType, quark: GQuark, data: gpointer);
pub fn g_type_get_qdata(_type: GType, quark: GQuark) -> gpointer;
pub fn g_type_query(_type: GType, query: *mut GTypeQuery);
pub fn g_type_register_static(parent_type: GType, type_name: *const gchar,
info: *const GTypeInfo, flags: GTypeFlags)
-> GType;
pub fn g_type_register_static_simple(parent_type: GType,
type_name: *const gchar,
class_size: guint,
class_init: GClassInitFunc,
instance_size: guint,
instance_init: GInstanceInitFunc,
flags: GTypeFlags) -> GType;
pub fn g_type_register_dynamic(parent_type: GType,
type_name: *const gchar,
plugin: *mut GTypePlugin,
flags: GTypeFlags) -> GType;
pub fn g_type_register_fundamental(type_id: GType,
type_name: *const gchar,
info: *const GTypeInfo,
finfo: *const GTypeFundamentalInfo,
flags: GTypeFlags) -> GType;
pub fn g_type_add_interface_static(instance_type: GType,
interface_type: GType,
info: *const GInterfaceInfo);
pub fn g_type_add_interface_dynamic(instance_type: GType,
interface_type: GType,
plugin: *mut GTypePlugin);
pub fn g_type_interface_add_prerequisite(interface_type: GType,
prerequisite_type: GType);
pub fn g_type_interface_prerequisites(interface_type: GType,
n_prerequisites: *mut guint)
-> *mut GType;
pub fn g_type_class_add_private(g_class: gpointer, private_size: gsize);
pub fn g_type_add_instance_private(class_type: GType, private_size: gsize)
-> gint;
pub fn g_type_instance_get_private(instance: *mut GTypeInstance,
private_type: GType) -> gpointer;
pub fn g_type_class_adjust_private_offset(g_class: gpointer,
private_size_or_offset:
*mut gint);
pub fn g_type_add_class_private(class_type: GType, private_size: gsize);
pub fn g_type_class_get_private(klass: *mut GTypeClass,
private_type: GType) -> gpointer;
pub fn g_type_class_get_instance_private_offset(g_class: gpointer)
-> gint;
pub fn g_type_ensure(_type: GType);
pub fn g_type_get_type_registration_serial() -> guint;
pub fn g_type_get_plugin(_type: GType) -> *mut GTypePlugin;
pub fn g_type_interface_get_plugin(instance_type: GType,
interface_type: GType)
-> *mut GTypePlugin;
pub fn g_type_fundamental_next() -> GType;
pub fn g_type_fundamental(type_id: GType) -> GType;
pub fn g_type_create_instance(_type: GType) -> *mut GTypeInstance;
pub fn g_type_free_instance(instance: *mut GTypeInstance);
pub fn g_type_add_class_cache_func(cache_data: gpointer,
cache_func: GTypeClassCacheFunc);
pub fn g_type_remove_class_cache_func(cache_data: gpointer,
cache_func: GTypeClassCacheFunc);
pub fn g_type_class_unref_uncached(g_class: gpointer);
pub fn g_type_add_interface_check(check_data: gpointer,
check_func: GTypeInterfaceCheckFunc);
pub fn g_type_remove_interface_check(check_data: gpointer,
check_func: GTypeInterfaceCheckFunc);
pub fn g_type_value_table_peek(_type: GType) -> *mut GTypeValueTable;
pub fn g_type_check_instance(instance: *mut GTypeInstance) -> gboolean;
pub fn g_type_check_instance_cast(instance: *mut GTypeInstance,
iface_type: GType)
-> *mut GTypeInstance;
pub fn g_type_check_instance_is_a(instance: *mut GTypeInstance,
iface_type: GType) -> gboolean;
pub fn g_type_check_instance_is_fundamentally_a(instance:
*mut GTypeInstance,
fundamental_type: GType)
-> gboolean;
pub fn g_type_check_class_cast(g_class: *mut GTypeClass, is_a_type: GType)
-> *mut GTypeClass;
pub fn g_type_check_class_is_a(g_class: *mut GTypeClass, is_a_type: GType)
-> gboolean;
pub fn g_type_check_is_value_type(_type: GType) -> gboolean;
pub fn g_type_check_value(value: *mut GValue) -> gboolean;
pub fn g_type_check_value_holds(value: *mut GValue, _type: GType)
-> gboolean;
pub fn g_type_test_flags(_type: GType, flags: guint) -> gboolean;
pub fn g_type_name_from_instance(instance: *mut GTypeInstance)
-> *const gchar;
pub fn g_type_name_from_class(g_class: *mut GTypeClass) -> *const gchar;
pub fn g_value_init(value: *mut GValue, g_type: GType) -> *mut GValue;
pub fn g_value_copy(src_value: *const GValue, dest_value: *mut GValue);
pub fn g_value_reset(value: *mut GValue) -> *mut GValue;
pub fn g_value_unset(value: *mut GValue);
pub fn g_value_set_instance(value: *mut GValue, instance: gpointer);
pub fn g_value_init_from_instance(value: *mut GValue, instance: gpointer);
pub fn g_value_fits_pointer(value: *const GValue) -> gboolean;
pub fn g_value_peek_pointer(value: *const GValue) -> gpointer;
pub fn g_value_type_compatible(src_type: GType, dest_type: GType)
-> gboolean;
pub fn g_value_type_transformable(src_type: GType, dest_type: GType)
-> gboolean;
pub fn g_value_transform(src_value: *const GValue,
dest_value: *mut GValue) -> gboolean;
pub fn g_value_register_transform_func(src_type: GType, dest_type: GType,
transform_func: GValueTransform);
pub fn g_param_spec_ref(pspec: *mut GParamSpec) -> *mut GParamSpec;
pub fn g_param_spec_unref(pspec: *mut GParamSpec);
pub fn g_param_spec_sink(pspec: *mut GParamSpec);
pub fn g_param_spec_ref_sink(pspec: *mut GParamSpec) -> *mut GParamSpec;
pub fn g_param_spec_get_qdata(pspec: *mut GParamSpec, quark: GQuark)
-> gpointer;
pub fn g_param_spec_set_qdata(pspec: *mut GParamSpec, quark: GQuark,
data: gpointer);
pub fn g_param_spec_set_qdata_full(pspec: *mut GParamSpec, quark: GQuark,
data: gpointer,
destroy: GDestroyNotify);
pub fn g_param_spec_steal_qdata(pspec: *mut GParamSpec, quark: GQuark)
-> gpointer;
pub fn g_param_spec_get_redirect_target(pspec: *mut GParamSpec)
-> *mut GParamSpec;
pub fn g_param_value_set_default(pspec: *mut GParamSpec,
value: *mut GValue);
pub fn g_param_value_defaults(pspec: *mut GParamSpec, value: *mut GValue)
-> gboolean;
pub fn g_param_value_validate(pspec: *mut GParamSpec, value: *mut GValue)
-> gboolean;
pub fn g_param_value_convert(pspec: *mut GParamSpec,
src_value: *const GValue,
dest_value: *mut GValue,
strict_validation: gboolean) -> gboolean;
pub fn g_param_values_cmp(pspec: *mut GParamSpec, value1: *const GValue,
value2: *const GValue) -> gint;
pub fn g_param_spec_get_name(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_param_spec_get_nick(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_param_spec_get_blurb(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_value_set_param(value: *mut GValue, param: *mut GParamSpec);
pub fn g_value_get_param(value: *const GValue) -> *mut GParamSpec;
pub fn g_value_dup_param(value: *const GValue) -> *mut GParamSpec;
pub fn g_value_take_param(value: *mut GValue, param: *mut GParamSpec);
pub fn g_value_set_param_take_ownership(value: *mut GValue,
param: *mut GParamSpec);
pub fn g_param_spec_get_default_value(param: *mut GParamSpec)
-> *const GValue;
pub fn g_param_type_register_static(name: *const gchar,
pspec_info: *const GParamSpecTypeInfo)
-> GType;
pub fn _g_param_type_register_static_constant(name: *const gchar,
pspec_info:
*const GParamSpecTypeInfo,
opt_type: GType) -> GType;
pub fn g_param_spec_internal(param_type: GType, name: *const gchar,
nick: *const gchar, blurb: *const gchar,
flags: GParamFlags) -> gpointer;
pub fn g_param_spec_pool_new(type_prefixing: gboolean)
-> *mut GParamSpecPool;
pub fn g_param_spec_pool_insert(pool: *mut GParamSpecPool,
pspec: *mut GParamSpec,
owner_type: GType);
pub fn g_param_spec_pool_remove(pool: *mut GParamSpecPool,
pspec: *mut GParamSpec);
pub fn g_param_spec_pool_lookup(pool: *mut GParamSpecPool,
param_name: *const gchar,
owner_type: GType,
walk_ancestors: gboolean)
-> *mut GParamSpec;
pub fn g_param_spec_pool_list_owned(pool: *mut GParamSpecPool,
owner_type: GType) -> *mut GList;
pub fn g_param_spec_pool_list(pool: *mut GParamSpecPool,
owner_type: GType, n_pspecs_p: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_cclosure_new(callback_func: GCallback, user_data: gpointer,
destroy_data: GClosureNotify) -> *mut GClosure;
pub fn g_cclosure_new_swap(callback_func: GCallback, user_data: gpointer,
destroy_data: GClosureNotify) -> *mut GClosure;
pub fn g_signal_type_cclosure_new(itype: GType, struct_offset: guint)
-> *mut GClosure;
pub fn g_closure_ref(closure: *mut GClosure) -> *mut GClosure;
pub fn g_closure_sink(closure: *mut GClosure);
pub fn g_closure_unref(closure: *mut GClosure);
pub fn g_closure_new_simple(sizeof_closure: guint, data: gpointer)
-> *mut GClosure;
pub fn g_closure_add_finalize_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_remove_finalize_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_add_invalidate_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_remove_invalidate_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_add_marshal_guards(closure: *mut GClosure,
pre_marshal_data: gpointer,
pre_marshal_notify: GClosureNotify,
post_marshal_data: gpointer,
post_marshal_notify: GClosureNotify);
pub fn g_closure_set_marshal(closure: *mut GClosure,
marshal: GClosureMarshal);
pub fn g_closure_set_meta_marshal(closure: *mut GClosure,
marshal_data: gpointer,
meta_marshal: GClosureMarshal);
pub fn g_closure_invalidate(closure: *mut GClosure);
pub fn g_closure_invoke(closure: *mut GClosure, return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer);
pub fn g_cclosure_marshal_generic(closure: *mut GClosure,
return_gvalue: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_generic_va(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args_list: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__VOID(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__VOIDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__BOOLEAN(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__BOOLEANv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__CHAR(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__CHARv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UCHAR(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UCHARv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__INT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__INTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UINT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UINTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__LONG(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__LONGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__ULONG(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__ULONGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__ENUM(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__ENUMv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__FLAGS(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__FLAGSv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__FLOAT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__FLOATv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__DOUBLE(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__DOUBLEv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__STRING(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__STRINGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__PARAM(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__PARAMv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__BOXED(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__BOXEDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__POINTER(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__POINTERv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__OBJECT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__OBJECTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__VARIANT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__VARIANTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UINT_POINTER(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UINT_POINTERv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_BOOLEAN__FLAGS(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_BOOLEAN__FLAGSv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_STRING__OBJECT_POINTER(closure: *mut GClosure,
return_value:
*mut GValue,
n_param_values: guint,
param_values:
*const GValue,
invocation_hint:
gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_STRING__OBJECT_POINTERv(closure: *mut GClosure,
return_value:
*mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types:
*mut GType);
pub fn g_cclosure_marshal_BOOLEAN__BOXED_BOXED(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values:
*const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_BOOLEAN__BOXED_BOXEDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_signal_newv(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_closure: *mut GClosure,
accumulator: GSignalAccumulator, accu_data: gpointer,
c_marshaller: GSignalCMarshaller, return_type: GType,
n_params: guint, param_types: *mut GType) -> guint;
pub fn g_signal_new_valist(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_closure: *mut GClosure,
accumulator: GSignalAccumulator,
accu_data: gpointer,
c_marshaller: GSignalCMarshaller,
return_type: GType, n_params: guint,
args: va_list) -> guint;
pub fn g_signal_new(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags, class_offset: guint,
accumulator: GSignalAccumulator, accu_data: gpointer,
c_marshaller: GSignalCMarshaller, return_type: GType,
n_params: guint, ...) -> guint;
pub fn g_signal_new_class_handler(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_handler: GCallback,
accumulator: GSignalAccumulator,
accu_data: gpointer,
c_marshaller: GSignalCMarshaller,
return_type: GType,
n_params: guint, ...) -> guint;
pub fn g_signal_set_va_marshaller(signal_id: guint, instance_type: GType,
va_marshaller: GSignalCVaMarshaller);
pub fn g_signal_emitv(instance_and_params: *const GValue,
signal_id: guint, detail: GQuark,
return_value: *mut GValue);
pub fn g_signal_emit_valist(instance: gpointer, signal_id: guint,
detail: GQuark, var_args: va_list);
pub fn g_signal_emit(instance: gpointer, signal_id: guint,
detail: GQuark, ...);
pub fn g_signal_emit_by_name(instance: gpointer,
detailed_signal: *const gchar, ...);
pub fn g_signal_lookup(name: *const gchar, itype: GType) -> guint;
pub fn g_signal_name(signal_id: guint) -> *const gchar;
pub fn g_signal_query(signal_id: guint, query: *mut GSignalQuery);
pub fn g_signal_list_ids(itype: GType, n_ids: *mut guint) -> *mut guint;
pub fn g_signal_parse_name(detailed_signal: *const gchar, itype: GType,
signal_id_p: *mut guint, detail_p: *mut GQuark,
force_detail_quark: gboolean) -> gboolean;
pub fn g_signal_get_invocation_hint(instance: gpointer)
-> *mut GSignalInvocationHint;
pub fn g_signal_stop_emission(instance: gpointer, signal_id: guint,
detail: GQuark);
pub fn g_signal_stop_emission_by_name(instance: gpointer,
detailed_signal: *const gchar);
pub fn g_signal_add_emission_hook(signal_id: guint, detail: GQuark,
hook_func: GSignalEmissionHook,
hook_data: gpointer,
data_destroy: GDestroyNotify) -> gulong;
pub fn g_signal_remove_emission_hook(signal_id: guint, hook_id: gulong);
pub fn g_signal_has_handler_pending(instance: gpointer, signal_id: guint,
detail: GQuark,
may_be_blocked: gboolean) -> gboolean;
pub fn g_signal_connect_closure_by_id(instance: gpointer,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
after: gboolean) -> gulong;
pub fn g_signal_connect_closure(instance: gpointer,
detailed_signal: *const gchar,
closure: *mut GClosure, after: gboolean)
-> gulong;
pub fn g_signal_connect_data(instance: gpointer,
detailed_signal: *const gchar,
c_handler: GCallback, data: gpointer,
destroy_data: GClosureNotify,
connect_flags: GConnectFlags) -> gulong;
pub fn g_signal_handler_block(instance: gpointer, handler_id: gulong);
pub fn g_signal_handler_unblock(instance: gpointer, handler_id: gulong);
pub fn g_signal_handler_disconnect(instance: gpointer,
handler_id: gulong);
pub fn g_signal_handler_is_connected(instance: gpointer,
handler_id: gulong) -> gboolean;
pub fn g_signal_handler_find(instance: gpointer, mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure, func: gpointer,
data: gpointer) -> gulong;
pub fn g_signal_handlers_block_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
func: gpointer, data: gpointer)
-> guint;
pub fn g_signal_handlers_unblock_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
func: gpointer, data: gpointer)
-> guint;
pub fn g_signal_handlers_disconnect_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint,
detail: GQuark,
closure: *mut GClosure,
func: gpointer,
data: gpointer) -> guint;
pub fn g_signal_override_class_closure(signal_id: guint,
instance_type: GType,
class_closure: *mut GClosure);
pub fn g_signal_override_class_handler(signal_name: *const gchar,
instance_type: GType,
class_handler: GCallback);
pub fn g_signal_chain_from_overridden(instance_and_params: *const GValue,
return_value: *mut GValue);
pub fn g_signal_chain_from_overridden_handler(instance: gpointer, ...);
pub fn g_signal_accumulator_true_handled(ihint:
*mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue,
dummy: gpointer) -> gboolean;
pub fn g_signal_accumulator_first_wins(ihint: *mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue,
dummy: gpointer) -> gboolean;
pub fn g_signal_handlers_destroy(instance: gpointer);
pub fn _g_signals_destroy(itype: GType);
pub fn g_date_get_type() -> GType;
pub fn g_strv_get_type() -> GType;
pub fn g_gstring_get_type() -> GType;
pub fn g_hash_table_get_type() -> GType;
pub fn g_array_get_type() -> GType;
pub fn g_byte_array_get_type() -> GType;
pub fn g_ptr_array_get_type() -> GType;
pub fn g_bytes_get_type() -> GType;
pub fn g_variant_type_get_gtype() -> GType;
pub fn g_regex_get_type() -> GType;
pub fn g_match_info_get_type() -> GType;
pub fn g_error_get_type() -> GType;
pub fn g_date_time_get_type() -> GType;
pub fn g_time_zone_get_type() -> GType;
pub fn g_io_channel_get_type() -> GType;
pub fn g_io_condition_get_type() -> GType;
pub fn g_variant_builder_get_type() -> GType;
pub fn g_variant_dict_get_type() -> GType;
pub fn g_key_file_get_type() -> GType;
pub fn g_main_loop_get_type() -> GType;
pub fn g_main_context_get_type() -> GType;
pub fn g_source_get_type() -> GType;
pub fn g_pollfd_get_type() -> GType;
pub fn g_thread_get_type() -> GType;
pub fn g_checksum_get_type() -> GType;
pub fn g_markup_parse_context_get_type() -> GType;
pub fn g_mapped_file_get_type() -> GType;
pub fn g_variant_get_gtype() -> GType;
pub fn g_boxed_copy(boxed_type: GType, src_boxed: gconstpointer)
-> gpointer;
pub fn g_boxed_free(boxed_type: GType, boxed: gpointer);
pub fn g_value_set_boxed(value: *mut GValue, v_boxed: gconstpointer);
pub fn g_value_set_static_boxed(value: *mut GValue,
v_boxed: gconstpointer);
pub fn g_value_take_boxed(value: *mut GValue, v_boxed: gconstpointer);
pub fn g_value_set_boxed_take_ownership(value: *mut GValue,
v_boxed: gconstpointer);
pub fn g_value_get_boxed(value: *const GValue) -> gpointer;
pub fn g_value_dup_boxed(value: *const GValue) -> gpointer;
pub fn g_boxed_type_register_static(name: *const gchar,
boxed_copy: GBoxedCopyFunc,
boxed_free: GBoxedFreeFunc) -> GType;
pub fn g_closure_get_type() -> GType;
pub fn g_value_get_type() -> GType;
pub fn g_initially_unowned_get_type() -> GType;
pub fn g_object_class_install_property(oclass: *mut GObjectClass,
property_id: guint,
pspec: *mut GParamSpec);
pub fn g_object_class_find_property(oclass: *mut GObjectClass,
property_name: *const gchar)
-> *mut GParamSpec;
pub fn g_object_class_list_properties(oclass: *mut GObjectClass,
n_properties: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_object_class_override_property(oclass: *mut GObjectClass,
property_id: guint,
name: *const gchar);
pub fn g_object_class_install_properties(oclass: *mut GObjectClass,
n_pspecs: guint,
pspecs: *mut *mut GParamSpec);
pub fn g_object_interface_install_property(g_iface: gpointer,
pspec: *mut GParamSpec);
pub fn g_object_interface_find_property(g_iface: gpointer,
property_name: *const gchar)
-> *mut GParamSpec;
pub fn g_object_interface_list_properties(g_iface: gpointer,
n_properties_p: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_object_get_type() -> GType;
pub fn g_object_new(object_type: GType,
first_property_name: *const gchar, ...) -> gpointer;
pub fn g_object_newv(object_type: GType, n_parameters: guint,
parameters: *mut GParameter) -> gpointer;
pub fn g_object_new_valist(object_type: GType,
first_property_name: *const gchar,
var_args: va_list) -> *mut GObject;
pub fn g_object_set(object: gpointer,
first_property_name: *const gchar, ...);
pub fn g_object_get(object: gpointer,
first_property_name: *const gchar, ...);
pub fn g_object_connect(object: gpointer, signal_spec: *const gchar, ...)
-> gpointer;
pub fn g_object_disconnect(object: gpointer,
signal_spec: *const gchar, ...);
pub fn g_object_set_valist(object: *mut GObject,
first_property_name: *const gchar,
var_args: va_list);
pub fn g_object_get_valist(object: *mut GObject,
first_property_name: *const gchar,
var_args: va_list);
pub fn g_object_set_property(object: *mut GObject,
property_name: *const gchar,
value: *const GValue);
pub fn g_object_get_property(object: *mut GObject,
property_name: *const gchar,
value: *mut GValue);
pub fn g_object_freeze_notify(object: *mut GObject);
pub fn g_object_notify(object: *mut GObject, property_name: *const gchar);
pub fn g_object_notify_by_pspec(object: *mut GObject,
pspec: *mut GParamSpec);
pub fn g_object_thaw_notify(object: *mut GObject);
pub fn g_object_is_floating(object: gpointer) -> gboolean;
pub fn g_object_ref_sink(object: gpointer) -> gpointer;
pub fn g_object_ref(object: gpointer) -> gpointer;
pub fn g_object_unref(object: gpointer);
pub fn g_object_weak_ref(object: *mut GObject, notify: GWeakNotify,
data: gpointer);
pub fn g_object_weak_unref(object: *mut GObject, notify: GWeakNotify,
data: gpointer);
pub fn g_object_add_weak_pointer(object: *mut GObject,
weak_pointer_location: *mut gpointer);
pub fn g_object_remove_weak_pointer(object: *mut GObject,
weak_pointer_location: *mut gpointer);
pub fn g_object_add_toggle_ref(object: *mut GObject,
notify: GToggleNotify, data: gpointer);
pub fn g_object_remove_toggle_ref(object: *mut GObject,
notify: GToggleNotify, data: gpointer);
pub fn g_object_get_qdata(object: *mut GObject, quark: GQuark)
-> gpointer;
pub fn g_object_set_qdata(object: *mut GObject, quark: GQuark,
data: gpointer);
pub fn g_object_set_qdata_full(object: *mut GObject, quark: GQuark,
data: gpointer, destroy: GDestroyNotify);
pub fn g_object_steal_qdata(object: *mut GObject, quark: GQuark)
-> gpointer;
pub fn g_object_dup_qdata(object: *mut GObject, quark: GQuark,
dup_func: GDuplicateFunc, user_data: gpointer)
-> gpointer;
pub fn g_object_replace_qdata(object: *mut GObject, quark: GQuark,
oldval: gpointer, newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_object_get_data(object: *mut GObject, key: *const gchar)
-> gpointer;
pub fn g_object_set_data(object: *mut GObject, key: *const gchar,
data: gpointer);
pub fn g_object_set_data_full(object: *mut GObject, key: *const gchar,
data: gpointer, destroy: GDestroyNotify);
pub fn g_object_steal_data(object: *mut GObject, key: *const gchar)
-> gpointer;
pub fn g_object_dup_data(object: *mut GObject, key: *const gchar,
dup_func: GDuplicateFunc, user_data: gpointer)
-> gpointer;
pub fn g_object_replace_data(object: *mut GObject, key: *const gchar,
oldval: gpointer, newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_object_watch_closure(object: *mut GObject,
closure: *mut GClosure);
pub fn g_cclosure_new_object(callback_func: GCallback,
object: *mut GObject) -> *mut GClosure;
pub fn g_cclosure_new_object_swap(callback_func: GCallback,
object: *mut GObject) -> *mut GClosure;
pub fn g_closure_new_object(sizeof_closure: guint, object: *mut GObject)
-> *mut GClosure;
pub fn g_value_set_object(value: *mut GValue, v_object: gpointer);
pub fn g_value_get_object(value: *const GValue) -> gpointer;
pub fn g_value_dup_object(value: *const GValue) -> gpointer;
pub fn g_signal_connect_object(instance: gpointer,
detailed_signal: *const gchar,
c_handler: GCallback, gobject: gpointer,
connect_flags: GConnectFlags) -> gulong;
pub fn g_object_force_floating(object: *mut GObject);
pub fn g_object_run_dispose(object: *mut GObject);
pub fn g_value_take_object(value: *mut GValue, v_object: gpointer);
pub fn g_value_set_object_take_ownership(value: *mut GValue,
v_object: gpointer);
pub fn g_object_compat_control(what: gsize, data: gpointer) -> gsize;
pub fn g_clear_object(object_ptr: *mut *mut GObject);
pub fn g_weak_ref_init(weak_ref: *mut GWeakRef, object: gpointer);
pub fn g_weak_ref_clear(weak_ref: *mut GWeakRef);
pub fn g_weak_ref_get(weak_ref: *mut GWeakRef) -> gpointer;
pub fn g_weak_ref_set(weak_ref: *mut GWeakRef, object: gpointer);
pub fn g_binding_flags_get_type() -> GType;
pub fn g_binding_get_type() -> GType;
pub fn g_binding_get_flags(binding: *mut GBinding) -> GBindingFlags;
pub fn g_binding_get_source(binding: *mut GBinding) -> *mut GObject;
pub fn g_binding_get_target(binding: *mut GBinding) -> *mut GObject;
pub fn g_binding_get_source_property(binding: *mut GBinding)
-> *const gchar;
pub fn g_binding_get_target_property(binding: *mut GBinding)
-> *const gchar;
pub fn g_binding_unbind(binding: *mut GBinding);
pub fn g_object_bind_property(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags) -> *mut GBinding;
pub fn g_object_bind_property_full(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags,
transform_to: GBindingTransformFunc,
transform_from: GBindingTransformFunc,
user_data: gpointer,
notify: GDestroyNotify)
-> *mut GBinding;
pub fn g_object_bind_property_with_closures(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags,
transform_to: *mut GClosure,
transform_from: *mut GClosure)
-> *mut GBinding;
pub fn g_enum_get_value(enum_class: *mut GEnumClass, value: gint)
-> *mut GEnumValue;
pub fn g_enum_get_value_by_name(enum_class: *mut GEnumClass,
name: *const gchar) -> *mut GEnumValue;
pub fn g_enum_get_value_by_nick(enum_class: *mut GEnumClass,
nick: *const gchar) -> *mut GEnumValue;
pub fn g_flags_get_first_value(flags_class: *mut GFlagsClass,
value: guint) -> *mut GFlagsValue;
pub fn g_flags_get_value_by_name(flags_class: *mut GFlagsClass,
name: *const gchar) -> *mut GFlagsValue;
pub fn g_flags_get_value_by_nick(flags_class: *mut GFlagsClass,
nick: *const gchar) -> *mut GFlagsValue;
pub fn g_value_set_enum(value: *mut GValue, v_enum: gint);
pub fn g_value_get_enum(value: *const GValue) -> gint;
pub fn g_value_set_flags(value: *mut GValue, v_flags: guint);
pub fn g_value_get_flags(value: *const GValue) -> guint;
pub fn g_enum_register_static(name: *const gchar,
const_static_values: *const GEnumValue)
-> GType;
pub fn g_flags_register_static(name: *const gchar,
const_static_values: *const GFlagsValue)
-> GType;
pub fn g_enum_complete_type_info(g_enum_type: GType, info: *mut GTypeInfo,
const_values: *const GEnumValue);
pub fn g_flags_complete_type_info(g_flags_type: GType,
info: *mut GTypeInfo,
const_values: *const GFlagsValue);
pub fn g_param_spec_char(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint8,
maximum: gint8, default_value: gint8,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_uchar(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint8,
maximum: guint8, default_value: guint8,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_boolean(name: *const gchar, nick: *const gchar,
blurb: *const gchar, default_value: gboolean,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_int(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint, maximum: gint,
default_value: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_uint(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint,
maximum: guint, default_value: guint,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_long(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: glong,
maximum: glong, default_value: glong,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_ulong(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gulong,
maximum: gulong, default_value: gulong,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_int64(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint64,
maximum: gint64, default_value: gint64,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_uint64(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint64,
maximum: guint64, default_value: guint64,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_unichar(name: *const gchar, nick: *const gchar,
blurb: *const gchar, default_value: gunichar,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_enum(name: *const gchar, nick: *const gchar,
blurb: *const gchar, enum_type: GType,
default_value: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_flags(name: *const gchar, nick: *const gchar,
blurb: *const gchar, flags_type: GType,
default_value: guint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_float(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gfloat,
maximum: gfloat, default_value: gfloat,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_double(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gdouble,
maximum: gdouble, default_value: gdouble,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_string(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
default_value: *const gchar,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_param(name: *const gchar, nick: *const gchar,
blurb: *const gchar, param_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_boxed(name: *const gchar, nick: *const gchar,
blurb: *const gchar, boxed_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_pointer(name: *const gchar, nick: *const gchar,
blurb: *const gchar, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_value_array(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
element_spec: *mut GParamSpec,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_object(name: *const gchar, nick: *const gchar,
blurb: *const gchar, object_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_override(name: *const gchar,
overridden: *mut GParamSpec)
-> *mut GParamSpec;
pub fn g_param_spec_gtype(name: *const gchar, nick: *const gchar,
blurb: *const gchar, is_a_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_variant(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
_type: *const GVariantType,
default_value: *mut GVariant,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_source_set_closure(source: *mut GSource, closure: *mut GClosure);
pub fn g_source_set_dummy_callback(source: *mut GSource);
pub fn g_type_module_get_type() -> GType;
pub fn g_type_module_use(module: *mut GTypeModule) -> gboolean;
pub fn g_type_module_unuse(module: *mut GTypeModule);
pub fn g_type_module_set_name(module: *mut GTypeModule,
name: *const gchar);
pub fn g_type_module_register_type(module: *mut GTypeModule,
parent_type: GType,
type_name: *const gchar,
type_info: *const GTypeInfo,
flags: GTypeFlags) -> GType;
pub fn g_type_module_add_interface(module: *mut GTypeModule,
instance_type: GType,
interface_type: GType,
interface_info: *const GInterfaceInfo);
pub fn g_type_module_register_enum(module: *mut GTypeModule,
name: *const gchar,
const_static_values: *const GEnumValue)
-> GType;
pub fn g_type_module_register_flags(module: *mut GTypeModule,
name: *const gchar,
const_static_values:
*const GFlagsValue) -> GType;
pub fn g_type_plugin_get_type() -> GType;
pub fn g_type_plugin_use(plugin: *mut GTypePlugin);
pub fn g_type_plugin_unuse(plugin: *mut GTypePlugin);
pub fn g_type_plugin_complete_type_info(plugin: *mut GTypePlugin,
g_type: GType,
info: *mut GTypeInfo,
value_table:
*mut GTypeValueTable);
pub fn g_type_plugin_complete_interface_info(plugin: *mut GTypePlugin,
instance_type: GType,
interface_type: GType,
info: *mut GInterfaceInfo);
pub fn g_value_array_get_type() -> GType;
pub fn g_value_array_get_nth(value_array: *mut GValueArray, index_: guint)
-> *mut GValue;
pub fn g_value_array_new(n_prealloced: guint) -> *mut GValueArray;
pub fn g_value_array_free(value_array: *mut GValueArray);
pub fn g_value_array_copy(value_array: *const GValueArray)
-> *mut GValueArray;
pub fn g_value_array_prepend(value_array: *mut GValueArray,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_append(value_array: *mut GValueArray,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_insert(value_array: *mut GValueArray, index_: guint,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_remove(value_array: *mut GValueArray, index_: guint)
-> *mut GValueArray;
pub fn g_value_array_sort(value_array: *mut GValueArray,
compare_func: GCompareFunc) -> *mut GValueArray;
pub fn g_value_array_sort_with_data(value_array: *mut GValueArray,
compare_func: GCompareDataFunc,
user_data: gpointer)
-> *mut GValueArray;
pub fn g_value_set_char(value: *mut GValue, v_char: gchar);
pub fn g_value_get_char(value: *const GValue) -> gchar;
pub fn g_value_set_schar(value: *mut GValue, v_char: gint8);
pub fn g_value_get_schar(value: *const GValue) -> gint8;
pub fn g_value_set_uchar(value: *mut GValue, v_uchar: guchar);
pub fn g_value_get_uchar(value: *const GValue) -> guchar;
pub fn g_value_set_boolean(value: *mut GValue, v_boolean: gboolean);
pub fn g_value_get_boolean(value: *const GValue) -> gboolean;
pub fn g_value_set_int(value: *mut GValue, v_int: gint);
pub fn g_value_get_int(value: *const GValue) -> gint;
pub fn g_value_set_uint(value: *mut GValue, v_uint: guint);
pub fn g_value_get_uint(value: *const GValue) -> guint;
pub fn g_value_set_long(value: *mut GValue, v_long: glong);
pub fn g_value_get_long(value: *const GValue) -> glong;
pub fn g_value_set_ulong(value: *mut GValue, v_ulong: gulong);
pub fn g_value_get_ulong(value: *const GValue) -> gulong;
pub fn g_value_set_int64(value: *mut GValue, v_int64: gint64);
pub fn g_value_get_int64(value: *const GValue) -> gint64;
pub fn g_value_set_uint64(value: *mut GValue, v_uint64: guint64);
pub fn g_value_get_uint64(value: *const GValue) -> guint64;
pub fn g_value_set_float(value: *mut GValue, v_float: gfloat);
pub fn g_value_get_float(value: *const GValue) -> gfloat;
pub fn g_value_set_double(value: *mut GValue, v_double: gdouble);
pub fn g_value_get_double(value: *const GValue) -> gdouble;
pub fn g_value_set_string(value: *mut GValue, v_string: *const gchar);
pub fn g_value_set_static_string(value: *mut GValue,
v_string: *const gchar);
pub fn g_value_get_string(value: *const GValue) -> *const gchar;
pub fn g_value_dup_string(value: *const GValue) -> *mut gchar;
pub fn g_value_set_pointer(value: *mut GValue, v_pointer: gpointer);
pub fn g_value_get_pointer(value: *const GValue) -> gpointer;
pub fn g_gtype_get_type() -> GType;
pub fn g_value_set_gtype(value: *mut GValue, v_gtype: GType);
pub fn g_value_get_gtype(value: *const GValue) -> GType;
pub fn g_value_set_variant(value: *mut GValue, variant: *mut GVariant);
pub fn g_value_take_variant(value: *mut GValue, variant: *mut GVariant);
pub fn g_value_get_variant(value: *const GValue) -> *mut GVariant;
pub fn g_value_dup_variant(value: *const GValue) -> *mut GVariant;
pub fn g_pointer_type_register_static(name: *const gchar) -> GType;
pub fn g_strdup_value_contents(value: *const GValue) -> *mut gchar;
pub fn g_value_take_string(value: *mut GValue, v_string: *mut gchar);
pub fn g_value_set_string_take_ownership(value: *mut GValue,
v_string: *mut gchar);
pub fn gst_object_flags_get_type() -> GType;
pub fn gst_allocator_flags_get_type() -> GType;
pub fn gst_bin_flags_get_type() -> GType;
pub fn gst_buffer_flags_get_type() -> GType;
pub fn gst_buffer_copy_flags_get_type() -> GType;
pub fn gst_buffer_pool_acquire_flags_get_type() -> GType;
pub fn gst_bus_flags_get_type() -> GType;
pub fn gst_bus_sync_reply_get_type() -> GType;
pub fn gst_caps_flags_get_type() -> GType;
pub fn gst_caps_intersect_mode_get_type() -> GType;
pub fn gst_clock_return_get_type() -> GType;
pub fn gst_clock_entry_type_get_type() -> GType;
pub fn gst_clock_flags_get_type() -> GType;
pub fn gst_debug_graph_details_get_type() -> GType;
pub fn gst_state_get_type() -> GType;
pub fn gst_state_change_return_get_type() -> GType;
pub fn gst_state_change_get_type() -> GType;
pub fn gst_element_flags_get_type() -> GType;
pub fn gst_core_error_get_type() -> GType;
pub fn gst_library_error_get_type() -> GType;
pub fn gst_resource_error_get_type() -> GType;
pub fn gst_stream_error_get_type() -> GType;
pub fn gst_event_type_flags_get_type() -> GType;
pub fn gst_event_type_get_type() -> GType;
pub fn gst_qos_type_get_type() -> GType;
pub fn gst_stream_flags_get_type() -> GType;
pub fn gst_format_get_type() -> GType;
pub fn gst_debug_level_get_type() -> GType;
pub fn gst_debug_color_flags_get_type() -> GType;
pub fn gst_debug_color_mode_get_type() -> GType;
pub fn gst_iterator_result_get_type() -> GType;
pub fn gst_iterator_item_get_type() -> GType;
pub fn gst_message_type_get_type() -> GType;
pub fn gst_structure_change_type_get_type() -> GType;
pub fn gst_stream_status_type_get_type() -> GType;
pub fn gst_progress_type_get_type() -> GType;
pub fn gst_meta_flags_get_type() -> GType;
pub fn gst_memory_flags_get_type() -> GType;
pub fn gst_map_flags_get_type() -> GType;
pub fn gst_mini_object_flags_get_type() -> GType;
pub fn gst_lock_flags_get_type() -> GType;
pub fn gst_pad_direction_get_type() -> GType;
pub fn gst_pad_mode_get_type() -> GType;
pub fn gst_pad_link_return_get_type() -> GType;
pub fn gst_flow_return_get_type() -> GType;
pub fn gst_pad_link_check_get_type() -> GType;
pub fn gst_pad_probe_type_get_type() -> GType;
pub fn gst_pad_probe_return_get_type() -> GType;
pub fn gst_pad_flags_get_type() -> GType;
pub fn gst_pad_presence_get_type() -> GType;
pub fn gst_pad_template_flags_get_type() -> GType;
pub fn gst_pipeline_flags_get_type() -> GType;
pub fn gst_plugin_error_get_type() -> GType;
pub fn gst_plugin_flags_get_type() -> GType;
pub fn gst_plugin_dependency_flags_get_type() -> GType;
pub fn gst_rank_get_type() -> GType;
pub fn gst_query_type_flags_get_type() -> GType;
pub fn gst_query_type_get_type() -> GType;
pub fn gst_buffering_mode_get_type() -> GType;
pub fn gst_scheduling_flags_get_type() -> GType;
pub fn gst_seek_type_get_type() -> GType;
pub fn gst_seek_flags_get_type() -> GType;
pub fn gst_segment_flags_get_type() -> GType;
pub fn gst_clock_type_get_type() -> GType;
pub fn gst_tag_merge_mode_get_type() -> GType;
pub fn gst_tag_flag_get_type() -> GType;
pub fn gst_tag_scope_get_type() -> GType;
pub fn gst_task_state_get_type() -> GType;
pub fn gst_toc_scope_get_type() -> GType;
pub fn gst_toc_entry_type_get_type() -> GType;
pub fn gst_toc_loop_type_get_type() -> GType;
pub fn gst_type_find_probability_get_type() -> GType;
pub fn gst_uri_error_get_type() -> GType;
pub fn gst_uri_type_get_type() -> GType;
pub fn gst_search_mode_get_type() -> GType;
pub fn gst_parse_error_get_type() -> GType;
pub fn gst_parse_flags_get_type() -> GType;
pub fn gst_atomic_queue_get_type() -> GType;
pub fn gst_atomic_queue_new(initial_size: guint) -> *mut GstAtomicQueue;
pub fn gst_atomic_queue_ref(queue: *mut GstAtomicQueue);
pub fn gst_atomic_queue_unref(queue: *mut GstAtomicQueue);
pub fn gst_atomic_queue_push(queue: *mut GstAtomicQueue, data: gpointer);
pub fn gst_atomic_queue_pop(queue: *mut GstAtomicQueue) -> gpointer;
pub fn gst_atomic_queue_peek(queue: *mut GstAtomicQueue) -> gpointer;
pub fn gst_atomic_queue_length(queue: *mut GstAtomicQueue) -> guint;
pub fn gst_object_get_type() -> GType;
pub fn gst_object_set_name(object: *mut GstObject, name: *const gchar)
-> gboolean;
pub fn gst_object_get_name(object: *mut GstObject) -> *mut gchar;
pub fn gst_object_set_parent(object: *mut GstObject,
parent: *mut GstObject) -> gboolean;
pub fn gst_object_get_parent(object: *mut GstObject) -> *mut GstObject;
pub fn gst_object_unparent(object: *mut GstObject);
pub fn gst_object_has_ancestor(object: *mut GstObject,
ancestor: *mut GstObject) -> gboolean;
pub fn gst_object_default_deep_notify(object: *mut GObject,
orig: *mut GstObject,
pspec: *mut GParamSpec,
excluded_props: *mut *mut gchar);
pub fn gst_object_ref(object: gpointer) -> gpointer;
pub fn gst_object_unref(object: gpointer);
pub fn gst_object_ref_sink(object: gpointer) -> gpointer;
pub fn gst_object_replace(oldobj: *mut *mut GstObject,
newobj: *mut GstObject) -> gboolean;
pub fn gst_object_get_path_string(object: *mut GstObject) -> *mut gchar;
pub fn gst_object_check_uniqueness(list: *mut GList, name: *const gchar)
-> gboolean;
pub fn gst_clock_get_type() -> GType;
pub fn gst_clock_set_resolution(clock: *mut GstClock,
resolution: GstClockTime) -> GstClockTime;
pub fn gst_clock_get_resolution(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_get_time(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_set_calibration(clock: *mut GstClock,
internal: GstClockTime,
external: GstClockTime,
rate_num: GstClockTime,
rate_denom: GstClockTime);
pub fn gst_clock_get_calibration(clock: *mut GstClock,
internal: *mut GstClockTime,
external: *mut GstClockTime,
rate_num: *mut GstClockTime,
rate_denom: *mut GstClockTime);
pub fn gst_clock_set_master(clock: *mut GstClock, master: *mut GstClock)
-> gboolean;
pub fn gst_clock_get_master(clock: *mut GstClock) -> *mut GstClock;
pub fn gst_clock_set_timeout(clock: *mut GstClock, timeout: GstClockTime);
pub fn gst_clock_get_timeout(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_add_observation(clock: *mut GstClock,
slave: GstClockTime,
master: GstClockTime,
r_squared: *mut gdouble) -> gboolean;
pub fn gst_clock_get_internal_time(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_adjust_unlocked(clock: *mut GstClock,
internal: GstClockTime) -> GstClockTime;
pub fn gst_clock_unadjust_unlocked(clock: *mut GstClock,
external: GstClockTime)
-> GstClockTime;
pub fn gst_clock_new_single_shot_id(clock: *mut GstClock,
time: GstClockTime) -> GstClockID;
pub fn gst_clock_new_periodic_id(clock: *mut GstClock,
start_time: GstClockTime,
interval: GstClockTime) -> GstClockID;
pub fn gst_clock_id_ref(id: GstClockID) -> GstClockID;
pub fn gst_clock_id_unref(id: GstClockID);
pub fn gst_clock_id_compare_func(id1: gconstpointer, id2: gconstpointer)
-> gint;
pub fn gst_clock_id_get_time(id: GstClockID) -> GstClockTime;
pub fn gst_clock_id_wait(id: GstClockID, jitter: *mut GstClockTimeDiff)
-> GstClockReturn;
pub fn gst_clock_id_wait_async(id: GstClockID, func: GstClockCallback,
user_data: gpointer,
destroy_data: GDestroyNotify)
-> GstClockReturn;
pub fn gst_clock_id_unschedule(id: GstClockID);
pub fn gst_clock_single_shot_id_reinit(clock: *mut GstClock,
id: GstClockID, time: GstClockTime)
-> gboolean;
pub fn gst_clock_periodic_id_reinit(clock: *mut GstClock, id: GstClockID,
start_time: GstClockTime,
interval: GstClockTime) -> gboolean;
pub fn gst_control_source_get_type() -> GType;
pub fn gst_control_source_get_value(_self: *mut GstControlSource,
timestamp: GstClockTime,
value: *mut gdouble) -> gboolean;
pub fn gst_control_source_get_value_array(_self: *mut GstControlSource,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut gdouble)
-> gboolean;
pub fn gst_control_binding_get_type() -> GType;
pub fn gst_control_binding_sync_values(binding: *mut GstControlBinding,
object: *mut GstObject,
timestamp: GstClockTime,
last_sync: GstClockTime)
-> gboolean;
pub fn gst_control_binding_get_value(binding: *mut GstControlBinding,
timestamp: GstClockTime)
-> *mut GValue;
pub fn gst_control_binding_get_value_array(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: gpointer) -> gboolean;
pub fn gst_control_binding_get_g_value_array(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut GValue)
-> gboolean;
pub fn gst_control_binding_set_disabled(binding: *mut GstControlBinding,
disabled: gboolean);
pub fn gst_control_binding_is_disabled(binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_suggest_next_sync(object: *mut GstObject)
-> GstClockTime;
pub fn gst_object_sync_values(object: *mut GstObject,
timestamp: GstClockTime) -> gboolean;
pub fn gst_object_has_active_control_bindings(object: *mut GstObject)
-> gboolean;
pub fn gst_object_set_control_bindings_disabled(object: *mut GstObject,
disabled: gboolean);
pub fn gst_object_set_control_binding_disabled(object: *mut GstObject,
property_name:
*const gchar,
disabled: gboolean);
pub fn gst_object_add_control_binding(object: *mut GstObject,
binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_get_control_binding(object: *mut GstObject,
property_name: *const gchar)
-> *mut GstControlBinding;
pub fn gst_object_remove_control_binding(object: *mut GstObject,
binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_get_value(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime) -> *mut GValue;
pub fn gst_object_get_value_array(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime,
interval: GstClockTime, n_values: guint,
values: gpointer) -> gboolean;
pub fn gst_object_get_g_value_array(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint, values: *mut GValue)
-> gboolean;
pub fn gst_object_get_control_rate(object: *mut GstObject)
-> GstClockTime;
pub fn gst_object_set_control_rate(object: *mut GstObject,
control_rate: GstClockTime);
pub fn gst_pad_mode_get_name(mode: GstPadMode) -> *const gchar;
pub fn gst_mini_object_init(mini_object: *mut GstMiniObject, flags: guint,
_type: GType,
copy_func: GstMiniObjectCopyFunction,
dispose_func: GstMiniObjectDisposeFunction,
free_func: GstMiniObjectFreeFunction);
pub fn gst_mini_object_ref(mini_object: *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_unref(mini_object: *mut GstMiniObject);
pub fn gst_mini_object_weak_ref(object: *mut GstMiniObject,
notify: GstMiniObjectNotify,
data: gpointer);
pub fn gst_mini_object_weak_unref(object: *mut GstMiniObject,
notify: GstMiniObjectNotify,
data: gpointer);
pub fn gst_mini_object_lock(object: *mut GstMiniObject,
flags: GstLockFlags) -> gboolean;
pub fn gst_mini_object_unlock(object: *mut GstMiniObject,
flags: GstLockFlags);
pub fn gst_mini_object_is_writable(mini_object: *const GstMiniObject)
-> gboolean;
pub fn gst_mini_object_make_writable(mini_object: *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_copy(mini_object: *const GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_set_qdata(object: *mut GstMiniObject,
quark: GQuark, data: gpointer,
destroy: GDestroyNotify);
pub fn gst_mini_object_get_qdata(object: *mut GstMiniObject,
quark: GQuark) -> gpointer;
pub fn gst_mini_object_steal_qdata(object: *mut GstMiniObject,
quark: GQuark) -> gpointer;
pub fn gst_mini_object_replace(olddata: *mut *mut GstMiniObject,
newdata: *mut GstMiniObject) -> gboolean;
pub fn gst_mini_object_take(olddata: *mut *mut GstMiniObject,
newdata: *mut GstMiniObject) -> gboolean;
pub fn gst_mini_object_steal(olddata: *mut *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_memory_get_type() -> GType;
pub fn gst_memory_init(mem: *mut GstMemory, flags: GstMemoryFlags,
allocator: *mut GstAllocator,
parent: *mut GstMemory, maxsize: gsize,
align: gsize, offset: gsize, size: gsize);
pub fn gst_memory_is_type(mem: *mut GstMemory, mem_type: *const gchar)
-> gboolean;
pub fn gst_memory_get_sizes(mem: *mut GstMemory, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_memory_resize(mem: *mut GstMemory, offset: gssize,
size: gsize);
pub fn gst_memory_make_mapped(mem: *mut GstMemory, info: *mut GstMapInfo,
flags: GstMapFlags) -> *mut GstMemory;
pub fn gst_memory_map(mem: *mut GstMemory, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_memory_unmap(mem: *mut GstMemory, info: *mut GstMapInfo);
pub fn gst_memory_copy(mem: *mut GstMemory, offset: gssize, size: gssize)
-> *mut GstMemory;
pub fn gst_memory_share(mem: *mut GstMemory, offset: gssize, size: gssize)
-> *mut GstMemory;
pub fn gst_memory_is_span(mem1: *mut GstMemory, mem2: *mut GstMemory,
offset: *mut gsize) -> gboolean;
pub fn gst_allocation_params_get_type() -> GType;
pub fn gst_allocator_get_type() -> GType;
pub fn gst_allocator_register(name: *const gchar,
allocator: *mut GstAllocator);
pub fn gst_allocator_find(name: *const gchar) -> *mut GstAllocator;
pub fn gst_allocator_set_default(allocator: *mut GstAllocator);
pub fn gst_allocation_params_init(params: *mut GstAllocationParams);
pub fn gst_allocation_params_copy(params: *const GstAllocationParams)
-> *mut GstAllocationParams;
pub fn gst_allocation_params_free(params: *mut GstAllocationParams);
pub fn gst_allocator_alloc(allocator: *mut GstAllocator, size: gsize,
params: *mut GstAllocationParams)
-> *mut GstMemory;
pub fn gst_allocator_free(allocator: *mut GstAllocator,
memory: *mut GstMemory);
pub fn gst_memory_new_wrapped(flags: GstMemoryFlags, data: gpointer,
maxsize: gsize, offset: gsize, size: gsize,
user_data: gpointer, notify: GDestroyNotify)
-> *mut GstMemory;
pub fn gst_buffer_get_type() -> GType;
pub fn gst_buffer_get_max_memory() -> guint;
pub fn gst_buffer_new() -> *mut GstBuffer;
pub fn gst_buffer_new_allocate(allocator: *mut GstAllocator, size: gsize,
params: *mut GstAllocationParams)
-> *mut GstBuffer;
pub fn gst_buffer_new_wrapped_full(flags: GstMemoryFlags, data: gpointer,
maxsize: gsize, offset: gsize,
size: gsize, user_data: gpointer,
notify: GDestroyNotify)
-> *mut GstBuffer;
pub fn gst_buffer_new_wrapped(data: gpointer, size: gsize)
-> *mut GstBuffer;
pub fn gst_buffer_n_memory(buffer: *mut GstBuffer) -> guint;
pub fn gst_buffer_insert_memory(buffer: *mut GstBuffer, idx: gint,
mem: *mut GstMemory);
pub fn gst_buffer_replace_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint, mem: *mut GstMemory);
pub fn gst_buffer_peek_memory(buffer: *mut GstBuffer, idx: guint)
-> *mut GstMemory;
pub fn gst_buffer_get_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint) -> *mut GstMemory;
pub fn gst_buffer_remove_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint);
pub fn gst_buffer_prepend_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_append_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_replace_memory(buffer: *mut GstBuffer, idx: guint,
mem: *mut GstMemory);
pub fn gst_buffer_replace_all_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_get_memory(buffer: *mut GstBuffer, idx: guint)
-> *mut GstMemory;
pub fn gst_buffer_get_all_memory(buffer: *mut GstBuffer)
-> *mut GstMemory;
pub fn gst_buffer_remove_memory(buffer: *mut GstBuffer, idx: guint);
pub fn gst_buffer_remove_all_memory(buffer: *mut GstBuffer);
pub fn gst_buffer_find_memory(buffer: *mut GstBuffer, offset: gsize,
size: gsize, idx: *mut guint,
length: *mut guint, skip: *mut gsize)
-> gboolean;
pub fn gst_buffer_is_memory_range_writable(buffer: *mut GstBuffer,
idx: guint, length: gint)
-> gboolean;
pub fn gst_buffer_is_all_memory_writable(buffer: *mut GstBuffer)
-> gboolean;
pub fn gst_buffer_fill(buffer: *mut GstBuffer, offset: gsize,
src: gconstpointer, size: gsize) -> gsize;
pub fn gst_buffer_extract(buffer: *mut GstBuffer, offset: gsize,
dest: gpointer, size: gsize) -> gsize;
pub fn gst_buffer_memcmp(buffer: *mut GstBuffer, offset: gsize,
mem: gconstpointer, size: gsize) -> gint;
pub fn gst_buffer_memset(buffer: *mut GstBuffer, offset: gsize,
val: guint8, size: gsize) -> gsize;
pub fn gst_buffer_get_sizes_range(buffer: *mut GstBuffer, idx: guint,
length: gint, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_buffer_resize_range(buffer: *mut GstBuffer, idx: guint,
length: gint, offset: gssize, size: gssize)
-> gboolean;
pub fn gst_buffer_get_sizes(buffer: *mut GstBuffer, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_buffer_get_size(buffer: *mut GstBuffer) -> gsize;
pub fn gst_buffer_resize(buffer: *mut GstBuffer, offset: gssize,
size: gssize);
pub fn gst_buffer_set_size(buffer: *mut GstBuffer, size: gssize);
pub fn gst_buffer_map_range(buffer: *mut GstBuffer, idx: guint,
length: gint, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_buffer_map(buffer: *mut GstBuffer, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_buffer_unmap(buffer: *mut GstBuffer, info: *mut GstMapInfo);
pub fn gst_buffer_extract_dup(buffer: *mut GstBuffer, offset: gsize,
size: gsize, dest: *mut gpointer,
dest_size: *mut gsize);
pub fn gst_buffer_copy_into(dest: *mut GstBuffer, src: *mut GstBuffer,
flags: GstBufferCopyFlags, offset: gsize,
size: gsize) -> gboolean;
pub fn gst_buffer_copy_region(parent: *mut GstBuffer,
flags: GstBufferCopyFlags, offset: gsize,
size: gsize) -> *mut GstBuffer;
pub fn gst_buffer_append_region(buf1: *mut GstBuffer,
buf2: *mut GstBuffer, offset: gssize,
size: gssize) -> *mut GstBuffer;
pub fn gst_buffer_append(buf1: *mut GstBuffer, buf2: *mut GstBuffer)
-> *mut GstBuffer;
pub fn gst_meta_api_type_register(api: *const gchar,
tags: *mut *const gchar) -> GType;
pub fn gst_meta_api_type_has_tag(api: GType, tag: GQuark) -> gboolean;
pub fn gst_meta_register(api: GType, _impl: *const gchar, size: gsize,
init_func: GstMetaInitFunction,
free_func: GstMetaFreeFunction,
transform_func: GstMetaTransformFunction)
-> *const GstMetaInfo;
pub fn gst_meta_get_info(_impl: *const gchar) -> *const GstMetaInfo;
pub fn gst_meta_api_type_get_tags(api: GType) -> *const *const gchar;
pub fn gst_buffer_get_meta(buffer: *mut GstBuffer, api: GType)
-> *mut GstMeta;
pub fn gst_buffer_add_meta(buffer: *mut GstBuffer,
info: *const GstMetaInfo, params: gpointer)
-> *mut GstMeta;
pub fn gst_buffer_remove_meta(buffer: *mut GstBuffer, meta: *mut GstMeta)
-> gboolean;
pub fn gst_buffer_iterate_meta(buffer: *mut GstBuffer,
state: *mut gpointer) -> *mut GstMeta;
pub fn gst_buffer_foreach_meta(buffer: *mut GstBuffer,
func: GstBufferForeachMetaFunc,
user_data: gpointer) -> gboolean;
pub fn gst_buffer_list_get_type() -> GType;
pub fn gst_buffer_list_new() -> *mut GstBufferList;
pub fn gst_buffer_list_new_sized(size: guint) -> *mut GstBufferList;
pub fn gst_buffer_list_length(list: *mut GstBufferList) -> guint;
pub fn gst_buffer_list_get(list: *mut GstBufferList, idx: guint)
-> *mut GstBuffer;
pub fn gst_buffer_list_insert(list: *mut GstBufferList, idx: gint,
buffer: *mut GstBuffer);
pub fn gst_buffer_list_remove(list: *mut GstBufferList, idx: guint,
length: guint);
pub fn gst_buffer_list_foreach(list: *mut GstBufferList,
func: GstBufferListFunc,
user_data: gpointer) -> gboolean;
pub fn gst_date_time_get_type() -> GType;
pub fn gst_date_time_has_year(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_month(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_day(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_time(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_second(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_get_year(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_month(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_day(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_hour(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_minute(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_second(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_microsecond(datetime: *const GstDateTime)
-> gint;
pub fn gst_date_time_get_time_zone_offset(datetime: *const GstDateTime)
-> gfloat;
pub fn gst_date_time_new_from_unix_epoch_local_time(secs: gint64)
-> *mut GstDateTime;
pub fn gst_date_time_new_from_unix_epoch_utc(secs: gint64)
-> *mut GstDateTime;
pub fn gst_date_time_new_local_time(year: gint, month: gint, day: gint,
hour: gint, minute: gint,
seconds: gdouble) -> *mut GstDateTime;
pub fn gst_date_time_new_y(year: gint) -> *mut GstDateTime;
pub fn gst_date_time_new_ym(year: gint, month: gint) -> *mut GstDateTime;
pub fn gst_date_time_new_ymd(year: gint, month: gint, day: gint)
-> *mut GstDateTime;
pub fn gst_date_time_new(tzoffset: gfloat, year: gint, month: gint,
day: gint, hour: gint, minute: gint,
seconds: gdouble) -> *mut GstDateTime;
pub fn gst_date_time_new_now_local_time() -> *mut GstDateTime;
pub fn gst_date_time_new_now_utc() -> *mut GstDateTime;
pub fn gst_date_time_to_iso8601_string(datetime: *mut GstDateTime)
-> *mut gchar;
pub fn gst_date_time_new_from_iso8601_string(string: *const gchar)
-> *mut GstDateTime;
pub fn gst_date_time_to_g_date_time(datetime: *mut GstDateTime)
-> *mut GDateTime;
pub fn gst_date_time_new_from_g_date_time(dt: *mut GDateTime)
-> *mut GstDateTime;
pub fn gst_date_time_ref(datetime: *mut GstDateTime) -> *mut GstDateTime;
pub fn gst_date_time_unref(datetime: *mut GstDateTime);
pub fn gst_structure_get_type() -> GType;
pub fn gst_structure_new_empty(name: *const gchar) -> *mut GstStructure;
pub fn gst_structure_new_id_empty(quark: GQuark) -> *mut GstStructure;
pub fn gst_structure_new(name: *const gchar,
firstfield: *const gchar, ...)
-> *mut GstStructure;
pub fn gst_structure_new_valist(name: *const gchar,
firstfield: *const gchar,
varargs: va_list) -> *mut GstStructure;
pub fn gst_structure_new_id(name_quark: GQuark, field_quark: GQuark, ...)
-> *mut GstStructure;
pub fn gst_structure_new_from_string(string: *const gchar)
-> *mut GstStructure;
pub fn gst_structure_copy(structure: *const GstStructure)
-> *mut GstStructure;
pub fn gst_structure_set_parent_refcount(structure: *mut GstStructure,
refcount: *mut gint) -> gboolean;
pub fn gst_structure_free(structure: *mut GstStructure);
pub fn gst_structure_get_name(structure: *const GstStructure)
-> *const gchar;
pub fn gst_structure_get_name_id(structure: *const GstStructure)
-> GQuark;
pub fn gst_structure_has_name(structure: *const GstStructure,
name: *const gchar) -> gboolean;
pub fn gst_structure_set_name(structure: *mut GstStructure,
name: *const gchar);
pub fn gst_structure_id_set_value(structure: *mut GstStructure,
field: GQuark, value: *const GValue);
pub fn gst_structure_set_value(structure: *mut GstStructure,
fieldname: *const gchar,
value: *const GValue);
pub fn gst_structure_id_take_value(structure: *mut GstStructure,
field: GQuark, value: *mut GValue);
pub fn gst_structure_take_value(structure: *mut GstStructure,
fieldname: *const gchar,
value: *mut GValue);
pub fn gst_structure_set(structure: *mut GstStructure,
fieldname: *const gchar, ...);
pub fn gst_structure_set_valist(structure: *mut GstStructure,
fieldname: *const gchar,
varargs: va_list);
pub fn gst_structure_id_set(structure: *mut GstStructure,
fieldname: GQuark, ...);
pub fn gst_structure_id_set_valist(structure: *mut GstStructure,
fieldname: GQuark, varargs: va_list);
pub fn gst_structure_get_valist(structure: *const GstStructure,
first_fieldname: *const ::libc::c_char,
args: va_list) -> gboolean;
pub fn gst_structure_get(structure: *const GstStructure,
first_fieldname: *const ::libc::c_char, ...)
-> gboolean;
pub fn gst_structure_id_get_valist(structure: *const GstStructure,
first_field_id: GQuark, args: va_list)
-> gboolean;
pub fn gst_structure_id_get(structure: *const GstStructure,
first_field_id: GQuark, ...) -> gboolean;
pub fn gst_structure_id_get_value(structure: *const GstStructure,
field: GQuark) -> *const GValue;
pub fn gst_structure_get_value(structure: *const GstStructure,
fieldname: *const gchar) -> *const GValue;
pub fn gst_structure_remove_field(structure: *mut GstStructure,
fieldname: *const gchar);
pub fn gst_structure_remove_fields(structure: *mut GstStructure,
fieldname: *const gchar, ...);
pub fn gst_structure_remove_fields_valist(structure: *mut GstStructure,
fieldname: *const gchar,
varargs: va_list);
pub fn gst_structure_remove_all_fields(structure: *mut GstStructure);
pub fn gst_structure_get_field_type(structure: *const GstStructure,
fieldname: *const gchar) -> GType;
pub fn gst_structure_foreach(structure: *const GstStructure,
func: GstStructureForeachFunc,
user_data: gpointer) -> gboolean;
pub fn gst_structure_map_in_place(structure: *mut GstStructure,
func: GstStructureMapFunc,
user_data: gpointer) -> gboolean;
pub fn gst_structure_n_fields(structure: *const GstStructure) -> gint;
pub fn gst_structure_nth_field_name(structure: *const GstStructure,
index: guint) -> *const gchar;
pub fn gst_structure_id_has_field(structure: *const GstStructure,
field: GQuark) -> gboolean;
pub fn gst_structure_id_has_field_typed(structure: *const GstStructure,
field: GQuark, _type: GType)
-> gboolean;
pub fn gst_structure_has_field(structure: *const GstStructure,
fieldname: *const gchar) -> gboolean;
pub fn gst_structure_has_field_typed(structure: *const GstStructure,
fieldname: *const gchar,
_type: GType) -> gboolean;
pub fn gst_structure_get_boolean(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gboolean) -> gboolean;
pub fn gst_structure_get_int(structure: *const GstStructure,
fieldname: *const gchar, value: *mut gint)
-> gboolean;
pub fn gst_structure_get_uint(structure: *const GstStructure,
fieldname: *const gchar, value: *mut guint)
-> gboolean;
pub fn gst_structure_get_int64(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gint64) -> gboolean;
pub fn gst_structure_get_uint64(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut guint64) -> gboolean;
pub fn gst_structure_get_double(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gdouble) -> gboolean;
pub fn gst_structure_get_date(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut *mut GDate) -> gboolean;
pub fn gst_structure_get_date_time(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_structure_get_clock_time(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut GstClockTime) -> gboolean;
pub fn gst_structure_get_string(structure: *const GstStructure,
fieldname: *const gchar) -> *const gchar;
pub fn gst_structure_get_enum(structure: *const GstStructure,
fieldname: *const gchar, enumtype: GType,
value: *mut gint) -> gboolean;
pub fn gst_structure_get_fraction(structure: *const GstStructure,
fieldname: *const gchar,
value_numerator: *mut gint,
value_denominator: *mut gint)
-> gboolean;
pub fn gst_structure_to_string(structure: *const GstStructure)
-> *mut gchar;
pub fn gst_structure_from_string(string: *const gchar,
end: *mut *mut gchar)
-> *mut GstStructure;
pub fn gst_structure_fixate_field_nearest_int(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target: ::libc::c_int)
-> gboolean;
pub fn gst_structure_fixate_field_nearest_double(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target: ::libc::c_double)
-> gboolean;
pub fn gst_structure_fixate_field_boolean(structure: *mut GstStructure,
field_name:
*const ::libc::c_char,
target: gboolean) -> gboolean;
pub fn gst_structure_fixate_field_string(structure: *mut GstStructure,
field_name:
*const ::libc::c_char,
target: *const gchar)
-> gboolean;
pub fn gst_structure_fixate_field_nearest_fraction(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target_numerator: gint,
target_denominator:
gint) -> gboolean;
pub fn gst_structure_fixate_field(structure: *mut GstStructure,
field_name: *const ::libc::c_char)
-> gboolean;
pub fn gst_structure_fixate(structure: *mut GstStructure);
pub fn gst_structure_is_equal(structure1: *const GstStructure,
structure2: *const GstStructure)
-> gboolean;
pub fn gst_structure_is_subset(subset: *const GstStructure,
superset: *const GstStructure) -> gboolean;
pub fn gst_structure_can_intersect(struct1: *const GstStructure,
struct2: *const GstStructure)
-> gboolean;
pub fn gst_structure_intersect(struct1: *const GstStructure,
struct2: *const GstStructure)
-> *mut GstStructure;
pub fn gst_caps_features_get_type() -> GType;
pub fn gst_is_caps_features(obj: gconstpointer) -> gboolean;
pub fn gst_caps_features_new_empty() -> *mut GstCapsFeatures;
pub fn gst_caps_features_new_any() -> *mut GstCapsFeatures;
pub fn gst_caps_features_new(feature1: *const gchar, ...)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_valist(feature1: *const gchar,
varargs: va_list)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_id(feature1: GQuark, ...)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_id_valist(feature1: GQuark, varargs: va_list)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_set_parent_refcount(features:
*mut GstCapsFeatures,
refcount: *mut gint)
-> gboolean;
pub fn gst_caps_features_copy(features: *const GstCapsFeatures)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_free(features: *mut GstCapsFeatures);
pub fn gst_caps_features_to_string(features: *const GstCapsFeatures)
-> *mut gchar;
pub fn gst_caps_features_from_string(features: *const gchar)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_get_size(features: *const GstCapsFeatures)
-> guint;
pub fn gst_caps_features_get_nth(features: *const GstCapsFeatures,
i: guint) -> *const gchar;
pub fn gst_caps_features_get_nth_id(features: *const GstCapsFeatures,
i: guint) -> GQuark;
pub fn gst_caps_features_contains(features: *const GstCapsFeatures,
feature: *const gchar) -> gboolean;
pub fn gst_caps_features_contains_id(features: *const GstCapsFeatures,
feature: GQuark) -> gboolean;
pub fn gst_caps_features_is_equal(features1: *const GstCapsFeatures,
features2: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_features_is_any(features: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_features_add(features: *mut GstCapsFeatures,
feature: *const gchar);
pub fn gst_caps_features_add_id(features: *mut GstCapsFeatures,
feature: GQuark);
pub fn gst_caps_features_remove(features: *mut GstCapsFeatures,
feature: *const gchar);
pub fn gst_caps_features_remove_id(features: *mut GstCapsFeatures,
feature: GQuark);
pub fn gst_caps_get_type() -> GType;
pub fn gst_caps_new_empty() -> *mut GstCaps;
pub fn gst_caps_new_any() -> *mut GstCaps;
pub fn gst_caps_new_empty_simple(media_type: *const ::libc::c_char)
-> *mut GstCaps;
pub fn gst_caps_new_simple(media_type: *const ::libc::c_char,
fieldname: *const ::libc::c_char, ...)
-> *mut GstCaps;
pub fn gst_caps_new_full(struct1: *mut GstStructure, ...) -> *mut GstCaps;
pub fn gst_caps_new_full_valist(structure: *mut GstStructure,
var_args: va_list) -> *mut GstCaps;
pub fn gst_static_caps_get_type() -> GType;
pub fn gst_static_caps_get(static_caps: *mut GstStaticCaps)
-> *mut GstCaps;
pub fn gst_static_caps_cleanup(static_caps: *mut GstStaticCaps);
pub fn gst_caps_append(caps1: *mut GstCaps, caps2: *mut GstCaps);
pub fn gst_caps_append_structure(caps: *mut GstCaps,
structure: *mut GstStructure);
pub fn gst_caps_append_structure_full(caps: *mut GstCaps,
structure: *mut GstStructure,
features: *mut GstCapsFeatures);
pub fn gst_caps_remove_structure(caps: *mut GstCaps, idx: guint);
pub fn gst_caps_merge(caps1: *mut GstCaps, caps2: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_merge_structure(caps: *mut GstCaps,
structure: *mut GstStructure)
-> *mut GstCaps;
pub fn gst_caps_merge_structure_full(caps: *mut GstCaps,
structure: *mut GstStructure,
features: *mut GstCapsFeatures)
-> *mut GstCaps;
pub fn gst_caps_get_size(caps: *const GstCaps) -> guint;
pub fn gst_caps_get_structure(caps: *const GstCaps, index: guint)
-> *mut GstStructure;
pub fn gst_caps_steal_structure(caps: *mut GstCaps, index: guint)
-> *mut GstStructure;
pub fn gst_caps_set_features(caps: *mut GstCaps, index: guint,
features: *mut GstCapsFeatures);
pub fn gst_caps_get_features(caps: *const GstCaps, index: guint)
-> *mut GstCapsFeatures;
pub fn gst_caps_copy_nth(caps: *const GstCaps, nth: guint)
-> *mut GstCaps;
pub fn gst_caps_truncate(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_set_value(caps: *mut GstCaps,
field: *const ::libc::c_char,
value: *const GValue);
pub fn gst_caps_set_simple(caps: *mut GstCaps,
field: *const ::libc::c_char, ...);
pub fn gst_caps_set_simple_valist(caps: *mut GstCaps,
field: *const ::libc::c_char,
varargs: va_list);
pub fn gst_caps_is_any(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_empty(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_fixed(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_always_compatible(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_is_subset(subset: *const GstCaps,
superset: *const GstCaps) -> gboolean;
pub fn gst_caps_is_subset_structure(caps: *const GstCaps,
structure: *const GstStructure)
-> gboolean;
pub fn gst_caps_is_subset_structure_full(caps: *const GstCaps,
structure: *const GstStructure,
features: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_is_equal(caps1: *const GstCaps, caps2: *const GstCaps)
-> gboolean;
pub fn gst_caps_is_equal_fixed(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_can_intersect(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_is_strictly_equal(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_intersect(caps1: *mut GstCaps, caps2: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_intersect_full(caps1: *mut GstCaps, caps2: *mut GstCaps,
mode: GstCapsIntersectMode)
-> *mut GstCaps;
pub fn gst_caps_subtract(minuend: *mut GstCaps, subtrahend: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_normalize(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_simplify(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_fixate(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_to_string(caps: *const GstCaps) -> *mut gchar;
pub fn gst_caps_from_string(string: *const gchar) -> *mut GstCaps;
pub fn gst_iterator_get_type() -> GType;
pub fn gst_iterator_new(size: guint, _type: GType, lock: *mut GMutex,
master_cookie: *mut guint32,
copy: GstIteratorCopyFunction,
next: GstIteratorNextFunction,
item: GstIteratorItemFunction,
resync: GstIteratorResyncFunction,
free: GstIteratorFreeFunction)
-> *mut GstIterator;
pub fn gst_iterator_new_list(_type: GType, lock: *mut GMutex,
master_cookie: *mut guint32,
list: *mut *mut GList, owner: *mut GObject,
item: GstIteratorItemFunction)
-> *mut GstIterator;
pub fn gst_iterator_new_single(_type: GType, object: *const GValue)
-> *mut GstIterator;
pub fn gst_iterator_copy(it: *const GstIterator) -> *mut GstIterator;
pub fn gst_iterator_next(it: *mut GstIterator, elem: *mut GValue)
-> GstIteratorResult;
pub fn gst_iterator_resync(it: *mut GstIterator);
pub fn gst_iterator_free(it: *mut GstIterator);
pub fn gst_iterator_push(it: *mut GstIterator, other: *mut GstIterator);
pub fn gst_iterator_filter(it: *mut GstIterator, func: GCompareFunc,
user_data: *const GValue) -> *mut GstIterator;
pub fn gst_iterator_fold(it: *mut GstIterator,
func: GstIteratorFoldFunction, ret: *mut GValue,
user_data: gpointer) -> GstIteratorResult;
pub fn gst_iterator_foreach(it: *mut GstIterator,
func: GstIteratorForeachFunction,
user_data: gpointer) -> GstIteratorResult;
pub fn gst_iterator_find_custom(it: *mut GstIterator, func: GCompareFunc,
elem: *mut GValue, user_data: gpointer)
-> gboolean;
pub fn gst_format_get_name(format: GstFormat) -> *const gchar;
pub fn gst_format_to_quark(format: GstFormat) -> GQuark;
pub fn gst_format_register(nick: *const gchar, description: *const gchar)
-> GstFormat;
pub fn gst_format_get_by_nick(nick: *const gchar) -> GstFormat;
pub fn gst_formats_contains(formats: *const GstFormat, format: GstFormat)
-> gboolean;
pub fn gst_format_get_details(format: GstFormat)
-> *const GstFormatDefinition;
pub fn gst_format_iterate_definitions() -> *mut GstIterator;
pub fn gst_segment_get_type() -> GType;
pub fn gst_segment_new() -> *mut GstSegment;
pub fn gst_segment_copy(segment: *const GstSegment) -> *mut GstSegment;
pub fn gst_segment_copy_into(src: *const GstSegment,
dest: *mut GstSegment);
pub fn gst_segment_free(segment: *mut GstSegment);
pub fn gst_segment_init(segment: *mut GstSegment, format: GstFormat);
pub fn gst_segment_to_stream_time(segment: *const GstSegment,
format: GstFormat, position: guint64)
-> guint64;
pub fn gst_segment_to_running_time(segment: *const GstSegment,
format: GstFormat, position: guint64)
-> guint64;
pub fn gst_segment_to_position(segment: *const GstSegment,
format: GstFormat, running_time: guint64)
-> guint64;
pub fn gst_segment_set_running_time(segment: *mut GstSegment,
format: GstFormat,
running_time: guint64) -> gboolean;
pub fn gst_segment_offset_running_time(segment: *mut GstSegment,
format: GstFormat, offset: gint64)
-> gboolean;
pub fn gst_segment_clip(segment: *const GstSegment, format: GstFormat,
start: guint64, stop: guint64,
clip_start: *mut guint64, clip_stop: *mut guint64)
-> gboolean;
pub fn gst_segment_do_seek(segment: *mut GstSegment, rate: gdouble,
format: GstFormat, flags: GstSeekFlags,
start_type: GstSeekType, start: guint64,
stop_type: GstSeekType, stop: guint64,
update: *mut gboolean) -> gboolean;
pub fn gst_sample_get_type() -> GType;
pub fn gst_sample_new(buffer: *mut GstBuffer, caps: *mut GstCaps,
segment: *const GstSegment, info: *mut GstStructure)
-> *mut GstSample;
pub fn gst_sample_get_buffer(sample: *mut GstSample) -> *mut GstBuffer;
pub fn gst_sample_get_caps(sample: *mut GstSample) -> *mut GstCaps;
pub fn gst_sample_get_segment(sample: *mut GstSample) -> *mut GstSegment;
pub fn gst_sample_get_info(sample: *mut GstSample) -> *const GstStructure;
pub fn gst_tag_list_get_type() -> GType;
pub fn gst_tag_register(name: *const gchar, flag: GstTagFlag,
_type: GType, nick: *const gchar,
blurb: *const gchar, func: GstTagMergeFunc);
pub fn gst_tag_register_static(name: *const gchar, flag: GstTagFlag,
_type: GType, nick: *const gchar,
blurb: *const gchar,
func: GstTagMergeFunc);
pub fn gst_tag_merge_use_first(dest: *mut GValue, src: *const GValue);
pub fn gst_tag_merge_strings_with_comma(dest: *mut GValue,
src: *const GValue);
pub fn gst_tag_exists(tag: *const gchar) -> gboolean;
pub fn gst_tag_get_type(tag: *const gchar) -> GType;
pub fn gst_tag_get_nick(tag: *const gchar) -> *const gchar;
pub fn gst_tag_get_description(tag: *const gchar) -> *const gchar;
pub fn gst_tag_get_flag(tag: *const gchar) -> GstTagFlag;
pub fn gst_tag_is_fixed(tag: *const gchar) -> gboolean;
pub fn gst_tag_list_new_empty() -> *mut GstTagList;
pub fn gst_tag_list_new(tag: *const gchar, ...) -> *mut GstTagList;
pub fn gst_tag_list_new_valist(var_args: va_list) -> *mut GstTagList;
pub fn gst_tag_list_set_scope(list: *mut GstTagList, scope: GstTagScope);
pub fn gst_tag_list_get_scope(list: *const GstTagList) -> GstTagScope;
pub fn gst_tag_list_to_string(list: *const GstTagList) -> *mut gchar;
pub fn gst_tag_list_new_from_string(str: *const gchar) -> *mut GstTagList;
pub fn gst_tag_list_n_tags(list: *const GstTagList) -> gint;
pub fn gst_tag_list_nth_tag_name(list: *const GstTagList, index: guint)
-> *const gchar;
pub fn gst_tag_list_is_empty(list: *const GstTagList) -> gboolean;
pub fn gst_tag_list_is_equal(list1: *const GstTagList,
list2: *const GstTagList) -> gboolean;
pub fn gst_tag_list_insert(into: *mut GstTagList, from: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_tag_list_merge(list1: *const GstTagList,
list2: *const GstTagList, mode: GstTagMergeMode)
-> *mut GstTagList;
pub fn gst_tag_list_get_tag_size(list: *const GstTagList,
tag: *const gchar) -> guint;
pub fn gst_tag_list_add(list: *mut GstTagList, mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_list_add_values(list: *mut GstTagList,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_list_add_valist(list: *mut GstTagList,
mode: GstTagMergeMode, tag: *const gchar,
var_args: va_list);
pub fn gst_tag_list_add_valist_values(list: *mut GstTagList,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_list_add_value(list: *mut GstTagList,
mode: GstTagMergeMode, tag: *const gchar,
value: *const GValue);
pub fn gst_tag_list_remove_tag(list: *mut GstTagList, tag: *const gchar);
pub fn gst_tag_list_foreach(list: *const GstTagList,
func: GstTagForeachFunc, user_data: gpointer);
pub fn gst_tag_list_get_value_index(list: *const GstTagList,
tag: *const gchar, index: guint)
-> *const GValue;
pub fn gst_tag_list_copy_value(dest: *mut GValue, list: *const GstTagList,
tag: *const gchar) -> gboolean;
pub fn gst_tag_list_get_boolean(list: *const GstTagList,
tag: *const gchar, value: *mut gboolean)
-> gboolean;
pub fn gst_tag_list_get_boolean_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gboolean) -> gboolean;
pub fn gst_tag_list_get_int(list: *const GstTagList, tag: *const gchar,
value: *mut gint) -> gboolean;
pub fn gst_tag_list_get_int_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gint) -> gboolean;
pub fn gst_tag_list_get_uint(list: *const GstTagList, tag: *const gchar,
value: *mut guint) -> gboolean;
pub fn gst_tag_list_get_uint_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut guint) -> gboolean;
pub fn gst_tag_list_get_int64(list: *const GstTagList, tag: *const gchar,
value: *mut gint64) -> gboolean;
pub fn gst_tag_list_get_int64_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gint64) -> gboolean;
pub fn gst_tag_list_get_uint64(list: *const GstTagList, tag: *const gchar,
value: *mut guint64) -> gboolean;
pub fn gst_tag_list_get_uint64_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut guint64) -> gboolean;
pub fn gst_tag_list_get_float(list: *const GstTagList, tag: *const gchar,
value: *mut gfloat) -> gboolean;
pub fn gst_tag_list_get_float_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gfloat) -> gboolean;
pub fn gst_tag_list_get_double(list: *const GstTagList, tag: *const gchar,
value: *mut gdouble) -> gboolean;
pub fn gst_tag_list_get_double_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gdouble) -> gboolean;
pub fn gst_tag_list_get_string(list: *const GstTagList, tag: *const gchar,
value: *mut *mut gchar) -> gboolean;
pub fn gst_tag_list_get_string_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut gchar) -> gboolean;
pub fn gst_tag_list_peek_string_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *const gchar)
-> gboolean;
pub fn gst_tag_list_get_pointer(list: *const GstTagList,
tag: *const gchar, value: *mut gpointer)
-> gboolean;
pub fn gst_tag_list_get_pointer_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gpointer) -> gboolean;
pub fn gst_tag_list_get_date(list: *const GstTagList, tag: *const gchar,
value: *mut *mut GDate) -> gboolean;
pub fn gst_tag_list_get_date_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut GDate) -> gboolean;
pub fn gst_tag_list_get_date_time(list: *const GstTagList,
tag: *const gchar,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_tag_list_get_date_time_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_tag_list_get_sample(list: *const GstTagList, tag: *const gchar,
sample: *mut *mut GstSample) -> gboolean;
pub fn gst_tag_list_get_sample_index(list: *const GstTagList,
tag: *const gchar, index: guint,
sample: *mut *mut GstSample)
-> gboolean;
pub fn gst_toc_get_type() -> GType;
pub fn gst_toc_entry_get_type() -> GType;
pub fn gst_toc_new(scope: GstTocScope) -> *mut GstToc;
pub fn gst_toc_get_scope(toc: *const GstToc) -> GstTocScope;
pub fn gst_toc_set_tags(toc: *mut GstToc, tags: *mut GstTagList);
pub fn gst_toc_merge_tags(toc: *mut GstToc, tags: *mut GstTagList,
mode: GstTagMergeMode);
pub fn gst_toc_get_tags(toc: *const GstToc) -> *mut GstTagList;
pub fn gst_toc_append_entry(toc: *mut GstToc, entry: *mut GstTocEntry);
pub fn gst_toc_get_entries(toc: *const GstToc) -> *mut GList;
pub fn gst_toc_dump(toc: *mut GstToc);
pub fn gst_toc_entry_new(_type: GstTocEntryType, uid: *const gchar)
-> *mut GstTocEntry;
pub fn gst_toc_find_entry(toc: *const GstToc, uid: *const gchar)
-> *mut GstTocEntry;
pub fn gst_toc_entry_get_entry_type(entry: *const GstTocEntry)
-> GstTocEntryType;
pub fn gst_toc_entry_get_uid(entry: *const GstTocEntry) -> *const gchar;
pub fn gst_toc_entry_append_sub_entry(entry: *mut GstTocEntry,
subentry: *mut GstTocEntry);
pub fn gst_toc_entry_get_sub_entries(entry: *const GstTocEntry)
-> *mut GList;
pub fn gst_toc_entry_set_tags(entry: *mut GstTocEntry,
tags: *mut GstTagList);
pub fn gst_toc_entry_merge_tags(entry: *mut GstTocEntry,
tags: *mut GstTagList,
mode: GstTagMergeMode);
pub fn gst_toc_entry_get_tags(entry: *const GstTocEntry)
-> *mut GstTagList;
pub fn gst_toc_entry_is_alternative(entry: *const GstTocEntry)
-> gboolean;
pub fn gst_toc_entry_is_sequence(entry: *const GstTocEntry) -> gboolean;
pub fn gst_toc_entry_set_start_stop_times(entry: *mut GstTocEntry,
start: gint64, stop: gint64);
pub fn gst_toc_entry_get_start_stop_times(entry: *const GstTocEntry,
start: *mut gint64,
stop: *mut gint64) -> gboolean;
pub fn gst_toc_entry_set_loop(entry: *mut GstTocEntry,
loop_type: GstTocLoopType,
repeat_count: gint);
pub fn gst_toc_entry_get_loop(entry: *const GstTocEntry,
loop_type: *mut GstTocLoopType,
repeat_count: *mut gint) -> gboolean;
pub fn gst_toc_entry_get_toc(entry: *mut GstTocEntry) -> *mut GstToc;
pub fn gst_toc_entry_get_parent(entry: *mut GstTocEntry)
-> *mut GstTocEntry;
pub fn gst_toc_entry_type_get_nick(_type: GstTocEntryType)
-> *const gchar;
pub fn gst_context_get_type() -> GType;
pub fn gst_context_new(context_type: *const gchar, persistent: gboolean)
-> *mut GstContext;
pub fn gst_context_get_context_type(context: *const GstContext)
-> *const gchar;
pub fn gst_context_has_context_type(context: *const GstContext,
context_type: *const gchar)
-> gboolean;
pub fn gst_context_get_structure(context: *const GstContext)
-> *const GstStructure;
pub fn gst_context_writable_structure(context: *mut GstContext)
-> *mut GstStructure;
pub fn gst_context_is_persistent(context: *const GstContext) -> gboolean;
pub fn gst_query_type_get_name(_type: GstQueryType) -> *const gchar;
pub fn gst_query_type_to_quark(_type: GstQueryType) -> GQuark;
pub fn gst_query_type_get_flags(_type: GstQueryType) -> GstQueryTypeFlags;
pub fn gst_query_get_type() -> GType;
pub fn gst_query_new_custom(_type: GstQueryType,
structure: *mut GstStructure)
-> *mut GstQuery;
pub fn gst_query_get_structure(query: *mut GstQuery)
-> *const GstStructure;
pub fn gst_query_writable_structure(query: *mut GstQuery)
-> *mut GstStructure;
pub fn gst_query_new_position(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_position(query: *mut GstQuery, format: GstFormat,
cur: gint64);
pub fn gst_query_parse_position(query: *mut GstQuery,
format: *mut GstFormat, cur: *mut gint64);
pub fn gst_query_new_duration(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_duration(query: *mut GstQuery, format: GstFormat,
duration: gint64);
pub fn gst_query_parse_duration(query: *mut GstQuery,
format: *mut GstFormat,
duration: *mut gint64);
pub fn gst_query_new_latency() -> *mut GstQuery;
pub fn gst_query_set_latency(query: *mut GstQuery, live: gboolean,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_query_parse_latency(query: *mut GstQuery, live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_query_new_convert(src_format: GstFormat, value: gint64,
dest_format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_convert(query: *mut GstQuery, src_format: GstFormat,
src_value: gint64, dest_format: GstFormat,
dest_value: gint64);
pub fn gst_query_parse_convert(query: *mut GstQuery,
src_format: *mut GstFormat,
src_value: *mut gint64,
dest_format: *mut GstFormat,
dest_value: *mut gint64);
pub fn gst_query_new_segment(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_segment(query: *mut GstQuery, rate: gdouble,
format: GstFormat, start_value: gint64,
stop_value: gint64);
pub fn gst_query_parse_segment(query: *mut GstQuery, rate: *mut gdouble,
format: *mut GstFormat,
start_value: *mut gint64,
stop_value: *mut gint64);
pub fn gst_query_new_seeking(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_seeking(query: *mut GstQuery, format: GstFormat,
seekable: gboolean, segment_start: gint64,
segment_end: gint64);
pub fn gst_query_parse_seeking(query: *mut GstQuery,
format: *mut GstFormat,
seekable: *mut gboolean,
segment_start: *mut gint64,
segment_end: *mut gint64);
pub fn gst_query_new_formats() -> *mut GstQuery;
pub fn gst_query_set_formats(query: *mut GstQuery, n_formats: gint, ...);
pub fn gst_query_set_formatsv(query: *mut GstQuery, n_formats: gint,
formats: *const GstFormat);
pub fn gst_query_parse_n_formats(query: *mut GstQuery,
n_formats: *mut guint);
pub fn gst_query_parse_nth_format(query: *mut GstQuery, nth: guint,
format: *mut GstFormat);
pub fn gst_query_new_buffering(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_buffering_percent(query: *mut GstQuery,
busy: gboolean, percent: gint);
pub fn gst_query_parse_buffering_percent(query: *mut GstQuery,
busy: *mut gboolean,
percent: *mut gint);
pub fn gst_query_set_buffering_stats(query: *mut GstQuery,
mode: GstBufferingMode, avg_in: gint,
avg_out: gint,
buffering_left: gint64);
pub fn gst_query_parse_buffering_stats(query: *mut GstQuery,
mode: *mut GstBufferingMode,
avg_in: *mut gint,
avg_out: *mut gint,
buffering_left: *mut gint64);
pub fn gst_query_set_buffering_range(query: *mut GstQuery,
format: GstFormat, start: gint64,
stop: gint64,
estimated_total: gint64);
pub fn gst_query_parse_buffering_range(query: *mut GstQuery,
format: *mut GstFormat,
start: *mut gint64,
stop: *mut gint64,
estimated_total: *mut gint64);
pub fn gst_query_add_buffering_range(query: *mut GstQuery, start: gint64,
stop: gint64) -> gboolean;
pub fn gst_query_get_n_buffering_ranges(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_buffering_range(query: *mut GstQuery,
index: guint,
start: *mut gint64,
stop: *mut gint64) -> gboolean;
pub fn gst_query_new_uri() -> *mut GstQuery;
pub fn gst_query_parse_uri(query: *mut GstQuery, uri: *mut *mut gchar);
pub fn gst_query_set_uri(query: *mut GstQuery, uri: *const gchar);
pub fn gst_query_parse_uri_redirection(query: *mut GstQuery,
uri: *mut *mut gchar);
pub fn gst_query_set_uri_redirection(query: *mut GstQuery,
uri: *const gchar);
pub fn gst_query_parse_uri_redirection_permanent(query: *mut GstQuery,
permanent:
*mut gboolean);
pub fn gst_query_set_uri_redirection_permanent(query: *mut GstQuery,
permanent: gboolean);
pub fn gst_query_new_allocation(caps: *mut GstCaps, need_pool: gboolean)
-> *mut GstQuery;
pub fn gst_query_parse_allocation(query: *mut GstQuery,
caps: *mut *mut GstCaps,
need_pool: *mut gboolean);
pub fn gst_query_add_allocation_pool(query: *mut GstQuery,
pool: *mut GstBufferPool,
size: guint, min_buffers: guint,
max_buffers: guint);
pub fn gst_query_get_n_allocation_pools(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_pool(query: *mut GstQuery,
index: guint,
pool: *mut *mut GstBufferPool,
size: *mut guint,
min_buffers: *mut guint,
max_buffers: *mut guint);
pub fn gst_query_set_nth_allocation_pool(query: *mut GstQuery,
index: guint,
pool: *mut GstBufferPool,
size: guint, min_buffers: guint,
max_buffers: guint);
pub fn gst_query_remove_nth_allocation_pool(query: *mut GstQuery,
index: guint);
pub fn gst_query_add_allocation_param(query: *mut GstQuery,
allocator: *mut GstAllocator,
params: *const GstAllocationParams);
pub fn gst_query_get_n_allocation_params(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_param(query: *mut GstQuery,
index: guint,
allocator:
*mut *mut GstAllocator,
params:
*mut GstAllocationParams);
pub fn gst_query_set_nth_allocation_param(query: *mut GstQuery,
index: guint,
allocator: *mut GstAllocator,
params:
*const GstAllocationParams);
pub fn gst_query_remove_nth_allocation_param(query: *mut GstQuery,
index: guint);
pub fn gst_query_add_allocation_meta(query: *mut GstQuery, api: GType,
params: *const GstStructure);
pub fn gst_query_get_n_allocation_metas(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_meta(query: *mut GstQuery,
index: guint,
params:
*mut *const GstStructure)
-> GType;
pub fn gst_query_remove_nth_allocation_meta(query: *mut GstQuery,
index: guint);
pub fn gst_query_find_allocation_meta(query: *mut GstQuery, api: GType,
index: *mut guint) -> gboolean;
pub fn gst_query_new_scheduling() -> *mut GstQuery;
pub fn gst_query_set_scheduling(query: *mut GstQuery,
flags: GstSchedulingFlags, minsize: gint,
maxsize: gint, align: gint);
pub fn gst_query_parse_scheduling(query: *mut GstQuery,
flags: *mut GstSchedulingFlags,
minsize: *mut gint, maxsize: *mut gint,
align: *mut gint);
pub fn gst_query_add_scheduling_mode(query: *mut GstQuery,
mode: GstPadMode);
pub fn gst_query_get_n_scheduling_modes(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_scheduling_mode(query: *mut GstQuery,
index: guint) -> GstPadMode;
pub fn gst_query_has_scheduling_mode(query: *mut GstQuery,
mode: GstPadMode) -> gboolean;
pub fn gst_query_has_scheduling_mode_with_flags(query: *mut GstQuery,
mode: GstPadMode,
flags: GstSchedulingFlags)
-> gboolean;
pub fn gst_query_new_accept_caps(caps: *mut GstCaps) -> *mut GstQuery;
pub fn gst_query_parse_accept_caps(query: *mut GstQuery,
caps: *mut *mut GstCaps);
pub fn gst_query_set_accept_caps_result(query: *mut GstQuery,
result: gboolean);
pub fn gst_query_parse_accept_caps_result(query: *mut GstQuery,
result: *mut gboolean);
pub fn gst_query_new_caps(filter: *mut GstCaps) -> *mut GstQuery;
pub fn gst_query_parse_caps(query: *mut GstQuery,
filter: *mut *mut GstCaps);
pub fn gst_query_set_caps_result(query: *mut GstQuery,
caps: *mut GstCaps);
pub fn gst_query_parse_caps_result(query: *mut GstQuery,
caps: *mut *mut GstCaps);
pub fn gst_query_new_drain() -> *mut GstQuery;
pub fn gst_query_new_context(context_type: *const gchar) -> *mut GstQuery;
pub fn gst_query_parse_context_type(query: *mut GstQuery,
context_type: *mut *const gchar)
-> gboolean;
pub fn gst_query_set_context(query: *mut GstQuery,
context: *mut GstContext);
pub fn gst_query_parse_context(query: *mut GstQuery,
context: *mut *mut GstContext);
pub fn gst_device_get_type() -> GType;
pub fn gst_device_create_element(device: *mut GstDevice,
name: *const gchar) -> *mut GstElement;
pub fn gst_device_get_caps(device: *mut GstDevice) -> *mut GstCaps;
pub fn gst_device_get_display_name(device: *mut GstDevice) -> *mut gchar;
pub fn gst_device_get_device_class(device: *mut GstDevice) -> *mut gchar;
pub fn gst_device_reconfigure_element(device: *mut GstDevice,
element: *mut GstElement)
-> gboolean;
pub fn gst_device_has_classesv(device: *mut GstDevice,
classes: *mut *mut gchar) -> gboolean;
pub fn gst_device_has_classes(device: *mut GstDevice,
classes: *const gchar) -> gboolean;
pub fn gst_message_get_type() -> GType;
pub fn gst_message_type_get_name(_type: GstMessageType) -> *const gchar;
pub fn gst_message_type_to_quark(_type: GstMessageType) -> GQuark;
pub fn gst_message_new_custom(_type: GstMessageType, src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_get_structure(message: *mut GstMessage)
-> *const GstStructure;
pub fn gst_message_has_name(message: *mut GstMessage, name: *const gchar)
-> gboolean;
pub fn gst_message_get_seqnum(message: *mut GstMessage) -> guint32;
pub fn gst_message_set_seqnum(message: *mut GstMessage, seqnum: guint32);
pub fn gst_message_new_eos(src: *mut GstObject) -> *mut GstMessage;
pub fn gst_message_new_error(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_error(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_warning(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_warning(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_info(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_info(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_tag(src: *mut GstObject, tag_list: *mut GstTagList)
-> *mut GstMessage;
pub fn gst_message_parse_tag(message: *mut GstMessage,
tag_list: *mut *mut GstTagList);
pub fn gst_message_new_buffering(src: *mut GstObject, percent: gint)
-> *mut GstMessage;
pub fn gst_message_parse_buffering(message: *mut GstMessage,
percent: *mut gint);
pub fn gst_message_set_buffering_stats(message: *mut GstMessage,
mode: GstBufferingMode,
avg_in: gint, avg_out: gint,
buffering_left: gint64);
pub fn gst_message_parse_buffering_stats(message: *mut GstMessage,
mode: *mut GstBufferingMode,
avg_in: *mut gint,
avg_out: *mut gint,
buffering_left: *mut gint64);
pub fn gst_message_new_state_changed(src: *mut GstObject,
oldstate: GstState,
newstate: GstState,
pending: GstState)
-> *mut GstMessage;
pub fn gst_message_parse_state_changed(message: *mut GstMessage,
oldstate: *mut GstState,
newstate: *mut GstState,
pending: *mut GstState);
pub fn gst_message_new_state_dirty(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_step_done(src: *mut GstObject, format: GstFormat,
amount: guint64, rate: gdouble,
flush: gboolean, intermediate: gboolean,
duration: guint64, eos: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_step_done(message: *mut GstMessage,
format: *mut GstFormat,
amount: *mut guint64,
rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean,
duration: *mut guint64,
eos: *mut gboolean);
pub fn gst_message_new_clock_provide(src: *mut GstObject,
clock: *mut GstClock,
ready: gboolean) -> *mut GstMessage;
pub fn gst_message_parse_clock_provide(message: *mut GstMessage,
clock: *mut *mut GstClock,
ready: *mut gboolean);
pub fn gst_message_new_clock_lost(src: *mut GstObject,
clock: *mut GstClock)
-> *mut GstMessage;
pub fn gst_message_parse_clock_lost(message: *mut GstMessage,
clock: *mut *mut GstClock);
pub fn gst_message_new_new_clock(src: *mut GstObject,
clock: *mut GstClock) -> *mut GstMessage;
pub fn gst_message_parse_new_clock(message: *mut GstMessage,
clock: *mut *mut GstClock);
pub fn gst_message_new_application(src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_new_element(src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_new_segment_start(src: *mut GstObject,
format: GstFormat, position: gint64)
-> *mut GstMessage;
pub fn gst_message_parse_segment_start(message: *mut GstMessage,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_message_new_segment_done(src: *mut GstObject,
format: GstFormat, position: gint64)
-> *mut GstMessage;
pub fn gst_message_parse_segment_done(message: *mut GstMessage,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_message_new_duration_changed(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_latency(src: *mut GstObject) -> *mut GstMessage;
pub fn gst_message_new_async_start(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_async_done(src: *mut GstObject,
running_time: GstClockTime)
-> *mut GstMessage;
pub fn gst_message_parse_async_done(message: *mut GstMessage,
running_time: *mut GstClockTime);
pub fn gst_message_new_structure_change(src: *mut GstObject,
_type: GstStructureChangeType,
owner: *mut GstElement,
busy: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_structure_change(message: *mut GstMessage,
_type:
*mut GstStructureChangeType,
owner: *mut *mut GstElement,
busy: *mut gboolean);
pub fn gst_message_new_stream_status(src: *mut GstObject,
_type: GstStreamStatusType,
owner: *mut GstElement)
-> *mut GstMessage;
pub fn gst_message_parse_stream_status(message: *mut GstMessage,
_type: *mut GstStreamStatusType,
owner: *mut *mut GstElement);
pub fn gst_message_set_stream_status_object(message: *mut GstMessage,
object: *const GValue);
pub fn gst_message_get_stream_status_object(message: *mut GstMessage)
-> *const GValue;
pub fn gst_message_new_request_state(src: *mut GstObject, state: GstState)
-> *mut GstMessage;
pub fn gst_message_parse_request_state(message: *mut GstMessage,
state: *mut GstState);
pub fn gst_message_new_step_start(src: *mut GstObject, active: gboolean,
format: GstFormat, amount: guint64,
rate: gdouble, flush: gboolean,
intermediate: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_step_start(message: *mut GstMessage,
active: *mut gboolean,
format: *mut GstFormat,
amount: *mut guint64,
rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean);
pub fn gst_message_new_qos(src: *mut GstObject, live: gboolean,
running_time: guint64, stream_time: guint64,
timestamp: guint64, duration: guint64)
-> *mut GstMessage;
pub fn gst_message_copy (msg: *const GstMessage) -> *mut GstMessage;
pub fn gst_message_set_qos_values(message: *mut GstMessage,
jitter: gint64, proportion: gdouble,
quality: gint);
pub fn gst_message_set_qos_stats(message: *mut GstMessage,
format: GstFormat, processed: guint64,
dropped: guint64);
pub fn gst_message_parse_qos(message: *mut GstMessage,
live: *mut gboolean,
running_time: *mut guint64,
stream_time: *mut guint64,
timestamp: *mut guint64,
duration: *mut guint64);
pub fn gst_message_parse_qos_values(message: *mut GstMessage,
jitter: *mut gint64,
proportion: *mut gdouble,
quality: *mut gint);
pub fn gst_message_parse_qos_stats(message: *mut GstMessage,
format: *mut GstFormat,
processed: *mut guint64,
dropped: *mut guint64);
pub fn gst_message_new_progress(src: *mut GstObject,
_type: GstProgressType,
code: *const gchar, text: *const gchar)
-> *mut GstMessage;
pub fn gst_message_parse_progress(message: *mut GstMessage,
_type: *mut GstProgressType,
code: *mut *mut gchar,
text: *mut *mut gchar);
pub fn gst_message_new_toc(src: *mut GstObject, toc: *mut GstToc,
updated: gboolean) -> *mut GstMessage;
pub fn gst_message_parse_toc(message: *mut GstMessage,
toc: *mut *mut GstToc,
updated: *mut gboolean);
pub fn gst_message_new_reset_time(src: *mut GstObject,
running_time: GstClockTime)
-> *mut GstMessage;
pub fn gst_message_parse_reset_time(message: *mut GstMessage,
running_time: *mut GstClockTime);
pub fn gst_message_new_stream_start(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_set_group_id(message: *mut GstMessage,
group_id: guint);
pub fn gst_message_parse_group_id(message: *mut GstMessage,
group_id: *mut guint) -> gboolean;
pub fn gst_message_new_need_context(src: *mut GstObject,
context_type: *const gchar)
-> *mut GstMessage;
pub fn gst_message_parse_context_type(message: *mut GstMessage,
context_type: *mut *const gchar)
-> gboolean;
pub fn gst_message_new_have_context(src: *mut GstObject,
context: *mut GstContext)
-> *mut GstMessage;
pub fn gst_message_parse_have_context(message: *mut GstMessage,
context: *mut *mut GstContext);
pub fn gst_message_new_device_added(src: *mut GstObject,
device: *mut GstDevice)
-> *mut GstMessage;
pub fn gst_message_parse_device_added(message: *mut GstMessage,
device: *mut *mut GstDevice);
pub fn gst_message_new_device_removed(src: *mut GstObject,
device: *mut GstDevice)
-> *mut GstMessage;
pub fn gst_message_parse_device_removed(message: *mut GstMessage,
device: *mut *mut GstDevice);
pub fn gst_event_type_get_name(_type: GstEventType) -> *const gchar;
pub fn gst_event_type_to_quark(_type: GstEventType) -> GQuark;
pub fn gst_event_type_get_flags(_type: GstEventType) -> GstEventTypeFlags;
pub fn gst_event_get_type() -> GType;
pub fn gst_event_new_custom(_type: GstEventType,
structure: *mut GstStructure)
-> *mut GstEvent;
pub fn gst_event_get_structure(event: *mut GstEvent)
-> *const GstStructure;
pub fn gst_event_writable_structure(event: *mut GstEvent)
-> *mut GstStructure;
pub fn gst_event_has_name(event: *mut GstEvent, name: *const gchar)
-> gboolean;
pub fn gst_event_get_seqnum(event: *mut GstEvent) -> guint32;
pub fn gst_event_set_seqnum(event: *mut GstEvent, seqnum: guint32);
pub fn gst_event_get_running_time_offset(event: *mut GstEvent) -> gint64;
pub fn gst_event_set_running_time_offset(event: *mut GstEvent,
offset: gint64);
pub fn gst_event_new_stream_start(stream_id: *const gchar)
-> *mut GstEvent;
pub fn gst_event_parse_stream_start(event: *mut GstEvent,
stream_id: *mut *const gchar);
pub fn gst_event_set_stream_flags(event: *mut GstEvent,
flags: GstStreamFlags);
pub fn gst_event_parse_stream_flags(event: *mut GstEvent,
flags: *mut GstStreamFlags);
pub fn gst_event_set_group_id(event: *mut GstEvent, group_id: guint);
pub fn gst_event_parse_group_id(event: *mut GstEvent,
group_id: *mut guint) -> gboolean;
pub fn gst_event_new_flush_start() -> *mut GstEvent;
pub fn gst_event_new_flush_stop(reset_time: gboolean) -> *mut GstEvent;
pub fn gst_event_parse_flush_stop(event: *mut GstEvent,
reset_time: *mut gboolean);
pub fn gst_event_new_eos() -> *mut GstEvent;
pub fn gst_event_new_gap(timestamp: GstClockTime, duration: GstClockTime)
-> *mut GstEvent;
pub fn gst_event_parse_gap(event: *mut GstEvent,
timestamp: *mut GstClockTime,
duration: *mut GstClockTime);
pub fn gst_event_new_caps(caps: *mut GstCaps) -> *mut GstEvent;
pub fn gst_event_parse_caps(event: *mut GstEvent,
caps: *mut *mut GstCaps);
pub fn gst_event_new_segment(segment: *const GstSegment) -> *mut GstEvent;
pub fn gst_event_parse_segment(event: *mut GstEvent,
segment: *mut *const GstSegment);
pub fn gst_event_copy_segment(event: *mut GstEvent,
segment: *mut GstSegment);
pub fn gst_event_new_tag(taglist: *mut GstTagList) -> *mut GstEvent;
pub fn gst_event_parse_tag(event: *mut GstEvent,
taglist: *mut *mut GstTagList);
pub fn gst_event_new_toc(toc: *mut GstToc, updated: gboolean)
-> *mut GstEvent;
pub fn gst_event_parse_toc(event: *mut GstEvent, toc: *mut *mut GstToc,
updated: *mut gboolean);
pub fn gst_event_new_buffer_size(format: GstFormat, minsize: gint64,
maxsize: gint64, async: gboolean)
-> *mut GstEvent;
pub fn gst_event_parse_buffer_size(event: *mut GstEvent,
format: *mut GstFormat,
minsize: *mut gint64,
maxsize: *mut gint64,
async: *mut gboolean);
pub fn gst_event_new_sink_message(name: *const gchar,
msg: *mut GstMessage) -> *mut GstEvent;
pub fn gst_event_parse_sink_message(event: *mut GstEvent,
msg: *mut *mut GstMessage);
pub fn gst_event_new_qos(_type: GstQOSType, proportion: gdouble,
diff: GstClockTimeDiff, timestamp: GstClockTime)
-> *mut GstEvent;
pub fn gst_event_parse_qos(event: *mut GstEvent, _type: *mut GstQOSType,
proportion: *mut gdouble,
diff: *mut GstClockTimeDiff,
timestamp: *mut GstClockTime);
pub fn gst_event_new_seek(rate: gdouble, format: GstFormat,
flags: GstSeekFlags, start_type: GstSeekType,
start: gint64, stop_type: GstSeekType,
stop: gint64) -> *mut GstEvent;
pub fn gst_event_parse_seek(event: *mut GstEvent, rate: *mut gdouble,
format: *mut GstFormat,
flags: *mut GstSeekFlags,
start_type: *mut GstSeekType,
start: *mut gint64,
stop_type: *mut GstSeekType,
stop: *mut gint64);
pub fn gst_event_new_navigation(structure: *mut GstStructure)
-> *mut GstEvent;
pub fn gst_event_new_latency(latency: GstClockTime) -> *mut GstEvent;
pub fn gst_event_parse_latency(event: *mut GstEvent,
latency: *mut GstClockTime);
pub fn gst_event_new_step(format: GstFormat, amount: guint64,
rate: gdouble, flush: gboolean,
intermediate: gboolean) -> *mut GstEvent;
pub fn gst_event_parse_step(event: *mut GstEvent, format: *mut GstFormat,
amount: *mut guint64, rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean);
pub fn gst_event_new_reconfigure() -> *mut GstEvent;
pub fn gst_event_new_toc_select(uid: *const gchar) -> *mut GstEvent;
pub fn gst_event_parse_toc_select(event: *mut GstEvent,
uid: *mut *mut gchar);
pub fn gst_event_new_segment_done(format: GstFormat, position: gint64)
-> *mut GstEvent;
pub fn gst_event_parse_segment_done(event: *mut GstEvent,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_task_pool_get_type() -> GType;
pub fn gst_task_pool_new() -> *mut GstTaskPool;
pub fn gst_task_pool_prepare(pool: *mut GstTaskPool,
error: *mut *mut GError);
pub fn gst_task_pool_push(pool: *mut GstTaskPool,
func: GstTaskPoolFunction, user_data: gpointer,
error: *mut *mut GError) -> gpointer;
pub fn gst_task_pool_join(pool: *mut GstTaskPool, id: gpointer);
pub fn gst_task_pool_cleanup(pool: *mut GstTaskPool);
pub fn gst_task_cleanup_all();
pub fn gst_task_get_type() -> GType;
pub fn gst_task_new(func: GstTaskFunction, user_data: gpointer,
notify: GDestroyNotify) -> *mut GstTask;
pub fn gst_task_set_lock(task: *mut GstTask, mutex: *mut GRecMutex);
pub fn gst_task_get_pool(task: *mut GstTask) -> *mut GstTaskPool;
pub fn gst_task_set_pool(task: *mut GstTask, pool: *mut GstTaskPool);
pub fn gst_task_set_enter_callback(task: *mut GstTask,
enter_func: GstTaskThreadFunc,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_task_set_leave_callback(task: *mut GstTask,
leave_func: GstTaskThreadFunc,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_task_get_state(task: *mut GstTask) -> GstTaskState;
pub fn gst_task_set_state(task: *mut GstTask, state: GstTaskState)
-> gboolean;
pub fn gst_task_start(task: *mut GstTask) -> gboolean;
pub fn gst_task_stop(task: *mut GstTask) -> gboolean;
pub fn gst_task_pause(task: *mut GstTask) -> gboolean;
pub fn gst_task_join(task: *mut GstTask) -> gboolean;
pub fn gst_pad_template_get_type() -> GType;
pub fn gst_static_pad_template_get_type() -> GType;
pub fn gst_pad_template_new(name_template: *const gchar,
direction: GstPadDirection,
presence: GstPadPresence, caps: *mut GstCaps)
-> *mut GstPadTemplate;
pub fn gst_static_pad_template_get(pad_template:
*mut GstStaticPadTemplate)
-> *mut GstPadTemplate;
pub fn gst_static_pad_template_get_caps(templ: *mut GstStaticPadTemplate)
-> *mut GstCaps;
pub fn gst_pad_template_get_caps(templ: *mut GstPadTemplate)
-> *mut GstCaps;
pub fn gst_pad_template_pad_created(templ: *mut GstPadTemplate,
pad: *mut GstPad);
pub fn gst_flow_get_name(ret: GstFlowReturn) -> *const gchar;
pub fn gst_flow_to_quark(ret: GstFlowReturn) -> GQuark;
pub fn gst_pad_link_get_name(ret: GstPadLinkReturn) -> *const gchar;
pub fn gst_pad_probe_info_get_event(info: *mut GstPadProbeInfo)
-> *mut GstEvent;
pub fn gst_pad_probe_info_get_query(info: *mut GstPadProbeInfo)
-> *mut GstQuery;
pub fn gst_pad_probe_info_get_buffer(info: *mut GstPadProbeInfo)
-> *mut GstBuffer;
pub fn gst_pad_probe_info_get_buffer_list(info: *mut GstPadProbeInfo)
-> *mut GstBufferList;
pub fn gst_pad_get_type() -> GType;
pub fn gst_pad_new(name: *const gchar, direction: GstPadDirection)
-> *mut GstPad;
pub fn gst_pad_new_from_template(templ: *mut GstPadTemplate,
name: *const gchar) -> *mut GstPad;
pub fn gst_pad_new_from_static_template(templ: *mut GstStaticPadTemplate,
name: *const gchar)
-> *mut GstPad;
pub fn gst_pad_get_direction(pad: *mut GstPad) -> GstPadDirection;
pub fn gst_pad_set_active(pad: *mut GstPad, active: gboolean) -> gboolean;
pub fn gst_pad_is_active(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_activate_mode(pad: *mut GstPad, mode: GstPadMode,
active: gboolean) -> gboolean;
pub fn gst_pad_add_probe(pad: *mut GstPad, mask: GstPadProbeType,
callback: GstPadProbeCallback,
user_data: gpointer,
destroy_data: GDestroyNotify) -> gulong;
pub fn gst_pad_remove_probe(pad: *mut GstPad, id: gulong);
pub fn gst_pad_is_blocked(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_is_blocking(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_mark_reconfigure(pad: *mut GstPad);
pub fn gst_pad_needs_reconfigure(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_check_reconfigure(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_set_element_private(pad: *mut GstPad, _priv: gpointer);
pub fn gst_pad_get_element_private(pad: *mut GstPad) -> gpointer;
pub fn gst_pad_get_pad_template(pad: *mut GstPad) -> *mut GstPadTemplate;
pub fn gst_pad_store_sticky_event(pad: *mut GstPad, event: *mut GstEvent)
-> GstFlowReturn;
pub fn gst_pad_get_sticky_event(pad: *mut GstPad,
event_type: GstEventType, idx: guint)
-> *mut GstEvent;
pub fn gst_pad_sticky_events_foreach(pad: *mut GstPad,
foreach_func:
GstPadStickyEventsForeachFunction,
user_data: gpointer);
pub fn gst_pad_set_activate_function_full(pad: *mut GstPad,
activate:
GstPadActivateFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_activatemode_function_full(pad: *mut GstPad,
activatemode:
GstPadActivateModeFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_chain_function_full(pad: *mut GstPad,
chain: GstPadChainFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_chain_list_function_full(pad: *mut GstPad,
chainlist:
GstPadChainListFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_getrange_function_full(pad: *mut GstPad,
get: GstPadGetRangeFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_event_function_full(pad: *mut GstPad,
event: GstPadEventFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_link_function_full(pad: *mut GstPad,
link: GstPadLinkFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_unlink_function_full(pad: *mut GstPad,
unlink: GstPadUnlinkFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_can_link(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> gboolean;
pub fn gst_pad_link(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> GstPadLinkReturn;
pub fn gst_pad_link_full(srcpad: *mut GstPad, sinkpad: *mut GstPad,
flags: GstPadLinkCheck) -> GstPadLinkReturn;
pub fn gst_pad_unlink(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> gboolean;
pub fn gst_pad_is_linked(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_get_peer(pad: *mut GstPad) -> *mut GstPad;
pub fn gst_pad_get_pad_template_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_get_current_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_has_current_caps(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_get_allowed_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_get_offset(pad: *mut GstPad) -> gint64;
pub fn gst_pad_set_offset(pad: *mut GstPad, offset: gint64);
pub fn gst_pad_push(pad: *mut GstPad, buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_pad_push_list(pad: *mut GstPad, list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_pad_pull_range(pad: *mut GstPad, offset: guint64, size: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn;
pub fn gst_pad_push_event(pad: *mut GstPad, event: *mut GstEvent)
-> gboolean;
pub fn gst_pad_event_default(pad: *mut GstPad, parent: *mut GstObject,
event: *mut GstEvent) -> gboolean;
pub fn gst_pad_get_last_flow_return(pad: *mut GstPad) -> GstFlowReturn;
pub fn gst_pad_chain(pad: *mut GstPad, buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_pad_chain_list(pad: *mut GstPad, list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_pad_get_range(pad: *mut GstPad, offset: guint64, size: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn;
pub fn gst_pad_send_event(pad: *mut GstPad, event: *mut GstEvent)
-> gboolean;
pub fn gst_pad_start_task(pad: *mut GstPad, func: GstTaskFunction,
user_data: gpointer, notify: GDestroyNotify)
-> gboolean;
pub fn gst_pad_pause_task(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_stop_task(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_set_iterate_internal_links_function_full(pad: *mut GstPad,
iterintlink:
GstPadIterIntLinkFunction,
user_data:
gpointer,
notify:
GDestroyNotify);
pub fn gst_pad_iterate_internal_links(pad: *mut GstPad)
-> *mut GstIterator;
pub fn gst_pad_iterate_internal_links_default(pad: *mut GstPad,
parent: *mut GstObject)
-> *mut GstIterator;
pub fn gst_pad_query(pad: *mut GstPad, query: *mut GstQuery) -> gboolean;
pub fn gst_pad_peer_query(pad: *mut GstPad, query: *mut GstQuery)
-> gboolean;
pub fn gst_pad_set_query_function_full(pad: *mut GstPad,
query: GstPadQueryFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_query_default(pad: *mut GstPad, parent: *mut GstObject,
query: *mut GstQuery) -> gboolean;
pub fn gst_pad_forward(pad: *mut GstPad, forward: GstPadForwardFunction,
user_data: gpointer) -> gboolean;
pub fn gst_bus_get_type() -> GType;
pub fn gst_bus_new() -> *mut GstBus;
pub fn gst_bus_post(bus: *mut GstBus, message: *mut GstMessage)
-> gboolean;
pub fn gst_bus_have_pending(bus: *mut GstBus) -> gboolean;
pub fn gst_bus_peek(bus: *mut GstBus) -> *mut GstMessage;
pub fn gst_bus_pop(bus: *mut GstBus) -> *mut GstMessage;
pub fn gst_bus_pop_filtered(bus: *mut GstBus, types: GstMessageType)
-> *mut GstMessage;
pub fn gst_bus_timed_pop(bus: *mut GstBus, timeout: GstClockTime)
-> *mut GstMessage;
pub fn gst_bus_timed_pop_filtered(bus: *mut GstBus, timeout: GstClockTime,
types: GstMessageType)
-> *mut GstMessage;
pub fn gst_bus_set_flushing(bus: *mut GstBus, flushing: gboolean);
pub fn gst_bus_set_sync_handler(bus: *mut GstBus, func: GstBusSyncHandler,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_bus_create_watch(bus: *mut GstBus) -> *mut GSource;
pub fn gst_bus_add_watch_full(bus: *mut GstBus, priority: gint,
func: GstBusFunc, user_data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn gst_bus_add_watch(bus: *mut GstBus, func: GstBusFunc,
user_data: gpointer) -> guint;
pub fn gst_bus_poll(bus: *mut GstBus, events: GstMessageType,
timeout: GstClockTime) -> *mut GstMessage;
pub fn gst_bus_async_signal_func(bus: *mut GstBus,
message: *mut GstMessage, data: gpointer)
-> gboolean;
pub fn gst_bus_sync_signal_handler(bus: *mut GstBus,
message: *mut GstMessage,
data: gpointer) -> GstBusSyncReply;
pub fn gst_bus_add_signal_watch(bus: *mut GstBus);
pub fn gst_bus_add_signal_watch_full(bus: *mut GstBus, priority: gint);
pub fn gst_bus_remove_signal_watch(bus: *mut GstBus);
pub fn gst_bus_enable_sync_message_emission(bus: *mut GstBus);
pub fn gst_bus_disable_sync_message_emission(bus: *mut GstBus);
pub fn gst_plugin_error_quark() -> GQuark;
pub fn gst_plugin_get_type() -> GType;
pub fn gst_plugin_register_static(major_version: gint,
minor_version: gint, name: *const gchar,
description: *const gchar,
init_func: GstPluginInitFunc,
version: *const gchar,
license: *const gchar,
source: *const gchar,
package: *const gchar,
origin: *const gchar) -> gboolean;
pub fn gst_plugin_register_static_full(major_version: gint,
minor_version: gint,
name: *const gchar,
description: *const gchar,
init_full_func:
GstPluginInitFullFunc,
version: *const gchar,
license: *const gchar,
source: *const gchar,
package: *const gchar,
origin: *const gchar,
user_data: gpointer) -> gboolean;
pub fn gst_plugin_get_name(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_description(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_filename(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_version(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_license(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_source(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_package(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_origin(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_release_date_string(plugin: *mut GstPlugin)
-> *const gchar;
pub fn gst_plugin_get_cache_data(plugin: *mut GstPlugin)
-> *const GstStructure;
pub fn gst_plugin_set_cache_data(plugin: *mut GstPlugin,
cache_data: *mut GstStructure);
pub fn gst_plugin_is_loaded(plugin: *mut GstPlugin) -> gboolean;
pub fn gst_plugin_load_file(filename: *const gchar,
error: *mut *mut GError) -> *mut GstPlugin;
pub fn gst_plugin_load(plugin: *mut GstPlugin) -> *mut GstPlugin;
pub fn gst_plugin_load_by_name(name: *const gchar) -> *mut GstPlugin;
pub fn gst_plugin_add_dependency(plugin: *mut GstPlugin,
env_vars: *mut *const gchar,
paths: *mut *const gchar,
names: *mut *const gchar,
flags: GstPluginDependencyFlags);
pub fn gst_plugin_add_dependency_simple(plugin: *mut GstPlugin,
env_vars: *const gchar,
paths: *const gchar,
names: *const gchar,
flags: GstPluginDependencyFlags);
pub fn gst_plugin_list_free(list: *mut GList);
pub fn gst_plugin_feature_get_type() -> GType;
pub fn gst_plugin_feature_load(feature: *mut GstPluginFeature)
-> *mut GstPluginFeature;
pub fn gst_plugin_feature_set_rank(feature: *mut GstPluginFeature,
rank: guint);
pub fn gst_plugin_feature_get_rank(feature: *mut GstPluginFeature)
-> guint;
pub fn gst_plugin_feature_get_plugin(feature: *mut GstPluginFeature)
-> *mut GstPlugin;
pub fn gst_plugin_feature_get_plugin_name(feature: *mut GstPluginFeature)
-> *const gchar;
pub fn gst_plugin_feature_list_free(list: *mut GList);
pub fn gst_plugin_feature_list_copy(list: *mut GList) -> *mut GList;
pub fn gst_plugin_feature_list_debug(list: *mut GList);
pub fn gst_plugin_feature_check_version(feature: *mut GstPluginFeature,
min_major: guint,
min_minor: guint,
min_micro: guint) -> gboolean;
pub fn gst_plugin_feature_rank_compare_func(p1: gconstpointer,
p2: gconstpointer) -> gint;
pub fn gst_uri_error_quark() -> GQuark;
pub fn gst_uri_protocol_is_valid(protocol: *const gchar) -> gboolean;
pub fn gst_uri_protocol_is_supported(_type: GstURIType,
protocol: *const gchar) -> gboolean;
pub fn gst_uri_is_valid(uri: *const gchar) -> gboolean;
pub fn gst_uri_get_protocol(uri: *const gchar) -> *mut gchar;
pub fn gst_uri_has_protocol(uri: *const gchar, protocol: *const gchar)
-> gboolean;
pub fn gst_uri_get_location(uri: *const gchar) -> *mut gchar;
pub fn gst_uri_construct(protocol: *const gchar, location: *const gchar)
-> *mut gchar;
pub fn gst_filename_to_uri(filename: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn gst_element_make_from_uri(_type: GstURIType, uri: *const gchar,
elementname: *const gchar,
error: *mut *mut GError)
-> *mut GstElement;
pub fn gst_uri_handler_get_type() -> GType;
pub fn gst_uri_handler_get_uri_type(handler: *mut GstURIHandler)
-> GstURIType;
pub fn gst_uri_handler_get_protocols(handler: *mut GstURIHandler)
-> *const *const gchar;
pub fn gst_uri_handler_get_uri(handler: *mut GstURIHandler) -> *mut gchar;
pub fn gst_uri_handler_set_uri(handler: *mut GstURIHandler,
uri: *const gchar, error: *mut *mut GError)
-> gboolean;
pub fn gst_element_factory_get_type() -> GType;
pub fn gst_element_factory_find(name: *const gchar)
-> *mut GstElementFactory;
pub fn gst_element_factory_get_element_type(factory:
*mut GstElementFactory)
-> GType;
pub fn gst_element_factory_get_metadata(factory: *mut GstElementFactory,
key: *const gchar)
-> *const gchar;
pub fn gst_element_factory_get_metadata_keys(factory:
*mut GstElementFactory)
-> *mut *mut gchar;
pub fn gst_element_factory_get_num_pad_templates(factory:
*mut GstElementFactory)
-> guint;
pub fn gst_element_factory_get_static_pad_templates(factory:
*mut GstElementFactory)
-> *const GList;
pub fn gst_element_factory_get_uri_type(factory: *mut GstElementFactory)
-> GstURIType;
pub fn gst_element_factory_get_uri_protocols(factory:
*mut GstElementFactory)
-> *const *const gchar;
pub fn gst_element_factory_has_interface(factory: *mut GstElementFactory,
interfacename: *const gchar)
-> gboolean;
pub fn gst_element_factory_create(factory: *mut GstElementFactory,
name: *const gchar) -> *mut GstElement;
pub fn gst_element_factory_make(factoryname: *const gchar,
name: *const gchar) -> *mut GstElement;
pub fn gst_element_register(plugin: *mut GstPlugin, name: *const gchar,
rank: guint, _type: GType) -> gboolean;
pub fn gst_element_factory_list_is_type(factory: *mut GstElementFactory,
_type: GstElementFactoryListType)
-> gboolean;
pub fn gst_element_factory_list_get_elements(_type:
GstElementFactoryListType,
minrank: GstRank)
-> *mut GList;
pub fn gst_element_factory_list_filter(list: *mut GList,
caps: *const GstCaps,
direction: GstPadDirection,
subsetonly: gboolean)
-> *mut GList;
pub fn gst_element_class_add_pad_template(klass: *mut GstElementClass,
templ: *mut GstPadTemplate);
pub fn gst_element_class_get_pad_template(element_class:
*mut GstElementClass,
name: *const gchar)
-> *mut GstPadTemplate;
pub fn gst_element_class_get_pad_template_list(element_class:
*mut GstElementClass)
-> *mut GList;
pub fn gst_element_class_set_metadata(klass: *mut GstElementClass,
longname: *const gchar,
classification: *const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_element_class_set_static_metadata(klass: *mut GstElementClass,
longname: *const gchar,
classification: *const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_element_class_add_metadata(klass: *mut GstElementClass,
key: *const gchar,
value: *const gchar);
pub fn gst_element_class_add_static_metadata(klass: *mut GstElementClass,
key: *const gchar,
value: *const gchar);
pub fn gst_element_class_get_metadata(klass: *mut GstElementClass,
key: *const gchar) -> *const gchar;
pub fn gst_element_get_type() -> GType;
pub fn gst_element_provide_clock(element: *mut GstElement)
-> *mut GstClock;
pub fn gst_element_get_clock(element: *mut GstElement) -> *mut GstClock;
pub fn gst_element_set_clock(element: *mut GstElement,
clock: *mut GstClock) -> gboolean;
pub fn gst_element_set_base_time(element: *mut GstElement,
time: GstClockTime);
pub fn gst_element_get_base_time(element: *mut GstElement)
-> GstClockTime;
pub fn gst_element_set_start_time(element: *mut GstElement,
time: GstClockTime);
pub fn gst_element_get_start_time(element: *mut GstElement)
-> GstClockTime;
pub fn gst_element_set_bus(element: *mut GstElement, bus: *mut GstBus);
pub fn gst_element_get_bus(element: *mut GstElement) -> *mut GstBus;
pub fn gst_element_set_context(element: *mut GstElement,
context: *mut GstContext);
pub fn gst_element_add_pad(element: *mut GstElement, pad: *mut GstPad)
-> gboolean;
pub fn gst_element_remove_pad(element: *mut GstElement, pad: *mut GstPad)
-> gboolean;
pub fn gst_element_no_more_pads(element: *mut GstElement);
pub fn gst_element_get_static_pad(element: *mut GstElement,
name: *const gchar) -> *mut GstPad;
pub fn gst_element_get_request_pad(element: *mut GstElement,
name: *const gchar) -> *mut GstPad;
pub fn gst_element_request_pad(element: *mut GstElement,
templ: *mut GstPadTemplate,
name: *const gchar, caps: *const GstCaps)
-> *mut GstPad;
pub fn gst_element_release_request_pad(element: *mut GstElement,
pad: *mut GstPad);
pub fn gst_element_iterate_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_iterate_src_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_iterate_sink_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_send_event(element: *mut GstElement,
event: *mut GstEvent) -> gboolean;
pub fn gst_element_seek(element: *mut GstElement, rate: gdouble,
format: GstFormat, flags: GstSeekFlags,
start_type: GstSeekType, start: gint64,
stop_type: GstSeekType, stop: gint64) -> gboolean;
pub fn gst_element_query(element: *mut GstElement, query: *mut GstQuery)
-> gboolean;
pub fn gst_element_post_message(element: *mut GstElement,
message: *mut GstMessage) -> gboolean;
pub fn _gst_element_error_printf(format: *const gchar, ...) -> *mut gchar;
pub fn gst_element_message_full(element: *mut GstElement,
_type: GstMessageType, domain: GQuark,
code: gint, text: *mut gchar,
debug: *mut gchar, file: *const gchar,
function: *const gchar, line: gint);
pub fn gst_element_is_locked_state(element: *mut GstElement) -> gboolean;
pub fn gst_element_set_locked_state(element: *mut GstElement,
locked_state: gboolean) -> gboolean;
pub fn gst_element_sync_state_with_parent(element: *mut GstElement)
-> gboolean;
pub fn gst_element_get_state(element: *mut GstElement,
state: *mut GstState, pending: *mut GstState,
timeout: GstClockTime)
-> GstStateChangeReturn;
pub fn gst_element_set_state(element: *mut GstElement, state: GstState)
-> GstStateChangeReturn;
pub fn gst_element_abort_state(element: *mut GstElement);
pub fn gst_element_change_state(element: *mut GstElement,
transition: GstStateChange)
-> GstStateChangeReturn;
pub fn gst_element_continue_state(element: *mut GstElement,
ret: GstStateChangeReturn)
-> GstStateChangeReturn;
pub fn gst_element_lost_state(element: *mut GstElement);
pub fn gst_element_get_factory(element: *mut GstElement)
-> *mut GstElementFactory;
pub fn gst_bin_get_type() -> GType;
pub fn gst_bin_new(name: *const gchar) -> *mut GstElement;
pub fn gst_bin_add(bin: *mut GstBin, element: *mut GstElement)
-> gboolean;
pub fn gst_bin_remove(bin: *mut GstBin, element: *mut GstElement)
-> gboolean;
pub fn gst_bin_get_by_name(bin: *mut GstBin, name: *const gchar)
-> *mut GstElement;
pub fn gst_bin_get_by_name_recurse_up(bin: *mut GstBin,
name: *const gchar)
-> *mut GstElement;
pub fn gst_bin_get_by_interface(bin: *mut GstBin, iface: GType)
-> *mut GstElement;
pub fn gst_bin_iterate_elements(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sorted(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_recurse(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sinks(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sources(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_all_by_interface(bin: *mut GstBin, iface: GType)
-> *mut GstIterator;
pub fn gst_bin_recalculate_latency(bin: *mut GstBin) -> gboolean;
pub fn gst_buffer_pool_get_type() -> GType;
pub fn gst_buffer_pool_new() -> *mut GstBufferPool;
pub fn gst_buffer_pool_set_active(pool: *mut GstBufferPool,
active: gboolean) -> gboolean;
pub fn gst_buffer_pool_is_active(pool: *mut GstBufferPool) -> gboolean;
pub fn gst_buffer_pool_set_config(pool: *mut GstBufferPool,
config: *mut GstStructure) -> gboolean;
pub fn gst_buffer_pool_get_config(pool: *mut GstBufferPool)
-> *mut GstStructure;
pub fn gst_buffer_pool_get_options(pool: *mut GstBufferPool)
-> *mut *const gchar;
pub fn gst_buffer_pool_has_option(pool: *mut GstBufferPool,
option: *const gchar) -> gboolean;
pub fn gst_buffer_pool_set_flushing(pool: *mut GstBufferPool,
flushing: gboolean);
pub fn gst_buffer_pool_config_set_params(config: *mut GstStructure,
caps: *mut GstCaps, size: guint,
min_buffers: guint,
max_buffers: guint);
pub fn gst_buffer_pool_config_get_params(config: *mut GstStructure,
caps: *mut *mut GstCaps,
size: *mut guint,
min_buffers: *mut guint,
max_buffers: *mut guint)
-> gboolean;
pub fn gst_buffer_pool_config_set_allocator(config: *mut GstStructure,
allocator: *mut GstAllocator,
params:
*const GstAllocationParams);
pub fn gst_buffer_pool_config_get_allocator(config: *mut GstStructure,
allocator:
*mut *mut GstAllocator,
params:
*mut GstAllocationParams)
-> gboolean;
pub fn gst_buffer_pool_config_n_options(config: *mut GstStructure)
-> guint;
pub fn gst_buffer_pool_config_add_option(config: *mut GstStructure,
option: *const gchar);
pub fn gst_buffer_pool_config_get_option(config: *mut GstStructure,
index: guint) -> *const gchar;
pub fn gst_buffer_pool_config_has_option(config: *mut GstStructure,
option: *const gchar)
-> gboolean;
pub fn gst_buffer_pool_config_validate_params(config: *mut GstStructure,
caps: *mut GstCaps,
size: guint,
min_buffers: guint,
max_buffers: guint)
-> gboolean;
pub fn gst_buffer_pool_acquire_buffer(pool: *mut GstBufferPool,
buffer: *mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn;
pub fn gst_buffer_pool_release_buffer(pool: *mut GstBufferPool,
buffer: *mut GstBuffer);
pub fn gst_child_proxy_get_type() -> GType;
pub fn gst_child_proxy_get_child_by_name(parent: *mut GstChildProxy,
name: *const gchar)
-> *mut GObject;
pub fn gst_child_proxy_get_children_count(parent: *mut GstChildProxy)
-> guint;
pub fn gst_child_proxy_get_child_by_index(parent: *mut GstChildProxy,
index: guint) -> *mut GObject;
pub fn gst_child_proxy_lookup(object: *mut GstChildProxy,
name: *const gchar,
target: *mut *mut GObject,
pspec: *mut *mut GParamSpec) -> gboolean;
pub fn gst_child_proxy_get_property(object: *mut GstChildProxy,
name: *const gchar,
value: *mut GValue);
pub fn gst_child_proxy_get_valist(object: *mut GstChildProxy,
first_property_name: *const gchar,
var_args: va_list);
pub fn gst_child_proxy_get(object: *mut GstChildProxy,
first_property_name: *const gchar, ...);
pub fn gst_child_proxy_set_property(object: *mut GstChildProxy,
name: *const gchar,
value: *const GValue);
pub fn gst_child_proxy_set_valist(object: *mut GstChildProxy,
first_property_name: *const gchar,
var_args: va_list);
pub fn gst_child_proxy_set(object: *mut GstChildProxy,
first_property_name: *const gchar, ...);
pub fn gst_child_proxy_child_added(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar);
pub fn gst_child_proxy_child_removed(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar);
pub fn gst_debug_bin_to_dot_file(bin: *mut GstBin,
details: GstDebugGraphDetails,
file_name: *const gchar);
pub fn gst_debug_bin_to_dot_file_with_ts(bin: *mut GstBin,
details: GstDebugGraphDetails,
file_name: *const gchar);
pub fn gst_device_provider_get_type() -> GType;
pub fn gst_device_provider_get_devices(provider: *mut GstDeviceProvider)
-> *mut GList;
pub fn gst_device_provider_start(provider: *mut GstDeviceProvider)
-> gboolean;
pub fn gst_device_provider_stop(provider: *mut GstDeviceProvider);
pub fn gst_device_provider_can_monitor(provider: *mut GstDeviceProvider)
-> gboolean;
pub fn gst_device_provider_get_bus(provider: *mut GstDeviceProvider)
-> *mut GstBus;
pub fn gst_device_provider_device_add(provider: *mut GstDeviceProvider,
device: *mut GstDevice);
pub fn gst_device_provider_device_remove(provider: *mut GstDeviceProvider,
device: *mut GstDevice);
pub fn gst_device_provider_class_set_metadata(klass:
*mut GstDeviceProviderClass,
longname: *const gchar,
classification:
*const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_device_provider_class_set_static_metadata(klass:
*mut GstDeviceProviderClass,
longname:
*const gchar,
classification:
*const gchar,
description:
*const gchar,
author:
*const gchar);
pub fn gst_device_provider_class_add_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar,
value: *const gchar);
pub fn gst_device_provider_class_add_static_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar,
value: *const gchar);
pub fn gst_device_provider_class_get_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar)
-> *const gchar;
pub fn gst_device_provider_get_factory(provider: *mut GstDeviceProvider)
-> *mut GstDeviceProviderFactory;
pub fn gst_device_provider_factory_get_type() -> GType;
pub fn gst_device_provider_factory_find(name: *const gchar)
-> *mut GstDeviceProviderFactory;
pub fn gst_device_provider_factory_get_device_provider_type(factory:
*mut GstDeviceProviderFactory)
-> GType;
pub fn gst_device_provider_factory_get_metadata(factory:
*mut GstDeviceProviderFactory,
key: *const gchar)
-> *const gchar;
pub fn gst_device_provider_factory_get_metadata_keys(factory:
*mut GstDeviceProviderFactory)
-> *mut *mut gchar;
pub fn gst_device_provider_factory_get(factory:
*mut GstDeviceProviderFactory)
-> *mut GstDeviceProvider;
pub fn gst_device_provider_factory_get_by_name(factoryname: *const gchar)
-> *mut GstDeviceProvider;
pub fn gst_device_provider_register(plugin: *mut GstPlugin,
name: *const gchar, rank: guint,
_type: GType) -> gboolean;
pub fn gst_device_provider_factory_has_classesv(factory:
*mut GstDeviceProviderFactory,
classes: *mut *mut gchar)
-> gboolean;
pub fn gst_device_provider_factory_has_classes(factory:
*mut GstDeviceProviderFactory,
classes: *const gchar)
-> gboolean;
pub fn gst_device_provider_factory_list_get_device_providers(minrank:
GstRank)
-> *mut GList;
pub fn __errno_location() -> *mut ::libc::c_int;
pub fn gst_error_get_message(domain: GQuark, code: gint) -> *mut gchar;
pub fn gst_stream_error_quark() -> GQuark;
pub fn gst_core_error_quark() -> GQuark;
pub fn gst_resource_error_quark() -> GQuark;
pub fn gst_library_error_quark() -> GQuark;
pub fn gst_proxy_pad_get_type() -> GType;
pub fn gst_proxy_pad_get_internal(pad: *mut GstProxyPad)
-> *mut GstProxyPad;
pub fn gst_proxy_pad_iterate_internal_links_default(pad: *mut GstPad,
parent:
*mut GstObject)
-> *mut GstIterator;
pub fn gst_proxy_pad_chain_default(pad: *mut GstPad,
parent: *mut GstObject,
buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_proxy_pad_chain_list_default(pad: *mut GstPad,
parent: *mut GstObject,
list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_proxy_pad_getrange_default(pad: *mut GstPad,
parent: *mut GstObject,
offset: guint64, size: guint,
buffer: *mut *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_ghost_pad_get_type() -> GType;
pub fn gst_ghost_pad_new(name: *const gchar, target: *mut GstPad)
-> *mut GstPad;
pub fn gst_ghost_pad_new_no_target(name: *const gchar,
dir: GstPadDirection) -> *mut GstPad;
pub fn gst_ghost_pad_new_from_template(name: *const gchar,
target: *mut GstPad,
templ: *mut GstPadTemplate)
-> *mut GstPad;
pub fn gst_ghost_pad_new_no_target_from_template(name: *const gchar,
templ:
*mut GstPadTemplate)
-> *mut GstPad;
pub fn gst_ghost_pad_get_target(gpad: *mut GstGhostPad) -> *mut GstPad;
pub fn gst_ghost_pad_set_target(gpad: *mut GstGhostPad,
newtarget: *mut GstPad) -> gboolean;
pub fn gst_ghost_pad_construct(gpad: *mut GstGhostPad) -> gboolean;
pub fn gst_ghost_pad_activate_mode_default(pad: *mut GstPad,
parent: *mut GstObject,
mode: GstPadMode,
active: gboolean) -> gboolean;
pub fn gst_ghost_pad_internal_activate_mode_default(pad: *mut GstPad,
parent:
*mut GstObject,
mode: GstPadMode,
active: gboolean)
-> gboolean;
pub fn gst_device_monitor_get_type() -> GType;
pub fn gst_device_monitor_new() -> *mut GstDeviceMonitor;
pub fn gst_device_monitor_get_bus(monitor: *mut GstDeviceMonitor)
-> *mut GstBus;
pub fn gst_device_monitor_get_devices(monitor: *mut GstDeviceMonitor)
-> *mut GList;
pub fn gst_device_monitor_start(monitor: *mut GstDeviceMonitor)
-> gboolean;
pub fn gst_device_monitor_stop(monitor: *mut GstDeviceMonitor);
pub fn gst_device_monitor_add_filter(monitor: *mut GstDeviceMonitor,
classes: *const gchar,
caps: *mut GstCaps) -> guint;
pub fn gst_device_monitor_remove_filter(monitor: *mut GstDeviceMonitor,
filter_id: guint) -> gboolean;
pub fn gst_debug_log(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject, format: *const gchar, ...);
pub fn gst_debug_log_valist(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject, format: *const gchar,
args: va_list);
pub fn _gst_debug_category_new(name: *const gchar, color: guint,
description: *const gchar)
-> *mut GstDebugCategory;
pub fn _gst_debug_get_category(name: *const gchar)
-> *mut GstDebugCategory;
pub fn _gst_debug_dump_mem(cat: *mut GstDebugCategory, file: *const gchar,
func: *const gchar, line: gint,
obj: *mut GObject, msg: *const gchar,
data: *const guint8, length: guint);
pub fn _gst_debug_register_funcptr(func: GstDebugFuncPtr,
ptrname: *const gchar);
pub fn _gst_debug_nameof_funcptr(func: GstDebugFuncPtr) -> *const gchar;
pub fn gst_debug_message_get(message: *mut GstDebugMessage)
-> *const gchar;
pub fn gst_debug_log_default(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject,
message: *mut GstDebugMessage,
unused: gpointer);
pub fn gst_debug_level_get_name(level: GstDebugLevel) -> *const gchar;
pub fn gst_debug_add_log_function(func: GstLogFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_debug_remove_log_function(func: GstLogFunction) -> guint;
pub fn gst_debug_remove_log_function_by_data(data: gpointer) -> guint;
pub fn gst_debug_set_active(active: gboolean);
pub fn gst_debug_is_active() -> gboolean;
pub fn gst_debug_set_colored(colored: gboolean);
pub fn gst_debug_set_color_mode(mode: GstDebugColorMode);
pub fn gst_debug_set_color_mode_from_string(mode: *const gchar);
pub fn gst_debug_is_colored() -> gboolean;
pub fn gst_debug_get_color_mode() -> GstDebugColorMode;
pub fn gst_debug_set_default_threshold(level: GstDebugLevel);
pub fn gst_debug_get_default_threshold() -> GstDebugLevel;
pub fn gst_debug_set_threshold_for_name(name: *const gchar,
level: GstDebugLevel);
pub fn gst_debug_set_threshold_from_string(list: *const gchar,
reset: gboolean);
pub fn gst_debug_unset_threshold_for_name(name: *const gchar);
pub fn gst_debug_category_free(category: *mut GstDebugCategory);
pub fn gst_debug_category_set_threshold(category: *mut GstDebugCategory,
level: GstDebugLevel);
pub fn gst_debug_category_reset_threshold(category:
*mut GstDebugCategory);
pub fn gst_debug_category_get_threshold(category: *mut GstDebugCategory)
-> GstDebugLevel;
pub fn gst_debug_category_get_name(category: *mut GstDebugCategory)
-> *const gchar;
pub fn gst_debug_category_get_color(category: *mut GstDebugCategory)
-> guint;
pub fn gst_debug_category_get_description(category: *mut GstDebugCategory)
-> *const gchar;
pub fn gst_debug_get_all_categories() -> *mut GSList;
pub fn gst_debug_construct_term_color(colorinfo: guint) -> *mut gchar;
pub fn gst_debug_construct_win_color(colorinfo: guint) -> gint;
pub fn gst_debug_print_stack_trace();
pub fn gst_int_range_get_type() -> GType;
pub fn gst_int64_range_get_type() -> GType;
pub fn gst_double_range_get_type() -> GType;
pub fn gst_fraction_range_get_type() -> GType;
pub fn gst_fraction_get_type() -> GType;
pub fn gst_value_list_get_type() -> GType;
pub fn gst_value_array_get_type() -> GType;
pub fn gst_bitmask_get_type() -> GType;
pub fn gst_g_thread_get_type() -> GType;
pub fn gst_value_register(table: *const GstValueTable);
pub fn gst_value_init_and_copy(dest: *mut GValue, src: *const GValue);
pub fn gst_value_serialize(value: *const GValue) -> *mut gchar;
pub fn gst_value_deserialize(dest: *mut GValue, src: *const gchar)
-> gboolean;
pub fn gst_value_list_append_value(value: *mut GValue,
append_value: *const GValue);
pub fn gst_value_list_append_and_take_value(value: *mut GValue,
append_value: *mut GValue);
pub fn gst_value_list_prepend_value(value: *mut GValue,
prepend_value: *const GValue);
pub fn gst_value_list_concat(dest: *mut GValue, value1: *const GValue,
value2: *const GValue);
pub fn gst_value_list_merge(dest: *mut GValue, value1: *const GValue,
value2: *const GValue);
pub fn gst_value_list_get_size(value: *const GValue) -> guint;
pub fn gst_value_list_get_value(value: *const GValue, index: guint)
-> *const GValue;
pub fn gst_value_array_append_value(value: *mut GValue,
append_value: *const GValue);
pub fn gst_value_array_append_and_take_value(value: *mut GValue,
append_value: *mut GValue);
pub fn gst_value_array_prepend_value(value: *mut GValue,
prepend_value: *const GValue);
pub fn gst_value_array_get_size(value: *const GValue) -> guint;
pub fn gst_value_array_get_value(value: *const GValue, index: guint)
-> *const GValue;
pub fn gst_value_set_int_range(value: *mut GValue, start: gint,
end: gint);
pub fn gst_value_set_int_range_step(value: *mut GValue, start: gint,
end: gint, step: gint);
pub fn gst_value_get_int_range_min(value: *const GValue) -> gint;
pub fn gst_value_get_int_range_max(value: *const GValue) -> gint;
pub fn gst_value_get_int_range_step(value: *const GValue) -> gint;
pub fn gst_value_set_int64_range(value: *mut GValue, start: gint64,
end: gint64);
pub fn gst_value_set_int64_range_step(value: *mut GValue, start: gint64,
end: gint64, step: gint64);
pub fn gst_value_get_int64_range_min(value: *const GValue) -> gint64;
pub fn gst_value_get_int64_range_max(value: *const GValue) -> gint64;
pub fn gst_value_get_int64_range_step(value: *const GValue) -> gint64;
pub fn gst_value_set_double_range(value: *mut GValue, start: gdouble,
end: gdouble);
pub fn gst_value_get_double_range_min(value: *const GValue) -> gdouble;
pub fn gst_value_get_double_range_max(value: *const GValue) -> gdouble;
pub fn gst_value_get_caps(value: *const GValue) -> *const GstCaps;
pub fn gst_value_set_caps(value: *mut GValue, caps: *const GstCaps);
pub fn gst_value_get_structure(value: *const GValue)
-> *const GstStructure;
pub fn gst_value_set_structure(value: *mut GValue,
structure: *const GstStructure);
pub fn gst_value_get_caps_features(value: *const GValue)
-> *const GstCapsFeatures;
pub fn gst_value_set_caps_features(value: *mut GValue,
features: *const GstCapsFeatures);
pub fn gst_value_set_fraction(value: *mut GValue, numerator: gint,
denominator: gint);
pub fn gst_value_get_fraction_numerator(value: *const GValue) -> gint;
pub fn gst_value_get_fraction_denominator(value: *const GValue) -> gint;
pub fn gst_value_fraction_multiply(product: *mut GValue,
factor1: *const GValue,
factor2: *const GValue) -> gboolean;
pub fn gst_value_fraction_subtract(dest: *mut GValue,
minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_set_fraction_range(value: *mut GValue,
start: *const GValue,
end: *const GValue);
pub fn gst_value_set_fraction_range_full(value: *mut GValue,
numerator_start: gint,
denominator_start: gint,
numerator_end: gint,
denominator_end: gint);
pub fn gst_value_get_fraction_range_min(value: *const GValue)
-> *const GValue;
pub fn gst_value_get_fraction_range_max(value: *const GValue)
-> *const GValue;
pub fn gst_value_get_bitmask(value: *const GValue) -> guint64;
pub fn gst_value_set_bitmask(value: *mut GValue, bitmask: guint64);
pub fn gst_value_compare(value1: *const GValue, value2: *const GValue)
-> gint;
pub fn gst_value_can_compare(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_is_subset(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_union(dest: *mut GValue, value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_can_union(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_intersect(dest: *mut GValue, value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_can_intersect(value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_subtract(dest: *mut GValue, minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_can_subtract(minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_is_fixed(value: *const GValue) -> gboolean;
pub fn gst_value_fixate(dest: *mut GValue, src: *const GValue)
-> gboolean;
pub fn gst_param_spec_fraction_get_type() -> GType;
pub fn gst_param_spec_fraction(name: *const gchar, nick: *const gchar,
blurb: *const gchar, min_num: gint,
min_denom: gint, max_num: gint,
max_denom: gint, default_num: gint,
default_denom: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn gst_pipeline_get_type() -> GType;
pub fn gst_pipeline_new(name: *const gchar) -> *mut GstElement;
pub fn gst_pipeline_get_bus(pipeline: *mut GstPipeline) -> *mut GstBus;
pub fn gst_pipeline_use_clock(pipeline: *mut GstPipeline,
clock: *mut GstClock);
pub fn gst_pipeline_set_clock(pipeline: *mut GstPipeline,
clock: *mut GstClock) -> gboolean;
pub fn gst_pipeline_get_clock(pipeline: *mut GstPipeline)
-> *mut GstClock;
pub fn gst_pipeline_auto_clock(pipeline: *mut GstPipeline);
pub fn gst_pipeline_set_delay(pipeline: *mut GstPipeline,
delay: GstClockTime);
pub fn gst_pipeline_get_delay(pipeline: *mut GstPipeline) -> GstClockTime;
pub fn gst_pipeline_set_auto_flush_bus(pipeline: *mut GstPipeline,
auto_flush: gboolean);
pub fn gst_pipeline_get_auto_flush_bus(pipeline: *mut GstPipeline)
-> gboolean;
pub fn gst_poll_new(controllable: gboolean) -> *mut GstPoll;
pub fn gst_poll_new_timer() -> *mut GstPoll;
pub fn gst_poll_free(set: *mut GstPoll);
pub fn gst_poll_get_read_gpollfd(set: *mut GstPoll, fd: *mut GPollFD);
pub fn gst_poll_fd_init(fd: *mut GstPollFD);
pub fn gst_poll_add_fd(set: *mut GstPoll, fd: *mut GstPollFD) -> gboolean;
pub fn gst_poll_remove_fd(set: *mut GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_ctl_write(set: *mut GstPoll, fd: *mut GstPollFD,
active: gboolean) -> gboolean;
pub fn gst_poll_fd_ctl_read(set: *mut GstPoll, fd: *mut GstPollFD,
active: gboolean) -> gboolean;
pub fn gst_poll_fd_ignored(set: *mut GstPoll, fd: *mut GstPollFD);
pub fn gst_poll_fd_has_closed(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_has_error(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_can_read(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_can_write(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_wait(set: *mut GstPoll, timeout: GstClockTime) -> gint;
pub fn gst_poll_set_controllable(set: *mut GstPoll,
controllable: gboolean) -> gboolean;
pub fn gst_poll_restart(set: *mut GstPoll);
pub fn gst_poll_set_flushing(set: *mut GstPoll, flushing: gboolean);
pub fn gst_poll_write_control(set: *mut GstPoll) -> gboolean;
pub fn gst_poll_read_control(set: *mut GstPoll) -> gboolean;
pub fn gst_preset_get_type() -> GType;
pub fn gst_preset_get_preset_names(preset: *mut GstPreset)
-> *mut *mut gchar;
pub fn gst_preset_get_property_names(preset: *mut GstPreset)
-> *mut *mut gchar;
pub fn gst_preset_load_preset(preset: *mut GstPreset, name: *const gchar)
-> gboolean;
pub fn gst_preset_save_preset(preset: *mut GstPreset, name: *const gchar)
-> gboolean;
pub fn gst_preset_rename_preset(preset: *mut GstPreset,
old_name: *const gchar,
new_name: *const gchar) -> gboolean;
pub fn gst_preset_delete_preset(preset: *mut GstPreset,
name: *const gchar) -> gboolean;
pub fn gst_preset_set_meta(preset: *mut GstPreset, name: *const gchar,
tag: *const gchar, value: *const gchar)
-> gboolean;
pub fn gst_preset_get_meta(preset: *mut GstPreset, name: *const gchar,
tag: *const gchar, value: *mut *mut gchar)
-> gboolean;
pub fn gst_preset_set_app_dir(app_dir: *const gchar) -> gboolean;
pub fn gst_preset_get_app_dir() -> *const gchar;
pub fn gst_registry_get_type() -> GType;
pub fn gst_registry_get() -> *mut GstRegistry;
pub fn gst_registry_scan_path(registry: *mut GstRegistry,
path: *const gchar) -> gboolean;
pub fn gst_registry_add_plugin(registry: *mut GstRegistry,
plugin: *mut GstPlugin) -> gboolean;
pub fn gst_registry_remove_plugin(registry: *mut GstRegistry,
plugin: *mut GstPlugin);
pub fn gst_registry_add_feature(registry: *mut GstRegistry,
feature: *mut GstPluginFeature)
-> gboolean;
pub fn gst_registry_remove_feature(registry: *mut GstRegistry,
feature: *mut GstPluginFeature);
pub fn gst_registry_get_plugin_list(registry: *mut GstRegistry)
-> *mut GList;
pub fn gst_registry_plugin_filter(registry: *mut GstRegistry,
filter: GstPluginFilter,
first: gboolean, user_data: gpointer)
-> *mut GList;
pub fn gst_registry_feature_filter(registry: *mut GstRegistry,
filter: GstPluginFeatureFilter,
first: gboolean, user_data: gpointer)
-> *mut GList;
pub fn gst_registry_get_feature_list(registry: *mut GstRegistry,
_type: GType) -> *mut GList;
pub fn gst_registry_get_feature_list_by_plugin(registry: *mut GstRegistry,
name: *const gchar)
-> *mut GList;
pub fn gst_registry_get_feature_list_cookie(registry: *mut GstRegistry)
-> guint32;
pub fn gst_registry_find_plugin(registry: *mut GstRegistry,
name: *const gchar) -> *mut GstPlugin;
pub fn gst_registry_find_feature(registry: *mut GstRegistry,
name: *const gchar, _type: GType)
-> *mut GstPluginFeature;
pub fn gst_registry_lookup(registry: *mut GstRegistry,
filename: *const ::libc::c_char)
-> *mut GstPlugin;
pub fn gst_registry_lookup_feature(registry: *mut GstRegistry,
name: *const ::libc::c_char)
-> *mut GstPluginFeature;
pub fn gst_registry_check_feature_version(registry: *mut GstRegistry,
feature_name: *const gchar,
min_major: guint,
min_minor: guint,
min_micro: guint) -> gboolean;
pub fn gst_system_clock_get_type() -> GType;
pub fn gst_system_clock_obtain() -> *mut GstClock;
pub fn gst_system_clock_set_default(new_clock: *mut GstClock);
pub fn gst_tag_setter_get_type() -> GType;
pub fn gst_tag_setter_reset_tags(setter: *mut GstTagSetter);
pub fn gst_tag_setter_merge_tags(setter: *mut GstTagSetter,
list: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_tag_setter_add_tags(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_setter_add_tag_values(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_setter_add_tag_valist(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_setter_add_tag_valist_values(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_setter_add_tag_value(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
value: *const GValue);
pub fn gst_tag_setter_get_tag_list(setter: *mut GstTagSetter)
-> *const GstTagList;
pub fn gst_tag_setter_set_tag_merge_mode(setter: *mut GstTagSetter,
mode: GstTagMergeMode);
pub fn gst_tag_setter_get_tag_merge_mode(setter: *mut GstTagSetter)
-> GstTagMergeMode;
pub fn gst_toc_setter_get_type() -> GType;
pub fn gst_toc_setter_reset(setter: *mut GstTocSetter);
pub fn gst_toc_setter_get_toc(setter: *mut GstTocSetter) -> *mut GstToc;
pub fn gst_toc_setter_set_toc(setter: *mut GstTocSetter,
toc: *mut GstToc);
pub fn gst_type_find_get_type() -> GType;
pub fn gst_type_find_peek(find: *mut GstTypeFind, offset: gint64,
size: guint) -> *const guint8;
pub fn gst_type_find_suggest(find: *mut GstTypeFind, probability: guint,
caps: *mut GstCaps);
pub fn gst_type_find_suggest_simple(find: *mut GstTypeFind,
probability: guint,
media_type: *const ::libc::c_char,
fieldname:
*const ::libc::c_char, ...);
pub fn gst_type_find_get_length(find: *mut GstTypeFind) -> guint64;
pub fn gst_type_find_register(plugin: *mut GstPlugin, name: *const gchar,
rank: guint, func: GstTypeFindFunction,
extensions: *const gchar,
possible_caps: *mut GstCaps, data: gpointer,
data_notify: GDestroyNotify) -> gboolean;
pub fn gst_type_find_factory_get_type() -> GType;
pub fn gst_type_find_factory_get_list() -> *mut GList;
pub fn gst_type_find_factory_get_extensions(factory:
*mut GstTypeFindFactory)
-> *const *const gchar;
pub fn gst_type_find_factory_get_caps(factory: *mut GstTypeFindFactory)
-> *mut GstCaps;
pub fn gst_type_find_factory_has_function(factory:
*mut GstTypeFindFactory)
-> gboolean;
pub fn gst_type_find_factory_call_function(factory:
*mut GstTypeFindFactory,
find: *mut GstTypeFind);
pub fn gst_parse_error_quark() -> GQuark;
pub fn gst_parse_context_get_type() -> GType;
pub fn gst_parse_context_new() -> *mut GstParseContext;
pub fn gst_parse_context_get_missing_elements(context:
*mut GstParseContext)
-> *mut *mut gchar;
pub fn gst_parse_context_free(context: *mut GstParseContext);
pub fn gst_parse_launch(pipeline_description: *const gchar,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_parse_launchv(argv: *mut *const gchar, error: *mut *mut GError)
-> *mut GstElement;
pub fn gst_parse_launch_full(pipeline_description: *const gchar,
context: *mut GstParseContext,
flags: GstParseFlags,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_parse_launchv_full(argv: *mut *const gchar,
context: *mut GstParseContext,
flags: GstParseFlags,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_util_set_value_from_string(value: *mut GValue,
value_str: *const gchar);
pub fn gst_util_set_object_arg(object: *mut GObject, name: *const gchar,
value: *const gchar);
pub fn gst_util_dump_mem(mem: *const guchar, size: guint);
pub fn gst_util_gdouble_to_guint64(value: gdouble) -> guint64;
pub fn gst_util_guint64_to_gdouble(value: guint64) -> gdouble;
pub fn gst_util_uint64_scale(val: guint64, num: guint64, denom: guint64)
-> guint64;
pub fn gst_util_uint64_scale_round(val: guint64, num: guint64,
denom: guint64) -> guint64;
pub fn gst_util_uint64_scale_ceil(val: guint64, num: guint64,
denom: guint64) -> guint64;
pub fn gst_util_uint64_scale_int(val: guint64, num: gint, denom: gint)
-> guint64;
pub fn gst_util_uint64_scale_int_round(val: guint64, num: gint,
denom: gint) -> guint64;
pub fn gst_util_uint64_scale_int_ceil(val: guint64, num: gint,
denom: gint) -> guint64;
pub fn gst_util_seqnum_next() -> guint32;
pub fn gst_util_seqnum_compare(s1: guint32, s2: guint32) -> gint32;
pub fn gst_util_group_id_next() -> guint;
pub fn gst_object_default_error(source: *mut GstObject,
error: *const GError,
debug: *const gchar);
pub fn gst_element_create_all_pads(element: *mut GstElement);
pub fn gst_element_get_compatible_pad(element: *mut GstElement,
pad: *mut GstPad,
caps: *mut GstCaps) -> *mut GstPad;
pub fn gst_element_get_compatible_pad_template(element: *mut GstElement,
compattempl:
*mut GstPadTemplate)
-> *mut GstPadTemplate;
pub fn gst_element_state_get_name(state: GstState) -> *const gchar;
pub fn gst_element_state_change_return_get_name(state_ret:
GstStateChangeReturn)
-> *const gchar;
pub fn gst_element_link(src: *mut GstElement, dest: *mut GstElement)
-> gboolean;
pub fn gst_element_link_many(element_1: *mut GstElement,
element_2: *mut GstElement, ...) -> gboolean;
pub fn gst_element_link_filtered(src: *mut GstElement,
dest: *mut GstElement,
filter: *mut GstCaps) -> gboolean;
pub fn gst_element_unlink(src: *mut GstElement, dest: *mut GstElement);
pub fn gst_element_unlink_many(element_1: *mut GstElement,
element_2: *mut GstElement, ...);
pub fn gst_element_link_pads(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar) -> gboolean;
pub fn gst_element_link_pads_full(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar,
flags: GstPadLinkCheck) -> gboolean;
pub fn gst_element_unlink_pads(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar);
pub fn gst_element_link_pads_filtered(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar,
filter: *mut GstCaps) -> gboolean;
pub fn gst_element_seek_simple(element: *mut GstElement,
format: GstFormat,
seek_flags: GstSeekFlags, seek_pos: gint64)
-> gboolean;
pub fn gst_element_factory_can_sink_all_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_src_all_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_sink_any_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_src_any_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_query_position(element: *mut GstElement,
format: GstFormat, cur: *mut gint64)
-> gboolean;
pub fn gst_element_query_duration(element: *mut GstElement,
format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_element_query_convert(element: *mut GstElement,
src_format: GstFormat, src_val: gint64,
dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_use_fixed_caps(pad: *mut GstPad);
pub fn gst_pad_get_parent_element(pad: *mut GstPad) -> *mut GstElement;
pub fn gst_pad_proxy_query_accept_caps(pad: *mut GstPad,
query: *mut GstQuery) -> gboolean;
pub fn gst_pad_proxy_query_caps(pad: *mut GstPad, query: *mut GstQuery)
-> gboolean;
pub fn gst_pad_query_position(pad: *mut GstPad, format: GstFormat,
cur: *mut gint64) -> gboolean;
pub fn gst_pad_query_duration(pad: *mut GstPad, format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_pad_query_convert(pad: *mut GstPad, src_format: GstFormat,
src_val: gint64, dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_query_caps(pad: *mut GstPad, filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_pad_query_accept_caps(pad: *mut GstPad, caps: *mut GstCaps)
-> gboolean;
pub fn gst_pad_peer_query_position(pad: *mut GstPad, format: GstFormat,
cur: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_duration(pad: *mut GstPad, format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_convert(pad: *mut GstPad, src_format: GstFormat,
src_val: gint64, dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_caps(pad: *mut GstPad, filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_pad_peer_query_accept_caps(pad: *mut GstPad,
caps: *mut GstCaps) -> gboolean;
pub fn gst_pad_create_stream_id(pad: *mut GstPad, parent: *mut GstElement,
stream_id: *const gchar) -> *mut gchar;
pub fn gst_pad_create_stream_id_printf(pad: *mut GstPad,
parent: *mut GstElement,
stream_id: *const gchar, ...)
-> *mut gchar;
pub fn gst_pad_create_stream_id_printf_valist(pad: *mut GstPad,
parent: *mut GstElement,
stream_id: *const gchar,
var_args: va_list)
-> *mut gchar;
pub fn gst_pad_get_stream_id(pad: *mut GstPad) -> *mut gchar;
pub fn gst_bin_add_many(bin: *mut GstBin,
element_1: *mut GstElement, ...);
pub fn gst_bin_remove_many(bin: *mut GstBin,
element_1: *mut GstElement, ...);
pub fn gst_bin_find_unlinked_pad(bin: *mut GstBin,
direction: GstPadDirection)
-> *mut GstPad;
pub fn gst_parse_bin_from_description(bin_description: *const gchar,
ghost_unlinked_pads: gboolean,
err: *mut *mut GError)
-> *mut GstElement;
pub fn gst_parse_bin_from_description_full(bin_description: *const gchar,
ghost_unlinked_pads: gboolean,
context: *mut GstParseContext,
flags: GstParseFlags,
err: *mut *mut GError)
-> *mut GstElement;
pub fn gst_util_get_timestamp() -> GstClockTime;
pub fn gst_util_array_binary_search(array: gpointer, num_elements: guint,
element_size: gsize,
search_func: GCompareDataFunc,
mode: GstSearchMode,
search_data: gconstpointer,
user_data: gpointer) -> gpointer;
pub fn gst_util_greatest_common_divisor(a: gint, b: gint) -> gint;
pub fn gst_util_greatest_common_divisor_int64(a: gint64, b: gint64)
-> gint64;
pub fn gst_util_fraction_to_double(src_n: gint, src_d: gint,
dest: *mut gdouble);
pub fn gst_util_double_to_fraction(src: gdouble, dest_n: *mut gint,
dest_d: *mut gint);
pub fn gst_util_fraction_multiply(a_n: gint, a_d: gint, b_n: gint,
b_d: gint, res_n: *mut gint,
res_d: *mut gint) -> gboolean;
pub fn gst_util_fraction_add(a_n: gint, a_d: gint, b_n: gint, b_d: gint,
res_n: *mut gint, res_d: *mut gint)
-> gboolean;
pub fn gst_util_fraction_compare(a_n: gint, a_d: gint, b_n: gint,
b_d: gint) -> gint;
pub fn gst_init(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char);
pub fn gst_init_check(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char,
err: *mut *mut GError) -> gboolean;
pub fn gst_is_initialized() -> gboolean;
pub fn gst_init_get_option_group() -> *mut GOptionGroup;
pub fn gst_deinit();
pub fn gst_version(major: *mut guint, minor: *mut guint,
micro: *mut guint, nano: *mut guint);
pub fn gst_version_string() -> *mut gchar;
pub fn gst_segtrap_is_enabled() -> gboolean;
pub fn gst_segtrap_set_enabled(enabled: gboolean);
pub fn gst_registry_fork_is_enabled() -> gboolean;
pub fn gst_registry_fork_set_enabled(enabled: gboolean);
pub fn gst_update_registry() -> gboolean;
pub fn gst_base_sink_get_type() -> GType;
pub fn gst_base_sink_do_preroll(sink: *mut GstBaseSink,
obj: *mut GstMiniObject) -> GstFlowReturn;
pub fn gst_base_sink_wait_preroll(sink: *mut GstBaseSink)
-> GstFlowReturn;
pub fn gst_base_sink_set_sync(sink: *mut GstBaseSink, sync: gboolean);
pub fn gst_base_sink_get_sync(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_max_lateness(sink: *mut GstBaseSink,
max_lateness: gint64);
pub fn gst_base_sink_get_max_lateness(sink: *mut GstBaseSink) -> gint64;
pub fn gst_base_sink_set_qos_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_qos_enabled(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_async_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_async_enabled(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_ts_offset(sink: *mut GstBaseSink,
offset: GstClockTimeDiff);
pub fn gst_base_sink_get_ts_offset(sink: *mut GstBaseSink)
-> GstClockTimeDiff;
pub fn gst_base_sink_get_last_sample(sink: *mut GstBaseSink)
-> *mut GstSample;
pub fn gst_base_sink_set_last_sample_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_last_sample_enabled(sink: *mut GstBaseSink)
-> gboolean;
pub fn gst_base_sink_query_latency(sink: *mut GstBaseSink,
live: *mut gboolean,
upstream_live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime)
-> gboolean;
pub fn gst_base_sink_get_latency(sink: *mut GstBaseSink) -> GstClockTime;
pub fn gst_base_sink_set_render_delay(sink: *mut GstBaseSink,
delay: GstClockTime);
pub fn gst_base_sink_get_render_delay(sink: *mut GstBaseSink)
-> GstClockTime;
pub fn gst_base_sink_set_blocksize(sink: *mut GstBaseSink,
blocksize: guint);
pub fn gst_base_sink_get_blocksize(sink: *mut GstBaseSink) -> guint;
pub fn gst_base_sink_set_throttle_time(sink: *mut GstBaseSink,
throttle: guint64);
pub fn gst_base_sink_get_throttle_time(sink: *mut GstBaseSink) -> guint64;
pub fn gst_base_sink_set_max_bitrate(sink: *mut GstBaseSink,
max_bitrate: guint64);
pub fn gst_base_sink_get_max_bitrate(sink: *mut GstBaseSink) -> guint64;
pub fn gst_base_sink_wait_clock(sink: *mut GstBaseSink,
time: GstClockTime,
jitter: *mut GstClockTimeDiff)
-> GstClockReturn;
pub fn gst_base_sink_wait(sink: *mut GstBaseSink, time: GstClockTime,
jitter: *mut GstClockTimeDiff) -> GstFlowReturn;
pub fn gst_app_sink_get_type() -> GType;
pub fn gst_app_sink_set_caps(appsink: *mut GstAppSink,
caps: *const GstCaps);
pub fn gst_app_sink_get_caps(appsink: *mut GstAppSink) -> *mut GstCaps;
pub fn gst_app_sink_is_eos(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_set_emit_signals(appsink: *mut GstAppSink,
emit: gboolean);
pub fn gst_app_sink_get_emit_signals(appsink: *mut GstAppSink)
-> gboolean;
pub fn gst_app_sink_set_max_buffers(appsink: *mut GstAppSink, max: guint);
pub fn gst_app_sink_get_max_buffers(appsink: *mut GstAppSink) -> guint;
pub fn gst_app_sink_set_drop(appsink: *mut GstAppSink, drop: gboolean);
pub fn gst_app_sink_get_drop(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_pull_preroll(appsink: *mut GstAppSink)
-> *mut GstSample;
pub fn gst_app_sink_pull_sample(appsink: *mut GstAppSink)
-> *mut GstSample;
pub fn gst_app_sink_set_callbacks(appsink: *mut GstAppSink,
callbacks: *mut GstAppSinkCallbacks,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_base_src_get_type() -> GType;
pub fn gst_base_src_wait_playing(src: *mut GstBaseSrc) -> GstFlowReturn;
pub fn gst_base_src_set_live(src: *mut GstBaseSrc, live: gboolean);
pub fn gst_base_src_is_live(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_set_format(src: *mut GstBaseSrc, format: GstFormat);
pub fn gst_base_src_set_dynamic_size(src: *mut GstBaseSrc,
dynamic: gboolean);
pub fn gst_base_src_set_automatic_eos(src: *mut GstBaseSrc,
automatic_eos: gboolean);
pub fn gst_base_src_set_async(src: *mut GstBaseSrc, async: gboolean);
pub fn gst_base_src_is_async(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_start_complete(basesrc: *mut GstBaseSrc,
ret: GstFlowReturn);
pub fn gst_base_src_start_wait(basesrc: *mut GstBaseSrc) -> GstFlowReturn;
pub fn gst_base_src_query_latency(src: *mut GstBaseSrc,
live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime)
-> gboolean;
pub fn gst_base_src_set_blocksize(src: *mut GstBaseSrc, blocksize: guint);
pub fn gst_base_src_get_blocksize(src: *mut GstBaseSrc) -> guint;
pub fn gst_base_src_set_do_timestamp(src: *mut GstBaseSrc,
timestamp: gboolean);
pub fn gst_base_src_get_do_timestamp(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_new_seamless_segment(src: *mut GstBaseSrc,
start: gint64, stop: gint64,
time: gint64) -> gboolean;
pub fn gst_base_src_set_caps(src: *mut GstBaseSrc, caps: *mut GstCaps)
-> gboolean;
pub fn gst_base_src_get_buffer_pool(src: *mut GstBaseSrc)
-> *mut GstBufferPool;
pub fn gst_base_src_get_allocator(src: *mut GstBaseSrc,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_push_src_get_type() -> GType;
pub fn gst_app_src_get_type() -> GType;
pub fn gst_app_stream_type_get_type() -> GType;
pub fn gst_app_src_set_caps(appsrc: *mut GstAppSrc, caps: *const GstCaps);
pub fn gst_app_src_get_caps(appsrc: *mut GstAppSrc) -> *mut GstCaps;
pub fn gst_app_src_set_size(appsrc: *mut GstAppSrc, size: gint64);
pub fn gst_app_src_get_size(appsrc: *mut GstAppSrc) -> gint64;
pub fn gst_app_src_set_stream_type(appsrc: *mut GstAppSrc,
_type: GstAppStreamType);
pub fn gst_app_src_get_stream_type(appsrc: *mut GstAppSrc)
-> GstAppStreamType;
pub fn gst_app_src_set_max_bytes(appsrc: *mut GstAppSrc, max: guint64);
pub fn gst_app_src_get_max_bytes(appsrc: *mut GstAppSrc) -> guint64;
pub fn gst_app_src_get_current_level_bytes(appsrc: *mut GstAppSrc)
-> guint64;
pub fn gst_app_src_set_latency(appsrc: *mut GstAppSrc, min: guint64,
max: guint64);
pub fn gst_app_src_get_latency(appsrc: *mut GstAppSrc, min: *mut guint64,
max: *mut guint64);
pub fn gst_app_src_set_emit_signals(appsrc: *mut GstAppSrc,
emit: gboolean);
pub fn gst_app_src_get_emit_signals(appsrc: *mut GstAppSrc) -> gboolean;
pub fn gst_app_src_push_buffer(appsrc: *mut GstAppSrc,
buffer: *mut GstBuffer) -> GstFlowReturn;
pub fn gst_app_src_end_of_stream(appsrc: *mut GstAppSrc) -> GstFlowReturn;
pub fn gst_app_src_set_callbacks(appsrc: *mut GstAppSrc,
callbacks: *mut GstAppSrcCallbacks,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_video_format_get_type() -> GType;
pub fn gst_video_format_flags_get_type() -> GType;
pub fn gst_video_pack_flags_get_type() -> GType;
pub fn gst_video_color_range_get_type() -> GType;
pub fn gst_video_color_matrix_get_type() -> GType;
pub fn gst_video_transfer_function_get_type() -> GType;
pub fn gst_video_color_primaries_get_type() -> GType;
pub fn gst_video_interlace_mode_get_type() -> GType;
pub fn gst_video_flags_get_type() -> GType;
pub fn gst_color_balance_type_get_type() -> GType;
pub fn gst_navigation_command_get_type() -> GType;
pub fn gst_navigation_query_type_get_type() -> GType;
pub fn gst_navigation_message_type_get_type() -> GType;
pub fn gst_navigation_event_type_get_type() -> GType;
pub fn gst_video_chroma_site_get_type() -> GType;
pub fn gst_video_chroma_method_get_type() -> GType;
pub fn gst_video_chroma_flags_get_type() -> GType;
pub fn gst_video_tile_type_get_type() -> GType;
pub fn gst_video_tile_mode_get_type() -> GType;
pub fn gst_video_tile_get_index(mode: GstVideoTileMode, x: gint, y: gint,
x_tiles: gint, y_tiles: gint) -> guint;
pub fn gst_video_chroma_from_string(s: *const gchar)
-> GstVideoChromaSite;
pub fn gst_video_chroma_to_string(site: GstVideoChromaSite)
-> *const gchar;
pub fn gst_video_chroma_resample_new(method: GstVideoChromaMethod,
site: GstVideoChromaSite,
flags: GstVideoChromaFlags,
format: GstVideoFormat,
h_factor: gint, v_factor: gint)
-> *mut GstVideoChromaResample;
pub fn gst_video_chroma_resample_free(resample:
*mut GstVideoChromaResample);
pub fn gst_video_chroma_resample_get_info(resample:
*mut GstVideoChromaResample,
n_lines: *mut guint,
offset: *mut gint);
pub fn gst_video_chroma_resample(resample: *mut GstVideoChromaResample,
lines: *mut gpointer, width: gint);
pub fn gst_video_format_from_masks(depth: gint, bpp: gint,
endianness: gint, red_mask: guint,
green_mask: guint, blue_mask: guint,
alpha_mask: guint) -> GstVideoFormat;
pub fn gst_video_format_from_fourcc(fourcc: guint32) -> GstVideoFormat;
pub fn gst_video_format_from_string(format: *const gchar)
-> GstVideoFormat;
pub fn gst_video_format_to_fourcc(format: GstVideoFormat) -> guint32;
pub fn gst_video_format_to_string(format: GstVideoFormat) -> *const gchar;
pub fn gst_video_format_get_info(format: GstVideoFormat)
-> *const GstVideoFormatInfo;
pub fn gst_video_format_get_palette(format: GstVideoFormat,
size: *mut gsize) -> gconstpointer;
pub fn gst_video_colorimetry_matches(cinfo: *mut GstVideoColorimetry,
color: *const gchar) -> gboolean;
pub fn gst_video_colorimetry_from_string(cinfo: *mut GstVideoColorimetry,
color: *const gchar) -> gboolean;
pub fn gst_video_colorimetry_to_string(cinfo: *mut GstVideoColorimetry)
-> *mut gchar;
pub fn gst_video_color_range_offsets(range: GstVideoColorRange,
info: *const GstVideoFormatInfo,
offset: *mut gint, scale: *mut gint);
pub fn gst_video_info_init(info: *mut GstVideoInfo);
pub fn gst_video_info_set_format(info: *mut GstVideoInfo,
format: GstVideoFormat, width: guint,
height: guint);
pub fn gst_video_info_from_caps(info: *mut GstVideoInfo,
caps: *const GstCaps) -> gboolean;
pub fn gst_video_info_to_caps(info: *mut GstVideoInfo) -> *mut GstCaps;
pub fn gst_video_info_convert(info: *mut GstVideoInfo,
src_format: GstFormat, src_value: gint64,
dest_format: GstFormat,
dest_value: *mut gint64) -> gboolean;
pub fn gst_video_info_is_equal(info: *const GstVideoInfo,
other: *const GstVideoInfo) -> gboolean;
pub fn gst_video_info_align(info: *mut GstVideoInfo,
align: *mut GstVideoAlignment);
pub fn gst_video_frame_map(frame: *mut GstVideoFrame,
info: *mut GstVideoInfo,
buffer: *mut GstBuffer, flags: GstMapFlags)
-> gboolean;
pub fn gst_video_frame_map_id(frame: *mut GstVideoFrame,
info: *mut GstVideoInfo,
buffer: *mut GstBuffer, id: gint,
flags: GstMapFlags) -> gboolean;
pub fn gst_video_frame_unmap(frame: *mut GstVideoFrame);
pub fn gst_video_frame_copy(dest: *mut GstVideoFrame,
src: *const GstVideoFrame) -> gboolean;
pub fn gst_video_frame_copy_plane(dest: *mut GstVideoFrame,
src: *const GstVideoFrame, plane: guint)
-> gboolean;
pub fn gst_video_alignment_reset(align: *mut GstVideoAlignment);
pub fn gst_video_calculate_display_ratio(dar_n: *mut guint,
dar_d: *mut guint,
video_width: guint,
video_height: guint,
video_par_n: guint,
video_par_d: guint,
display_par_n: guint,
display_par_d: guint)
-> gboolean;
pub fn gst_video_convert_sample_async(sample: *mut GstSample,
to_caps: *const GstCaps,
timeout: GstClockTime,
callback:
GstVideoConvertSampleCallback,
user_data: gpointer,
destroy_notify: GDestroyNotify);
pub fn gst_video_convert_sample(sample: *mut GstSample,
to_caps: *const GstCaps,
timeout: GstClockTime,
error: *mut *mut GError)
-> *mut GstSample;
pub fn gst_color_balance_channel_get_type() -> GType;
pub fn gst_color_balance_get_type() -> GType;
pub fn gst_color_balance_list_channels(balance: *mut GstColorBalance)
-> *const GList;
pub fn gst_color_balance_set_value(balance: *mut GstColorBalance,
channel: *mut GstColorBalanceChannel,
value: gint);
pub fn gst_color_balance_get_value(balance: *mut GstColorBalance,
channel: *mut GstColorBalanceChannel)
-> gint;
pub fn gst_color_balance_get_balance_type(balance: *mut GstColorBalance)
-> GstColorBalanceType;
pub fn gst_color_balance_value_changed(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint);
pub fn gst_adapter_get_type() -> GType;
pub fn gst_adapter_new() -> *mut GstAdapter;
pub fn gst_adapter_clear(adapter: *mut GstAdapter);
pub fn gst_adapter_push(adapter: *mut GstAdapter, buf: *mut GstBuffer);
pub fn gst_adapter_map(adapter: *mut GstAdapter, size: gsize)
-> gconstpointer;
pub fn gst_adapter_unmap(adapter: *mut GstAdapter);
pub fn gst_adapter_copy(adapter: *mut GstAdapter, dest: gpointer,
offset: gsize, size: gsize);
pub fn gst_adapter_copy_bytes(adapter: *mut GstAdapter, offset: gsize,
size: gsize) -> *mut GBytes;
pub fn gst_adapter_flush(adapter: *mut GstAdapter, flush: gsize);
pub fn gst_adapter_take(adapter: *mut GstAdapter, nbytes: gsize)
-> gpointer;
pub fn gst_adapter_take_buffer(adapter: *mut GstAdapter, nbytes: gsize)
-> *mut GstBuffer;
pub fn gst_adapter_take_list(adapter: *mut GstAdapter, nbytes: gsize)
-> *mut GList;
pub fn gst_adapter_take_buffer_fast(adapter: *mut GstAdapter,
nbytes: gsize) -> *mut GstBuffer;
pub fn gst_adapter_available(adapter: *mut GstAdapter) -> gsize;
pub fn gst_adapter_available_fast(adapter: *mut GstAdapter) -> gsize;
pub fn gst_adapter_prev_pts(adapter: *mut GstAdapter,
distance: *mut guint64) -> GstClockTime;
pub fn gst_adapter_prev_dts(adapter: *mut GstAdapter,
distance: *mut guint64) -> GstClockTime;
pub fn gst_adapter_prev_pts_at_offset(adapter: *mut GstAdapter,
offset: gsize,
distance: *mut guint64)
-> GstClockTime;
pub fn gst_adapter_prev_dts_at_offset(adapter: *mut GstAdapter,
offset: gsize,
distance: *mut guint64)
-> GstClockTime;
pub fn gst_adapter_masked_scan_uint32(adapter: *mut GstAdapter,
mask: guint32, pattern: guint32,
offset: gsize, size: gsize)
-> gssize;
pub fn gst_adapter_masked_scan_uint32_peek(adapter: *mut GstAdapter,
mask: guint32,
pattern: guint32,
offset: gsize, size: gsize,
value: *mut guint32) -> gssize;
pub fn gst_video_codec_state_get_type() -> GType;
pub fn gst_video_codec_state_ref(state: *mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_codec_state_unref(state: *mut GstVideoCodecState);
pub fn gst_video_codec_frame_get_type() -> GType;
pub fn gst_video_codec_frame_ref(frame: *mut GstVideoCodecFrame)
-> *mut GstVideoCodecFrame;
pub fn gst_video_codec_frame_unref(frame: *mut GstVideoCodecFrame);
pub fn gst_video_codec_frame_set_user_data(frame: *mut GstVideoCodecFrame,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_video_codec_frame_get_user_data(frame: *mut GstVideoCodecFrame)
-> gpointer;
pub fn _gst_video_decoder_error(dec: *mut GstVideoDecoder, weight: gint,
domain: GQuark, code: gint,
txt: *mut gchar, debug: *mut gchar,
file: *const gchar,
function: *const gchar, line: gint)
-> GstFlowReturn;
pub fn gst_video_decoder_get_type() -> GType;
pub fn gst_video_decoder_set_packetized(decoder: *mut GstVideoDecoder,
packetized: gboolean);
pub fn gst_video_decoder_get_packetized(decoder: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_set_estimate_rate(dec: *mut GstVideoDecoder,
enabled: gboolean);
pub fn gst_video_decoder_get_estimate_rate(dec: *mut GstVideoDecoder)
-> gint;
pub fn gst_video_decoder_set_max_errors(dec: *mut GstVideoDecoder,
num: gint);
pub fn gst_video_decoder_get_max_errors(dec: *mut GstVideoDecoder)
-> gint;
pub fn gst_video_decoder_set_needs_format(dec: *mut GstVideoDecoder,
enabled: gboolean);
pub fn gst_video_decoder_get_needs_format(dec: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_set_latency(decoder: *mut GstVideoDecoder,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_video_decoder_get_latency(decoder: *mut GstVideoDecoder,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_video_decoder_get_allocator(decoder: *mut GstVideoDecoder,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_video_decoder_get_buffer_pool(decoder: *mut GstVideoDecoder)
-> *mut GstBufferPool;
pub fn gst_video_decoder_get_frame(decoder: *mut GstVideoDecoder,
frame_number: ::libc::c_int)
-> *mut GstVideoCodecFrame;
pub fn gst_video_decoder_get_oldest_frame(decoder: *mut GstVideoDecoder)
-> *mut GstVideoCodecFrame;
pub fn gst_video_decoder_get_frames(decoder: *mut GstVideoDecoder)
-> *mut GList;
pub fn gst_video_decoder_add_to_frame(decoder: *mut GstVideoDecoder,
n_bytes: ::libc::c_int);
pub fn gst_video_decoder_have_frame(decoder: *mut GstVideoDecoder)
-> GstFlowReturn;
pub fn gst_video_decoder_get_pending_frame_size(decoder:
*mut GstVideoDecoder)
-> gsize;
pub fn gst_video_decoder_allocate_output_buffer(decoder:
*mut GstVideoDecoder)
-> *mut GstBuffer;
pub fn gst_video_decoder_allocate_output_frame(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_set_output_state(decoder: *mut GstVideoDecoder,
fmt: GstVideoFormat,
width: guint, height: guint,
reference:
*mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_decoder_get_output_state(decoder: *mut GstVideoDecoder)
-> *mut GstVideoCodecState;
pub fn gst_video_decoder_negotiate(decoder: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_get_max_decode_time(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstClockTimeDiff;
pub fn gst_video_decoder_get_qos_proportion(decoder: *mut GstVideoDecoder)
-> gdouble;
pub fn gst_video_decoder_finish_frame(decoder: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_drop_frame(dec: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_release_frame(dec: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame);
pub fn gst_video_decoder_merge_tags(decoder: *mut GstVideoDecoder,
tags: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_video_encoder_get_type() -> GType;
pub fn gst_video_encoder_get_output_state(encoder: *mut GstVideoEncoder)
-> *mut GstVideoCodecState;
pub fn gst_video_encoder_set_output_state(encoder: *mut GstVideoEncoder,
caps: *mut GstCaps,
reference:
*mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_encoder_negotiate(encoder: *mut GstVideoEncoder)
-> gboolean;
pub fn gst_video_encoder_get_frame(encoder: *mut GstVideoEncoder,
frame_number: ::libc::c_int)
-> *mut GstVideoCodecFrame;
pub fn gst_video_encoder_get_oldest_frame(encoder: *mut GstVideoEncoder)
-> *mut GstVideoCodecFrame;
pub fn gst_video_encoder_get_frames(encoder: *mut GstVideoEncoder)
-> *mut GList;
pub fn gst_video_encoder_allocate_output_buffer(encoder:
*mut GstVideoEncoder,
size: gsize)
-> *mut GstBuffer;
pub fn gst_video_encoder_allocate_output_frame(encoder:
*mut GstVideoEncoder,
frame:
*mut GstVideoCodecFrame,
size: gsize)
-> GstFlowReturn;
pub fn gst_video_encoder_finish_frame(encoder: *mut GstVideoEncoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_encoder_proxy_getcaps(enc: *mut GstVideoEncoder,
caps: *mut GstCaps,
filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_video_encoder_set_latency(encoder: *mut GstVideoEncoder,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_video_encoder_get_latency(encoder: *mut GstVideoEncoder,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_video_encoder_set_headers(encoder: *mut GstVideoEncoder,
headers: *mut GList);
pub fn gst_video_encoder_merge_tags(encoder: *mut GstVideoEncoder,
tags: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_video_encoder_get_allocator(encoder: *mut GstVideoEncoder,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_base_transform_get_type() -> GType;
pub fn gst_base_transform_set_passthrough(trans: *mut GstBaseTransform,
passthrough: gboolean);
pub fn gst_base_transform_is_passthrough(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_set_in_place(trans: *mut GstBaseTransform,
in_place: gboolean);
pub fn gst_base_transform_is_in_place(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_update_qos(trans: *mut GstBaseTransform,
proportion: gdouble,
diff: GstClockTimeDiff,
timestamp: GstClockTime);
pub fn gst_base_transform_set_qos_enabled(trans: *mut GstBaseTransform,
enabled: gboolean);
pub fn gst_base_transform_is_qos_enabled(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_set_gap_aware(trans: *mut GstBaseTransform,
gap_aware: gboolean);
pub fn gst_base_transform_set_prefer_passthrough(trans:
*mut GstBaseTransform,
prefer_passthrough:
gboolean);
pub fn gst_base_transform_get_buffer_pool(trans: *mut GstBaseTransform)
-> *mut GstBufferPool;
pub fn gst_base_transform_get_allocator(trans: *mut GstBaseTransform,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_base_transform_reconfigure_sink(trans: *mut GstBaseTransform);
pub fn gst_base_transform_reconfigure_src(trans: *mut GstBaseTransform);
pub fn gst_video_filter_get_type() -> GType;
pub fn gst_video_meta_api_get_type() -> GType;
pub fn gst_video_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_get_video_meta_id(buffer: *mut GstBuffer, id: gint)
-> *mut GstVideoMeta;
pub fn gst_buffer_add_video_meta(buffer: *mut GstBuffer,
flags: GstVideoFrameFlags,
format: GstVideoFormat, width: guint,
height: guint) -> *mut GstVideoMeta;
pub fn gst_buffer_add_video_meta_full(buffer: *mut GstBuffer,
flags: GstVideoFrameFlags,
format: GstVideoFormat,
width: guint, height: guint,
n_planes: guint, offset: *mut gsize,
stride: *mut gint)
-> *mut GstVideoMeta;
pub fn gst_video_meta_map(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo, data: *mut gpointer,
stride: *mut gint, flags: GstMapFlags)
-> gboolean;
pub fn gst_video_meta_unmap(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo) -> gboolean;
pub fn gst_video_crop_meta_api_get_type() -> GType;
pub fn gst_video_crop_meta_get_info() -> *const GstMetaInfo;
pub fn gst_video_meta_transform_scale_get_quark() -> GQuark;
pub fn gst_video_gl_texture_upload_meta_api_get_type() -> GType;
pub fn gst_video_gl_texture_upload_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_add_video_gl_texture_upload_meta(buffer: *mut GstBuffer,
texture_orientation:
GstVideoGLTextureOrientation,
n_textures: guint,
texture_type:
*mut GstVideoGLTextureType,
upload:
GstVideoGLTextureUpload,
user_data: gpointer,
user_data_copy:
GBoxedCopyFunc,
user_data_free:
GBoxedFreeFunc)
-> *mut GstVideoGLTextureUploadMeta;
pub fn gst_video_gl_texture_upload_meta_upload(meta:
*mut GstVideoGLTextureUploadMeta,
texture_id: *mut guint)
-> gboolean;
pub fn gst_video_region_of_interest_meta_api_get_type() -> GType;
pub fn gst_video_region_of_interest_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_get_video_region_of_interest_meta_id(buffer:
*mut GstBuffer,
id: gint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_add_video_region_of_interest_meta(buffer:
*mut GstBuffer,
roi_type:
*const gchar,
x: guint, y: guint,
w: guint, h: guint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_add_video_region_of_interest_meta_id(buffer:
*mut GstBuffer,
roi_type: GQuark,
x: guint, y: guint,
w: guint, h: guint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_pool_config_set_video_alignment(config:
*mut GstStructure,
align:
*mut GstVideoAlignment);
pub fn gst_buffer_pool_config_get_video_alignment(config:
*mut GstStructure,
align:
*mut GstVideoAlignment)
-> gboolean;
pub fn gst_video_buffer_pool_get_type() -> GType;
pub fn gst_video_buffer_pool_new() -> *mut GstBufferPool;
pub fn gst_video_sink_get_type() -> GType;
pub fn gst_video_sink_center_rect(src: GstVideoRectangle,
dst: GstVideoRectangle,
result: *mut GstVideoRectangle,
scaling: gboolean);
pub fn gst_navigation_get_type() -> GType;
pub fn gst_navigation_query_get_type(query: *mut GstQuery)
-> GstNavigationQueryType;
pub fn gst_navigation_query_new_commands() -> *mut GstQuery;
pub fn gst_navigation_query_set_commands(query: *mut GstQuery,
n_cmds: gint, ...);
pub fn gst_navigation_query_set_commandsv(query: *mut GstQuery,
n_cmds: gint,
cmds:
*mut GstNavigationCommand);
pub fn gst_navigation_query_parse_commands_length(query: *mut GstQuery,
n_cmds: *mut guint)
-> gboolean;
pub fn gst_navigation_query_parse_commands_nth(query: *mut GstQuery,
nth: guint,
cmd:
*mut GstNavigationCommand)
-> gboolean;
pub fn gst_navigation_query_new_angles() -> *mut GstQuery;
pub fn gst_navigation_query_set_angles(query: *mut GstQuery,
cur_angle: guint, n_angles: guint);
pub fn gst_navigation_query_parse_angles(query: *mut GstQuery,
cur_angle: *mut guint,
n_angles: *mut guint)
-> gboolean;
pub fn gst_navigation_message_get_type(message: *mut GstMessage)
-> GstNavigationMessageType;
pub fn gst_navigation_message_new_mouse_over(src: *mut GstObject,
active: gboolean)
-> *mut GstMessage;
pub fn gst_navigation_message_parse_mouse_over(message: *mut GstMessage,
active: *mut gboolean)
-> gboolean;
pub fn gst_navigation_message_new_commands_changed(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_navigation_message_new_angles_changed(src: *mut GstObject,
cur_angle: guint,
n_angles: guint)
-> *mut GstMessage;
pub fn gst_navigation_message_parse_angles_changed(message:
*mut GstMessage,
cur_angle: *mut guint,
n_angles: *mut guint)
-> gboolean;
pub fn gst_navigation_event_get_type(event: *mut GstEvent)
-> GstNavigationEventType;
pub fn gst_navigation_event_parse_key_event(event: *mut GstEvent,
key: *mut *const gchar)
-> gboolean;
pub fn gst_navigation_event_parse_mouse_button_event(event: *mut GstEvent,
button: *mut gint,
x: *mut gdouble,
y: *mut gdouble)
-> gboolean;
pub fn gst_navigation_event_parse_mouse_move_event(event: *mut GstEvent,
x: *mut gdouble,
y: *mut gdouble)
-> gboolean;
pub fn gst_navigation_event_parse_command(event: *mut GstEvent,
command:
*mut GstNavigationCommand)
-> gboolean;
pub fn gst_navigation_send_event(navigation: *mut GstNavigation,
structure: *mut GstStructure);
pub fn gst_navigation_send_key_event(navigation: *mut GstNavigation,
event: *const ::libc::c_char,
key: *const ::libc::c_char);
pub fn gst_navigation_send_mouse_event(navigation: *mut GstNavigation,
event: *const ::libc::c_char,
button: ::libc::c_int,
x: ::libc::c_double,
y: ::libc::c_double);
pub fn gst_navigation_send_command(navigation: *mut GstNavigation,
command: GstNavigationCommand);
pub fn gst_video_blend_scale_linear_RGBA(src: *mut GstVideoInfo,
src_buffer: *mut GstBuffer,
dest_height: gint,
dest_width: gint,
dest: *mut GstVideoInfo,
dest_buffer:
*mut *mut GstBuffer);
pub fn gst_video_blend(dest: *mut GstVideoFrame, src: *mut GstVideoFrame,
x: gint, y: gint, global_alpha: gfloat)
-> gboolean;
pub fn gst_video_event_new_still_frame(in_still: gboolean)
-> *mut GstEvent;
pub fn gst_video_event_parse_still_frame(event: *mut GstEvent,
in_still: *mut gboolean)
-> gboolean;
pub fn gst_video_event_new_downstream_force_key_unit(timestamp:
GstClockTime,
stream_time:
GstClockTime,
running_time:
GstClockTime,
all_headers:
gboolean,
count: guint)
-> *mut GstEvent;
pub fn gst_video_event_parse_downstream_force_key_unit(event:
*mut GstEvent,
timestamp:
*mut GstClockTime,
stream_time:
*mut GstClockTime,
running_time:
*mut GstClockTime,
all_headers:
*mut gboolean,
count: *mut guint)
-> gboolean;
pub fn gst_video_event_new_upstream_force_key_unit(running_time:
GstClockTime,
all_headers: gboolean,
count: guint)
-> *mut GstEvent;
pub fn gst_video_event_parse_upstream_force_key_unit(event: *mut GstEvent,
running_time:
*mut GstClockTime,
all_headers:
*mut gboolean,
count: *mut guint)
-> gboolean;
pub fn gst_video_event_is_force_key_unit(event: *mut GstEvent)
-> gboolean;
pub fn gst_video_orientation_get_type() -> GType;
pub fn gst_video_orientation_get_hflip(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean) -> gboolean;
pub fn gst_video_orientation_get_vflip(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean) -> gboolean;
pub fn gst_video_orientation_get_hcenter(video_orientation:
*mut GstVideoOrientation,
center: *mut gint) -> gboolean;
pub fn gst_video_orientation_get_vcenter(video_orientation:
*mut GstVideoOrientation,
center: *mut gint) -> gboolean;
pub fn gst_video_orientation_set_hflip(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean;
pub fn gst_video_orientation_set_vflip(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean;
pub fn gst_video_orientation_set_hcenter(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean;
pub fn gst_video_orientation_set_vcenter(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean;
pub fn gst_video_overlay_rectangle_get_type() -> GType;
pub fn gst_video_overlay_rectangle_new_raw(pixels: *mut GstBuffer,
render_x: gint, render_y: gint,
render_width: guint,
render_height: guint,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_rectangle_copy(rectangle:
*mut GstVideoOverlayRectangle)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_rectangle_get_seqnum(rectangle:
*mut GstVideoOverlayRectangle)
-> guint;
pub fn gst_video_overlay_rectangle_set_render_rectangle(rectangle:
*mut GstVideoOverlayRectangle,
render_x: gint,
render_y: gint,
render_width:
guint,
render_height:
guint);
pub fn gst_video_overlay_rectangle_get_render_rectangle(rectangle:
*mut GstVideoOverlayRectangle,
render_x:
*mut gint,
render_y:
*mut gint,
render_width:
*mut guint,
render_height:
*mut guint)
-> gboolean;
pub fn gst_video_overlay_rectangle_get_pixels_raw(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_argb(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_ayuv(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_raw(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_argb(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_ayuv(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_flags(rectangle:
*mut GstVideoOverlayRectangle)
-> GstVideoOverlayFormatFlags;
pub fn gst_video_overlay_rectangle_get_global_alpha(rectangle:
*mut GstVideoOverlayRectangle)
-> gfloat;
pub fn gst_video_overlay_rectangle_set_global_alpha(rectangle:
*mut GstVideoOverlayRectangle,
global_alpha: gfloat);
pub fn gst_video_overlay_composition_get_type() -> GType;
pub fn gst_video_overlay_composition_copy(comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_make_writable(comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_new(rectangle:
*mut GstVideoOverlayRectangle)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_add_rectangle(comp:
*mut GstVideoOverlayComposition,
rectangle:
*mut GstVideoOverlayRectangle);
pub fn gst_video_overlay_composition_n_rectangles(comp:
*mut GstVideoOverlayComposition)
-> guint;
pub fn gst_video_overlay_composition_get_rectangle(comp:
*mut GstVideoOverlayComposition,
n: guint)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_composition_get_seqnum(comp:
*mut GstVideoOverlayComposition)
-> guint;
pub fn gst_video_overlay_composition_blend(comp:
*mut GstVideoOverlayComposition,
video_buf: *mut GstVideoFrame)
-> gboolean;
pub fn gst_video_overlay_composition_meta_api_get_type() -> GType;
pub fn gst_video_overlay_composition_meta_get_info()
-> *const GstMetaInfo;
pub fn gst_buffer_add_video_overlay_composition_meta(buf: *mut GstBuffer,
comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayCompositionMeta;
pub fn gst_video_overlay_get_type() -> GType;
pub fn gst_video_overlay_set_render_rectangle(overlay:
*mut GstVideoOverlay,
x: gint, y: gint,
width: gint, height: gint)
-> gboolean;
pub fn gst_video_overlay_expose(overlay: *mut GstVideoOverlay);
pub fn gst_video_overlay_handle_events(overlay: *mut GstVideoOverlay,
handle_events: gboolean);
pub fn gst_video_overlay_set_window_handle(overlay: *mut GstVideoOverlay,
handle: guintptr);
pub fn gst_video_overlay_got_window_handle(overlay: *mut GstVideoOverlay,
handle: guintptr);
pub fn gst_video_overlay_prepare_window_handle(overlay:
*mut GstVideoOverlay);
pub fn gst_is_video_overlay_prepare_window_handle_message(msg:
*mut GstMessage)
-> gboolean;
}
ffi: 64bits types were wrong in 32bit platforms
/* automatically generated by rust-bindgen */
#![allow(raw_pointer_derive,non_camel_case_types,non_snake_case,non_upper_case_globals,missing_copy_implementations)]
pub use self::GstState::*;
pub type __builtin_va_list = ::libc::c_void;
pub type ptrdiff_t = ::libc::c_long;
pub type size_t = ::libc::c_ulong;
pub type wchar_t = ::libc::c_int;
pub type gint8 = ::libc::c_char;
pub type guint8 = ::libc::c_uchar;
pub type gint16 = ::libc::c_short;
pub type guint16 = ::libc::c_ushort;
pub type gint32 = ::libc::c_int;
pub type guint32 = ::libc::c_uint;
pub type gint64 = ::libc::c_longlong;
pub type guint64 = ::libc::c_ulonglong;
pub type gssize = ::libc::c_longlong;
pub type gsize = ::libc::c_ulonglong;
pub type goffset = gint64;
pub type gintptr = ::libc::c_long;
pub type guintptr = ::libc::c_ulong;
pub type GPid = ::libc::c_int;
pub type __u_char = ::libc::c_uchar;
pub type __u_short = ::libc::c_ushort;
pub type __u_int = ::libc::c_uint;
pub type __u_long = ::libc::c_ulong;
pub type __int8_t = ::libc::c_char;
pub type __uint8_t = ::libc::c_uchar;
pub type __int16_t = ::libc::c_short;
pub type __uint16_t = ::libc::c_ushort;
pub type __int32_t = ::libc::c_int;
pub type __uint32_t = ::libc::c_uint;
pub type __int64_t = ::libc::c_longlong;
pub type __uint64_t = ::libc::c_ulonglong;
pub type __quad_t = ::libc::c_long;
pub type __u_quad_t = ::libc::c_ulong;
pub type __dev_t = ::libc::c_ulong;
pub type __uid_t = ::libc::c_uint;
pub type __gid_t = ::libc::c_uint;
pub type __ino_t = ::libc::c_ulong;
pub type __ino64_t = ::libc::c_ulonglong;
pub type __mode_t = ::libc::c_uint;
pub type __nlink_t = ::libc::c_ulong;
pub type __off_t = ::libc::c_long;
pub type __off64_t = ::libc::c_longlong;
pub type __pid_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed1 {
pub __val: [::libc::c_int; 2u],
}
impl ::std::default::Default for Struct_Unnamed1 {
fn default() -> Struct_Unnamed1 { unsafe { ::std::mem::zeroed() } }
}
pub type __fsid_t = Struct_Unnamed1;
pub type __clock_t = ::libc::c_long;
pub type __rlim_t = ::libc::c_ulong;
pub type __rlim64_t = ::libc::c_ulong;
pub type __id_t = ::libc::c_uint;
pub type __time_t = ::libc::c_long;
pub type __useconds_t = ::libc::c_uint;
pub type __suseconds_t = ::libc::c_long;
pub type __daddr_t = ::libc::c_int;
pub type __key_t = ::libc::c_int;
pub type __clockid_t = ::libc::c_int;
pub type __timer_t = *mut ::libc::c_void;
pub type __blksize_t = ::libc::c_long;
pub type __blkcnt_t = ::libc::c_long;
pub type __blkcnt64_t = ::libc::c_long;
pub type __fsblkcnt_t = ::libc::c_ulong;
pub type __fsblkcnt64_t = ::libc::c_ulong;
pub type __fsfilcnt_t = ::libc::c_ulong;
pub type __fsfilcnt64_t = ::libc::c_ulong;
pub type __fsword_t = ::libc::c_long;
pub type __ssize_t = ::libc::c_long;
pub type __syscall_slong_t = ::libc::c_long;
pub type __syscall_ulong_t = ::libc::c_ulong;
pub type __loff_t = __off64_t;
pub type __qaddr_t = *mut __quad_t;
pub type __caddr_t = *mut ::libc::c_char;
pub type __intptr_t = ::libc::c_long;
pub type __socklen_t = ::libc::c_uint;
pub type clock_t = __clock_t;
pub type time_t = __time_t;
pub type clockid_t = __clockid_t;
pub type timer_t = __timer_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_timespec {
pub tv_sec: __time_t,
pub tv_nsec: __syscall_slong_t,
}
impl ::std::default::Default for Struct_timespec {
fn default() -> Struct_timespec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_tm {
pub tm_sec: ::libc::c_int,
pub tm_min: ::libc::c_int,
pub tm_hour: ::libc::c_int,
pub tm_mday: ::libc::c_int,
pub tm_mon: ::libc::c_int,
pub tm_year: ::libc::c_int,
pub tm_wday: ::libc::c_int,
pub tm_yday: ::libc::c_int,
pub tm_isdst: ::libc::c_int,
pub tm_gmtoff: ::libc::c_long,
pub tm_zone: *const ::libc::c_char,
}
impl ::std::default::Default for Struct_tm {
fn default() -> Struct_tm { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_itimerspec {
pub it_interval: Struct_timespec,
pub it_value: Struct_timespec,
}
impl ::std::default::Default for Struct_itimerspec {
fn default() -> Struct_itimerspec { unsafe { ::std::mem::zeroed() } }
}
pub type pid_t = __pid_t;
pub enum Struct___locale_data { }
#[repr(C)]
#[derive(Copy)]
pub struct Struct___locale_struct {
pub __locales: [*mut Struct___locale_data; 13u],
pub __ctype_b: *const ::libc::c_ushort,
pub __ctype_tolower: *const ::libc::c_int,
pub __ctype_toupper: *const ::libc::c_int,
pub __names: [*const ::libc::c_char; 13u],
}
impl ::std::default::Default for Struct___locale_struct {
fn default() -> Struct___locale_struct { unsafe { ::std::mem::zeroed() } }
}
pub type __locale_t = *mut Struct___locale_struct;
pub type locale_t = __locale_t;
pub type gchar = ::libc::c_char;
pub type gshort = ::libc::c_short;
pub type glong = ::libc::c_long;
pub type gint = ::libc::c_int;
pub type gboolean = gint;
pub type guchar = ::libc::c_uchar;
pub type gushort = ::libc::c_ushort;
pub type gulong = ::libc::c_ulong;
pub type guint = ::libc::c_uint;
pub type gfloat = ::libc::c_float;
pub type gdouble = ::libc::c_double;
pub type gpointer = *mut ::libc::c_void;
pub type gconstpointer = *const ::libc::c_void;
pub type GCompareFunc =
::std::option::Option<extern "C" fn(a: gconstpointer, b: gconstpointer)
-> gint>;
pub type GCompareDataFunc =
::std::option::Option<extern "C" fn
(a: gconstpointer, b: gconstpointer,
user_data: gpointer) -> gint>;
pub type GEqualFunc =
::std::option::Option<extern "C" fn(a: gconstpointer, b: gconstpointer)
-> gboolean>;
pub type GDestroyNotify =
::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GFunc =
::std::option::Option<extern "C" fn(data: gpointer, user_data: gpointer)>;
pub type GHashFunc =
::std::option::Option<extern "C" fn(key: gconstpointer) -> guint>;
pub type GHFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer,
user_data: gpointer)>;
pub type GFreeFunc = ::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GTranslateFunc =
::std::option::Option<extern "C" fn(str: *const gchar, data: gpointer)
-> *const gchar>;
pub type GDoubleIEEE754 = Union__GDoubleIEEE754;
pub type GFloatIEEE754 = Union__GFloatIEEE754;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GFloatIEEE754 {
pub _bindgen_data_: [u32; 1u],
}
impl Union__GFloatIEEE754 {
pub unsafe fn v_float(&mut self) -> *mut gfloat {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn mpn(&mut self) -> *mut Struct_Unnamed2 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GFloatIEEE754 {
fn default() -> Union__GFloatIEEE754 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed2 {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
}
impl ::std::default::Default for Struct_Unnamed2 {
fn default() -> Struct_Unnamed2 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union__GDoubleIEEE754 {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GDoubleIEEE754 {
pub unsafe fn v_double(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn mpn(&mut self) -> *mut Struct_Unnamed3 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GDoubleIEEE754 {
fn default() -> Union__GDoubleIEEE754 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed3 {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
}
impl ::std::default::Default for Struct_Unnamed3 {
fn default() -> Struct_Unnamed3 { unsafe { ::std::mem::zeroed() } }
}
pub type GTimeVal = Struct__GTimeVal;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTimeVal {
pub tv_sec: glong,
pub tv_usec: glong,
}
impl ::std::default::Default for Struct__GTimeVal {
fn default() -> Struct__GTimeVal { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GBytes { }
pub type GBytes = Struct__GBytes;
pub type GArray = Struct__GArray;
pub type GByteArray = Struct__GByteArray;
pub type GPtrArray = Struct__GPtrArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GArray {
pub data: *mut gchar,
pub len: guint,
}
impl ::std::default::Default for Struct__GArray {
fn default() -> Struct__GArray { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GByteArray {
pub data: *mut guint8,
pub len: guint,
}
impl ::std::default::Default for Struct__GByteArray {
fn default() -> Struct__GByteArray { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPtrArray {
pub pdata: *mut gpointer,
pub len: guint,
}
impl ::std::default::Default for Struct__GPtrArray {
fn default() -> Struct__GPtrArray { unsafe { ::std::mem::zeroed() } }
}
pub type va_list = __builtin_va_list;
pub type __gnuc_va_list = __builtin_va_list;
pub type GQuark = guint32;
pub type GError = Struct__GError;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GError {
pub domain: GQuark,
pub code: gint,
pub message: *mut gchar,
}
impl ::std::default::Default for Struct__GError {
fn default() -> Struct__GError { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed4 = ::libc::c_uint;
pub const G_THREAD_ERROR_AGAIN: ::libc::c_uint = 0;
pub type GThreadError = Enum_Unnamed4;
pub type GThreadFunc =
::std::option::Option<extern "C" fn(data: gpointer) -> gpointer>;
pub type GThread = Struct__GThread;
pub type GMutex = Union__GMutex;
pub type GRecMutex = Struct__GRecMutex;
pub type GRWLock = Struct__GRWLock;
pub type GCond = Struct__GCond;
pub type GPrivate = Struct__GPrivate;
pub type GOnce = Struct__GOnce;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GMutex {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GMutex {
pub unsafe fn p(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn i(&mut self) -> *mut [guint; 2u] {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GMutex {
fn default() -> Union__GMutex { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GRWLock {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GRWLock {
fn default() -> Struct__GRWLock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCond {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GCond {
fn default() -> Struct__GCond { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GRecMutex {
pub p: gpointer,
pub i: [guint; 2u],
}
impl ::std::default::Default for Struct__GRecMutex {
fn default() -> Struct__GRecMutex { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPrivate {
pub p: gpointer,
pub notify: GDestroyNotify,
pub future: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GPrivate {
fn default() -> Struct__GPrivate { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed5 = ::libc::c_uint;
pub const G_ONCE_STATUS_NOTCALLED: ::libc::c_uint = 0;
pub const G_ONCE_STATUS_PROGRESS: ::libc::c_uint = 1;
pub const G_ONCE_STATUS_READY: ::libc::c_uint = 2;
pub type GOnceStatus = Enum_Unnamed5;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GOnce {
pub status: GOnceStatus,
pub retval: gpointer,
}
impl ::std::default::Default for Struct__GOnce {
fn default() -> Struct__GOnce { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GAsyncQueue { }
pub type GAsyncQueue = Struct__GAsyncQueue;
pub type __sig_atomic_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed6 {
pub __val: [::libc::c_ulong; 16u],
}
impl ::std::default::Default for Struct_Unnamed6 {
fn default() -> Struct_Unnamed6 { unsafe { ::std::mem::zeroed() } }
}
pub type __sigset_t = Struct_Unnamed6;
pub type sig_atomic_t = __sig_atomic_t;
pub type sigset_t = __sigset_t;
pub type uid_t = __uid_t;
#[repr(C)]
#[derive(Copy)]
pub struct Union_sigval {
pub _bindgen_data_: [u64; 1u],
}
impl Union_sigval {
pub unsafe fn sival_int(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn sival_ptr(&mut self) -> *mut *mut ::libc::c_void {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_sigval {
fn default() -> Union_sigval { unsafe { ::std::mem::zeroed() } }
}
pub type sigval_t = Union_sigval;
pub type __sigchld_clock_t = __clock_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed7 {
pub si_signo: ::libc::c_int,
pub si_errno: ::libc::c_int,
pub si_code: ::libc::c_int,
pub _sifields: Union_Unnamed8,
}
impl ::std::default::Default for Struct_Unnamed7 {
fn default() -> Struct_Unnamed7 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed8 {
pub _bindgen_data_: [u64; 14u],
}
impl Union_Unnamed8 {
pub unsafe fn _pad(&mut self) -> *mut [::libc::c_int; 28u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _kill(&mut self) -> *mut Struct_Unnamed9 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _timer(&mut self) -> *mut Struct_Unnamed10 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _rt(&mut self) -> *mut Struct_Unnamed11 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigchld(&mut self) -> *mut Struct_Unnamed12 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigfault(&mut self) -> *mut Struct_Unnamed13 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigpoll(&mut self) -> *mut Struct_Unnamed14 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigsys(&mut self) -> *mut Struct_Unnamed15 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed8 {
fn default() -> Union_Unnamed8 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed9 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
}
impl ::std::default::Default for Struct_Unnamed9 {
fn default() -> Struct_Unnamed9 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed10 {
pub si_tid: ::libc::c_int,
pub si_overrun: ::libc::c_int,
pub si_sigval: sigval_t,
}
impl ::std::default::Default for Struct_Unnamed10 {
fn default() -> Struct_Unnamed10 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed11 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
pub si_sigval: sigval_t,
}
impl ::std::default::Default for Struct_Unnamed11 {
fn default() -> Struct_Unnamed11 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed12 {
pub si_pid: __pid_t,
pub si_uid: __uid_t,
pub si_status: ::libc::c_int,
pub si_utime: __sigchld_clock_t,
pub si_stime: __sigchld_clock_t,
}
impl ::std::default::Default for Struct_Unnamed12 {
fn default() -> Struct_Unnamed12 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed13 {
pub si_addr: *mut ::libc::c_void,
pub si_addr_lsb: ::libc::c_short,
}
impl ::std::default::Default for Struct_Unnamed13 {
fn default() -> Struct_Unnamed13 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed14 {
pub si_band: ::libc::c_long,
pub si_fd: ::libc::c_int,
}
impl ::std::default::Default for Struct_Unnamed14 {
fn default() -> Struct_Unnamed14 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed15 {
pub _call_addr: *mut ::libc::c_void,
pub _syscall: ::libc::c_int,
pub _arch: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed15 {
fn default() -> Struct_Unnamed15 { unsafe { ::std::mem::zeroed() } }
}
pub type siginfo_t = Struct_Unnamed7;
pub type Enum_Unnamed16 = ::libc::c_int;
pub const SI_ASYNCNL: ::libc::c_int = -60;
pub const SI_TKILL: ::libc::c_int = -6;
pub const SI_SIGIO: ::libc::c_int = -5;
pub const SI_ASYNCIO: ::libc::c_int = -4;
pub const SI_MESGQ: ::libc::c_int = -3;
pub const SI_TIMER: ::libc::c_int = -2;
pub const SI_QUEUE: ::libc::c_int = -1;
pub const SI_USER: ::libc::c_int = 0;
pub const SI_KERNEL: ::libc::c_int = 128;
pub type Enum_Unnamed17 = ::libc::c_uint;
pub const ILL_ILLOPC: ::libc::c_uint = 1;
pub const ILL_ILLOPN: ::libc::c_uint = 2;
pub const ILL_ILLADR: ::libc::c_uint = 3;
pub const ILL_ILLTRP: ::libc::c_uint = 4;
pub const ILL_PRVOPC: ::libc::c_uint = 5;
pub const ILL_PRVREG: ::libc::c_uint = 6;
pub const ILL_COPROC: ::libc::c_uint = 7;
pub const ILL_BADSTK: ::libc::c_uint = 8;
pub type Enum_Unnamed18 = ::libc::c_uint;
pub const FPE_INTDIV: ::libc::c_uint = 1;
pub const FPE_INTOVF: ::libc::c_uint = 2;
pub const FPE_FLTDIV: ::libc::c_uint = 3;
pub const FPE_FLTOVF: ::libc::c_uint = 4;
pub const FPE_FLTUND: ::libc::c_uint = 5;
pub const FPE_FLTRES: ::libc::c_uint = 6;
pub const FPE_FLTINV: ::libc::c_uint = 7;
pub const FPE_FLTSUB: ::libc::c_uint = 8;
pub type Enum_Unnamed19 = ::libc::c_uint;
pub const SEGV_MAPERR: ::libc::c_uint = 1;
pub const SEGV_ACCERR: ::libc::c_uint = 2;
pub type Enum_Unnamed20 = ::libc::c_uint;
pub const BUS_ADRALN: ::libc::c_uint = 1;
pub const BUS_ADRERR: ::libc::c_uint = 2;
pub const BUS_OBJERR: ::libc::c_uint = 3;
pub const BUS_MCEERR_AR: ::libc::c_uint = 4;
pub const BUS_MCEERR_AO: ::libc::c_uint = 5;
pub type Enum_Unnamed21 = ::libc::c_uint;
pub const TRAP_BRKPT: ::libc::c_uint = 1;
pub const TRAP_TRACE: ::libc::c_uint = 2;
pub type Enum_Unnamed22 = ::libc::c_uint;
pub const CLD_EXITED: ::libc::c_uint = 1;
pub const CLD_KILLED: ::libc::c_uint = 2;
pub const CLD_DUMPED: ::libc::c_uint = 3;
pub const CLD_TRAPPED: ::libc::c_uint = 4;
pub const CLD_STOPPED: ::libc::c_uint = 5;
pub const CLD_CONTINUED: ::libc::c_uint = 6;
pub type Enum_Unnamed23 = ::libc::c_uint;
pub const POLL_IN: ::libc::c_uint = 1;
pub const POLL_OUT: ::libc::c_uint = 2;
pub const POLL_MSG: ::libc::c_uint = 3;
pub const POLL_ERR: ::libc::c_uint = 4;
pub const POLL_PRI: ::libc::c_uint = 5;
pub const POLL_HUP: ::libc::c_uint = 6;
pub type pthread_attr_t = Union_pthread_attr_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigevent {
pub sigev_value: sigval_t,
pub sigev_signo: ::libc::c_int,
pub sigev_notify: ::libc::c_int,
pub _sigev_un: Union_Unnamed24,
}
impl ::std::default::Default for Struct_sigevent {
fn default() -> Struct_sigevent { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed24 {
pub _bindgen_data_: [u64; 6u],
}
impl Union_Unnamed24 {
pub unsafe fn _pad(&mut self) -> *mut [::libc::c_int; 12u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _tid(&mut self) -> *mut __pid_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn _sigev_thread(&mut self) -> *mut Struct_Unnamed25 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed24 {
fn default() -> Union_Unnamed24 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed25 {
pub _function: ::std::option::Option<extern "C" fn(arg1: sigval_t)>,
pub _attribute: *mut pthread_attr_t,
}
impl ::std::default::Default for Struct_Unnamed25 {
fn default() -> Struct_Unnamed25 { unsafe { ::std::mem::zeroed() } }
}
pub type sigevent_t = Struct_sigevent;
pub type Enum_Unnamed26 = ::libc::c_uint;
pub const SIGEV_SIGNAL: ::libc::c_uint = 0;
pub const SIGEV_NONE: ::libc::c_uint = 1;
pub const SIGEV_THREAD: ::libc::c_uint = 2;
pub const SIGEV_THREAD_ID: ::libc::c_uint = 4;
pub type __sighandler_t =
::std::option::Option<extern "C" fn(arg1: ::libc::c_int)>;
pub type sig_t = __sighandler_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigaction {
pub __sigaction_handler: Union_Unnamed27,
pub sa_mask: __sigset_t,
pub sa_flags: ::libc::c_int,
pub sa_restorer: ::std::option::Option<extern "C" fn()>,
}
impl ::std::default::Default for Struct_sigaction {
fn default() -> Struct_sigaction { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed27 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed27 {
pub unsafe fn sa_handler(&mut self) -> *mut __sighandler_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn sa_sigaction(&mut self)
->
*mut ::std::option::Option<extern "C" fn
(arg1: ::libc::c_int,
arg2: *mut siginfo_t,
arg3: *mut ::libc::c_void)> {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed27 {
fn default() -> Union_Unnamed27 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigvec {
pub sv_handler: __sighandler_t,
pub sv_mask: ::libc::c_int,
pub sv_flags: ::libc::c_int,
}
impl ::std::default::Default for Struct_sigvec {
fn default() -> Struct_sigvec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpx_sw_bytes {
pub magic1: __uint32_t,
pub extended_size: __uint32_t,
pub xstate_bv: __uint64_t,
pub xstate_size: __uint32_t,
pub padding: [__uint32_t; 7u],
}
impl ::std::default::Default for Struct__fpx_sw_bytes {
fn default() -> Struct__fpx_sw_bytes { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
}
impl ::std::default::Default for Struct__fpreg {
fn default() -> Struct__fpreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpxreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
pub padding: [::libc::c_ushort; 3u],
}
impl ::std::default::Default for Struct__fpxreg {
fn default() -> Struct__fpxreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xmmreg {
pub element: [__uint32_t; 4u],
}
impl ::std::default::Default for Struct__xmmreg {
fn default() -> Struct__xmmreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__fpstate {
pub cwd: __uint16_t,
pub swd: __uint16_t,
pub ftw: __uint16_t,
pub fop: __uint16_t,
pub rip: __uint64_t,
pub rdp: __uint64_t,
pub mxcsr: __uint32_t,
pub mxcr_mask: __uint32_t,
pub _st: [Struct__fpxreg; 8u],
pub _xmm: [Struct__xmmreg; 16u],
pub padding: [__uint32_t; 24u],
}
impl ::std::default::Default for Struct__fpstate {
fn default() -> Struct__fpstate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigcontext {
pub r8: __uint64_t,
pub r9: __uint64_t,
pub r10: __uint64_t,
pub r11: __uint64_t,
pub r12: __uint64_t,
pub r13: __uint64_t,
pub r14: __uint64_t,
pub r15: __uint64_t,
pub rdi: __uint64_t,
pub rsi: __uint64_t,
pub rbp: __uint64_t,
pub rbx: __uint64_t,
pub rdx: __uint64_t,
pub rax: __uint64_t,
pub rcx: __uint64_t,
pub rsp: __uint64_t,
pub rip: __uint64_t,
pub eflags: __uint64_t,
pub cs: ::libc::c_ushort,
pub gs: ::libc::c_ushort,
pub fs: ::libc::c_ushort,
pub __pad0: ::libc::c_ushort,
pub err: __uint64_t,
pub trapno: __uint64_t,
pub oldmask: __uint64_t,
pub cr2: __uint64_t,
pub _bindgen_data_1_: [u64; 1u],
pub __reserved1: [__uint64_t; 8u],
}
impl Struct_sigcontext {
pub unsafe fn fpstate(&mut self) -> *mut *mut Struct__fpstate {
::std::mem::transmute(&self._bindgen_data_1_)
}
pub unsafe fn __fpstate_word(&mut self) -> *mut __uint64_t {
::std::mem::transmute(&self._bindgen_data_1_)
}
}
impl ::std::default::Default for Struct_sigcontext {
fn default() -> Struct_sigcontext { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xsave_hdr {
pub xstate_bv: __uint64_t,
pub reserved1: [__uint64_t; 2u],
pub reserved2: [__uint64_t; 5u],
}
impl ::std::default::Default for Struct__xsave_hdr {
fn default() -> Struct__xsave_hdr { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__ymmh_state {
pub ymmh_space: [__uint32_t; 64u],
}
impl ::std::default::Default for Struct__ymmh_state {
fn default() -> Struct__ymmh_state { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__xstate {
pub fpstate: Struct__fpstate,
pub xstate_hdr: Struct__xsave_hdr,
pub ymmh: Struct__ymmh_state,
}
impl ::std::default::Default for Struct__xstate {
fn default() -> Struct__xstate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigstack {
pub ss_sp: *mut ::libc::c_void,
pub ss_onstack: ::libc::c_int,
}
impl ::std::default::Default for Struct_sigstack {
fn default() -> Struct_sigstack { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed28 = ::libc::c_uint;
pub const SS_ONSTACK: ::libc::c_uint = 1;
pub const SS_DISABLE: ::libc::c_uint = 2;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sigaltstack {
pub ss_sp: *mut ::libc::c_void,
pub ss_flags: ::libc::c_int,
pub ss_size: size_t,
}
impl ::std::default::Default for Struct_sigaltstack {
fn default() -> Struct_sigaltstack { unsafe { ::std::mem::zeroed() } }
}
pub type stack_t = Struct_sigaltstack;
pub type greg_t = ::libc::c_longlong;
pub type gregset_t = [greg_t; 23u];
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_fpxreg {
pub significand: [::libc::c_ushort; 4u],
pub exponent: ::libc::c_ushort,
pub padding: [::libc::c_ushort; 3u],
}
impl ::std::default::Default for Struct__libc_fpxreg {
fn default() -> Struct__libc_fpxreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_xmmreg {
pub element: [__uint32_t; 4u],
}
impl ::std::default::Default for Struct__libc_xmmreg {
fn default() -> Struct__libc_xmmreg { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__libc_fpstate {
pub cwd: __uint16_t,
pub swd: __uint16_t,
pub ftw: __uint16_t,
pub fop: __uint16_t,
pub rip: __uint64_t,
pub rdp: __uint64_t,
pub mxcsr: __uint32_t,
pub mxcr_mask: __uint32_t,
pub _st: [Struct__libc_fpxreg; 8u],
pub _xmm: [Struct__libc_xmmreg; 16u],
pub padding: [__uint32_t; 24u],
}
impl ::std::default::Default for Struct__libc_fpstate {
fn default() -> Struct__libc_fpstate { unsafe { ::std::mem::zeroed() } }
}
pub type fpregset_t = *mut Struct__libc_fpstate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed29 {
pub gregs: gregset_t,
pub fpregs: fpregset_t,
pub __reserved1: [::libc::c_ulonglong; 8u],
}
impl ::std::default::Default for Struct_Unnamed29 {
fn default() -> Struct_Unnamed29 { unsafe { ::std::mem::zeroed() } }
}
pub type mcontext_t = Struct_Unnamed29;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_ucontext {
pub uc_flags: ::libc::c_ulong,
pub uc_link: *mut Struct_ucontext,
pub uc_stack: stack_t,
pub uc_mcontext: mcontext_t,
pub uc_sigmask: __sigset_t,
pub __fpregs_mem: Struct__libc_fpstate,
}
impl ::std::default::Default for Struct_ucontext {
fn default() -> Struct_ucontext { unsafe { ::std::mem::zeroed() } }
}
pub type ucontext_t = Struct_ucontext;
pub type pthread_t = ::libc::c_ulong;
#[repr(C)]
#[derive(Copy)]
pub struct Union_pthread_attr_t {
pub _bindgen_data_: [u64; 7u],
}
impl Union_pthread_attr_t {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 56u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_pthread_attr_t {
fn default() -> Union_pthread_attr_t { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_internal_list {
pub __prev: *mut Struct___pthread_internal_list,
pub __next: *mut Struct___pthread_internal_list,
}
impl ::std::default::Default for Struct___pthread_internal_list {
fn default() -> Struct___pthread_internal_list {
unsafe { ::std::mem::zeroed() }
}
}
pub type __pthread_list_t = Struct___pthread_internal_list;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed30 {
pub _bindgen_data_: [u64; 5u],
}
impl Union_Unnamed30 {
pub unsafe fn __data(&mut self) -> *mut Struct___pthread_mutex_s {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 40u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed30 {
fn default() -> Union_Unnamed30 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_mutex_s {
pub __lock: ::libc::c_int,
pub __count: ::libc::c_uint,
pub __owner: ::libc::c_int,
pub __nusers: ::libc::c_uint,
pub __kind: ::libc::c_int,
pub __spins: ::libc::c_short,
pub __elision: ::libc::c_short,
pub __list: __pthread_list_t,
}
impl ::std::default::Default for Struct___pthread_mutex_s {
fn default() -> Struct___pthread_mutex_s {
unsafe { ::std::mem::zeroed() }
}
}
pub type pthread_mutex_t = Union_Unnamed30;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed31 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed31 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed31 {
fn default() -> Union_Unnamed31 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_mutexattr_t = Union_Unnamed31;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed32 {
pub _bindgen_data_: [u64; 6u],
}
impl Union_Unnamed32 {
pub unsafe fn __data(&mut self) -> *mut Struct_Unnamed33 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 48u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_longlong {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed32 {
fn default() -> Union_Unnamed32 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed33 {
pub __lock: ::libc::c_int,
pub __futex: ::libc::c_uint,
pub __total_seq: ::libc::c_ulonglong,
pub __wakeup_seq: ::libc::c_ulonglong,
pub __woken_seq: ::libc::c_ulonglong,
pub __mutex: *mut ::libc::c_void,
pub __nwaiters: ::libc::c_uint,
pub __broadcast_seq: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed33 {
fn default() -> Struct_Unnamed33 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_cond_t = Union_Unnamed32;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed34 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed34 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed34 {
fn default() -> Union_Unnamed34 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_condattr_t = Union_Unnamed34;
pub type pthread_key_t = ::libc::c_uint;
pub type pthread_once_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed35 {
pub _bindgen_data_: [u64; 7u],
}
impl Union_Unnamed35 {
pub unsafe fn __data(&mut self) -> *mut Struct_Unnamed36 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 56u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed35 {
fn default() -> Union_Unnamed35 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed36 {
pub __lock: ::libc::c_int,
pub __nr_readers: ::libc::c_uint,
pub __readers_wakeup: ::libc::c_uint,
pub __writer_wakeup: ::libc::c_uint,
pub __nr_readers_queued: ::libc::c_uint,
pub __nr_writers_queued: ::libc::c_uint,
pub __writer: ::libc::c_int,
pub __shared: ::libc::c_int,
pub __pad1: ::libc::c_ulong,
pub __pad2: ::libc::c_ulong,
pub __flags: ::libc::c_uint,
}
impl ::std::default::Default for Struct_Unnamed36 {
fn default() -> Struct_Unnamed36 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_rwlock_t = Union_Unnamed35;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed37 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed37 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 8u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed37 {
fn default() -> Union_Unnamed37 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_rwlockattr_t = Union_Unnamed37;
pub type pthread_spinlock_t = ::libc::c_int;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed38 {
pub _bindgen_data_: [u64; 4u],
}
impl Union_Unnamed38 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 32u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_long {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed38 {
fn default() -> Union_Unnamed38 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_barrier_t = Union_Unnamed38;
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed39 {
pub _bindgen_data_: [u32; 1u],
}
impl Union_Unnamed39 {
pub unsafe fn __size(&mut self) -> *mut [::libc::c_char; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn __align(&mut self) -> *mut ::libc::c_int {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed39 {
fn default() -> Union_Unnamed39 { unsafe { ::std::mem::zeroed() } }
}
pub type pthread_barrierattr_t = Union_Unnamed39;
pub type Enum_Unnamed40 = ::libc::c_uint;
pub const G_BOOKMARK_FILE_ERROR_INVALID_URI: ::libc::c_uint = 0;
pub const G_BOOKMARK_FILE_ERROR_INVALID_VALUE: ::libc::c_uint = 1;
pub const G_BOOKMARK_FILE_ERROR_APP_NOT_REGISTERED: ::libc::c_uint = 2;
pub const G_BOOKMARK_FILE_ERROR_URI_NOT_FOUND: ::libc::c_uint = 3;
pub const G_BOOKMARK_FILE_ERROR_READ: ::libc::c_uint = 4;
pub const G_BOOKMARK_FILE_ERROR_UNKNOWN_ENCODING: ::libc::c_uint = 5;
pub const G_BOOKMARK_FILE_ERROR_WRITE: ::libc::c_uint = 6;
pub const G_BOOKMARK_FILE_ERROR_FILE_NOT_FOUND: ::libc::c_uint = 7;
pub type GBookmarkFileError = Enum_Unnamed40;
pub enum Struct__GBookmarkFile { }
pub type GBookmarkFile = Struct__GBookmarkFile;
pub type Enum_Unnamed41 = ::libc::c_uint;
pub const G_CHECKSUM_MD5: ::libc::c_uint = 0;
pub const G_CHECKSUM_SHA1: ::libc::c_uint = 1;
pub const G_CHECKSUM_SHA256: ::libc::c_uint = 2;
pub const G_CHECKSUM_SHA512: ::libc::c_uint = 3;
pub type GChecksumType = Enum_Unnamed41;
pub enum Struct__GChecksum { }
pub type GChecksum = Struct__GChecksum;
pub type Enum_Unnamed42 = ::libc::c_uint;
pub const G_CONVERT_ERROR_NO_CONVERSION: ::libc::c_uint = 0;
pub const G_CONVERT_ERROR_ILLEGAL_SEQUENCE: ::libc::c_uint = 1;
pub const G_CONVERT_ERROR_FAILED: ::libc::c_uint = 2;
pub const G_CONVERT_ERROR_PARTIAL_INPUT: ::libc::c_uint = 3;
pub const G_CONVERT_ERROR_BAD_URI: ::libc::c_uint = 4;
pub const G_CONVERT_ERROR_NOT_ABSOLUTE_PATH: ::libc::c_uint = 5;
pub const G_CONVERT_ERROR_NO_MEMORY: ::libc::c_uint = 6;
pub type GConvertError = Enum_Unnamed42;
pub enum Struct__GIConv { }
pub type GIConv = *mut Struct__GIConv;
pub enum Struct__GData { }
pub type GData = Struct__GData;
pub type GDataForeachFunc =
::std::option::Option<extern "C" fn
(key_id: GQuark, data: gpointer,
user_data: gpointer)>;
pub type GDuplicateFunc =
::std::option::Option<extern "C" fn(data: gpointer, user_data: gpointer)
-> gpointer>;
pub type GTime = gint32;
pub type GDateYear = guint16;
pub type GDateDay = guint8;
pub type GDate = Struct__GDate;
pub type Enum_Unnamed43 = ::libc::c_uint;
pub const G_DATE_DAY: ::libc::c_uint = 0;
pub const G_DATE_MONTH: ::libc::c_uint = 1;
pub const G_DATE_YEAR: ::libc::c_uint = 2;
pub type GDateDMY = Enum_Unnamed43;
pub type Enum_Unnamed44 = ::libc::c_uint;
pub const G_DATE_BAD_WEEKDAY: ::libc::c_uint = 0;
pub const G_DATE_MONDAY: ::libc::c_uint = 1;
pub const G_DATE_TUESDAY: ::libc::c_uint = 2;
pub const G_DATE_WEDNESDAY: ::libc::c_uint = 3;
pub const G_DATE_THURSDAY: ::libc::c_uint = 4;
pub const G_DATE_FRIDAY: ::libc::c_uint = 5;
pub const G_DATE_SATURDAY: ::libc::c_uint = 6;
pub const G_DATE_SUNDAY: ::libc::c_uint = 7;
pub type GDateWeekday = Enum_Unnamed44;
pub type Enum_Unnamed45 = ::libc::c_uint;
pub const G_DATE_BAD_MONTH: ::libc::c_uint = 0;
pub const G_DATE_JANUARY: ::libc::c_uint = 1;
pub const G_DATE_FEBRUARY: ::libc::c_uint = 2;
pub const G_DATE_MARCH: ::libc::c_uint = 3;
pub const G_DATE_APRIL: ::libc::c_uint = 4;
pub const G_DATE_MAY: ::libc::c_uint = 5;
pub const G_DATE_JUNE: ::libc::c_uint = 6;
pub const G_DATE_JULY: ::libc::c_uint = 7;
pub const G_DATE_AUGUST: ::libc::c_uint = 8;
pub const G_DATE_SEPTEMBER: ::libc::c_uint = 9;
pub const G_DATE_OCTOBER: ::libc::c_uint = 10;
pub const G_DATE_NOVEMBER: ::libc::c_uint = 11;
pub const G_DATE_DECEMBER: ::libc::c_uint = 12;
pub type GDateMonth = Enum_Unnamed45;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GDate {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
}
impl ::std::default::Default for Struct__GDate {
fn default() -> Struct__GDate { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTimeZone { }
pub type GTimeZone = Struct__GTimeZone;
pub type Enum_Unnamed46 = ::libc::c_uint;
pub const G_TIME_TYPE_STANDARD: ::libc::c_uint = 0;
pub const G_TIME_TYPE_DAYLIGHT: ::libc::c_uint = 1;
pub const G_TIME_TYPE_UNIVERSAL: ::libc::c_uint = 2;
pub type GTimeType = Enum_Unnamed46;
pub type GTimeSpan = gint64;
pub enum Struct__GDateTime { }
pub type GDateTime = Struct__GDateTime;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_dirent {
pub d_ino: __ino_t,
pub d_off: __off_t,
pub d_reclen: ::libc::c_ushort,
pub d_type: ::libc::c_uchar,
pub d_name: [::libc::c_char; 256u],
}
impl ::std::default::Default for Struct_dirent {
fn default() -> Struct_dirent { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed47 = ::libc::c_uint;
pub const DT_UNKNOWN: ::libc::c_uint = 0;
pub const DT_FIFO: ::libc::c_uint = 1;
pub const DT_CHR: ::libc::c_uint = 2;
pub const DT_DIR: ::libc::c_uint = 4;
pub const DT_BLK: ::libc::c_uint = 6;
pub const DT_REG: ::libc::c_uint = 8;
pub const DT_LNK: ::libc::c_uint = 10;
pub const DT_SOCK: ::libc::c_uint = 12;
pub const DT_WHT: ::libc::c_uint = 14;
pub enum Struct___dirstream { }
pub type DIR = Struct___dirstream;
pub enum Struct__GDir { }
pub type GDir = Struct__GDir;
pub type Enum_Unnamed48 = ::libc::c_uint;
pub const G_FILE_ERROR_EXIST: ::libc::c_uint = 0;
pub const G_FILE_ERROR_ISDIR: ::libc::c_uint = 1;
pub const G_FILE_ERROR_ACCES: ::libc::c_uint = 2;
pub const G_FILE_ERROR_NAMETOOLONG: ::libc::c_uint = 3;
pub const G_FILE_ERROR_NOENT: ::libc::c_uint = 4;
pub const G_FILE_ERROR_NOTDIR: ::libc::c_uint = 5;
pub const G_FILE_ERROR_NXIO: ::libc::c_uint = 6;
pub const G_FILE_ERROR_NODEV: ::libc::c_uint = 7;
pub const G_FILE_ERROR_ROFS: ::libc::c_uint = 8;
pub const G_FILE_ERROR_TXTBSY: ::libc::c_uint = 9;
pub const G_FILE_ERROR_FAULT: ::libc::c_uint = 10;
pub const G_FILE_ERROR_LOOP: ::libc::c_uint = 11;
pub const G_FILE_ERROR_NOSPC: ::libc::c_uint = 12;
pub const G_FILE_ERROR_NOMEM: ::libc::c_uint = 13;
pub const G_FILE_ERROR_MFILE: ::libc::c_uint = 14;
pub const G_FILE_ERROR_NFILE: ::libc::c_uint = 15;
pub const G_FILE_ERROR_BADF: ::libc::c_uint = 16;
pub const G_FILE_ERROR_INVAL: ::libc::c_uint = 17;
pub const G_FILE_ERROR_PIPE: ::libc::c_uint = 18;
pub const G_FILE_ERROR_AGAIN: ::libc::c_uint = 19;
pub const G_FILE_ERROR_INTR: ::libc::c_uint = 20;
pub const G_FILE_ERROR_IO: ::libc::c_uint = 21;
pub const G_FILE_ERROR_PERM: ::libc::c_uint = 22;
pub const G_FILE_ERROR_NOSYS: ::libc::c_uint = 23;
pub const G_FILE_ERROR_FAILED: ::libc::c_uint = 24;
pub type GFileError = Enum_Unnamed48;
pub type Enum_Unnamed49 = ::libc::c_uint;
pub const G_FILE_TEST_IS_REGULAR: ::libc::c_uint = 1;
pub const G_FILE_TEST_IS_SYMLINK: ::libc::c_uint = 2;
pub const G_FILE_TEST_IS_DIR: ::libc::c_uint = 4;
pub const G_FILE_TEST_IS_EXECUTABLE: ::libc::c_uint = 8;
pub const G_FILE_TEST_EXISTS: ::libc::c_uint = 16;
pub type GFileTest = Enum_Unnamed49;
pub type GMemVTable = Struct__GMemVTable;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GMemVTable {
pub malloc: ::std::option::Option<extern "C" fn(n_bytes: gsize)
-> gpointer>,
pub realloc: ::std::option::Option<extern "C" fn
(mem: gpointer, n_bytes: gsize)
-> gpointer>,
pub free: ::std::option::Option<extern "C" fn(mem: gpointer)>,
pub calloc: ::std::option::Option<extern "C" fn
(n_blocks: gsize,
n_block_bytes: gsize) -> gpointer>,
pub try_malloc: ::std::option::Option<extern "C" fn(n_bytes: gsize)
-> gpointer>,
pub try_realloc: ::std::option::Option<extern "C" fn
(mem: gpointer, n_bytes: gsize)
-> gpointer>,
}
impl ::std::default::Default for Struct__GMemVTable {
fn default() -> Struct__GMemVTable { unsafe { ::std::mem::zeroed() } }
}
pub type GNode = Struct__GNode;
pub type Enum_Unnamed50 = ::libc::c_uint;
pub const G_TRAVERSE_LEAVES: ::libc::c_uint = 1;
pub const G_TRAVERSE_NON_LEAVES: ::libc::c_uint = 2;
pub const G_TRAVERSE_ALL: ::libc::c_uint = 3;
pub const G_TRAVERSE_MASK: ::libc::c_uint = 3;
pub const G_TRAVERSE_LEAFS: ::libc::c_uint = 1;
pub const G_TRAVERSE_NON_LEAFS: ::libc::c_uint = 2;
pub type GTraverseFlags = Enum_Unnamed50;
pub type Enum_Unnamed51 = ::libc::c_uint;
pub const G_IN_ORDER: ::libc::c_uint = 0;
pub const G_PRE_ORDER: ::libc::c_uint = 1;
pub const G_POST_ORDER: ::libc::c_uint = 2;
pub const G_LEVEL_ORDER: ::libc::c_uint = 3;
pub type GTraverseType = Enum_Unnamed51;
pub type GNodeTraverseFunc =
::std::option::Option<extern "C" fn(node: *mut GNode, data: gpointer)
-> gboolean>;
pub type GNodeForeachFunc =
::std::option::Option<extern "C" fn(node: *mut GNode, data: gpointer)>;
pub type GCopyFunc =
::std::option::Option<extern "C" fn(src: gconstpointer, data: gpointer)
-> gpointer>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GNode {
pub data: gpointer,
pub next: *mut GNode,
pub prev: *mut GNode,
pub parent: *mut GNode,
pub children: *mut GNode,
}
impl ::std::default::Default for Struct__GNode {
fn default() -> Struct__GNode { unsafe { ::std::mem::zeroed() } }
}
pub type GList = Struct__GList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GList {
pub data: gpointer,
pub next: *mut GList,
pub prev: *mut GList,
}
impl ::std::default::Default for Struct__GList {
fn default() -> Struct__GList { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GHashTable { }
pub type GHashTable = Struct__GHashTable;
pub type GHRFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer,
user_data: gpointer) -> gboolean>;
pub type GHashTableIter = Struct__GHashTableIter;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHashTableIter {
pub dummy1: gpointer,
pub dummy2: gpointer,
pub dummy3: gpointer,
pub dummy4: ::libc::c_int,
pub dummy5: gboolean,
pub dummy6: gpointer,
}
impl ::std::default::Default for Struct__GHashTableIter {
fn default() -> Struct__GHashTableIter { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GHmac { }
pub type GHmac = Struct__GHmac;
pub type GHook = Struct__GHook;
pub type GHookList = Struct__GHookList;
pub type GHookCompareFunc =
::std::option::Option<extern "C" fn
(new_hook: *mut GHook, sibling: *mut GHook)
-> gint>;
pub type GHookFindFunc =
::std::option::Option<extern "C" fn(hook: *mut GHook, data: gpointer)
-> gboolean>;
pub type GHookMarshaller =
::std::option::Option<extern "C" fn
(hook: *mut GHook, marshal_data: gpointer)>;
pub type GHookCheckMarshaller =
::std::option::Option<extern "C" fn
(hook: *mut GHook, marshal_data: gpointer)
-> gboolean>;
pub type GHookFunc = ::std::option::Option<extern "C" fn(data: gpointer)>;
pub type GHookCheckFunc =
::std::option::Option<extern "C" fn(data: gpointer) -> gboolean>;
pub type GHookFinalizeFunc =
::std::option::Option<extern "C" fn
(hook_list: *mut GHookList, hook: *mut GHook)>;
pub type Enum_Unnamed52 = ::libc::c_uint;
pub const G_HOOK_FLAG_ACTIVE: ::libc::c_uint = 1;
pub const G_HOOK_FLAG_IN_CALL: ::libc::c_uint = 2;
pub const G_HOOK_FLAG_MASK: ::libc::c_uint = 15;
pub type GHookFlagMask = Enum_Unnamed52;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHookList {
pub seq_id: gulong,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub hooks: *mut GHook,
pub dummy3: gpointer,
pub finalize_hook: GHookFinalizeFunc,
pub dummy: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GHookList {
fn default() -> Struct__GHookList { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GHook {
pub data: gpointer,
pub next: *mut GHook,
pub prev: *mut GHook,
pub ref_count: guint,
pub hook_id: gulong,
pub flags: guint,
pub func: gpointer,
pub destroy: GDestroyNotify,
}
impl ::std::default::Default for Struct__GHook {
fn default() -> Struct__GHook { unsafe { ::std::mem::zeroed() } }
}
pub type GPollFD = Struct__GPollFD;
pub type GPollFunc =
::std::option::Option<extern "C" fn
(ufds: *mut GPollFD, nfsd: guint,
timeout_: gint) -> gint>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GPollFD {
pub fd: gint,
pub events: gushort,
pub revents: gushort,
}
impl ::std::default::Default for Struct__GPollFD {
fn default() -> Struct__GPollFD { unsafe { ::std::mem::zeroed() } }
}
pub type GSList = Struct__GSList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSList {
pub data: gpointer,
pub next: *mut GSList,
}
impl ::std::default::Default for Struct__GSList {
fn default() -> Struct__GSList { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed53 = ::libc::c_uint;
pub const G_IO_IN: ::libc::c_uint = 1;
pub const G_IO_OUT: ::libc::c_uint = 4;
pub const G_IO_PRI: ::libc::c_uint = 2;
pub const G_IO_ERR: ::libc::c_uint = 8;
pub const G_IO_HUP: ::libc::c_uint = 16;
pub const G_IO_NVAL: ::libc::c_uint = 32;
pub type GIOCondition = Enum_Unnamed53;
pub enum Struct__GMainContext { }
pub type GMainContext = Struct__GMainContext;
pub enum Struct__GMainLoop { }
pub type GMainLoop = Struct__GMainLoop;
pub type GSource = Struct__GSource;
pub enum Struct__GSourcePrivate { }
pub type GSourcePrivate = Struct__GSourcePrivate;
pub type GSourceCallbackFuncs = Struct__GSourceCallbackFuncs;
pub type GSourceFuncs = Struct__GSourceFuncs;
pub type GSourceFunc =
::std::option::Option<extern "C" fn(user_data: gpointer) -> gboolean>;
pub type GChildWatchFunc =
::std::option::Option<extern "C" fn
(pid: GPid, status: gint, user_data: gpointer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSource {
pub callback_data: gpointer,
pub callback_funcs: *mut GSourceCallbackFuncs,
pub source_funcs: *const GSourceFuncs,
pub ref_count: guint,
pub context: *mut GMainContext,
pub priority: gint,
pub flags: guint,
pub source_id: guint,
pub poll_fds: *mut GSList,
pub prev: *mut GSource,
pub next: *mut GSource,
pub name: *mut ::libc::c_char,
pub _priv: *mut GSourcePrivate,
}
impl ::std::default::Default for Struct__GSource {
fn default() -> Struct__GSource { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSourceCallbackFuncs {
pub _ref: ::std::option::Option<extern "C" fn(cb_data: gpointer)>,
pub unref: ::std::option::Option<extern "C" fn(cb_data: gpointer)>,
pub get: ::std::option::Option<extern "C" fn
(cb_data: gpointer,
source: *mut GSource,
func: *mut GSourceFunc,
data: *mut gpointer)>,
}
impl ::std::default::Default for Struct__GSourceCallbackFuncs {
fn default() -> Struct__GSourceCallbackFuncs {
unsafe { ::std::mem::zeroed() }
}
}
pub type GSourceDummyMarshal = ::std::option::Option<extern "C" fn()>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSourceFuncs {
pub prepare: ::std::option::Option<extern "C" fn
(source: *mut GSource,
timeout_: *mut gint) -> gboolean>,
pub check: ::std::option::Option<extern "C" fn(source: *mut GSource)
-> gboolean>,
pub dispatch: ::std::option::Option<extern "C" fn
(source: *mut GSource,
callback: GSourceFunc,
user_data: gpointer)
-> gboolean>,
pub finalize: ::std::option::Option<extern "C" fn(source: *mut GSource)>,
pub closure_callback: GSourceFunc,
pub closure_marshal: GSourceDummyMarshal,
}
impl ::std::default::Default for Struct__GSourceFuncs {
fn default() -> Struct__GSourceFuncs { unsafe { ::std::mem::zeroed() } }
}
pub type gunichar = guint32;
pub type gunichar2 = guint16;
pub type Enum_Unnamed54 = ::libc::c_uint;
pub const G_UNICODE_CONTROL: ::libc::c_uint = 0;
pub const G_UNICODE_FORMAT: ::libc::c_uint = 1;
pub const G_UNICODE_UNASSIGNED: ::libc::c_uint = 2;
pub const G_UNICODE_PRIVATE_USE: ::libc::c_uint = 3;
pub const G_UNICODE_SURROGATE: ::libc::c_uint = 4;
pub const G_UNICODE_LOWERCASE_LETTER: ::libc::c_uint = 5;
pub const G_UNICODE_MODIFIER_LETTER: ::libc::c_uint = 6;
pub const G_UNICODE_OTHER_LETTER: ::libc::c_uint = 7;
pub const G_UNICODE_TITLECASE_LETTER: ::libc::c_uint = 8;
pub const G_UNICODE_UPPERCASE_LETTER: ::libc::c_uint = 9;
pub const G_UNICODE_SPACING_MARK: ::libc::c_uint = 10;
pub const G_UNICODE_ENCLOSING_MARK: ::libc::c_uint = 11;
pub const G_UNICODE_NON_SPACING_MARK: ::libc::c_uint = 12;
pub const G_UNICODE_DECIMAL_NUMBER: ::libc::c_uint = 13;
pub const G_UNICODE_LETTER_NUMBER: ::libc::c_uint = 14;
pub const G_UNICODE_OTHER_NUMBER: ::libc::c_uint = 15;
pub const G_UNICODE_CONNECT_PUNCTUATION: ::libc::c_uint = 16;
pub const G_UNICODE_DASH_PUNCTUATION: ::libc::c_uint = 17;
pub const G_UNICODE_CLOSE_PUNCTUATION: ::libc::c_uint = 18;
pub const G_UNICODE_FINAL_PUNCTUATION: ::libc::c_uint = 19;
pub const G_UNICODE_INITIAL_PUNCTUATION: ::libc::c_uint = 20;
pub const G_UNICODE_OTHER_PUNCTUATION: ::libc::c_uint = 21;
pub const G_UNICODE_OPEN_PUNCTUATION: ::libc::c_uint = 22;
pub const G_UNICODE_CURRENCY_SYMBOL: ::libc::c_uint = 23;
pub const G_UNICODE_MODIFIER_SYMBOL: ::libc::c_uint = 24;
pub const G_UNICODE_MATH_SYMBOL: ::libc::c_uint = 25;
pub const G_UNICODE_OTHER_SYMBOL: ::libc::c_uint = 26;
pub const G_UNICODE_LINE_SEPARATOR: ::libc::c_uint = 27;
pub const G_UNICODE_PARAGRAPH_SEPARATOR: ::libc::c_uint = 28;
pub const G_UNICODE_SPACE_SEPARATOR: ::libc::c_uint = 29;
pub type GUnicodeType = Enum_Unnamed54;
pub type Enum_Unnamed55 = ::libc::c_uint;
pub const G_UNICODE_BREAK_MANDATORY: ::libc::c_uint = 0;
pub const G_UNICODE_BREAK_CARRIAGE_RETURN: ::libc::c_uint = 1;
pub const G_UNICODE_BREAK_LINE_FEED: ::libc::c_uint = 2;
pub const G_UNICODE_BREAK_COMBINING_MARK: ::libc::c_uint = 3;
pub const G_UNICODE_BREAK_SURROGATE: ::libc::c_uint = 4;
pub const G_UNICODE_BREAK_ZERO_WIDTH_SPACE: ::libc::c_uint = 5;
pub const G_UNICODE_BREAK_INSEPARABLE: ::libc::c_uint = 6;
pub const G_UNICODE_BREAK_NON_BREAKING_GLUE: ::libc::c_uint = 7;
pub const G_UNICODE_BREAK_CONTINGENT: ::libc::c_uint = 8;
pub const G_UNICODE_BREAK_SPACE: ::libc::c_uint = 9;
pub const G_UNICODE_BREAK_AFTER: ::libc::c_uint = 10;
pub const G_UNICODE_BREAK_BEFORE: ::libc::c_uint = 11;
pub const G_UNICODE_BREAK_BEFORE_AND_AFTER: ::libc::c_uint = 12;
pub const G_UNICODE_BREAK_HYPHEN: ::libc::c_uint = 13;
pub const G_UNICODE_BREAK_NON_STARTER: ::libc::c_uint = 14;
pub const G_UNICODE_BREAK_OPEN_PUNCTUATION: ::libc::c_uint = 15;
pub const G_UNICODE_BREAK_CLOSE_PUNCTUATION: ::libc::c_uint = 16;
pub const G_UNICODE_BREAK_QUOTATION: ::libc::c_uint = 17;
pub const G_UNICODE_BREAK_EXCLAMATION: ::libc::c_uint = 18;
pub const G_UNICODE_BREAK_IDEOGRAPHIC: ::libc::c_uint = 19;
pub const G_UNICODE_BREAK_NUMERIC: ::libc::c_uint = 20;
pub const G_UNICODE_BREAK_INFIX_SEPARATOR: ::libc::c_uint = 21;
pub const G_UNICODE_BREAK_SYMBOL: ::libc::c_uint = 22;
pub const G_UNICODE_BREAK_ALPHABETIC: ::libc::c_uint = 23;
pub const G_UNICODE_BREAK_PREFIX: ::libc::c_uint = 24;
pub const G_UNICODE_BREAK_POSTFIX: ::libc::c_uint = 25;
pub const G_UNICODE_BREAK_COMPLEX_CONTEXT: ::libc::c_uint = 26;
pub const G_UNICODE_BREAK_AMBIGUOUS: ::libc::c_uint = 27;
pub const G_UNICODE_BREAK_UNKNOWN: ::libc::c_uint = 28;
pub const G_UNICODE_BREAK_NEXT_LINE: ::libc::c_uint = 29;
pub const G_UNICODE_BREAK_WORD_JOINER: ::libc::c_uint = 30;
pub const G_UNICODE_BREAK_HANGUL_L_JAMO: ::libc::c_uint = 31;
pub const G_UNICODE_BREAK_HANGUL_V_JAMO: ::libc::c_uint = 32;
pub const G_UNICODE_BREAK_HANGUL_T_JAMO: ::libc::c_uint = 33;
pub const G_UNICODE_BREAK_HANGUL_LV_SYLLABLE: ::libc::c_uint = 34;
pub const G_UNICODE_BREAK_HANGUL_LVT_SYLLABLE: ::libc::c_uint = 35;
pub const G_UNICODE_BREAK_CLOSE_PARANTHESIS: ::libc::c_uint = 36;
pub const G_UNICODE_BREAK_CONDITIONAL_JAPANESE_STARTER: ::libc::c_uint = 37;
pub const G_UNICODE_BREAK_HEBREW_LETTER: ::libc::c_uint = 38;
pub const G_UNICODE_BREAK_REGIONAL_INDICATOR: ::libc::c_uint = 39;
pub type GUnicodeBreakType = Enum_Unnamed55;
pub type Enum_Unnamed56 = ::libc::c_int;
pub const G_UNICODE_SCRIPT_INVALID_CODE: ::libc::c_int = -1;
pub const G_UNICODE_SCRIPT_COMMON: ::libc::c_int = 0;
pub const G_UNICODE_SCRIPT_INHERITED: ::libc::c_int = 1;
pub const G_UNICODE_SCRIPT_ARABIC: ::libc::c_int = 2;
pub const G_UNICODE_SCRIPT_ARMENIAN: ::libc::c_int = 3;
pub const G_UNICODE_SCRIPT_BENGALI: ::libc::c_int = 4;
pub const G_UNICODE_SCRIPT_BOPOMOFO: ::libc::c_int = 5;
pub const G_UNICODE_SCRIPT_CHEROKEE: ::libc::c_int = 6;
pub const G_UNICODE_SCRIPT_COPTIC: ::libc::c_int = 7;
pub const G_UNICODE_SCRIPT_CYRILLIC: ::libc::c_int = 8;
pub const G_UNICODE_SCRIPT_DESERET: ::libc::c_int = 9;
pub const G_UNICODE_SCRIPT_DEVANAGARI: ::libc::c_int = 10;
pub const G_UNICODE_SCRIPT_ETHIOPIC: ::libc::c_int = 11;
pub const G_UNICODE_SCRIPT_GEORGIAN: ::libc::c_int = 12;
pub const G_UNICODE_SCRIPT_GOTHIC: ::libc::c_int = 13;
pub const G_UNICODE_SCRIPT_GREEK: ::libc::c_int = 14;
pub const G_UNICODE_SCRIPT_GUJARATI: ::libc::c_int = 15;
pub const G_UNICODE_SCRIPT_GURMUKHI: ::libc::c_int = 16;
pub const G_UNICODE_SCRIPT_HAN: ::libc::c_int = 17;
pub const G_UNICODE_SCRIPT_HANGUL: ::libc::c_int = 18;
pub const G_UNICODE_SCRIPT_HEBREW: ::libc::c_int = 19;
pub const G_UNICODE_SCRIPT_HIRAGANA: ::libc::c_int = 20;
pub const G_UNICODE_SCRIPT_KANNADA: ::libc::c_int = 21;
pub const G_UNICODE_SCRIPT_KATAKANA: ::libc::c_int = 22;
pub const G_UNICODE_SCRIPT_KHMER: ::libc::c_int = 23;
pub const G_UNICODE_SCRIPT_LAO: ::libc::c_int = 24;
pub const G_UNICODE_SCRIPT_LATIN: ::libc::c_int = 25;
pub const G_UNICODE_SCRIPT_MALAYALAM: ::libc::c_int = 26;
pub const G_UNICODE_SCRIPT_MONGOLIAN: ::libc::c_int = 27;
pub const G_UNICODE_SCRIPT_MYANMAR: ::libc::c_int = 28;
pub const G_UNICODE_SCRIPT_OGHAM: ::libc::c_int = 29;
pub const G_UNICODE_SCRIPT_OLD_ITALIC: ::libc::c_int = 30;
pub const G_UNICODE_SCRIPT_ORIYA: ::libc::c_int = 31;
pub const G_UNICODE_SCRIPT_RUNIC: ::libc::c_int = 32;
pub const G_UNICODE_SCRIPT_SINHALA: ::libc::c_int = 33;
pub const G_UNICODE_SCRIPT_SYRIAC: ::libc::c_int = 34;
pub const G_UNICODE_SCRIPT_TAMIL: ::libc::c_int = 35;
pub const G_UNICODE_SCRIPT_TELUGU: ::libc::c_int = 36;
pub const G_UNICODE_SCRIPT_THAANA: ::libc::c_int = 37;
pub const G_UNICODE_SCRIPT_THAI: ::libc::c_int = 38;
pub const G_UNICODE_SCRIPT_TIBETAN: ::libc::c_int = 39;
pub const G_UNICODE_SCRIPT_CANADIAN_ABORIGINAL: ::libc::c_int = 40;
pub const G_UNICODE_SCRIPT_YI: ::libc::c_int = 41;
pub const G_UNICODE_SCRIPT_TAGALOG: ::libc::c_int = 42;
pub const G_UNICODE_SCRIPT_HANUNOO: ::libc::c_int = 43;
pub const G_UNICODE_SCRIPT_BUHID: ::libc::c_int = 44;
pub const G_UNICODE_SCRIPT_TAGBANWA: ::libc::c_int = 45;
pub const G_UNICODE_SCRIPT_BRAILLE: ::libc::c_int = 46;
pub const G_UNICODE_SCRIPT_CYPRIOT: ::libc::c_int = 47;
pub const G_UNICODE_SCRIPT_LIMBU: ::libc::c_int = 48;
pub const G_UNICODE_SCRIPT_OSMANYA: ::libc::c_int = 49;
pub const G_UNICODE_SCRIPT_SHAVIAN: ::libc::c_int = 50;
pub const G_UNICODE_SCRIPT_LINEAR_B: ::libc::c_int = 51;
pub const G_UNICODE_SCRIPT_TAI_LE: ::libc::c_int = 52;
pub const G_UNICODE_SCRIPT_UGARITIC: ::libc::c_int = 53;
pub const G_UNICODE_SCRIPT_NEW_TAI_LUE: ::libc::c_int = 54;
pub const G_UNICODE_SCRIPT_BUGINESE: ::libc::c_int = 55;
pub const G_UNICODE_SCRIPT_GLAGOLITIC: ::libc::c_int = 56;
pub const G_UNICODE_SCRIPT_TIFINAGH: ::libc::c_int = 57;
pub const G_UNICODE_SCRIPT_SYLOTI_NAGRI: ::libc::c_int = 58;
pub const G_UNICODE_SCRIPT_OLD_PERSIAN: ::libc::c_int = 59;
pub const G_UNICODE_SCRIPT_KHAROSHTHI: ::libc::c_int = 60;
pub const G_UNICODE_SCRIPT_UNKNOWN: ::libc::c_int = 61;
pub const G_UNICODE_SCRIPT_BALINESE: ::libc::c_int = 62;
pub const G_UNICODE_SCRIPT_CUNEIFORM: ::libc::c_int = 63;
pub const G_UNICODE_SCRIPT_PHOENICIAN: ::libc::c_int = 64;
pub const G_UNICODE_SCRIPT_PHAGS_PA: ::libc::c_int = 65;
pub const G_UNICODE_SCRIPT_NKO: ::libc::c_int = 66;
pub const G_UNICODE_SCRIPT_KAYAH_LI: ::libc::c_int = 67;
pub const G_UNICODE_SCRIPT_LEPCHA: ::libc::c_int = 68;
pub const G_UNICODE_SCRIPT_REJANG: ::libc::c_int = 69;
pub const G_UNICODE_SCRIPT_SUNDANESE: ::libc::c_int = 70;
pub const G_UNICODE_SCRIPT_SAURASHTRA: ::libc::c_int = 71;
pub const G_UNICODE_SCRIPT_CHAM: ::libc::c_int = 72;
pub const G_UNICODE_SCRIPT_OL_CHIKI: ::libc::c_int = 73;
pub const G_UNICODE_SCRIPT_VAI: ::libc::c_int = 74;
pub const G_UNICODE_SCRIPT_CARIAN: ::libc::c_int = 75;
pub const G_UNICODE_SCRIPT_LYCIAN: ::libc::c_int = 76;
pub const G_UNICODE_SCRIPT_LYDIAN: ::libc::c_int = 77;
pub const G_UNICODE_SCRIPT_AVESTAN: ::libc::c_int = 78;
pub const G_UNICODE_SCRIPT_BAMUM: ::libc::c_int = 79;
pub const G_UNICODE_SCRIPT_EGYPTIAN_HIEROGLYPHS: ::libc::c_int = 80;
pub const G_UNICODE_SCRIPT_IMPERIAL_ARAMAIC: ::libc::c_int = 81;
pub const G_UNICODE_SCRIPT_INSCRIPTIONAL_PAHLAVI: ::libc::c_int = 82;
pub const G_UNICODE_SCRIPT_INSCRIPTIONAL_PARTHIAN: ::libc::c_int = 83;
pub const G_UNICODE_SCRIPT_JAVANESE: ::libc::c_int = 84;
pub const G_UNICODE_SCRIPT_KAITHI: ::libc::c_int = 85;
pub const G_UNICODE_SCRIPT_LISU: ::libc::c_int = 86;
pub const G_UNICODE_SCRIPT_MEETEI_MAYEK: ::libc::c_int = 87;
pub const G_UNICODE_SCRIPT_OLD_SOUTH_ARABIAN: ::libc::c_int = 88;
pub const G_UNICODE_SCRIPT_OLD_TURKIC: ::libc::c_int = 89;
pub const G_UNICODE_SCRIPT_SAMARITAN: ::libc::c_int = 90;
pub const G_UNICODE_SCRIPT_TAI_THAM: ::libc::c_int = 91;
pub const G_UNICODE_SCRIPT_TAI_VIET: ::libc::c_int = 92;
pub const G_UNICODE_SCRIPT_BATAK: ::libc::c_int = 93;
pub const G_UNICODE_SCRIPT_BRAHMI: ::libc::c_int = 94;
pub const G_UNICODE_SCRIPT_MANDAIC: ::libc::c_int = 95;
pub const G_UNICODE_SCRIPT_CHAKMA: ::libc::c_int = 96;
pub const G_UNICODE_SCRIPT_MEROITIC_CURSIVE: ::libc::c_int = 97;
pub const G_UNICODE_SCRIPT_MEROITIC_HIEROGLYPHS: ::libc::c_int = 98;
pub const G_UNICODE_SCRIPT_MIAO: ::libc::c_int = 99;
pub const G_UNICODE_SCRIPT_SHARADA: ::libc::c_int = 100;
pub const G_UNICODE_SCRIPT_SORA_SOMPENG: ::libc::c_int = 101;
pub const G_UNICODE_SCRIPT_TAKRI: ::libc::c_int = 102;
pub const G_UNICODE_SCRIPT_BASSA_VAH: ::libc::c_int = 103;
pub const G_UNICODE_SCRIPT_CAUCASIAN_ALBANIAN: ::libc::c_int = 104;
pub const G_UNICODE_SCRIPT_DUPLOYAN: ::libc::c_int = 105;
pub const G_UNICODE_SCRIPT_ELBASAN: ::libc::c_int = 106;
pub const G_UNICODE_SCRIPT_GRANTHA: ::libc::c_int = 107;
pub const G_UNICODE_SCRIPT_KHOJKI: ::libc::c_int = 108;
pub const G_UNICODE_SCRIPT_KHUDAWADI: ::libc::c_int = 109;
pub const G_UNICODE_SCRIPT_LINEAR_A: ::libc::c_int = 110;
pub const G_UNICODE_SCRIPT_MAHAJANI: ::libc::c_int = 111;
pub const G_UNICODE_SCRIPT_MANICHAEAN: ::libc::c_int = 112;
pub const G_UNICODE_SCRIPT_MENDE_KIKAKUI: ::libc::c_int = 113;
pub const G_UNICODE_SCRIPT_MODI: ::libc::c_int = 114;
pub const G_UNICODE_SCRIPT_MRO: ::libc::c_int = 115;
pub const G_UNICODE_SCRIPT_NABATAEAN: ::libc::c_int = 116;
pub const G_UNICODE_SCRIPT_OLD_NORTH_ARABIAN: ::libc::c_int = 117;
pub const G_UNICODE_SCRIPT_OLD_PERMIC: ::libc::c_int = 118;
pub const G_UNICODE_SCRIPT_PAHAWH_HMONG: ::libc::c_int = 119;
pub const G_UNICODE_SCRIPT_PALMYRENE: ::libc::c_int = 120;
pub const G_UNICODE_SCRIPT_PAU_CIN_HAU: ::libc::c_int = 121;
pub const G_UNICODE_SCRIPT_PSALTER_PAHLAVI: ::libc::c_int = 122;
pub const G_UNICODE_SCRIPT_SIDDHAM: ::libc::c_int = 123;
pub const G_UNICODE_SCRIPT_TIRHUTA: ::libc::c_int = 124;
pub const G_UNICODE_SCRIPT_WARANG_CITI: ::libc::c_int = 125;
pub type GUnicodeScript = Enum_Unnamed56;
pub type Enum_Unnamed57 = ::libc::c_uint;
pub const G_NORMALIZE_DEFAULT: ::libc::c_uint = 0;
pub const G_NORMALIZE_NFD: ::libc::c_uint = 0;
pub const G_NORMALIZE_DEFAULT_COMPOSE: ::libc::c_uint = 1;
pub const G_NORMALIZE_NFC: ::libc::c_uint = 1;
pub const G_NORMALIZE_ALL: ::libc::c_uint = 2;
pub const G_NORMALIZE_NFKD: ::libc::c_uint = 2;
pub const G_NORMALIZE_ALL_COMPOSE: ::libc::c_uint = 3;
pub const G_NORMALIZE_NFKC: ::libc::c_uint = 3;
pub type GNormalizeMode = Enum_Unnamed57;
pub type Enum_Unnamed58 = ::libc::c_uint;
pub const G_USER_DIRECTORY_DESKTOP: ::libc::c_uint = 0;
pub const G_USER_DIRECTORY_DOCUMENTS: ::libc::c_uint = 1;
pub const G_USER_DIRECTORY_DOWNLOAD: ::libc::c_uint = 2;
pub const G_USER_DIRECTORY_MUSIC: ::libc::c_uint = 3;
pub const G_USER_DIRECTORY_PICTURES: ::libc::c_uint = 4;
pub const G_USER_DIRECTORY_PUBLIC_SHARE: ::libc::c_uint = 5;
pub const G_USER_DIRECTORY_TEMPLATES: ::libc::c_uint = 6;
pub const G_USER_DIRECTORY_VIDEOS: ::libc::c_uint = 7;
pub const G_USER_N_DIRECTORIES: ::libc::c_uint = 8;
pub type GUserDirectory = Enum_Unnamed58;
pub type GDebugKey = Struct__GDebugKey;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GDebugKey {
pub key: *const gchar,
pub value: guint,
}
impl ::std::default::Default for Struct__GDebugKey {
fn default() -> Struct__GDebugKey { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed59 = ::libc::c_uint;
pub const G_FORMAT_SIZE_DEFAULT: ::libc::c_uint = 0;
pub const G_FORMAT_SIZE_LONG_FORMAT: ::libc::c_uint = 1;
pub const G_FORMAT_SIZE_IEC_UNITS: ::libc::c_uint = 2;
pub type GFormatSizeFlags = Enum_Unnamed59;
pub type GVoidFunc = ::std::option::Option<extern "C" fn()>;
pub type GString = Struct__GString;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GString {
pub _str: *mut gchar,
pub len: gsize,
pub allocated_len: gsize,
}
impl ::std::default::Default for Struct__GString {
fn default() -> Struct__GString { unsafe { ::std::mem::zeroed() } }
}
pub type GIOChannel = Struct__GIOChannel;
pub type GIOFuncs = Struct__GIOFuncs;
pub type Enum_Unnamed60 = ::libc::c_uint;
pub const G_IO_ERROR_NONE: ::libc::c_uint = 0;
pub const G_IO_ERROR_AGAIN: ::libc::c_uint = 1;
pub const G_IO_ERROR_INVAL: ::libc::c_uint = 2;
pub const G_IO_ERROR_UNKNOWN: ::libc::c_uint = 3;
pub type GIOError = Enum_Unnamed60;
pub type Enum_Unnamed61 = ::libc::c_uint;
pub const G_IO_CHANNEL_ERROR_FBIG: ::libc::c_uint = 0;
pub const G_IO_CHANNEL_ERROR_INVAL: ::libc::c_uint = 1;
pub const G_IO_CHANNEL_ERROR_IO: ::libc::c_uint = 2;
pub const G_IO_CHANNEL_ERROR_ISDIR: ::libc::c_uint = 3;
pub const G_IO_CHANNEL_ERROR_NOSPC: ::libc::c_uint = 4;
pub const G_IO_CHANNEL_ERROR_NXIO: ::libc::c_uint = 5;
pub const G_IO_CHANNEL_ERROR_OVERFLOW: ::libc::c_uint = 6;
pub const G_IO_CHANNEL_ERROR_PIPE: ::libc::c_uint = 7;
pub const G_IO_CHANNEL_ERROR_FAILED: ::libc::c_uint = 8;
pub type GIOChannelError = Enum_Unnamed61;
pub type Enum_Unnamed62 = ::libc::c_uint;
pub const G_IO_STATUS_ERROR: ::libc::c_uint = 0;
pub const G_IO_STATUS_NORMAL: ::libc::c_uint = 1;
pub const G_IO_STATUS_EOF: ::libc::c_uint = 2;
pub const G_IO_STATUS_AGAIN: ::libc::c_uint = 3;
pub type GIOStatus = Enum_Unnamed62;
pub type Enum_Unnamed63 = ::libc::c_uint;
pub const G_SEEK_CUR: ::libc::c_uint = 0;
pub const G_SEEK_SET: ::libc::c_uint = 1;
pub const G_SEEK_END: ::libc::c_uint = 2;
pub type GSeekType = Enum_Unnamed63;
pub type Enum_Unnamed64 = ::libc::c_uint;
pub const G_IO_FLAG_APPEND: ::libc::c_uint = 1;
pub const G_IO_FLAG_NONBLOCK: ::libc::c_uint = 2;
pub const G_IO_FLAG_IS_READABLE: ::libc::c_uint = 4;
pub const G_IO_FLAG_IS_WRITABLE: ::libc::c_uint = 8;
pub const G_IO_FLAG_IS_WRITEABLE: ::libc::c_uint = 8;
pub const G_IO_FLAG_IS_SEEKABLE: ::libc::c_uint = 16;
pub const G_IO_FLAG_MASK: ::libc::c_uint = 31;
pub const G_IO_FLAG_GET_MASK: ::libc::c_uint = 31;
pub const G_IO_FLAG_SET_MASK: ::libc::c_uint = 3;
pub type GIOFlags = Enum_Unnamed64;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GIOChannel {
pub ref_count: gint,
pub funcs: *mut GIOFuncs,
pub encoding: *mut gchar,
pub read_cd: GIConv,
pub write_cd: GIConv,
pub line_term: *mut gchar,
pub line_term_len: guint,
pub buf_size: gsize,
pub read_buf: *mut GString,
pub encoded_read_buf: *mut GString,
pub write_buf: *mut GString,
pub partial_write_buf: [gchar; 6u],
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub reserved1: gpointer,
pub reserved2: gpointer,
}
impl ::std::default::Default for Struct__GIOChannel {
fn default() -> Struct__GIOChannel { unsafe { ::std::mem::zeroed() } }
}
pub type GIOFunc =
::std::option::Option<extern "C" fn
(source: *mut GIOChannel,
condition: GIOCondition, data: gpointer)
-> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GIOFuncs {
pub io_read: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
buf: *mut gchar, count: gsize,
bytes_read: *mut gsize,
err: *mut *mut GError)
-> GIOStatus>,
pub io_write: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
buf: *const gchar, count: gsize,
bytes_written: *mut gsize,
err: *mut *mut GError)
-> GIOStatus>,
pub io_seek: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
offset: gint64, _type: GSeekType,
err: *mut *mut GError)
-> GIOStatus>,
pub io_close: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
err: *mut *mut GError)
-> GIOStatus>,
pub io_create_watch: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
condition: GIOCondition)
-> *mut GSource>,
pub io_free: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel)>,
pub io_set_flags: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel,
flags: GIOFlags,
err: *mut *mut GError)
-> GIOStatus>,
pub io_get_flags: ::std::option::Option<extern "C" fn
(channel: *mut GIOChannel)
-> GIOFlags>,
}
impl ::std::default::Default for Struct__GIOFuncs {
fn default() -> Struct__GIOFuncs { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed65 = ::libc::c_uint;
pub const G_KEY_FILE_ERROR_UNKNOWN_ENCODING: ::libc::c_uint = 0;
pub const G_KEY_FILE_ERROR_PARSE: ::libc::c_uint = 1;
pub const G_KEY_FILE_ERROR_NOT_FOUND: ::libc::c_uint = 2;
pub const G_KEY_FILE_ERROR_KEY_NOT_FOUND: ::libc::c_uint = 3;
pub const G_KEY_FILE_ERROR_GROUP_NOT_FOUND: ::libc::c_uint = 4;
pub const G_KEY_FILE_ERROR_INVALID_VALUE: ::libc::c_uint = 5;
pub type GKeyFileError = Enum_Unnamed65;
pub enum Struct__GKeyFile { }
pub type GKeyFile = Struct__GKeyFile;
pub type Enum_Unnamed66 = ::libc::c_uint;
pub const G_KEY_FILE_NONE: ::libc::c_uint = 0;
pub const G_KEY_FILE_KEEP_COMMENTS: ::libc::c_uint = 1;
pub const G_KEY_FILE_KEEP_TRANSLATIONS: ::libc::c_uint = 2;
pub type GKeyFileFlags = Enum_Unnamed66;
pub enum Struct__GMappedFile { }
pub type GMappedFile = Struct__GMappedFile;
pub type Enum_Unnamed67 = ::libc::c_uint;
pub const G_MARKUP_ERROR_BAD_UTF8: ::libc::c_uint = 0;
pub const G_MARKUP_ERROR_EMPTY: ::libc::c_uint = 1;
pub const G_MARKUP_ERROR_PARSE: ::libc::c_uint = 2;
pub const G_MARKUP_ERROR_UNKNOWN_ELEMENT: ::libc::c_uint = 3;
pub const G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE: ::libc::c_uint = 4;
pub const G_MARKUP_ERROR_INVALID_CONTENT: ::libc::c_uint = 5;
pub const G_MARKUP_ERROR_MISSING_ATTRIBUTE: ::libc::c_uint = 6;
pub type GMarkupError = Enum_Unnamed67;
pub type Enum_Unnamed68 = ::libc::c_uint;
pub const G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG: ::libc::c_uint = 1;
pub const G_MARKUP_TREAT_CDATA_AS_TEXT: ::libc::c_uint = 2;
pub const G_MARKUP_PREFIX_ERROR_POSITION: ::libc::c_uint = 4;
pub const G_MARKUP_IGNORE_QUALIFIED: ::libc::c_uint = 8;
pub type GMarkupParseFlags = Enum_Unnamed68;
pub enum Struct__GMarkupParseContext { }
pub type GMarkupParseContext = Struct__GMarkupParseContext;
pub type GMarkupParser = Struct__GMarkupParser;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GMarkupParser {
pub start_element: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
element_name: *const gchar,
attribute_names:
*mut *const gchar,
attribute_values:
*mut *const gchar,
user_data: gpointer,
error: *mut *mut GError)>,
pub end_element: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
element_name: *const gchar,
user_data: gpointer,
error: *mut *mut GError)>,
pub text: ::std::option::Option<extern "C" fn
(context: *mut GMarkupParseContext,
text: *const gchar, text_len: gsize,
user_data: gpointer,
error: *mut *mut GError)>,
pub passthrough: ::std::option::Option<extern "C" fn
(context:
*mut GMarkupParseContext,
passthrough_text:
*const gchar,
text_len: gsize,
user_data: gpointer,
error: *mut *mut GError)>,
pub error: ::std::option::Option<extern "C" fn
(context: *mut GMarkupParseContext,
error: *mut GError,
user_data: gpointer)>,
}
impl ::std::default::Default for Struct__GMarkupParser {
fn default() -> Struct__GMarkupParser { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed69 = ::libc::c_uint;
pub const G_MARKUP_COLLECT_INVALID: ::libc::c_uint = 0;
pub const G_MARKUP_COLLECT_STRING: ::libc::c_uint = 1;
pub const G_MARKUP_COLLECT_STRDUP: ::libc::c_uint = 2;
pub const G_MARKUP_COLLECT_BOOLEAN: ::libc::c_uint = 3;
pub const G_MARKUP_COLLECT_TRISTATE: ::libc::c_uint = 4;
pub const G_MARKUP_COLLECT_OPTIONAL: ::libc::c_uint = 65536;
pub type GMarkupCollectType = Enum_Unnamed69;
pub type Enum_Unnamed70 = ::libc::c_int;
pub const G_LOG_FLAG_RECURSION: ::libc::c_int = 1;
pub const G_LOG_FLAG_FATAL: ::libc::c_int = 2;
pub const G_LOG_LEVEL_ERROR: ::libc::c_int = 4;
pub const G_LOG_LEVEL_CRITICAL: ::libc::c_int = 8;
pub const G_LOG_LEVEL_WARNING: ::libc::c_int = 16;
pub const G_LOG_LEVEL_MESSAGE: ::libc::c_int = 32;
pub const G_LOG_LEVEL_INFO: ::libc::c_int = 64;
pub const G_LOG_LEVEL_DEBUG: ::libc::c_int = 128;
pub const G_LOG_LEVEL_MASK: ::libc::c_int = -4;
pub type GLogLevelFlags = Enum_Unnamed70;
pub type GLogFunc =
::std::option::Option<extern "C" fn
(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar, user_data: gpointer)>;
pub type GPrintFunc =
::std::option::Option<extern "C" fn(string: *const gchar)>;
pub enum Struct__GOptionContext { }
pub type GOptionContext = Struct__GOptionContext;
pub enum Struct__GOptionGroup { }
pub type GOptionGroup = Struct__GOptionGroup;
pub type GOptionEntry = Struct__GOptionEntry;
pub type Enum_Unnamed71 = ::libc::c_uint;
pub const G_OPTION_FLAG_NONE: ::libc::c_uint = 0;
pub const G_OPTION_FLAG_HIDDEN: ::libc::c_uint = 1;
pub const G_OPTION_FLAG_IN_MAIN: ::libc::c_uint = 2;
pub const G_OPTION_FLAG_REVERSE: ::libc::c_uint = 4;
pub const G_OPTION_FLAG_NO_ARG: ::libc::c_uint = 8;
pub const G_OPTION_FLAG_FILENAME: ::libc::c_uint = 16;
pub const G_OPTION_FLAG_OPTIONAL_ARG: ::libc::c_uint = 32;
pub const G_OPTION_FLAG_NOALIAS: ::libc::c_uint = 64;
pub type GOptionFlags = Enum_Unnamed71;
pub type Enum_Unnamed72 = ::libc::c_uint;
pub const G_OPTION_ARG_NONE: ::libc::c_uint = 0;
pub const G_OPTION_ARG_STRING: ::libc::c_uint = 1;
pub const G_OPTION_ARG_INT: ::libc::c_uint = 2;
pub const G_OPTION_ARG_CALLBACK: ::libc::c_uint = 3;
pub const G_OPTION_ARG_FILENAME: ::libc::c_uint = 4;
pub const G_OPTION_ARG_STRING_ARRAY: ::libc::c_uint = 5;
pub const G_OPTION_ARG_FILENAME_ARRAY: ::libc::c_uint = 6;
pub const G_OPTION_ARG_DOUBLE: ::libc::c_uint = 7;
pub const G_OPTION_ARG_INT64: ::libc::c_uint = 8;
pub type GOptionArg = Enum_Unnamed72;
pub type GOptionArgFunc =
::std::option::Option<extern "C" fn
(option_name: *const gchar, value: *const gchar,
data: gpointer, error: *mut *mut GError)
-> gboolean>;
pub type GOptionParseFunc =
::std::option::Option<extern "C" fn
(context: *mut GOptionContext,
group: *mut GOptionGroup, data: gpointer,
error: *mut *mut GError) -> gboolean>;
pub type GOptionErrorFunc =
::std::option::Option<extern "C" fn
(context: *mut GOptionContext,
group: *mut GOptionGroup, data: gpointer,
error: *mut *mut GError)>;
pub type Enum_Unnamed73 = ::libc::c_uint;
pub const G_OPTION_ERROR_UNKNOWN_OPTION: ::libc::c_uint = 0;
pub const G_OPTION_ERROR_BAD_VALUE: ::libc::c_uint = 1;
pub const G_OPTION_ERROR_FAILED: ::libc::c_uint = 2;
pub type GOptionError = Enum_Unnamed73;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GOptionEntry {
pub long_name: *const gchar,
pub short_name: gchar,
pub flags: gint,
pub arg: GOptionArg,
pub arg_data: gpointer,
pub description: *const gchar,
pub arg_description: *const gchar,
}
impl ::std::default::Default for Struct__GOptionEntry {
fn default() -> Struct__GOptionEntry { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GPatternSpec { }
pub type GPatternSpec = Struct__GPatternSpec;
pub type GQueue = Struct__GQueue;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GQueue {
pub head: *mut GList,
pub tail: *mut GList,
pub length: guint,
}
impl ::std::default::Default for Struct__GQueue {
fn default() -> Struct__GQueue { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GRand { }
pub type GRand = Struct__GRand;
pub type Enum_Unnamed74 = ::libc::c_uint;
pub const G_REGEX_ERROR_COMPILE: ::libc::c_uint = 0;
pub const G_REGEX_ERROR_OPTIMIZE: ::libc::c_uint = 1;
pub const G_REGEX_ERROR_REPLACE: ::libc::c_uint = 2;
pub const G_REGEX_ERROR_MATCH: ::libc::c_uint = 3;
pub const G_REGEX_ERROR_INTERNAL: ::libc::c_uint = 4;
pub const G_REGEX_ERROR_STRAY_BACKSLASH: ::libc::c_uint = 101;
pub const G_REGEX_ERROR_MISSING_CONTROL_CHAR: ::libc::c_uint = 102;
pub const G_REGEX_ERROR_UNRECOGNIZED_ESCAPE: ::libc::c_uint = 103;
pub const G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER: ::libc::c_uint = 104;
pub const G_REGEX_ERROR_QUANTIFIER_TOO_BIG: ::libc::c_uint = 105;
pub const G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS: ::libc::c_uint = 106;
pub const G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS: ::libc::c_uint =
107;
pub const G_REGEX_ERROR_RANGE_OUT_OF_ORDER: ::libc::c_uint = 108;
pub const G_REGEX_ERROR_NOTHING_TO_REPEAT: ::libc::c_uint = 109;
pub const G_REGEX_ERROR_UNRECOGNIZED_CHARACTER: ::libc::c_uint = 112;
pub const G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS: ::libc::c_uint = 113;
pub const G_REGEX_ERROR_UNMATCHED_PARENTHESIS: ::libc::c_uint = 114;
pub const G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE: ::libc::c_uint = 115;
pub const G_REGEX_ERROR_UNTERMINATED_COMMENT: ::libc::c_uint = 118;
pub const G_REGEX_ERROR_EXPRESSION_TOO_LARGE: ::libc::c_uint = 120;
pub const G_REGEX_ERROR_MEMORY_ERROR: ::libc::c_uint = 121;
pub const G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND: ::libc::c_uint = 125;
pub const G_REGEX_ERROR_MALFORMED_CONDITION: ::libc::c_uint = 126;
pub const G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES: ::libc::c_uint = 127;
pub const G_REGEX_ERROR_ASSERTION_EXPECTED: ::libc::c_uint = 128;
pub const G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME: ::libc::c_uint = 130;
pub const G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED: ::libc::c_uint
=
131;
pub const G_REGEX_ERROR_HEX_CODE_TOO_LARGE: ::libc::c_uint = 134;
pub const G_REGEX_ERROR_INVALID_CONDITION: ::libc::c_uint = 135;
pub const G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND: ::libc::c_uint = 136;
pub const G_REGEX_ERROR_INFINITE_LOOP: ::libc::c_uint = 140;
pub const G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR: ::libc::c_uint =
142;
pub const G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME: ::libc::c_uint = 143;
pub const G_REGEX_ERROR_MALFORMED_PROPERTY: ::libc::c_uint = 146;
pub const G_REGEX_ERROR_UNKNOWN_PROPERTY: ::libc::c_uint = 147;
pub const G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG: ::libc::c_uint = 148;
pub const G_REGEX_ERROR_TOO_MANY_SUBPATTERNS: ::libc::c_uint = 149;
pub const G_REGEX_ERROR_INVALID_OCTAL_VALUE: ::libc::c_uint = 151;
pub const G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE: ::libc::c_uint = 154;
pub const G_REGEX_ERROR_DEFINE_REPETION: ::libc::c_uint = 155;
pub const G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS: ::libc::c_uint = 156;
pub const G_REGEX_ERROR_MISSING_BACK_REFERENCE: ::libc::c_uint = 157;
pub const G_REGEX_ERROR_INVALID_RELATIVE_REFERENCE: ::libc::c_uint = 158;
pub const G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN:
::libc::c_uint =
159;
pub const G_REGEX_ERROR_UNKNOWN_BACKTRACKING_CONTROL_VERB: ::libc::c_uint =
160;
pub const G_REGEX_ERROR_NUMBER_TOO_BIG: ::libc::c_uint = 161;
pub const G_REGEX_ERROR_MISSING_SUBPATTERN_NAME: ::libc::c_uint = 162;
pub const G_REGEX_ERROR_MISSING_DIGIT: ::libc::c_uint = 163;
pub const G_REGEX_ERROR_INVALID_DATA_CHARACTER: ::libc::c_uint = 164;
pub const G_REGEX_ERROR_EXTRA_SUBPATTERN_NAME: ::libc::c_uint = 165;
pub const G_REGEX_ERROR_BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED:
::libc::c_uint =
166;
pub const G_REGEX_ERROR_INVALID_CONTROL_CHAR: ::libc::c_uint = 168;
pub const G_REGEX_ERROR_MISSING_NAME: ::libc::c_uint = 169;
pub const G_REGEX_ERROR_NOT_SUPPORTED_IN_CLASS: ::libc::c_uint = 171;
pub const G_REGEX_ERROR_TOO_MANY_FORWARD_REFERENCES: ::libc::c_uint = 172;
pub const G_REGEX_ERROR_NAME_TOO_LONG: ::libc::c_uint = 175;
pub const G_REGEX_ERROR_CHARACTER_VALUE_TOO_LARGE: ::libc::c_uint = 176;
pub type GRegexError = Enum_Unnamed74;
pub type Enum_Unnamed75 = ::libc::c_uint;
pub const G_REGEX_CASELESS: ::libc::c_uint = 1;
pub const G_REGEX_MULTILINE: ::libc::c_uint = 2;
pub const G_REGEX_DOTALL: ::libc::c_uint = 4;
pub const G_REGEX_EXTENDED: ::libc::c_uint = 8;
pub const G_REGEX_ANCHORED: ::libc::c_uint = 16;
pub const G_REGEX_DOLLAR_ENDONLY: ::libc::c_uint = 32;
pub const G_REGEX_UNGREEDY: ::libc::c_uint = 512;
pub const G_REGEX_RAW: ::libc::c_uint = 2048;
pub const G_REGEX_NO_AUTO_CAPTURE: ::libc::c_uint = 4096;
pub const G_REGEX_OPTIMIZE: ::libc::c_uint = 8192;
pub const G_REGEX_FIRSTLINE: ::libc::c_uint = 262144;
pub const G_REGEX_DUPNAMES: ::libc::c_uint = 524288;
pub const G_REGEX_NEWLINE_CR: ::libc::c_uint = 1048576;
pub const G_REGEX_NEWLINE_LF: ::libc::c_uint = 2097152;
pub const G_REGEX_NEWLINE_CRLF: ::libc::c_uint = 3145728;
pub const G_REGEX_NEWLINE_ANYCRLF: ::libc::c_uint = 5242880;
pub const G_REGEX_BSR_ANYCRLF: ::libc::c_uint = 8388608;
pub const G_REGEX_JAVASCRIPT_COMPAT: ::libc::c_uint = 33554432;
pub type GRegexCompileFlags = Enum_Unnamed75;
pub type Enum_Unnamed76 = ::libc::c_uint;
pub const G_REGEX_MATCH_ANCHORED: ::libc::c_uint = 16;
pub const G_REGEX_MATCH_NOTBOL: ::libc::c_uint = 128;
pub const G_REGEX_MATCH_NOTEOL: ::libc::c_uint = 256;
pub const G_REGEX_MATCH_NOTEMPTY: ::libc::c_uint = 1024;
pub const G_REGEX_MATCH_PARTIAL: ::libc::c_uint = 32768;
pub const G_REGEX_MATCH_NEWLINE_CR: ::libc::c_uint = 1048576;
pub const G_REGEX_MATCH_NEWLINE_LF: ::libc::c_uint = 2097152;
pub const G_REGEX_MATCH_NEWLINE_CRLF: ::libc::c_uint = 3145728;
pub const G_REGEX_MATCH_NEWLINE_ANY: ::libc::c_uint = 4194304;
pub const G_REGEX_MATCH_NEWLINE_ANYCRLF: ::libc::c_uint = 5242880;
pub const G_REGEX_MATCH_BSR_ANYCRLF: ::libc::c_uint = 8388608;
pub const G_REGEX_MATCH_BSR_ANY: ::libc::c_uint = 16777216;
pub const G_REGEX_MATCH_PARTIAL_SOFT: ::libc::c_uint = 32768;
pub const G_REGEX_MATCH_PARTIAL_HARD: ::libc::c_uint = 134217728;
pub const G_REGEX_MATCH_NOTEMPTY_ATSTART: ::libc::c_uint = 268435456;
pub type GRegexMatchFlags = Enum_Unnamed76;
pub enum Struct__GRegex { }
pub type GRegex = Struct__GRegex;
pub enum Struct__GMatchInfo { }
pub type GMatchInfo = Struct__GMatchInfo;
pub type GRegexEvalCallback =
::std::option::Option<extern "C" fn
(match_info: *const GMatchInfo,
result: *mut GString, user_data: gpointer)
-> gboolean>;
pub type GScanner = Struct__GScanner;
pub type GScannerConfig = Struct__GScannerConfig;
pub type GTokenValue = Union__GTokenValue;
pub type GScannerMsgFunc =
::std::option::Option<extern "C" fn
(scanner: *mut GScanner, message: *mut gchar,
error: gboolean)>;
pub type Enum_Unnamed77 = ::libc::c_uint;
pub const G_ERR_UNKNOWN: ::libc::c_uint = 0;
pub const G_ERR_UNEXP_EOF: ::libc::c_uint = 1;
pub const G_ERR_UNEXP_EOF_IN_STRING: ::libc::c_uint = 2;
pub const G_ERR_UNEXP_EOF_IN_COMMENT: ::libc::c_uint = 3;
pub const G_ERR_NON_DIGIT_IN_CONST: ::libc::c_uint = 4;
pub const G_ERR_DIGIT_RADIX: ::libc::c_uint = 5;
pub const G_ERR_FLOAT_RADIX: ::libc::c_uint = 6;
pub const G_ERR_FLOAT_MALFORMED: ::libc::c_uint = 7;
pub type GErrorType = Enum_Unnamed77;
pub type Enum_Unnamed78 = ::libc::c_uint;
pub const G_TOKEN_EOF: ::libc::c_uint = 0;
pub const G_TOKEN_LEFT_PAREN: ::libc::c_uint = 40;
pub const G_TOKEN_RIGHT_PAREN: ::libc::c_uint = 41;
pub const G_TOKEN_LEFT_CURLY: ::libc::c_uint = 123;
pub const G_TOKEN_RIGHT_CURLY: ::libc::c_uint = 125;
pub const G_TOKEN_LEFT_BRACE: ::libc::c_uint = 91;
pub const G_TOKEN_RIGHT_BRACE: ::libc::c_uint = 93;
pub const G_TOKEN_EQUAL_SIGN: ::libc::c_uint = 61;
pub const G_TOKEN_COMMA: ::libc::c_uint = 44;
pub const G_TOKEN_NONE: ::libc::c_uint = 256;
pub const G_TOKEN_ERROR: ::libc::c_uint = 257;
pub const G_TOKEN_CHAR: ::libc::c_uint = 258;
pub const G_TOKEN_BINARY: ::libc::c_uint = 259;
pub const G_TOKEN_OCTAL: ::libc::c_uint = 260;
pub const G_TOKEN_INT: ::libc::c_uint = 261;
pub const G_TOKEN_HEX: ::libc::c_uint = 262;
pub const G_TOKEN_FLOAT: ::libc::c_uint = 263;
pub const G_TOKEN_STRING: ::libc::c_uint = 264;
pub const G_TOKEN_SYMBOL: ::libc::c_uint = 265;
pub const G_TOKEN_IDENTIFIER: ::libc::c_uint = 266;
pub const G_TOKEN_IDENTIFIER_NULL: ::libc::c_uint = 267;
pub const G_TOKEN_COMMENT_SINGLE: ::libc::c_uint = 268;
pub const G_TOKEN_COMMENT_MULTI: ::libc::c_uint = 269;
pub const G_TOKEN_LAST: ::libc::c_uint = 270;
pub type GTokenType = Enum_Unnamed78;
#[repr(C)]
#[derive(Copy)]
pub struct Union__GTokenValue {
pub _bindgen_data_: [u64; 1u],
}
impl Union__GTokenValue {
pub unsafe fn v_symbol(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_identifier(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_binary(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_octal(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int64(&mut self) -> *mut guint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_float(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_hex(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_string(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_comment(&mut self) -> *mut *mut gchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_char(&mut self) -> *mut guchar {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_error(&mut self) -> *mut guint {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union__GTokenValue {
fn default() -> Union__GTokenValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GScannerConfig {
pub cset_skip_characters: *mut gchar,
pub cset_identifier_first: *mut gchar,
pub cset_identifier_nth: *mut gchar,
pub cpair_comment_single: *mut gchar,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub _bindgen_bitfield_7_: guint,
pub _bindgen_bitfield_8_: guint,
pub _bindgen_bitfield_9_: guint,
pub _bindgen_bitfield_10_: guint,
pub _bindgen_bitfield_11_: guint,
pub _bindgen_bitfield_12_: guint,
pub _bindgen_bitfield_13_: guint,
pub _bindgen_bitfield_14_: guint,
pub _bindgen_bitfield_15_: guint,
pub _bindgen_bitfield_16_: guint,
pub _bindgen_bitfield_17_: guint,
pub _bindgen_bitfield_18_: guint,
pub _bindgen_bitfield_19_: guint,
pub _bindgen_bitfield_20_: guint,
pub _bindgen_bitfield_21_: guint,
pub _bindgen_bitfield_22_: guint,
pub padding_dummy: guint,
}
impl ::std::default::Default for Struct__GScannerConfig {
fn default() -> Struct__GScannerConfig { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GScanner {
pub user_data: gpointer,
pub max_parse_errors: guint,
pub parse_errors: guint,
pub input_name: *const gchar,
pub qdata: *mut GData,
pub config: *mut GScannerConfig,
pub token: GTokenType,
pub value: GTokenValue,
pub line: guint,
pub position: guint,
pub next_token: GTokenType,
pub next_value: GTokenValue,
pub next_line: guint,
pub next_position: guint,
pub symbol_table: *mut GHashTable,
pub input_fd: gint,
pub text: *const gchar,
pub text_end: *const gchar,
pub buffer: *mut gchar,
pub scope_id: guint,
pub msg_handler: GScannerMsgFunc,
}
impl ::std::default::Default for Struct__GScanner {
fn default() -> Struct__GScanner { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GSequence { }
pub type GSequence = Struct__GSequence;
pub enum Struct__GSequenceNode { }
pub type GSequenceIter = Struct__GSequenceNode;
pub type GSequenceIterCompareFunc =
::std::option::Option<extern "C" fn
(a: *mut GSequenceIter, b: *mut GSequenceIter,
data: gpointer) -> gint>;
pub type Enum_Unnamed79 = ::libc::c_uint;
pub const G_SHELL_ERROR_BAD_QUOTING: ::libc::c_uint = 0;
pub const G_SHELL_ERROR_EMPTY_STRING: ::libc::c_uint = 1;
pub const G_SHELL_ERROR_FAILED: ::libc::c_uint = 2;
pub type GShellError = Enum_Unnamed79;
pub type Enum_Unnamed80 = ::libc::c_uint;
pub const G_SLICE_CONFIG_ALWAYS_MALLOC: ::libc::c_uint = 1;
pub const G_SLICE_CONFIG_BYPASS_MAGAZINES: ::libc::c_uint = 2;
pub const G_SLICE_CONFIG_WORKING_SET_MSECS: ::libc::c_uint = 3;
pub const G_SLICE_CONFIG_COLOR_INCREMENT: ::libc::c_uint = 4;
pub const G_SLICE_CONFIG_CHUNK_SIZES: ::libc::c_uint = 5;
pub const G_SLICE_CONFIG_CONTENTION_COUNTER: ::libc::c_uint = 6;
pub type GSliceConfig = Enum_Unnamed80;
pub type Enum_Unnamed81 = ::libc::c_uint;
pub const G_SPAWN_ERROR_FORK: ::libc::c_uint = 0;
pub const G_SPAWN_ERROR_READ: ::libc::c_uint = 1;
pub const G_SPAWN_ERROR_CHDIR: ::libc::c_uint = 2;
pub const G_SPAWN_ERROR_ACCES: ::libc::c_uint = 3;
pub const G_SPAWN_ERROR_PERM: ::libc::c_uint = 4;
pub const G_SPAWN_ERROR_TOO_BIG: ::libc::c_uint = 5;
pub const G_SPAWN_ERROR_2BIG: ::libc::c_uint = 5;
pub const G_SPAWN_ERROR_NOEXEC: ::libc::c_uint = 6;
pub const G_SPAWN_ERROR_NAMETOOLONG: ::libc::c_uint = 7;
pub const G_SPAWN_ERROR_NOENT: ::libc::c_uint = 8;
pub const G_SPAWN_ERROR_NOMEM: ::libc::c_uint = 9;
pub const G_SPAWN_ERROR_NOTDIR: ::libc::c_uint = 10;
pub const G_SPAWN_ERROR_LOOP: ::libc::c_uint = 11;
pub const G_SPAWN_ERROR_TXTBUSY: ::libc::c_uint = 12;
pub const G_SPAWN_ERROR_IO: ::libc::c_uint = 13;
pub const G_SPAWN_ERROR_NFILE: ::libc::c_uint = 14;
pub const G_SPAWN_ERROR_MFILE: ::libc::c_uint = 15;
pub const G_SPAWN_ERROR_INVAL: ::libc::c_uint = 16;
pub const G_SPAWN_ERROR_ISDIR: ::libc::c_uint = 17;
pub const G_SPAWN_ERROR_LIBBAD: ::libc::c_uint = 18;
pub const G_SPAWN_ERROR_FAILED: ::libc::c_uint = 19;
pub type GSpawnError = Enum_Unnamed81;
pub type GSpawnChildSetupFunc =
::std::option::Option<extern "C" fn(user_data: gpointer)>;
pub type Enum_Unnamed82 = ::libc::c_uint;
pub const G_SPAWN_DEFAULT: ::libc::c_uint = 0;
pub const G_SPAWN_LEAVE_DESCRIPTORS_OPEN: ::libc::c_uint = 1;
pub const G_SPAWN_DO_NOT_REAP_CHILD: ::libc::c_uint = 2;
pub const G_SPAWN_SEARCH_PATH: ::libc::c_uint = 4;
pub const G_SPAWN_STDOUT_TO_DEV_NULL: ::libc::c_uint = 8;
pub const G_SPAWN_STDERR_TO_DEV_NULL: ::libc::c_uint = 16;
pub const G_SPAWN_CHILD_INHERITS_STDIN: ::libc::c_uint = 32;
pub const G_SPAWN_FILE_AND_ARGV_ZERO: ::libc::c_uint = 64;
pub const G_SPAWN_SEARCH_PATH_FROM_ENVP: ::libc::c_uint = 128;
pub const G_SPAWN_CLOEXEC_PIPES: ::libc::c_uint = 256;
pub type GSpawnFlags = Enum_Unnamed82;
pub type Enum_Unnamed83 = ::libc::c_uint;
pub const G_ASCII_ALNUM: ::libc::c_uint = 1;
pub const G_ASCII_ALPHA: ::libc::c_uint = 2;
pub const G_ASCII_CNTRL: ::libc::c_uint = 4;
pub const G_ASCII_DIGIT: ::libc::c_uint = 8;
pub const G_ASCII_GRAPH: ::libc::c_uint = 16;
pub const G_ASCII_LOWER: ::libc::c_uint = 32;
pub const G_ASCII_PRINT: ::libc::c_uint = 64;
pub const G_ASCII_PUNCT: ::libc::c_uint = 128;
pub const G_ASCII_SPACE: ::libc::c_uint = 256;
pub const G_ASCII_UPPER: ::libc::c_uint = 512;
pub const G_ASCII_XDIGIT: ::libc::c_uint = 1024;
pub type GAsciiType = Enum_Unnamed83;
pub enum Struct__GStringChunk { }
pub type GStringChunk = Struct__GStringChunk;
pub enum Struct_GTestCase { }
pub type GTestCase = Struct_GTestCase;
pub enum Struct_GTestSuite { }
pub type GTestSuite = Struct_GTestSuite;
pub type GTestFunc = ::std::option::Option<extern "C" fn()>;
pub type GTestDataFunc =
::std::option::Option<extern "C" fn(user_data: gconstpointer)>;
pub type GTestFixtureFunc =
::std::option::Option<extern "C" fn
(fixture: gpointer, user_data: gconstpointer)>;
pub type Enum_Unnamed84 = ::libc::c_uint;
pub const G_TEST_TRAP_SILENCE_STDOUT: ::libc::c_uint = 128;
pub const G_TEST_TRAP_SILENCE_STDERR: ::libc::c_uint = 256;
pub const G_TEST_TRAP_INHERIT_STDIN: ::libc::c_uint = 512;
pub type GTestTrapFlags = Enum_Unnamed84;
pub type Enum_Unnamed85 = ::libc::c_uint;
pub const G_TEST_SUBPROCESS_INHERIT_STDIN: ::libc::c_uint = 1;
pub const G_TEST_SUBPROCESS_INHERIT_STDOUT: ::libc::c_uint = 2;
pub const G_TEST_SUBPROCESS_INHERIT_STDERR: ::libc::c_uint = 4;
pub type GTestSubprocessFlags = Enum_Unnamed85;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed86 {
pub test_initialized: gboolean,
pub test_quick: gboolean,
pub test_perf: gboolean,
pub test_verbose: gboolean,
pub test_quiet: gboolean,
pub test_undefined: gboolean,
}
impl ::std::default::Default for Struct_Unnamed86 {
fn default() -> Struct_Unnamed86 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestConfig = Struct_Unnamed86;
pub type Enum_Unnamed87 = ::libc::c_uint;
pub const G_TEST_LOG_NONE: ::libc::c_uint = 0;
pub const G_TEST_LOG_ERROR: ::libc::c_uint = 1;
pub const G_TEST_LOG_START_BINARY: ::libc::c_uint = 2;
pub const G_TEST_LOG_LIST_CASE: ::libc::c_uint = 3;
pub const G_TEST_LOG_SKIP_CASE: ::libc::c_uint = 4;
pub const G_TEST_LOG_START_CASE: ::libc::c_uint = 5;
pub const G_TEST_LOG_STOP_CASE: ::libc::c_uint = 6;
pub const G_TEST_LOG_MIN_RESULT: ::libc::c_uint = 7;
pub const G_TEST_LOG_MAX_RESULT: ::libc::c_uint = 8;
pub const G_TEST_LOG_MESSAGE: ::libc::c_uint = 9;
pub const G_TEST_LOG_START_SUITE: ::libc::c_uint = 10;
pub const G_TEST_LOG_STOP_SUITE: ::libc::c_uint = 11;
pub type GTestLogType = Enum_Unnamed87;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed88 {
pub log_type: GTestLogType,
pub n_strings: guint,
pub strings: *mut *mut gchar,
pub n_nums: guint,
pub nums: *mut ::libc::c_double,
}
impl ::std::default::Default for Struct_Unnamed88 {
fn default() -> Struct_Unnamed88 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestLogMsg = Struct_Unnamed88;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed89 {
pub data: *mut GString,
pub msgs: *mut GSList,
}
impl ::std::default::Default for Struct_Unnamed89 {
fn default() -> Struct_Unnamed89 { unsafe { ::std::mem::zeroed() } }
}
pub type GTestLogBuffer = Struct_Unnamed89;
pub type GTestLogFatalFunc =
::std::option::Option<extern "C" fn
(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed90 = ::libc::c_uint;
pub const G_TEST_DIST: ::libc::c_uint = 0;
pub const G_TEST_BUILT: ::libc::c_uint = 1;
pub type GTestFileType = Enum_Unnamed90;
pub type GThreadPool = Struct__GThreadPool;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThreadPool {
pub func: GFunc,
pub user_data: gpointer,
pub exclusive: gboolean,
}
impl ::std::default::Default for Struct__GThreadPool {
fn default() -> Struct__GThreadPool { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTimer { }
pub type GTimer = Struct__GTimer;
pub type GTrashStack = Struct__GTrashStack;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTrashStack {
pub next: *mut GTrashStack,
}
impl ::std::default::Default for Struct__GTrashStack {
fn default() -> Struct__GTrashStack { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GTree { }
pub type GTree = Struct__GTree;
pub type GTraverseFunc =
::std::option::Option<extern "C" fn
(key: gpointer, value: gpointer, data: gpointer)
-> gboolean>;
pub enum Struct__GVariantType { }
pub type GVariantType = Struct__GVariantType;
pub enum Struct__GVariant { }
pub type GVariant = Struct__GVariant;
pub type Enum_Unnamed91 = ::libc::c_uint;
pub const G_VARIANT_CLASS_BOOLEAN: ::libc::c_uint = 98;
pub const G_VARIANT_CLASS_BYTE: ::libc::c_uint = 121;
pub const G_VARIANT_CLASS_INT16: ::libc::c_uint = 110;
pub const G_VARIANT_CLASS_UINT16: ::libc::c_uint = 113;
pub const G_VARIANT_CLASS_INT32: ::libc::c_uint = 105;
pub const G_VARIANT_CLASS_UINT32: ::libc::c_uint = 117;
pub const G_VARIANT_CLASS_INT64: ::libc::c_uint = 120;
pub const G_VARIANT_CLASS_UINT64: ::libc::c_uint = 116;
pub const G_VARIANT_CLASS_HANDLE: ::libc::c_uint = 104;
pub const G_VARIANT_CLASS_DOUBLE: ::libc::c_uint = 100;
pub const G_VARIANT_CLASS_STRING: ::libc::c_uint = 115;
pub const G_VARIANT_CLASS_OBJECT_PATH: ::libc::c_uint = 111;
pub const G_VARIANT_CLASS_SIGNATURE: ::libc::c_uint = 103;
pub const G_VARIANT_CLASS_VARIANT: ::libc::c_uint = 118;
pub const G_VARIANT_CLASS_MAYBE: ::libc::c_uint = 109;
pub const G_VARIANT_CLASS_ARRAY: ::libc::c_uint = 97;
pub const G_VARIANT_CLASS_TUPLE: ::libc::c_uint = 40;
pub const G_VARIANT_CLASS_DICT_ENTRY: ::libc::c_uint = 123;
pub type GVariantClass = Enum_Unnamed91;
pub type GVariantIter = Struct__GVariantIter;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantIter {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantIter {
fn default() -> Struct__GVariantIter { unsafe { ::std::mem::zeroed() } }
}
pub type GVariantBuilder = Struct__GVariantBuilder;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantBuilder {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantBuilder {
fn default() -> Struct__GVariantBuilder {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed92 = ::libc::c_uint;
pub const G_VARIANT_PARSE_ERROR_FAILED: ::libc::c_uint = 0;
pub const G_VARIANT_PARSE_ERROR_BASIC_TYPE_EXPECTED: ::libc::c_uint = 1;
pub const G_VARIANT_PARSE_ERROR_CANNOT_INFER_TYPE: ::libc::c_uint = 2;
pub const G_VARIANT_PARSE_ERROR_DEFINITE_TYPE_EXPECTED: ::libc::c_uint = 3;
pub const G_VARIANT_PARSE_ERROR_INPUT_NOT_AT_END: ::libc::c_uint = 4;
pub const G_VARIANT_PARSE_ERROR_INVALID_CHARACTER: ::libc::c_uint = 5;
pub const G_VARIANT_PARSE_ERROR_INVALID_FORMAT_STRING: ::libc::c_uint = 6;
pub const G_VARIANT_PARSE_ERROR_INVALID_OBJECT_PATH: ::libc::c_uint = 7;
pub const G_VARIANT_PARSE_ERROR_INVALID_SIGNATURE: ::libc::c_uint = 8;
pub const G_VARIANT_PARSE_ERROR_INVALID_TYPE_STRING: ::libc::c_uint = 9;
pub const G_VARIANT_PARSE_ERROR_NO_COMMON_TYPE: ::libc::c_uint = 10;
pub const G_VARIANT_PARSE_ERROR_NUMBER_OUT_OF_RANGE: ::libc::c_uint = 11;
pub const G_VARIANT_PARSE_ERROR_NUMBER_TOO_BIG: ::libc::c_uint = 12;
pub const G_VARIANT_PARSE_ERROR_TYPE_ERROR: ::libc::c_uint = 13;
pub const G_VARIANT_PARSE_ERROR_UNEXPECTED_TOKEN: ::libc::c_uint = 14;
pub const G_VARIANT_PARSE_ERROR_UNKNOWN_KEYWORD: ::libc::c_uint = 15;
pub const G_VARIANT_PARSE_ERROR_UNTERMINATED_STRING_CONSTANT: ::libc::c_uint =
16;
pub const G_VARIANT_PARSE_ERROR_VALUE_EXPECTED: ::libc::c_uint = 17;
pub type GVariantParseError = Enum_Unnamed92;
pub type GVariantDict = Struct__GVariantDict;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GVariantDict {
pub x: [gsize; 16u],
}
impl ::std::default::Default for Struct__GVariantDict {
fn default() -> Struct__GVariantDict { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GAllocator { }
pub type GAllocator = Struct__GAllocator;
pub enum Struct__GMemChunk { }
pub type GMemChunk = Struct__GMemChunk;
pub enum Struct__GCache { }
pub type GCache = Struct__GCache;
pub type GCacheNewFunc =
::std::option::Option<extern "C" fn(key: gpointer) -> gpointer>;
pub type GCacheDupFunc =
::std::option::Option<extern "C" fn(value: gpointer) -> gpointer>;
pub type GCacheDestroyFunc =
::std::option::Option<extern "C" fn(value: gpointer)>;
pub type GCompletion = Struct__GCompletion;
pub type GCompletionFunc =
::std::option::Option<extern "C" fn(arg1: gpointer) -> *mut gchar>;
pub type GCompletionStrncmpFunc =
::std::option::Option<extern "C" fn
(s1: *const gchar, s2: *const gchar, n: gsize)
-> gint>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCompletion {
pub items: *mut GList,
pub func: GCompletionFunc,
pub prefix: *mut gchar,
pub cache: *mut GList,
pub strncmp_func: GCompletionStrncmpFunc,
}
impl ::std::default::Default for Struct__GCompletion {
fn default() -> Struct__GCompletion { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GRelation { }
pub type GRelation = Struct__GRelation;
pub type GTuples = Struct__GTuples;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTuples {
pub len: guint,
}
impl ::std::default::Default for Struct__GTuples {
fn default() -> Struct__GTuples { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed93 = ::libc::c_uint;
pub const G_THREAD_PRIORITY_LOW: ::libc::c_uint = 0;
pub const G_THREAD_PRIORITY_NORMAL: ::libc::c_uint = 1;
pub const G_THREAD_PRIORITY_HIGH: ::libc::c_uint = 2;
pub const G_THREAD_PRIORITY_URGENT: ::libc::c_uint = 3;
pub type GThreadPriority = Enum_Unnamed93;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThread {
pub func: GThreadFunc,
pub data: gpointer,
pub joinable: gboolean,
pub priority: GThreadPriority,
}
impl ::std::default::Default for Struct__GThread {
fn default() -> Struct__GThread { unsafe { ::std::mem::zeroed() } }
}
pub type GThreadFunctions = Struct__GThreadFunctions;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GThreadFunctions {
pub mutex_new: ::std::option::Option<extern "C" fn() -> *mut GMutex>,
pub mutex_lock: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)>,
pub mutex_trylock: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)
-> gboolean>,
pub mutex_unlock: ::std::option::Option<extern "C" fn
(mutex: *mut GMutex)>,
pub mutex_free: ::std::option::Option<extern "C" fn(mutex: *mut GMutex)>,
pub cond_new: ::std::option::Option<extern "C" fn() -> *mut GCond>,
pub cond_signal: ::std::option::Option<extern "C" fn(cond: *mut GCond)>,
pub cond_broadcast: ::std::option::Option<extern "C" fn
(cond: *mut GCond)>,
pub cond_wait: ::std::option::Option<extern "C" fn
(cond: *mut GCond,
mutex: *mut GMutex)>,
pub cond_timed_wait: ::std::option::Option<extern "C" fn
(cond: *mut GCond,
mutex: *mut GMutex,
end_time: *mut GTimeVal)
-> gboolean>,
pub cond_free: ::std::option::Option<extern "C" fn(cond: *mut GCond)>,
pub private_new: ::std::option::Option<extern "C" fn
(destructor: GDestroyNotify)
-> *mut GPrivate>,
pub private_get: ::std::option::Option<extern "C" fn
(private_key: *mut GPrivate)
-> gpointer>,
pub private_set: ::std::option::Option<extern "C" fn
(private_key: *mut GPrivate,
data: gpointer)>,
pub thread_create: ::std::option::Option<extern "C" fn
(func: GThreadFunc,
data: gpointer,
stack_size: gulong,
joinable: gboolean,
bound: gboolean,
priority: GThreadPriority,
thread: gpointer,
error: *mut *mut GError)>,
pub thread_yield: ::std::option::Option<extern "C" fn()>,
pub thread_join: ::std::option::Option<extern "C" fn(thread: gpointer)>,
pub thread_exit: ::std::option::Option<extern "C" fn()>,
pub thread_set_priority: ::std::option::Option<extern "C" fn
(thread: gpointer,
priority:
GThreadPriority)>,
pub thread_self: ::std::option::Option<extern "C" fn(thread: gpointer)>,
pub thread_equal: ::std::option::Option<extern "C" fn
(thread1: gpointer,
thread2: gpointer)
-> gboolean>,
}
impl ::std::default::Default for Struct__GThreadFunctions {
fn default() -> Struct__GThreadFunctions {
unsafe { ::std::mem::zeroed() }
}
}
pub type u_char = __u_char;
pub type u_short = __u_short;
pub type u_int = __u_int;
pub type u_long = __u_long;
pub type quad_t = __quad_t;
pub type u_quad_t = __u_quad_t;
pub type fsid_t = __fsid_t;
pub type loff_t = __loff_t;
pub type ino_t = __ino_t;
pub type dev_t = __dev_t;
pub type gid_t = __gid_t;
pub type mode_t = __mode_t;
pub type nlink_t = __nlink_t;
pub type off_t = __off_t;
pub type id_t = __id_t;
pub type ssize_t = __ssize_t;
pub type daddr_t = __daddr_t;
pub type caddr_t = __caddr_t;
pub type key_t = __key_t;
pub type ulong = ::libc::c_ulong;
pub type ushort = ::libc::c_ushort;
pub type _uint = ::libc::c_uint;
pub type int8_t = ::libc::c_char;
pub type int16_t = ::libc::c_short;
pub type int32_t = ::libc::c_int;
pub type int64_t = ::libc::c_long;
pub type u_int8_t = ::libc::c_uchar;
pub type u_int16_t = ::libc::c_ushort;
pub type u_int32_t = ::libc::c_uint;
pub type u_int64_t = ::libc::c_ulong;
pub type register_t = ::libc::c_long;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_timeval {
pub tv_sec: __time_t,
pub tv_usec: __suseconds_t,
}
impl ::std::default::Default for Struct_timeval {
fn default() -> Struct_timeval { unsafe { ::std::mem::zeroed() } }
}
pub type suseconds_t = __suseconds_t;
pub type __fd_mask = ::libc::c_long;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed94 {
pub __fds_bits: [__fd_mask; 16u],
}
impl ::std::default::Default for Struct_Unnamed94 {
fn default() -> Struct_Unnamed94 { unsafe { ::std::mem::zeroed() } }
}
pub type fd_set = Struct_Unnamed94;
pub type fd_mask = __fd_mask;
pub type blksize_t = __blksize_t;
pub type blkcnt_t = __blkcnt_t;
pub type fsblkcnt_t = __fsblkcnt_t;
pub type fsfilcnt_t = __fsfilcnt_t;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_sched_param {
pub __sched_priority: ::libc::c_int,
}
impl ::std::default::Default for Struct_sched_param {
fn default() -> Struct_sched_param { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___sched_param {
pub __sched_priority: ::libc::c_int,
}
impl ::std::default::Default for Struct___sched_param {
fn default() -> Struct___sched_param { unsafe { ::std::mem::zeroed() } }
}
pub type __cpu_mask = ::libc::c_ulong;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed95 {
pub __bits: [__cpu_mask; 16u],
}
impl ::std::default::Default for Struct_Unnamed95 {
fn default() -> Struct_Unnamed95 { unsafe { ::std::mem::zeroed() } }
}
pub type cpu_set_t = Struct_Unnamed95;
pub type __jmp_buf = [::libc::c_long; 8u];
pub type Enum_Unnamed96 = ::libc::c_uint;
pub const PTHREAD_CREATE_JOINABLE: ::libc::c_uint = 0;
pub const PTHREAD_CREATE_DETACHED: ::libc::c_uint = 1;
pub type Enum_Unnamed97 = ::libc::c_uint;
pub const PTHREAD_MUTEX_TIMED_NP: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_RECURSIVE_NP: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ERRORCHECK_NP: ::libc::c_uint = 2;
pub const PTHREAD_MUTEX_ADAPTIVE_NP: ::libc::c_uint = 3;
pub const PTHREAD_MUTEX_NORMAL: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_RECURSIVE: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ERRORCHECK: ::libc::c_uint = 2;
pub const PTHREAD_MUTEX_DEFAULT: ::libc::c_uint = 0;
pub type Enum_Unnamed98 = ::libc::c_uint;
pub const PTHREAD_MUTEX_STALLED: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_STALLED_NP: ::libc::c_uint = 0;
pub const PTHREAD_MUTEX_ROBUST: ::libc::c_uint = 1;
pub const PTHREAD_MUTEX_ROBUST_NP: ::libc::c_uint = 1;
pub type Enum_Unnamed99 = ::libc::c_uint;
pub const PTHREAD_PRIO_NONE: ::libc::c_uint = 0;
pub const PTHREAD_PRIO_INHERIT: ::libc::c_uint = 1;
pub const PTHREAD_PRIO_PROTECT: ::libc::c_uint = 2;
pub type Enum_Unnamed100 = ::libc::c_uint;
pub const PTHREAD_RWLOCK_PREFER_READER_NP: ::libc::c_uint = 0;
pub const PTHREAD_RWLOCK_PREFER_WRITER_NP: ::libc::c_uint = 1;
pub const PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP: ::libc::c_uint = 2;
pub const PTHREAD_RWLOCK_DEFAULT_NP: ::libc::c_uint = 0;
pub type Enum_Unnamed101 = ::libc::c_uint;
pub const PTHREAD_INHERIT_SCHED: ::libc::c_uint = 0;
pub const PTHREAD_EXPLICIT_SCHED: ::libc::c_uint = 1;
pub type Enum_Unnamed102 = ::libc::c_uint;
pub const PTHREAD_SCOPE_SYSTEM: ::libc::c_uint = 0;
pub const PTHREAD_SCOPE_PROCESS: ::libc::c_uint = 1;
pub type Enum_Unnamed103 = ::libc::c_uint;
pub const PTHREAD_PROCESS_PRIVATE: ::libc::c_uint = 0;
pub const PTHREAD_PROCESS_SHARED: ::libc::c_uint = 1;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__pthread_cleanup_buffer {
pub __routine: ::std::option::Option<extern "C" fn
(arg1: *mut ::libc::c_void)>,
pub __arg: *mut ::libc::c_void,
pub __canceltype: ::libc::c_int,
pub __prev: *mut Struct__pthread_cleanup_buffer,
}
impl ::std::default::Default for Struct__pthread_cleanup_buffer {
fn default() -> Struct__pthread_cleanup_buffer {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed104 = ::libc::c_uint;
pub const PTHREAD_CANCEL_ENABLE: ::libc::c_uint = 0;
pub const PTHREAD_CANCEL_DISABLE: ::libc::c_uint = 1;
pub type Enum_Unnamed105 = ::libc::c_uint;
pub const PTHREAD_CANCEL_DEFERRED: ::libc::c_uint = 0;
pub const PTHREAD_CANCEL_ASYNCHRONOUS: ::libc::c_uint = 1;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed106 {
pub __cancel_jmp_buf: [Struct_Unnamed107; 1u],
pub __pad: [*mut ::libc::c_void; 4u],
}
impl ::std::default::Default for Struct_Unnamed106 {
fn default() -> Struct_Unnamed106 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed107 {
pub __cancel_jmp_buf: __jmp_buf,
pub __mask_was_saved: ::libc::c_int,
}
impl ::std::default::Default for Struct_Unnamed107 {
fn default() -> Struct_Unnamed107 { unsafe { ::std::mem::zeroed() } }
}
pub type __pthread_unwind_buf_t = Struct_Unnamed106;
#[repr(C)]
#[derive(Copy)]
pub struct Struct___pthread_cleanup_frame {
pub __cancel_routine: ::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)>,
pub __cancel_arg: *mut ::libc::c_void,
pub __do_it: ::libc::c_int,
pub __cancel_type: ::libc::c_int,
}
impl ::std::default::Default for Struct___pthread_cleanup_frame {
fn default() -> Struct___pthread_cleanup_frame {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct___jmp_buf_tag { }
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed108 {
pub mutex: *mut GMutex,
pub unused: pthread_mutex_t,
}
impl ::std::default::Default for Struct_Unnamed108 {
fn default() -> Struct_Unnamed108 { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticMutex = Struct_Unnamed108;
pub type GStaticRecMutex = Struct__GStaticRecMutex;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticRecMutex {
pub mutex: GStaticMutex,
pub depth: guint,
pub unused: Union_Unnamed109,
}
impl ::std::default::Default for Struct__GStaticRecMutex {
fn default() -> Struct__GStaticRecMutex {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed109 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed109 {
pub unsafe fn owner(&mut self) -> *mut pthread_t {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn dummy(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed109 {
fn default() -> Union_Unnamed109 { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticRWLock = Struct__GStaticRWLock;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticRWLock {
pub mutex: GStaticMutex,
pub read_cond: *mut GCond,
pub write_cond: *mut GCond,
pub read_counter: guint,
pub have_writer: gboolean,
pub want_to_read: guint,
pub want_to_write: guint,
}
impl ::std::default::Default for Struct__GStaticRWLock {
fn default() -> Struct__GStaticRWLock { unsafe { ::std::mem::zeroed() } }
}
pub type GStaticPrivate = Struct__GStaticPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GStaticPrivate {
pub index: guint,
}
impl ::std::default::Default for Struct__GStaticPrivate {
fn default() -> Struct__GStaticPrivate { unsafe { ::std::mem::zeroed() } }
}
pub type GType = gsize;
pub type GValue = Struct__GValue;
pub enum Union__GTypeCValue { }
pub type GTypeCValue = Union__GTypeCValue;
pub enum Struct__GTypePlugin { }
pub type GTypePlugin = Struct__GTypePlugin;
pub type GTypeClass = Struct__GTypeClass;
pub type GTypeInterface = Struct__GTypeInterface;
pub type GTypeInstance = Struct__GTypeInstance;
pub type GTypeInfo = Struct__GTypeInfo;
pub type GTypeFundamentalInfo = Struct__GTypeFundamentalInfo;
pub type GInterfaceInfo = Struct__GInterfaceInfo;
pub type GTypeValueTable = Struct__GTypeValueTable;
pub type GTypeQuery = Struct__GTypeQuery;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeClass {
pub g_type: GType,
}
impl ::std::default::Default for Struct__GTypeClass {
fn default() -> Struct__GTypeClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInstance {
pub g_class: *mut GTypeClass,
}
impl ::std::default::Default for Struct__GTypeInstance {
fn default() -> Struct__GTypeInstance { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInterface {
pub g_type: GType,
pub g_instance_type: GType,
}
impl ::std::default::Default for Struct__GTypeInterface {
fn default() -> Struct__GTypeInterface { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeQuery {
pub _type: GType,
pub type_name: *const gchar,
pub class_size: guint,
pub instance_size: guint,
}
impl ::std::default::Default for Struct__GTypeQuery {
fn default() -> Struct__GTypeQuery { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed110 = ::libc::c_uint;
pub const G_TYPE_DEBUG_NONE: ::libc::c_uint = 0;
pub const G_TYPE_DEBUG_OBJECTS: ::libc::c_uint = 1;
pub const G_TYPE_DEBUG_SIGNALS: ::libc::c_uint = 2;
pub const G_TYPE_DEBUG_MASK: ::libc::c_uint = 3;
pub type GTypeDebugFlags = Enum_Unnamed110;
pub type GBaseInitFunc =
::std::option::Option<extern "C" fn(g_class: gpointer)>;
pub type GBaseFinalizeFunc =
::std::option::Option<extern "C" fn(g_class: gpointer)>;
pub type GClassInitFunc =
::std::option::Option<extern "C" fn
(g_class: gpointer, class_data: gpointer)>;
pub type GClassFinalizeFunc =
::std::option::Option<extern "C" fn
(g_class: gpointer, class_data: gpointer)>;
pub type GInstanceInitFunc =
::std::option::Option<extern "C" fn
(instance: *mut GTypeInstance,
g_class: gpointer)>;
pub type GInterfaceInitFunc =
::std::option::Option<extern "C" fn
(g_iface: gpointer, iface_data: gpointer)>;
pub type GInterfaceFinalizeFunc =
::std::option::Option<extern "C" fn
(g_iface: gpointer, iface_data: gpointer)>;
pub type GTypeClassCacheFunc =
::std::option::Option<extern "C" fn
(cache_data: gpointer, g_class: *mut GTypeClass)
-> gboolean>;
pub type GTypeInterfaceCheckFunc =
::std::option::Option<extern "C" fn
(check_data: gpointer, g_iface: gpointer)>;
pub type Enum_Unnamed111 = ::libc::c_uint;
pub const G_TYPE_FLAG_CLASSED: ::libc::c_uint = 1;
pub const G_TYPE_FLAG_INSTANTIATABLE: ::libc::c_uint = 2;
pub const G_TYPE_FLAG_DERIVABLE: ::libc::c_uint = 4;
pub const G_TYPE_FLAG_DEEP_DERIVABLE: ::libc::c_uint = 8;
pub type GTypeFundamentalFlags = Enum_Unnamed111;
pub type Enum_Unnamed112 = ::libc::c_uint;
pub const G_TYPE_FLAG_ABSTRACT: ::libc::c_uint = 16;
pub const G_TYPE_FLAG_VALUE_ABSTRACT: ::libc::c_uint = 32;
pub type GTypeFlags = Enum_Unnamed112;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeInfo {
pub class_size: guint16,
pub base_init: GBaseInitFunc,
pub base_finalize: GBaseFinalizeFunc,
pub class_init: GClassInitFunc,
pub class_finalize: GClassFinalizeFunc,
pub class_data: gconstpointer,
pub instance_size: guint16,
pub n_preallocs: guint16,
pub instance_init: GInstanceInitFunc,
pub value_table: *const GTypeValueTable,
}
impl ::std::default::Default for Struct__GTypeInfo {
fn default() -> Struct__GTypeInfo { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeFundamentalInfo {
pub type_flags: GTypeFundamentalFlags,
}
impl ::std::default::Default for Struct__GTypeFundamentalInfo {
fn default() -> Struct__GTypeFundamentalInfo {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GInterfaceInfo {
pub interface_init: GInterfaceInitFunc,
pub interface_finalize: GInterfaceFinalizeFunc,
pub interface_data: gpointer,
}
impl ::std::default::Default for Struct__GInterfaceInfo {
fn default() -> Struct__GInterfaceInfo { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeValueTable {
pub value_init: ::std::option::Option<extern "C" fn(value: *mut GValue)>,
pub value_free: ::std::option::Option<extern "C" fn(value: *mut GValue)>,
pub value_copy: ::std::option::Option<extern "C" fn
(src_value: *const GValue,
dest_value: *mut GValue)>,
pub value_peek_pointer: ::std::option::Option<extern "C" fn
(value: *const GValue)
-> gpointer>,
pub collect_format: *const gchar,
pub collect_value: ::std::option::Option<extern "C" fn
(value: *mut GValue,
n_collect_values: guint,
collect_values:
*mut GTypeCValue,
collect_flags: guint)
-> *mut gchar>,
pub lcopy_format: *const gchar,
pub lcopy_value: ::std::option::Option<extern "C" fn
(value: *const GValue,
n_collect_values: guint,
collect_values:
*mut GTypeCValue,
collect_flags: guint)
-> *mut gchar>,
}
impl ::std::default::Default for Struct__GTypeValueTable {
fn default() -> Struct__GTypeValueTable {
unsafe { ::std::mem::zeroed() }
}
}
pub type GValueTransform =
::std::option::Option<extern "C" fn
(src_value: *const GValue,
dest_value: *mut GValue)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GValue {
pub g_type: GType,
pub data: [Union_Unnamed113; 2u],
}
impl ::std::default::Default for Struct__GValue {
fn default() -> Struct__GValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed113 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed113 {
pub unsafe fn v_int(&mut self) -> *mut gint {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_uint(&mut self) -> *mut guint {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_long(&mut self) -> *mut glong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_ulong(&mut self) -> *mut gulong {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_int64(&mut self) -> *mut gint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_uint64(&mut self) -> *mut guint64 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_float(&mut self) -> *mut gfloat {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_double(&mut self) -> *mut gdouble {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn v_pointer(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed113 {
fn default() -> Union_Unnamed113 { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed114 = ::libc::c_int;
pub const G_PARAM_READABLE: ::libc::c_int = 1;
pub const G_PARAM_WRITABLE: ::libc::c_int = 2;
pub const G_PARAM_READWRITE: ::libc::c_int = 3;
pub const G_PARAM_CONSTRUCT: ::libc::c_int = 4;
pub const G_PARAM_CONSTRUCT_ONLY: ::libc::c_int = 8;
pub const G_PARAM_LAX_VALIDATION: ::libc::c_int = 16;
pub const G_PARAM_STATIC_NAME: ::libc::c_int = 32;
pub const G_PARAM_PRIVATE: ::libc::c_int = 32;
pub const G_PARAM_STATIC_NICK: ::libc::c_int = 64;
pub const G_PARAM_STATIC_BLURB: ::libc::c_int = 128;
pub const G_PARAM_EXPLICIT_NOTIFY: ::libc::c_int = 1073741824;
pub const G_PARAM_DEPRECATED: ::libc::c_int = -2147483648;
pub type GParamFlags = Enum_Unnamed114;
pub type GParamSpec = Struct__GParamSpec;
pub type GParamSpecClass = Struct__GParamSpecClass;
pub type GParameter = Struct__GParameter;
pub enum Struct__GParamSpecPool { }
pub type GParamSpecPool = Struct__GParamSpecPool;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpec {
pub g_type_instance: GTypeInstance,
pub name: *const gchar,
pub flags: GParamFlags,
pub value_type: GType,
pub owner_type: GType,
pub _nick: *mut gchar,
pub _blurb: *mut gchar,
pub qdata: *mut GData,
pub ref_count: guint,
pub param_id: guint,
}
impl ::std::default::Default for Struct__GParamSpec {
fn default() -> Struct__GParamSpec { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecClass {
pub g_type_class: GTypeClass,
pub value_type: GType,
pub finalize: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_set_default: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)>,
pub value_validate: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)
-> gboolean>,
pub values_cmp: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value1: *const GValue,
value2: *const GValue)
-> gint>,
pub dummy: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GParamSpecClass {
fn default() -> Struct__GParamSpecClass {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParameter {
pub name: *const gchar,
pub value: GValue,
}
impl ::std::default::Default for Struct__GParameter {
fn default() -> Struct__GParameter { unsafe { ::std::mem::zeroed() } }
}
pub type GParamSpecTypeInfo = Struct__GParamSpecTypeInfo;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecTypeInfo {
pub instance_size: guint16,
pub n_preallocs: guint16,
pub instance_init: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_type: GType,
pub finalize: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec)>,
pub value_set_default: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)>,
pub value_validate: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value: *mut GValue)
-> gboolean>,
pub values_cmp: ::std::option::Option<extern "C" fn
(pspec: *mut GParamSpec,
value1: *const GValue,
value2: *const GValue)
-> gint>,
}
impl ::std::default::Default for Struct__GParamSpecTypeInfo {
fn default() -> Struct__GParamSpecTypeInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type GClosure = Struct__GClosure;
pub type GClosureNotifyData = Struct__GClosureNotifyData;
pub type GCallback = ::std::option::Option<extern "C" fn()>;
pub type GClosureNotify =
::std::option::Option<extern "C" fn
(data: gpointer, closure: *mut GClosure)>;
pub type GClosureMarshal =
::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer)>;
pub type GVaClosureMarshal =
::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue, instance: gpointer,
args: va_list, marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType)>;
pub type GCClosure = Struct__GCClosure;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GClosureNotifyData {
pub data: gpointer,
pub notify: GClosureNotify,
}
impl ::std::default::Default for Struct__GClosureNotifyData {
fn default() -> Struct__GClosureNotifyData {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GClosure {
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
pub _bindgen_bitfield_3_: guint,
pub _bindgen_bitfield_4_: guint,
pub _bindgen_bitfield_5_: guint,
pub _bindgen_bitfield_6_: guint,
pub _bindgen_bitfield_7_: guint,
pub _bindgen_bitfield_8_: guint,
pub _bindgen_bitfield_9_: guint,
pub _bindgen_bitfield_10_: guint,
pub marshal: ::std::option::Option<extern "C" fn
(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer)>,
pub data: gpointer,
pub notifiers: *mut GClosureNotifyData,
}
impl ::std::default::Default for Struct__GClosure {
fn default() -> Struct__GClosure { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GCClosure {
pub closure: GClosure,
pub callback: gpointer,
}
impl ::std::default::Default for Struct__GCClosure {
fn default() -> Struct__GCClosure { unsafe { ::std::mem::zeroed() } }
}
pub type GSignalQuery = Struct__GSignalQuery;
pub type GSignalInvocationHint = Struct__GSignalInvocationHint;
pub type GSignalCMarshaller = GClosureMarshal;
pub type GSignalCVaMarshaller = GVaClosureMarshal;
pub type GSignalEmissionHook =
::std::option::Option<extern "C" fn
(ihint: *mut GSignalInvocationHint,
n_param_values: guint,
param_values: *const GValue, data: gpointer)
-> gboolean>;
pub type GSignalAccumulator =
::std::option::Option<extern "C" fn
(ihint: *mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue, data: gpointer)
-> gboolean>;
pub type Enum_Unnamed115 = ::libc::c_uint;
pub const G_SIGNAL_RUN_FIRST: ::libc::c_uint = 1;
pub const G_SIGNAL_RUN_LAST: ::libc::c_uint = 2;
pub const G_SIGNAL_RUN_CLEANUP: ::libc::c_uint = 4;
pub const G_SIGNAL_NO_RECURSE: ::libc::c_uint = 8;
pub const G_SIGNAL_DETAILED: ::libc::c_uint = 16;
pub const G_SIGNAL_ACTION: ::libc::c_uint = 32;
pub const G_SIGNAL_NO_HOOKS: ::libc::c_uint = 64;
pub const G_SIGNAL_MUST_COLLECT: ::libc::c_uint = 128;
pub const G_SIGNAL_DEPRECATED: ::libc::c_uint = 256;
pub type GSignalFlags = Enum_Unnamed115;
pub type Enum_Unnamed116 = ::libc::c_uint;
pub const G_CONNECT_AFTER: ::libc::c_uint = 1;
pub const G_CONNECT_SWAPPED: ::libc::c_uint = 2;
pub type GConnectFlags = Enum_Unnamed116;
pub type Enum_Unnamed117 = ::libc::c_uint;
pub const G_SIGNAL_MATCH_ID: ::libc::c_uint = 1;
pub const G_SIGNAL_MATCH_DETAIL: ::libc::c_uint = 2;
pub const G_SIGNAL_MATCH_CLOSURE: ::libc::c_uint = 4;
pub const G_SIGNAL_MATCH_FUNC: ::libc::c_uint = 8;
pub const G_SIGNAL_MATCH_DATA: ::libc::c_uint = 16;
pub const G_SIGNAL_MATCH_UNBLOCKED: ::libc::c_uint = 32;
pub type GSignalMatchType = Enum_Unnamed117;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSignalInvocationHint {
pub signal_id: guint,
pub detail: GQuark,
pub run_type: GSignalFlags,
}
impl ::std::default::Default for Struct__GSignalInvocationHint {
fn default() -> Struct__GSignalInvocationHint {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GSignalQuery {
pub signal_id: guint,
pub signal_name: *const gchar,
pub itype: GType,
pub signal_flags: GSignalFlags,
pub return_type: GType,
pub n_params: guint,
pub param_types: *const GType,
}
impl ::std::default::Default for Struct__GSignalQuery {
fn default() -> Struct__GSignalQuery { unsafe { ::std::mem::zeroed() } }
}
pub type GStrv = *mut *mut gchar;
pub type GBoxedCopyFunc =
::std::option::Option<extern "C" fn(boxed: gpointer) -> gpointer>;
pub type GBoxedFreeFunc =
::std::option::Option<extern "C" fn(boxed: gpointer)>;
pub type GObject = Struct__GObject;
pub type GObjectClass = Struct__GObjectClass;
pub type GInitiallyUnowned = Struct__GObject;
pub type GInitiallyUnownedClass = Struct__GObjectClass;
pub type GObjectConstructParam = Struct__GObjectConstructParam;
pub type GObjectGetPropertyFunc =
::std::option::Option<extern "C" fn
(object: *mut GObject, property_id: guint,
value: *mut GValue, pspec: *mut GParamSpec)>;
pub type GObjectSetPropertyFunc =
::std::option::Option<extern "C" fn
(object: *mut GObject, property_id: guint,
value: *const GValue, pspec: *mut GParamSpec)>;
pub type GObjectFinalizeFunc =
::std::option::Option<extern "C" fn(object: *mut GObject)>;
pub type GWeakNotify =
::std::option::Option<extern "C" fn
(data: gpointer,
where_the_object_was: *mut GObject)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObject {
pub g_type_instance: GTypeInstance,
pub ref_count: guint,
pub qdata: *mut GData,
}
impl ::std::default::Default for Struct__GObject {
fn default() -> Struct__GObject { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObjectClass {
pub g_type_class: GTypeClass,
pub construct_properties: *mut GSList,
pub constructor: ::std::option::Option<extern "C" fn
(_type: GType,
n_construct_properties: guint,
construct_properties:
*mut GObjectConstructParam)
-> *mut GObject>,
pub set_property: ::std::option::Option<extern "C" fn
(object: *mut GObject,
property_id: guint,
value: *const GValue,
pspec: *mut GParamSpec)>,
pub get_property: ::std::option::Option<extern "C" fn
(object: *mut GObject,
property_id: guint,
value: *mut GValue,
pspec: *mut GParamSpec)>,
pub dispose: ::std::option::Option<extern "C" fn(object: *mut GObject)>,
pub finalize: ::std::option::Option<extern "C" fn(object: *mut GObject)>,
pub dispatch_properties_changed: ::std::option::Option<extern "C" fn
(object:
*mut GObject,
n_pspecs:
guint,
pspecs:
*mut *mut GParamSpec)>,
pub notify: ::std::option::Option<extern "C" fn
(object: *mut GObject,
pspec: *mut GParamSpec)>,
pub constructed: ::std::option::Option<extern "C" fn
(object: *mut GObject)>,
pub flags: gsize,
pub pdummy: [gpointer; 6u],
}
impl ::std::default::Default for Struct__GObjectClass {
fn default() -> Struct__GObjectClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GObjectConstructParam {
pub pspec: *mut GParamSpec,
pub value: *mut GValue,
}
impl ::std::default::Default for Struct__GObjectConstructParam {
fn default() -> Struct__GObjectConstructParam {
unsafe { ::std::mem::zeroed() }
}
}
pub type GToggleNotify =
::std::option::Option<extern "C" fn
(data: gpointer, object: *mut GObject,
is_last_ref: gboolean)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed118 {
pub _priv: Union_Unnamed119,
}
impl ::std::default::Default for Struct_Unnamed118 {
fn default() -> Struct_Unnamed118 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed119 {
pub _bindgen_data_: [u64; 1u],
}
impl Union_Unnamed119 {
pub unsafe fn p(&mut self) -> *mut gpointer {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed119 {
fn default() -> Union_Unnamed119 { unsafe { ::std::mem::zeroed() } }
}
pub type GWeakRef = Struct_Unnamed118;
pub enum Struct__GBinding { }
pub type GBinding = Struct__GBinding;
pub type GBindingTransformFunc =
::std::option::Option<extern "C" fn
(binding: *mut GBinding,
from_value: *const GValue,
to_value: *mut GValue, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed120 = ::libc::c_uint;
pub const G_BINDING_DEFAULT: ::libc::c_uint = 0;
pub const G_BINDING_BIDIRECTIONAL: ::libc::c_uint = 1;
pub const G_BINDING_SYNC_CREATE: ::libc::c_uint = 2;
pub const G_BINDING_INVERT_BOOLEAN: ::libc::c_uint = 4;
pub type GBindingFlags = Enum_Unnamed120;
pub type GEnumClass = Struct__GEnumClass;
pub type GFlagsClass = Struct__GFlagsClass;
pub type GEnumValue = Struct__GEnumValue;
pub type GFlagsValue = Struct__GFlagsValue;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GEnumClass {
pub g_type_class: GTypeClass,
pub minimum: gint,
pub maximum: gint,
pub n_values: guint,
pub values: *mut GEnumValue,
}
impl ::std::default::Default for Struct__GEnumClass {
fn default() -> Struct__GEnumClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GFlagsClass {
pub g_type_class: GTypeClass,
pub mask: guint,
pub n_values: guint,
pub values: *mut GFlagsValue,
}
impl ::std::default::Default for Struct__GFlagsClass {
fn default() -> Struct__GFlagsClass { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GEnumValue {
pub value: gint,
pub value_name: *const gchar,
pub value_nick: *const gchar,
}
impl ::std::default::Default for Struct__GEnumValue {
fn default() -> Struct__GEnumValue { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GFlagsValue {
pub value: guint,
pub value_name: *const gchar,
pub value_nick: *const gchar,
}
impl ::std::default::Default for Struct__GFlagsValue {
fn default() -> Struct__GFlagsValue { unsafe { ::std::mem::zeroed() } }
}
pub type GParamSpecChar = Struct__GParamSpecChar;
pub type GParamSpecUChar = Struct__GParamSpecUChar;
pub type GParamSpecBoolean = Struct__GParamSpecBoolean;
pub type GParamSpecInt = Struct__GParamSpecInt;
pub type GParamSpecUInt = Struct__GParamSpecUInt;
pub type GParamSpecLong = Struct__GParamSpecLong;
pub type GParamSpecULong = Struct__GParamSpecULong;
pub type GParamSpecInt64 = Struct__GParamSpecInt64;
pub type GParamSpecUInt64 = Struct__GParamSpecUInt64;
pub type GParamSpecUnichar = Struct__GParamSpecUnichar;
pub type GParamSpecEnum = Struct__GParamSpecEnum;
pub type GParamSpecFlags = Struct__GParamSpecFlags;
pub type GParamSpecFloat = Struct__GParamSpecFloat;
pub type GParamSpecDouble = Struct__GParamSpecDouble;
pub type GParamSpecString = Struct__GParamSpecString;
pub type GParamSpecParam = Struct__GParamSpecParam;
pub type GParamSpecBoxed = Struct__GParamSpecBoxed;
pub type GParamSpecPointer = Struct__GParamSpecPointer;
pub type GParamSpecValueArray = Struct__GParamSpecValueArray;
pub type GParamSpecObject = Struct__GParamSpecObject;
pub type GParamSpecOverride = Struct__GParamSpecOverride;
pub type GParamSpecGType = Struct__GParamSpecGType;
pub type GParamSpecVariant = Struct__GParamSpecVariant;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecChar {
pub parent_instance: GParamSpec,
pub minimum: gint8,
pub maximum: gint8,
pub default_value: gint8,
}
impl ::std::default::Default for Struct__GParamSpecChar {
fn default() -> Struct__GParamSpecChar { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUChar {
pub parent_instance: GParamSpec,
pub minimum: guint8,
pub maximum: guint8,
pub default_value: guint8,
}
impl ::std::default::Default for Struct__GParamSpecUChar {
fn default() -> Struct__GParamSpecUChar {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecBoolean {
pub parent_instance: GParamSpec,
pub default_value: gboolean,
}
impl ::std::default::Default for Struct__GParamSpecBoolean {
fn default() -> Struct__GParamSpecBoolean {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecInt {
pub parent_instance: GParamSpec,
pub minimum: gint,
pub maximum: gint,
pub default_value: gint,
}
impl ::std::default::Default for Struct__GParamSpecInt {
fn default() -> Struct__GParamSpecInt { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUInt {
pub parent_instance: GParamSpec,
pub minimum: guint,
pub maximum: guint,
pub default_value: guint,
}
impl ::std::default::Default for Struct__GParamSpecUInt {
fn default() -> Struct__GParamSpecUInt { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecLong {
pub parent_instance: GParamSpec,
pub minimum: glong,
pub maximum: glong,
pub default_value: glong,
}
impl ::std::default::Default for Struct__GParamSpecLong {
fn default() -> Struct__GParamSpecLong { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecULong {
pub parent_instance: GParamSpec,
pub minimum: gulong,
pub maximum: gulong,
pub default_value: gulong,
}
impl ::std::default::Default for Struct__GParamSpecULong {
fn default() -> Struct__GParamSpecULong {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecInt64 {
pub parent_instance: GParamSpec,
pub minimum: gint64,
pub maximum: gint64,
pub default_value: gint64,
}
impl ::std::default::Default for Struct__GParamSpecInt64 {
fn default() -> Struct__GParamSpecInt64 {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUInt64 {
pub parent_instance: GParamSpec,
pub minimum: guint64,
pub maximum: guint64,
pub default_value: guint64,
}
impl ::std::default::Default for Struct__GParamSpecUInt64 {
fn default() -> Struct__GParamSpecUInt64 {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecUnichar {
pub parent_instance: GParamSpec,
pub default_value: gunichar,
}
impl ::std::default::Default for Struct__GParamSpecUnichar {
fn default() -> Struct__GParamSpecUnichar {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecEnum {
pub parent_instance: GParamSpec,
pub enum_class: *mut GEnumClass,
pub default_value: gint,
}
impl ::std::default::Default for Struct__GParamSpecEnum {
fn default() -> Struct__GParamSpecEnum { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecFlags {
pub parent_instance: GParamSpec,
pub flags_class: *mut GFlagsClass,
pub default_value: guint,
}
impl ::std::default::Default for Struct__GParamSpecFlags {
fn default() -> Struct__GParamSpecFlags {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecFloat {
pub parent_instance: GParamSpec,
pub minimum: gfloat,
pub maximum: gfloat,
pub default_value: gfloat,
pub epsilon: gfloat,
}
impl ::std::default::Default for Struct__GParamSpecFloat {
fn default() -> Struct__GParamSpecFloat {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecDouble {
pub parent_instance: GParamSpec,
pub minimum: gdouble,
pub maximum: gdouble,
pub default_value: gdouble,
pub epsilon: gdouble,
}
impl ::std::default::Default for Struct__GParamSpecDouble {
fn default() -> Struct__GParamSpecDouble {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecString {
pub parent_instance: GParamSpec,
pub default_value: *mut gchar,
pub cset_first: *mut gchar,
pub cset_nth: *mut gchar,
pub substitutor: gchar,
pub _bindgen_bitfield_1_: guint,
pub _bindgen_bitfield_2_: guint,
}
impl ::std::default::Default for Struct__GParamSpecString {
fn default() -> Struct__GParamSpecString {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecParam {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecParam {
fn default() -> Struct__GParamSpecParam {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecBoxed {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecBoxed {
fn default() -> Struct__GParamSpecBoxed {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecPointer {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecPointer {
fn default() -> Struct__GParamSpecPointer {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecValueArray {
pub parent_instance: GParamSpec,
pub element_spec: *mut GParamSpec,
pub fixed_n_elements: guint,
}
impl ::std::default::Default for Struct__GParamSpecValueArray {
fn default() -> Struct__GParamSpecValueArray {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecObject {
pub parent_instance: GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecObject {
fn default() -> Struct__GParamSpecObject {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecOverride {
pub parent_instance: GParamSpec,
pub overridden: *mut GParamSpec,
}
impl ::std::default::Default for Struct__GParamSpecOverride {
fn default() -> Struct__GParamSpecOverride {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecGType {
pub parent_instance: GParamSpec,
pub is_a_type: GType,
}
impl ::std::default::Default for Struct__GParamSpecGType {
fn default() -> Struct__GParamSpecGType {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GParamSpecVariant {
pub parent_instance: GParamSpec,
pub _type: *mut GVariantType,
pub default_value: *mut GVariant,
pub padding: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GParamSpecVariant {
fn default() -> Struct__GParamSpecVariant {
unsafe { ::std::mem::zeroed() }
}
}
pub type GTypeModule = Struct__GTypeModule;
pub type GTypeModuleClass = Struct__GTypeModuleClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeModule {
pub parent_instance: GObject,
pub use_count: guint,
pub type_infos: *mut GSList,
pub interface_infos: *mut GSList,
pub name: *mut gchar,
}
impl ::std::default::Default for Struct__GTypeModule {
fn default() -> Struct__GTypeModule { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypeModuleClass {
pub parent_class: GObjectClass,
pub load: ::std::option::Option<extern "C" fn(module: *mut GTypeModule)
-> gboolean>,
pub unload: ::std::option::Option<extern "C" fn
(module: *mut GTypeModule)>,
pub reserved1: ::std::option::Option<extern "C" fn()>,
pub reserved2: ::std::option::Option<extern "C" fn()>,
pub reserved3: ::std::option::Option<extern "C" fn()>,
pub reserved4: ::std::option::Option<extern "C" fn()>,
}
impl ::std::default::Default for Struct__GTypeModuleClass {
fn default() -> Struct__GTypeModuleClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GTypePluginClass = Struct__GTypePluginClass;
pub type GTypePluginUse =
::std::option::Option<extern "C" fn(plugin: *mut GTypePlugin)>;
pub type GTypePluginUnuse =
::std::option::Option<extern "C" fn(plugin: *mut GTypePlugin)>;
pub type GTypePluginCompleteTypeInfo =
::std::option::Option<extern "C" fn
(plugin: *mut GTypePlugin, g_type: GType,
info: *mut GTypeInfo,
value_table: *mut GTypeValueTable)>;
pub type GTypePluginCompleteInterfaceInfo =
::std::option::Option<extern "C" fn
(plugin: *mut GTypePlugin, instance_type: GType,
interface_type: GType,
info: *mut GInterfaceInfo)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GTypePluginClass {
pub base_iface: GTypeInterface,
pub use_plugin: GTypePluginUse,
pub unuse_plugin: GTypePluginUnuse,
pub complete_type_info: GTypePluginCompleteTypeInfo,
pub complete_interface_info: GTypePluginCompleteInterfaceInfo,
}
impl ::std::default::Default for Struct__GTypePluginClass {
fn default() -> Struct__GTypePluginClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GValueArray = Struct__GValueArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GValueArray {
pub n_values: guint,
pub values: *mut GValue,
pub n_prealloced: guint,
}
impl ::std::default::Default for Struct__GValueArray {
fn default() -> Struct__GValueArray { unsafe { ::std::mem::zeroed() } }
}
pub type gchararray = *mut gchar;
pub enum Struct__GstAtomicQueue { }
pub type GstAtomicQueue = Struct__GstAtomicQueue;
pub type GstElement = Struct__GstElement;
pub type GstElementClass = Struct__GstElementClass;
#[repr(C)]
#[derive(Copy,Debug)]
pub enum GstState{
GST_STATE_VOID_PENDING = 0,
GST_STATE_NULL = 1,
GST_STATE_READY = 2,
GST_STATE_PAUSED = 3,
GST_STATE_PLAYING = 4,
}
/*pub type Enum_Unnamed121 = ::libc::c_uint;
pub const GST_STATE_VOID_PENDING: ::libc::c_uint = 0;
pub const GST_STATE_NULL: ::libc::c_uint = 1;
pub const GST_STATE_READY: ::libc::c_uint = 2;
pub const GST_STATE_PAUSED: ::libc::c_uint = 3;
pub const GST_STATE_PLAYING: ::libc::c_uint = 4;
pub type GstState = Enum_Unnamed121;*/
pub type Enum_Unnamed122 = ::libc::c_uint;
pub const GST_OBJECT_FLAG_LAST: ::libc::c_uint = 16;
pub type GstObjectFlags = Enum_Unnamed122;
pub type GstObject = Struct__GstObject;
pub type GstObjectClass = Struct__GstObjectClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstObject {
pub object: GInitiallyUnowned,
pub lock: GMutex,
pub name: *mut gchar,
pub parent: *mut GstObject,
pub flags: guint32,
pub control_bindings: *mut GList,
pub control_rate: guint64,
pub last_sync: guint64,
pub _gst_reserved: gpointer,
}
impl ::std::default::Default for Struct__GstObject {
fn default() -> Struct__GstObject { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstObjectClass {
pub parent_class: GInitiallyUnownedClass,
pub path_string_separator: *const gchar,
pub deep_notify: ::std::option::Option<extern "C" fn
(object: *mut GstObject,
orig: *mut GstObject,
pspec: *mut GParamSpec)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstObjectClass {
fn default() -> Struct__GstObjectClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstClockTime = guint64;
pub type GstClockTimeDiff = gint64;
pub type GstClockID = gpointer;
pub type GstClockEntry = Struct__GstClockEntry;
pub type GstClock = Struct__GstClock;
pub type GstClockClass = Struct__GstClockClass;
pub enum Struct__GstClockPrivate { }
pub type GstClockPrivate = Struct__GstClockPrivate;
pub type GstClockCallback =
::std::option::Option<extern "C" fn
(clock: *mut GstClock, time: GstClockTime,
id: GstClockID, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed123 = ::libc::c_uint;
pub const GST_CLOCK_OK: ::libc::c_uint = 0;
pub const GST_CLOCK_EARLY: ::libc::c_uint = 1;
pub const GST_CLOCK_UNSCHEDULED: ::libc::c_uint = 2;
pub const GST_CLOCK_BUSY: ::libc::c_uint = 3;
pub const GST_CLOCK_BADTIME: ::libc::c_uint = 4;
pub const GST_CLOCK_ERROR: ::libc::c_uint = 5;
pub const GST_CLOCK_UNSUPPORTED: ::libc::c_uint = 6;
pub const GST_CLOCK_DONE: ::libc::c_uint = 7;
pub type GstClockReturn = Enum_Unnamed123;
pub type Enum_Unnamed124 = ::libc::c_uint;
pub const GST_CLOCK_ENTRY_SINGLE: ::libc::c_uint = 0;
pub const GST_CLOCK_ENTRY_PERIODIC: ::libc::c_uint = 1;
pub type GstClockEntryType = Enum_Unnamed124;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClockEntry {
pub refcount: gint,
pub clock: *mut GstClock,
pub _type: GstClockEntryType,
pub time: GstClockTime,
pub interval: GstClockTime,
pub status: GstClockReturn,
pub func: GstClockCallback,
pub user_data: gpointer,
pub destroy_data: GDestroyNotify,
pub unscheduled: gboolean,
pub woken_up: gboolean,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClockEntry {
fn default() -> Struct__GstClockEntry { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed125 = ::libc::c_uint;
pub const GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC: ::libc::c_uint = 16;
pub const GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC: ::libc::c_uint = 32;
pub const GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC: ::libc::c_uint = 64;
pub const GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC: ::libc::c_uint = 128;
pub const GST_CLOCK_FLAG_CAN_SET_RESOLUTION: ::libc::c_uint = 256;
pub const GST_CLOCK_FLAG_CAN_SET_MASTER: ::libc::c_uint = 512;
pub const GST_CLOCK_FLAG_LAST: ::libc::c_uint = 4096;
pub type GstClockFlags = Enum_Unnamed125;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClock {
pub object: GstObject,
pub _priv: *mut GstClockPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClock {
fn default() -> Struct__GstClock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstClockClass {
pub parent_class: GstObjectClass,
pub change_resolution: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
old_resolution:
GstClockTime,
new_resolution:
GstClockTime)
-> GstClockTime>,
pub get_resolution: ::std::option::Option<extern "C" fn
(clock: *mut GstClock)
-> GstClockTime>,
pub get_internal_time: ::std::option::Option<extern "C" fn
(clock: *mut GstClock)
-> GstClockTime>,
pub wait: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry,
jitter: *mut GstClockTimeDiff)
-> GstClockReturn>,
pub wait_async: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry)
-> GstClockReturn>,
pub unschedule: ::std::option::Option<extern "C" fn
(clock: *mut GstClock,
entry: *mut GstClockEntry)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstClockClass {
fn default() -> Struct__GstClockClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstControlSource = Struct__GstControlSource;
pub type GstControlSourceClass = Struct__GstControlSourceClass;
pub type GstTimedValue = Struct__GstTimedValue;
pub enum Struct__GstValueArray { }
pub type GstValueArray = Struct__GstValueArray;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTimedValue {
pub timestamp: GstClockTime,
pub value: gdouble,
}
impl ::std::default::Default for Struct__GstTimedValue {
fn default() -> Struct__GstTimedValue { unsafe { ::std::mem::zeroed() } }
}
pub type GstControlSourceGetValue =
::std::option::Option<extern "C" fn
(_self: *mut GstControlSource,
timestamp: GstClockTime, value: *mut gdouble)
-> gboolean>;
pub type GstControlSourceGetValueArray =
::std::option::Option<extern "C" fn
(_self: *mut GstControlSource,
timestamp: GstClockTime,
interval: GstClockTime, n_values: guint,
values: *mut gdouble) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlSource {
pub parent: GstObject,
pub get_value: GstControlSourceGetValue,
pub get_value_array: GstControlSourceGetValueArray,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlSource {
fn default() -> Struct__GstControlSource {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlSourceClass {
pub parent_class: GstObjectClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlSourceClass {
fn default() -> Struct__GstControlSourceClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstControlBinding = Struct__GstControlBinding;
pub type GstControlBindingClass = Struct__GstControlBindingClass;
pub type GstControlBindingConvert =
::std::option::Option<extern "C" fn
(binding: *mut GstControlBinding,
src_value: gdouble, dest_value: *mut GValue)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlBinding {
pub parent: GstObject,
pub name: *mut gchar,
pub pspec: *mut GParamSpec,
pub object: *mut GstObject,
pub disabled: gboolean,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlBinding {
fn default() -> Struct__GstControlBinding {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstControlBindingClass {
pub parent_class: GstObjectClass,
pub sync_values: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
object: *mut GstObject,
timestamp: GstClockTime,
last_sync: GstClockTime)
-> gboolean>,
pub get_value: ::std::option::Option<extern "C" fn
(binding: *mut GstControlBinding,
timestamp: GstClockTime)
-> *mut GValue>,
pub get_value_array: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: gpointer)
-> gboolean>,
pub get_g_value_array: ::std::option::Option<extern "C" fn
(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut GValue)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstControlBindingClass {
fn default() -> Struct__GstControlBindingClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPad = Struct__GstPad;
pub enum Struct__GstPadPrivate { }
pub type GstPadPrivate = Struct__GstPadPrivate;
pub type GstPadClass = Struct__GstPadClass;
pub type GstPadProbeInfo = Struct__GstPadProbeInfo;
pub type Enum_Unnamed126 = ::libc::c_uint;
pub const GST_PAD_UNKNOWN: ::libc::c_uint = 0;
pub const GST_PAD_SRC: ::libc::c_uint = 1;
pub const GST_PAD_SINK: ::libc::c_uint = 2;
pub type GstPadDirection = Enum_Unnamed126;
pub type Enum_Unnamed127 = ::libc::c_uint;
pub const GST_PAD_MODE_NONE: ::libc::c_uint = 0;
pub const GST_PAD_MODE_PUSH: ::libc::c_uint = 1;
pub const GST_PAD_MODE_PULL: ::libc::c_uint = 2;
pub type GstPadMode = Enum_Unnamed127;
pub type GstMiniObject = Struct__GstMiniObject;
pub type GstMiniObjectCopyFunction =
::std::option::Option<extern "C" fn(obj: *const GstMiniObject)
-> *mut GstMiniObject>;
pub type GstMiniObjectDisposeFunction =
::std::option::Option<extern "C" fn(obj: *mut GstMiniObject) -> gboolean>;
pub type GstMiniObjectFreeFunction =
::std::option::Option<extern "C" fn(obj: *mut GstMiniObject)>;
pub type GstMiniObjectNotify =
::std::option::Option<extern "C" fn
(user_data: gpointer, obj: *mut GstMiniObject)>;
pub type Enum_Unnamed128 = ::libc::c_uint;
pub const GST_MINI_OBJECT_FLAG_LOCKABLE: ::libc::c_uint = 1;
pub const GST_MINI_OBJECT_FLAG_LOCK_READONLY: ::libc::c_uint = 2;
pub const GST_MINI_OBJECT_FLAG_LAST: ::libc::c_uint = 16;
pub type GstMiniObjectFlags = Enum_Unnamed128;
pub type Enum_Unnamed129 = ::libc::c_uint;
pub const GST_LOCK_FLAG_READ: ::libc::c_uint = 1;
pub const GST_LOCK_FLAG_WRITE: ::libc::c_uint = 2;
pub const GST_LOCK_FLAG_EXCLUSIVE: ::libc::c_uint = 4;
pub const GST_LOCK_FLAG_LAST: ::libc::c_uint = 256;
pub type GstLockFlags = Enum_Unnamed129;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMiniObject {
pub _type: GType,
pub refcount: gint,
pub lockstate: gint,
pub flags: guint,
pub copy: GstMiniObjectCopyFunction,
pub dispose: GstMiniObjectDisposeFunction,
pub free: GstMiniObjectFreeFunction,
pub n_qdata: guint,
pub qdata: gpointer,
}
impl ::std::default::Default for Struct__GstMiniObject {
fn default() -> Struct__GstMiniObject { unsafe { ::std::mem::zeroed() } }
}
pub type GstMemory = Struct__GstMemory;
pub type GstAllocator = Struct__GstAllocator;
pub type Enum_Unnamed130 = ::libc::c_uint;
pub const GST_MEMORY_FLAG_READONLY: ::libc::c_uint = 2;
pub const GST_MEMORY_FLAG_NO_SHARE: ::libc::c_uint = 16;
pub const GST_MEMORY_FLAG_ZERO_PREFIXED: ::libc::c_uint = 32;
pub const GST_MEMORY_FLAG_ZERO_PADDED: ::libc::c_uint = 64;
pub const GST_MEMORY_FLAG_PHYSICALLY_CONTIGUOUS: ::libc::c_uint = 128;
pub const GST_MEMORY_FLAG_NOT_MAPPABLE: ::libc::c_uint = 256;
pub const GST_MEMORY_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstMemoryFlags = Enum_Unnamed130;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMemory {
pub mini_object: GstMiniObject,
pub allocator: *mut GstAllocator,
pub parent: *mut GstMemory,
pub maxsize: gsize,
pub align: gsize,
pub offset: gsize,
pub size: gsize,
}
impl ::std::default::Default for Struct__GstMemory {
fn default() -> Struct__GstMemory { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed131 = ::libc::c_uint;
pub const GST_MAP_READ: ::libc::c_uint = 1;
pub const GST_MAP_WRITE: ::libc::c_uint = 2;
pub const GST_MAP_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstMapFlags = Enum_Unnamed131;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed132 {
pub memory: *mut GstMemory,
pub flags: GstMapFlags,
pub data: *mut guint8,
pub size: gsize,
pub maxsize: gsize,
pub user_data: [gpointer; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed132 {
fn default() -> Struct_Unnamed132 { unsafe { ::std::mem::zeroed() } }
}
pub type GstMapInfo = Struct_Unnamed132;
pub type GstMemoryMapFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, maxsize: gsize,
flags: GstMapFlags) -> gpointer>;
pub type GstMemoryUnmapFunction =
::std::option::Option<extern "C" fn(mem: *mut GstMemory)>;
pub type GstMemoryCopyFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, offset: gssize,
size: gssize) -> *mut GstMemory>;
pub type GstMemoryShareFunction =
::std::option::Option<extern "C" fn
(mem: *mut GstMemory, offset: gssize,
size: gssize) -> *mut GstMemory>;
pub type GstMemoryIsSpanFunction =
::std::option::Option<extern "C" fn
(mem1: *mut GstMemory, mem2: *mut GstMemory,
offset: *mut gsize) -> gboolean>;
pub enum Struct__GstAllocatorPrivate { }
pub type GstAllocatorPrivate = Struct__GstAllocatorPrivate;
pub type GstAllocatorClass = Struct__GstAllocatorClass;
pub type GstAllocationParams = Struct__GstAllocationParams;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocationParams {
pub flags: GstMemoryFlags,
pub align: gsize,
pub prefix: gsize,
pub padding: gsize,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAllocationParams {
fn default() -> Struct__GstAllocationParams {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed133 = ::libc::c_uint;
pub const GST_ALLOCATOR_FLAG_CUSTOM_ALLOC: ::libc::c_uint = 16;
pub const GST_ALLOCATOR_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstAllocatorFlags = Enum_Unnamed133;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocator {
pub object: GstObject,
pub mem_type: *const gchar,
pub mem_map: GstMemoryMapFunction,
pub mem_unmap: GstMemoryUnmapFunction,
pub mem_copy: GstMemoryCopyFunction,
pub mem_share: GstMemoryShareFunction,
pub mem_is_span: GstMemoryIsSpanFunction,
pub _gst_reserved: [gpointer; 4u],
pub _priv: *mut GstAllocatorPrivate,
}
impl ::std::default::Default for Struct__GstAllocator {
fn default() -> Struct__GstAllocator { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAllocatorClass {
pub object_class: GstObjectClass,
pub alloc: ::std::option::Option<extern "C" fn
(allocator: *mut GstAllocator,
size: gsize,
params: *mut GstAllocationParams)
-> *mut GstMemory>,
pub free: ::std::option::Option<extern "C" fn
(allocator: *mut GstAllocator,
memory: *mut GstMemory)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAllocatorClass {
fn default() -> Struct__GstAllocatorClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstBuffer = Struct__GstBuffer;
pub type GstBufferPool = Struct__GstBufferPool;
pub type Enum_Unnamed134 = ::libc::c_uint;
pub const GST_BUFFER_FLAG_LIVE: ::libc::c_uint = 16;
pub const GST_BUFFER_FLAG_DECODE_ONLY: ::libc::c_uint = 32;
pub const GST_BUFFER_FLAG_DISCONT: ::libc::c_uint = 64;
pub const GST_BUFFER_FLAG_RESYNC: ::libc::c_uint = 128;
pub const GST_BUFFER_FLAG_CORRUPTED: ::libc::c_uint = 256;
pub const GST_BUFFER_FLAG_MARKER: ::libc::c_uint = 512;
pub const GST_BUFFER_FLAG_HEADER: ::libc::c_uint = 1024;
pub const GST_BUFFER_FLAG_GAP: ::libc::c_uint = 2048;
pub const GST_BUFFER_FLAG_DROPPABLE: ::libc::c_uint = 4096;
pub const GST_BUFFER_FLAG_DELTA_UNIT: ::libc::c_uint = 8192;
pub const GST_BUFFER_FLAG_TAG_MEMORY: ::libc::c_uint = 16384;
pub const GST_BUFFER_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstBufferFlags = Enum_Unnamed134;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBuffer {
pub mini_object: GstMiniObject,
pub pool: *mut GstBufferPool,
pub pts: GstClockTime,
pub dts: GstClockTime,
pub duration: GstClockTime,
pub offset: guint64,
pub offset_end: guint64,
}
impl ::std::default::Default for Struct__GstBuffer {
fn default() -> Struct__GstBuffer { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed135 = ::libc::c_uint;
pub const GST_BUFFER_COPY_NONE: ::libc::c_uint = 0;
pub const GST_BUFFER_COPY_FLAGS: ::libc::c_uint = 1;
pub const GST_BUFFER_COPY_TIMESTAMPS: ::libc::c_uint = 2;
pub const GST_BUFFER_COPY_META: ::libc::c_uint = 4;
pub const GST_BUFFER_COPY_MEMORY: ::libc::c_uint = 8;
pub const GST_BUFFER_COPY_MERGE: ::libc::c_uint = 16;
pub const GST_BUFFER_COPY_DEEP: ::libc::c_uint = 32;
pub type GstBufferCopyFlags = Enum_Unnamed135;
pub type GstMeta = Struct__GstMeta;
pub type GstMetaInfo = Struct__GstMetaInfo;
pub type Enum_Unnamed136 = ::libc::c_uint;
pub const GST_META_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_META_FLAG_READONLY: ::libc::c_uint = 1;
pub const GST_META_FLAG_POOLED: ::libc::c_uint = 2;
pub const GST_META_FLAG_LOCKED: ::libc::c_uint = 4;
pub const GST_META_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstMetaFlags = Enum_Unnamed136;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMeta {
pub flags: GstMetaFlags,
pub info: *const GstMetaInfo,
}
impl ::std::default::Default for Struct__GstMeta {
fn default() -> Struct__GstMeta { unsafe { ::std::mem::zeroed() } }
}
pub type GstMetaInitFunction =
::std::option::Option<extern "C" fn
(meta: *mut GstMeta, params: gpointer,
buffer: *mut GstBuffer) -> gboolean>;
pub type GstMetaFreeFunction =
::std::option::Option<extern "C" fn
(meta: *mut GstMeta, buffer: *mut GstBuffer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed137 {
pub region: gboolean,
pub offset: gsize,
pub size: gsize,
}
impl ::std::default::Default for Struct_Unnamed137 {
fn default() -> Struct_Unnamed137 { unsafe { ::std::mem::zeroed() } }
}
pub type GstMetaTransformCopy = Struct_Unnamed137;
pub type GstMetaTransformFunction =
::std::option::Option<extern "C" fn
(transbuf: *mut GstBuffer, meta: *mut GstMeta,
buffer: *mut GstBuffer, _type: GQuark,
data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMetaInfo {
pub api: GType,
pub _type: GType,
pub size: gsize,
pub init_func: GstMetaInitFunction,
pub free_func: GstMetaFreeFunction,
pub transform_func: GstMetaTransformFunction,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstMetaInfo {
fn default() -> Struct__GstMetaInfo { unsafe { ::std::mem::zeroed() } }
}
pub type GstBufferForeachMetaFunc =
::std::option::Option<extern "C" fn
(buffer: *mut GstBuffer,
meta: *mut *mut GstMeta, user_data: gpointer)
-> gboolean>;
pub enum Struct__GstBufferList { }
pub type GstBufferList = Struct__GstBufferList;
pub type GstBufferListFunc =
::std::option::Option<extern "C" fn
(buffer: *mut *mut GstBuffer, idx: guint,
user_data: gpointer) -> gboolean>;
pub enum Struct__GstDateTime { }
pub type GstDateTime = Struct__GstDateTime;
pub type GstStructure = Struct__GstStructure;
pub type GstStructureForeachFunc =
::std::option::Option<extern "C" fn
(field_id: GQuark, value: *const GValue,
user_data: gpointer) -> gboolean>;
pub type GstStructureMapFunc =
::std::option::Option<extern "C" fn
(field_id: GQuark, value: *mut GValue,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStructure {
pub _type: GType,
pub name: GQuark,
}
impl ::std::default::Default for Struct__GstStructure {
fn default() -> Struct__GstStructure { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstCapsFeatures { }
pub type GstCapsFeatures = Struct__GstCapsFeatures;
pub type Enum_Unnamed138 = ::libc::c_uint;
pub const GST_CAPS_FLAG_ANY: ::libc::c_uint = 16;
pub type GstCapsFlags = Enum_Unnamed138;
pub type Enum_Unnamed139 = ::libc::c_uint;
pub const GST_CAPS_INTERSECT_ZIG_ZAG: ::libc::c_uint = 0;
pub const GST_CAPS_INTERSECT_FIRST: ::libc::c_uint = 1;
pub type GstCapsIntersectMode = Enum_Unnamed139;
pub type GstCaps = Struct__GstCaps;
pub type GstStaticCaps = Struct__GstStaticCaps;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstCaps {
pub mini_object: GstMiniObject,
}
impl ::std::default::Default for Struct__GstCaps {
fn default() -> Struct__GstCaps { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStaticCaps {
pub caps: *mut GstCaps,
pub string: *const ::libc::c_char,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstStaticCaps {
fn default() -> Struct__GstStaticCaps { unsafe { ::std::mem::zeroed() } }
}
pub type GstPadTemplate = Struct__GstPadTemplate;
pub type GstPadTemplateClass = Struct__GstPadTemplateClass;
pub type GstStaticPadTemplate = Struct__GstStaticPadTemplate;
pub type GstEvent = Struct__GstEvent;
pub type Enum_Unnamed140 = ::libc::c_uint;
pub const GST_EVENT_TYPE_UPSTREAM: ::libc::c_uint = 1;
pub const GST_EVENT_TYPE_DOWNSTREAM: ::libc::c_uint = 2;
pub const GST_EVENT_TYPE_SERIALIZED: ::libc::c_uint = 4;
pub const GST_EVENT_TYPE_STICKY: ::libc::c_uint = 8;
pub const GST_EVENT_TYPE_STICKY_MULTI: ::libc::c_uint = 16;
pub type GstEventTypeFlags = Enum_Unnamed140;
pub type Enum_Unnamed141 = ::libc::c_uint;
pub const GST_EVENT_UNKNOWN: ::libc::c_uint = 0;
pub const GST_EVENT_FLUSH_START: ::libc::c_uint = 2563;
pub const GST_EVENT_FLUSH_STOP: ::libc::c_uint = 5127;
pub const GST_EVENT_STREAM_START: ::libc::c_uint = 10254;
pub const GST_EVENT_CAPS: ::libc::c_uint = 12814;
pub const GST_EVENT_SEGMENT: ::libc::c_uint = 17934;
pub const GST_EVENT_TAG: ::libc::c_uint = 20510;
pub const GST_EVENT_BUFFERSIZE: ::libc::c_uint = 23054;
pub const GST_EVENT_SINK_MESSAGE: ::libc::c_uint = 25630;
pub const GST_EVENT_EOS: ::libc::c_uint = 28174;
pub const GST_EVENT_TOC: ::libc::c_uint = 30750;
pub const GST_EVENT_SEGMENT_DONE: ::libc::c_uint = 38406;
pub const GST_EVENT_GAP: ::libc::c_uint = 40966;
pub const GST_EVENT_QOS: ::libc::c_uint = 48641;
pub const GST_EVENT_SEEK: ::libc::c_uint = 51201;
pub const GST_EVENT_NAVIGATION: ::libc::c_uint = 53761;
pub const GST_EVENT_LATENCY: ::libc::c_uint = 56321;
pub const GST_EVENT_STEP: ::libc::c_uint = 58881;
pub const GST_EVENT_RECONFIGURE: ::libc::c_uint = 61441;
pub const GST_EVENT_TOC_SELECT: ::libc::c_uint = 64001;
pub const GST_EVENT_CUSTOM_UPSTREAM: ::libc::c_uint = 69121;
pub const GST_EVENT_CUSTOM_DOWNSTREAM: ::libc::c_uint = 71686;
pub const GST_EVENT_CUSTOM_DOWNSTREAM_OOB: ::libc::c_uint = 74242;
pub const GST_EVENT_CUSTOM_DOWNSTREAM_STICKY: ::libc::c_uint = 76830;
pub const GST_EVENT_CUSTOM_BOTH: ::libc::c_uint = 79367;
pub const GST_EVENT_CUSTOM_BOTH_OOB: ::libc::c_uint = 81923;
pub type GstEventType = Enum_Unnamed141;
pub type Enum_Unnamed142 = ::libc::c_uint;
pub const GST_ITERATOR_DONE: ::libc::c_uint = 0;
pub const GST_ITERATOR_OK: ::libc::c_uint = 1;
pub const GST_ITERATOR_RESYNC: ::libc::c_uint = 2;
pub const GST_ITERATOR_ERROR: ::libc::c_uint = 3;
pub type GstIteratorResult = Enum_Unnamed142;
pub type GstIterator = Struct__GstIterator;
pub type Enum_Unnamed143 = ::libc::c_uint;
pub const GST_ITERATOR_ITEM_SKIP: ::libc::c_uint = 0;
pub const GST_ITERATOR_ITEM_PASS: ::libc::c_uint = 1;
pub const GST_ITERATOR_ITEM_END: ::libc::c_uint = 2;
pub type GstIteratorItem = Enum_Unnamed143;
pub type GstIteratorCopyFunction =
::std::option::Option<extern "C" fn
(it: *const GstIterator,
copy: *mut GstIterator)>;
pub type GstIteratorItemFunction =
::std::option::Option<extern "C" fn
(it: *mut GstIterator, item: *const GValue)
-> GstIteratorItem>;
pub type GstIteratorNextFunction =
::std::option::Option<extern "C" fn
(it: *mut GstIterator, result: *mut GValue)
-> GstIteratorResult>;
pub type GstIteratorResyncFunction =
::std::option::Option<extern "C" fn(it: *mut GstIterator)>;
pub type GstIteratorFreeFunction =
::std::option::Option<extern "C" fn(it: *mut GstIterator)>;
pub type GstIteratorForeachFunction =
::std::option::Option<extern "C" fn
(item: *const GValue, user_data: gpointer)>;
pub type GstIteratorFoldFunction =
::std::option::Option<extern "C" fn
(item: *const GValue, ret: *mut GValue,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstIterator {
pub copy: GstIteratorCopyFunction,
pub next: GstIteratorNextFunction,
pub item: GstIteratorItemFunction,
pub resync: GstIteratorResyncFunction,
pub free: GstIteratorFreeFunction,
pub pushed: *mut GstIterator,
pub _type: GType,
pub lock: *mut GMutex,
pub cookie: guint32,
pub master_cookie: *mut guint32,
pub size: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstIterator {
fn default() -> Struct__GstIterator { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed144 = ::libc::c_uint;
pub const GST_FORMAT_UNDEFINED: ::libc::c_uint = 0;
pub const GST_FORMAT_DEFAULT: ::libc::c_uint = 1;
pub const GST_FORMAT_BYTES: ::libc::c_uint = 2;
pub const GST_FORMAT_TIME: ::libc::c_uint = 3;
pub const GST_FORMAT_BUFFERS: ::libc::c_uint = 4;
pub const GST_FORMAT_PERCENT: ::libc::c_uint = 5;
pub type GstFormat = Enum_Unnamed144;
pub type GstFormatDefinition = Struct__GstFormatDefinition;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstFormatDefinition {
pub value: GstFormat,
pub nick: *const gchar,
pub description: *const gchar,
pub quark: GQuark,
}
impl ::std::default::Default for Struct__GstFormatDefinition {
fn default() -> Struct__GstFormatDefinition {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstSegment = Struct__GstSegment;
pub type Enum_Unnamed145 = ::libc::c_uint;
pub const GST_SEEK_TYPE_NONE: ::libc::c_uint = 0;
pub const GST_SEEK_TYPE_SET: ::libc::c_uint = 1;
pub const GST_SEEK_TYPE_END: ::libc::c_uint = 2;
pub type GstSeekType = Enum_Unnamed145;
pub type Enum_Unnamed146 = ::libc::c_uint;
pub const GST_SEEK_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_SEEK_FLAG_FLUSH: ::libc::c_uint = 1;
pub const GST_SEEK_FLAG_ACCURATE: ::libc::c_uint = 2;
pub const GST_SEEK_FLAG_KEY_UNIT: ::libc::c_uint = 4;
pub const GST_SEEK_FLAG_SEGMENT: ::libc::c_uint = 8;
pub const GST_SEEK_FLAG_SKIP: ::libc::c_uint = 16;
pub const GST_SEEK_FLAG_SNAP_BEFORE: ::libc::c_uint = 32;
pub const GST_SEEK_FLAG_SNAP_AFTER: ::libc::c_uint = 64;
pub const GST_SEEK_FLAG_SNAP_NEAREST: ::libc::c_uint = 96;
pub type GstSeekFlags = Enum_Unnamed146;
pub type Enum_Unnamed147 = ::libc::c_uint;
pub const GST_SEGMENT_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_SEGMENT_FLAG_RESET: ::libc::c_uint = 1;
pub const GST_SEGMENT_FLAG_SKIP: ::libc::c_uint = 16;
pub const GST_SEGMENT_FLAG_SEGMENT: ::libc::c_uint = 8;
pub type GstSegmentFlags = Enum_Unnamed147;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSegment {
pub flags: GstSegmentFlags,
pub rate: gdouble,
pub applied_rate: gdouble,
pub format: GstFormat,
pub base: guint64,
pub offset: guint64,
pub start: guint64,
pub stop: guint64,
pub time: guint64,
pub position: guint64,
pub duration: guint64,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSegment {
fn default() -> Struct__GstSegment { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstSample { }
pub type GstSample = Struct__GstSample;
pub type Enum_Unnamed148 = ::libc::c_uint;
pub const GST_TAG_MERGE_UNDEFINED: ::libc::c_uint = 0;
pub const GST_TAG_MERGE_REPLACE_ALL: ::libc::c_uint = 1;
pub const GST_TAG_MERGE_REPLACE: ::libc::c_uint = 2;
pub const GST_TAG_MERGE_APPEND: ::libc::c_uint = 3;
pub const GST_TAG_MERGE_PREPEND: ::libc::c_uint = 4;
pub const GST_TAG_MERGE_KEEP: ::libc::c_uint = 5;
pub const GST_TAG_MERGE_KEEP_ALL: ::libc::c_uint = 6;
pub const GST_TAG_MERGE_COUNT: ::libc::c_uint = 7;
pub type GstTagMergeMode = Enum_Unnamed148;
pub type Enum_Unnamed149 = ::libc::c_uint;
pub const GST_TAG_FLAG_UNDEFINED: ::libc::c_uint = 0;
pub const GST_TAG_FLAG_META: ::libc::c_uint = 1;
pub const GST_TAG_FLAG_ENCODED: ::libc::c_uint = 2;
pub const GST_TAG_FLAG_DECODED: ::libc::c_uint = 3;
pub const GST_TAG_FLAG_COUNT: ::libc::c_uint = 4;
pub type GstTagFlag = Enum_Unnamed149;
pub type GstTagList = Struct__GstTagList;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTagList {
pub mini_object: GstMiniObject,
}
impl ::std::default::Default for Struct__GstTagList {
fn default() -> Struct__GstTagList { unsafe { ::std::mem::zeroed() } }
}
pub type GstTagForeachFunc =
::std::option::Option<extern "C" fn
(list: *const GstTagList, tag: *const gchar,
user_data: gpointer)>;
pub type GstTagMergeFunc =
::std::option::Option<extern "C" fn
(dest: *mut GValue, src: *const GValue)>;
pub type Enum_Unnamed150 = ::libc::c_uint;
pub const GST_TAG_SCOPE_STREAM: ::libc::c_uint = 0;
pub const GST_TAG_SCOPE_GLOBAL: ::libc::c_uint = 1;
pub type GstTagScope = Enum_Unnamed150;
pub type GstMessage = Struct__GstMessage;
pub type Enum_Unnamed151 = ::libc::c_int;
pub const GST_MESSAGE_UNKNOWN: ::libc::c_int = 0;
pub const GST_MESSAGE_EOS: ::libc::c_int = 1;
pub const GST_MESSAGE_ERROR: ::libc::c_int = 2;
pub const GST_MESSAGE_WARNING: ::libc::c_int = 4;
pub const GST_MESSAGE_INFO: ::libc::c_int = 8;
pub const GST_MESSAGE_TAG: ::libc::c_int = 16;
pub const GST_MESSAGE_BUFFERING: ::libc::c_int = 32;
pub const GST_MESSAGE_STATE_CHANGED: ::libc::c_int = 64;
pub const GST_MESSAGE_STATE_DIRTY: ::libc::c_int = 128;
pub const GST_MESSAGE_STEP_DONE: ::libc::c_int = 256;
pub const GST_MESSAGE_CLOCK_PROVIDE: ::libc::c_int = 512;
pub const GST_MESSAGE_CLOCK_LOST: ::libc::c_int = 1024;
pub const GST_MESSAGE_NEW_CLOCK: ::libc::c_int = 2048;
pub const GST_MESSAGE_STRUCTURE_CHANGE: ::libc::c_int = 4096;
pub const GST_MESSAGE_STREAM_STATUS: ::libc::c_int = 8192;
pub const GST_MESSAGE_APPLICATION: ::libc::c_int = 16384;
pub const GST_MESSAGE_ELEMENT: ::libc::c_int = 32768;
pub const GST_MESSAGE_SEGMENT_START: ::libc::c_int = 65536;
pub const GST_MESSAGE_SEGMENT_DONE: ::libc::c_int = 131072;
pub const GST_MESSAGE_DURATION_CHANGED: ::libc::c_int = 262144;
pub const GST_MESSAGE_LATENCY: ::libc::c_int = 524288;
pub const GST_MESSAGE_ASYNC_START: ::libc::c_int = 1048576;
pub const GST_MESSAGE_ASYNC_DONE: ::libc::c_int = 2097152;
pub const GST_MESSAGE_REQUEST_STATE: ::libc::c_int = 4194304;
pub const GST_MESSAGE_STEP_START: ::libc::c_int = 8388608;
pub const GST_MESSAGE_QOS: ::libc::c_int = 16777216;
pub const GST_MESSAGE_PROGRESS: ::libc::c_int = 33554432;
pub const GST_MESSAGE_TOC: ::libc::c_int = 67108864;
pub const GST_MESSAGE_RESET_TIME: ::libc::c_int = 134217728;
pub const GST_MESSAGE_STREAM_START: ::libc::c_int = 268435456;
pub const GST_MESSAGE_NEED_CONTEXT: ::libc::c_int = 536870912;
pub const GST_MESSAGE_HAVE_CONTEXT: ::libc::c_int = 1073741824;
pub const GST_MESSAGE_EXTENDED: ::libc::c_int = -2147483648;
pub const GST_MESSAGE_DEVICE_ADDED: ::libc::c_int = -2147483647;
pub const GST_MESSAGE_DEVICE_REMOVED: ::libc::c_int = -2147483646;
pub const GST_MESSAGE_ANY: ::libc::c_int = -1;
pub type GstMessageType = Enum_Unnamed151;
pub enum Struct__GstTocEntry { }
pub type GstTocEntry = Struct__GstTocEntry;
pub enum Struct__GstToc { }
pub type GstToc = Struct__GstToc;
pub type Enum_Unnamed152 = ::libc::c_uint;
pub const GST_TOC_SCOPE_GLOBAL: ::libc::c_uint = 1;
pub const GST_TOC_SCOPE_CURRENT: ::libc::c_uint = 2;
pub type GstTocScope = Enum_Unnamed152;
pub type Enum_Unnamed153 = ::libc::c_int;
pub const GST_TOC_ENTRY_TYPE_ANGLE: ::libc::c_int = -3;
pub const GST_TOC_ENTRY_TYPE_VERSION: ::libc::c_int = -2;
pub const GST_TOC_ENTRY_TYPE_EDITION: ::libc::c_int = -1;
pub const GST_TOC_ENTRY_TYPE_INVALID: ::libc::c_int = 0;
pub const GST_TOC_ENTRY_TYPE_TITLE: ::libc::c_int = 1;
pub const GST_TOC_ENTRY_TYPE_TRACK: ::libc::c_int = 2;
pub const GST_TOC_ENTRY_TYPE_CHAPTER: ::libc::c_int = 3;
pub type GstTocEntryType = Enum_Unnamed153;
pub type Enum_Unnamed154 = ::libc::c_uint;
pub const GST_TOC_LOOP_NONE: ::libc::c_uint = 0;
pub const GST_TOC_LOOP_FORWARD: ::libc::c_uint = 1;
pub const GST_TOC_LOOP_REVERSE: ::libc::c_uint = 2;
pub const GST_TOC_LOOP_PING_PONG: ::libc::c_uint = 3;
pub type GstTocLoopType = Enum_Unnamed154;
pub enum Struct__GstContext { }
pub type GstContext = Struct__GstContext;
pub type GstQuery = Struct__GstQuery;
pub type Enum_Unnamed155 = ::libc::c_uint;
pub const GST_QUERY_TYPE_UPSTREAM: ::libc::c_uint = 1;
pub const GST_QUERY_TYPE_DOWNSTREAM: ::libc::c_uint = 2;
pub const GST_QUERY_TYPE_SERIALIZED: ::libc::c_uint = 4;
pub type GstQueryTypeFlags = Enum_Unnamed155;
pub type Enum_Unnamed156 = ::libc::c_uint;
pub const GST_QUERY_UNKNOWN: ::libc::c_uint = 0;
pub const GST_QUERY_POSITION: ::libc::c_uint = 2563;
pub const GST_QUERY_DURATION: ::libc::c_uint = 5123;
pub const GST_QUERY_LATENCY: ::libc::c_uint = 7683;
pub const GST_QUERY_JITTER: ::libc::c_uint = 10243;
pub const GST_QUERY_RATE: ::libc::c_uint = 12803;
pub const GST_QUERY_SEEKING: ::libc::c_uint = 15363;
pub const GST_QUERY_SEGMENT: ::libc::c_uint = 17923;
pub const GST_QUERY_CONVERT: ::libc::c_uint = 20483;
pub const GST_QUERY_FORMATS: ::libc::c_uint = 23043;
pub const GST_QUERY_BUFFERING: ::libc::c_uint = 28163;
pub const GST_QUERY_CUSTOM: ::libc::c_uint = 30723;
pub const GST_QUERY_URI: ::libc::c_uint = 33283;
pub const GST_QUERY_ALLOCATION: ::libc::c_uint = 35846;
pub const GST_QUERY_SCHEDULING: ::libc::c_uint = 38401;
pub const GST_QUERY_ACCEPT_CAPS: ::libc::c_uint = 40963;
pub const GST_QUERY_CAPS: ::libc::c_uint = 43523;
pub const GST_QUERY_DRAIN: ::libc::c_uint = 46086;
pub const GST_QUERY_CONTEXT: ::libc::c_uint = 48643;
pub type GstQueryType = Enum_Unnamed156;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstQuery {
pub mini_object: GstMiniObject,
pub _type: GstQueryType,
}
impl ::std::default::Default for Struct__GstQuery {
fn default() -> Struct__GstQuery { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed157 = ::libc::c_uint;
pub const GST_BUFFERING_STREAM: ::libc::c_uint = 0;
pub const GST_BUFFERING_DOWNLOAD: ::libc::c_uint = 1;
pub const GST_BUFFERING_TIMESHIFT: ::libc::c_uint = 2;
pub const GST_BUFFERING_LIVE: ::libc::c_uint = 3;
pub type GstBufferingMode = Enum_Unnamed157;
pub type Enum_Unnamed158 = ::libc::c_uint;
pub const GST_SCHEDULING_FLAG_SEEKABLE: ::libc::c_uint = 1;
pub const GST_SCHEDULING_FLAG_SEQUENTIAL: ::libc::c_uint = 2;
pub const GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED: ::libc::c_uint = 4;
pub type GstSchedulingFlags = Enum_Unnamed158;
pub type GstDevice = Struct__GstDevice;
pub type GstDeviceClass = Struct__GstDeviceClass;
pub enum Struct__GstDevicePrivate { }
pub type GstDevicePrivate = Struct__GstDevicePrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDevice {
pub parent: GstObject,
pub _priv: *mut GstDevicePrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDevice {
fn default() -> Struct__GstDevice { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceClass {
pub parent_class: GstObjectClass,
pub create_element: ::std::option::Option<extern "C" fn
(device: *mut GstDevice,
name: *const gchar)
-> *mut GstElement>,
pub reconfigure_element: ::std::option::Option<extern "C" fn
(device:
*mut GstDevice,
element:
*mut GstElement)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceClass {
fn default() -> Struct__GstDeviceClass { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed159 = ::libc::c_uint;
pub const GST_STRUCTURE_CHANGE_TYPE_PAD_LINK: ::libc::c_uint = 0;
pub const GST_STRUCTURE_CHANGE_TYPE_PAD_UNLINK: ::libc::c_uint = 1;
pub type GstStructureChangeType = Enum_Unnamed159;
pub type Enum_Unnamed160 = ::libc::c_uint;
pub const GST_STREAM_STATUS_TYPE_CREATE: ::libc::c_uint = 0;
pub const GST_STREAM_STATUS_TYPE_ENTER: ::libc::c_uint = 1;
pub const GST_STREAM_STATUS_TYPE_LEAVE: ::libc::c_uint = 2;
pub const GST_STREAM_STATUS_TYPE_DESTROY: ::libc::c_uint = 3;
pub const GST_STREAM_STATUS_TYPE_START: ::libc::c_uint = 8;
pub const GST_STREAM_STATUS_TYPE_PAUSE: ::libc::c_uint = 9;
pub const GST_STREAM_STATUS_TYPE_STOP: ::libc::c_uint = 10;
pub type GstStreamStatusType = Enum_Unnamed160;
pub type Enum_Unnamed161 = ::libc::c_uint;
pub const GST_PROGRESS_TYPE_START: ::libc::c_uint = 0;
pub const GST_PROGRESS_TYPE_CONTINUE: ::libc::c_uint = 1;
pub const GST_PROGRESS_TYPE_COMPLETE: ::libc::c_uint = 2;
pub const GST_PROGRESS_TYPE_CANCELED: ::libc::c_uint = 3;
pub const GST_PROGRESS_TYPE_ERROR: ::libc::c_uint = 4;
pub type GstProgressType = Enum_Unnamed161;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstMessage {
pub mini_object: GstMiniObject,
pub _type: GstMessageType,
pub timestamp: guint64,
pub src: *mut GstObject,
pub seqnum: guint32,
pub lock: GMutex,
pub cond: GCond,
}
impl ::std::default::Default for Struct__GstMessage {
fn default() -> Struct__GstMessage { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed162 = ::libc::c_uint;
pub const GST_QOS_TYPE_OVERFLOW: ::libc::c_uint = 0;
pub const GST_QOS_TYPE_UNDERFLOW: ::libc::c_uint = 1;
pub const GST_QOS_TYPE_THROTTLE: ::libc::c_uint = 2;
pub type GstQOSType = Enum_Unnamed162;
pub type Enum_Unnamed163 = ::libc::c_uint;
pub const GST_STREAM_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_STREAM_FLAG_SPARSE: ::libc::c_uint = 1;
pub const GST_STREAM_FLAG_SELECT: ::libc::c_uint = 2;
pub const GST_STREAM_FLAG_UNSELECT: ::libc::c_uint = 4;
pub type GstStreamFlags = Enum_Unnamed163;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstEvent {
pub mini_object: GstMiniObject,
pub _type: GstEventType,
pub timestamp: guint64,
pub seqnum: guint32,
}
impl ::std::default::Default for Struct__GstEvent {
fn default() -> Struct__GstEvent { unsafe { ::std::mem::zeroed() } }
}
pub type GstTaskPool = Struct__GstTaskPool;
pub type GstTaskPoolClass = Struct__GstTaskPoolClass;
pub type GstTaskPoolFunction =
::std::option::Option<extern "C" fn(user_data: *mut ::libc::c_void)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskPool {
pub object: GstObject,
pub pool: *mut GThreadPool,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskPool {
fn default() -> Struct__GstTaskPool { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskPoolClass {
pub parent_class: GstObjectClass,
pub prepare: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
error: *mut *mut GError)>,
pub cleanup: ::std::option::Option<extern "C" fn(pool: *mut GstTaskPool)>,
pub push: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
func: GstTaskPoolFunction,
user_data: gpointer,
error: *mut *mut GError)
-> gpointer>,
pub join: ::std::option::Option<extern "C" fn
(pool: *mut GstTaskPool,
id: gpointer)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskPoolClass {
fn default() -> Struct__GstTaskPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstTaskFunction =
::std::option::Option<extern "C" fn(user_data: gpointer)>;
pub type GstTask = Struct__GstTask;
pub type GstTaskClass = Struct__GstTaskClass;
pub enum Struct__GstTaskPrivate { }
pub type GstTaskPrivate = Struct__GstTaskPrivate;
pub type Enum_Unnamed164 = ::libc::c_uint;
pub const GST_TASK_STARTED: ::libc::c_uint = 0;
pub const GST_TASK_STOPPED: ::libc::c_uint = 1;
pub const GST_TASK_PAUSED: ::libc::c_uint = 2;
pub type GstTaskState = Enum_Unnamed164;
pub type GstTaskThreadFunc =
::std::option::Option<extern "C" fn
(task: *mut GstTask, thread: *mut GThread,
user_data: gpointer)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTask {
pub object: GstObject,
pub state: GstTaskState,
pub cond: GCond,
pub lock: *mut GRecMutex,
pub func: GstTaskFunction,
pub user_data: gpointer,
pub notify: GDestroyNotify,
pub running: gboolean,
pub thread: *mut GThread,
pub _priv: *mut GstTaskPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTask {
fn default() -> Struct__GstTask { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTaskClass {
pub parent_class: GstObjectClass,
pub pool: *mut GstTaskPool,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTaskClass {
fn default() -> Struct__GstTaskClass { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed165 = ::libc::c_uint;
pub const GST_PAD_ALWAYS: ::libc::c_uint = 0;
pub const GST_PAD_SOMETIMES: ::libc::c_uint = 1;
pub const GST_PAD_REQUEST: ::libc::c_uint = 2;
pub type GstPadPresence = Enum_Unnamed165;
pub type Enum_Unnamed166 = ::libc::c_uint;
pub const GST_PAD_TEMPLATE_FLAG_LAST: ::libc::c_uint = 256;
pub type GstPadTemplateFlags = Enum_Unnamed166;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadTemplate {
pub object: GstObject,
pub name_template: *mut gchar,
pub direction: GstPadDirection,
pub presence: GstPadPresence,
pub caps: *mut GstCaps,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadTemplate {
fn default() -> Struct__GstPadTemplate { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadTemplateClass {
pub parent_class: GstObjectClass,
pub pad_created: ::std::option::Option<extern "C" fn
(templ: *mut GstPadTemplate,
pad: *mut GstPad)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadTemplateClass {
fn default() -> Struct__GstPadTemplateClass {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstStaticPadTemplate {
pub name_template: *const gchar,
pub direction: GstPadDirection,
pub presence: GstPadPresence,
pub static_caps: GstStaticCaps,
}
impl ::std::default::Default for Struct__GstStaticPadTemplate {
fn default() -> Struct__GstStaticPadTemplate {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed167 = ::libc::c_int;
pub const GST_PAD_LINK_OK: ::libc::c_int = 0;
pub const GST_PAD_LINK_WRONG_HIERARCHY: ::libc::c_int = -1;
pub const GST_PAD_LINK_WAS_LINKED: ::libc::c_int = -2;
pub const GST_PAD_LINK_WRONG_DIRECTION: ::libc::c_int = -3;
pub const GST_PAD_LINK_NOFORMAT: ::libc::c_int = -4;
pub const GST_PAD_LINK_NOSCHED: ::libc::c_int = -5;
pub const GST_PAD_LINK_REFUSED: ::libc::c_int = -6;
pub type GstPadLinkReturn = Enum_Unnamed167;
pub type Enum_Unnamed168 = ::libc::c_int;
pub const GST_FLOW_CUSTOM_SUCCESS_2: ::libc::c_int = 102;
pub const GST_FLOW_CUSTOM_SUCCESS_1: ::libc::c_int = 101;
pub const GST_FLOW_CUSTOM_SUCCESS: ::libc::c_int = 100;
pub const GST_FLOW_OK: ::libc::c_int = 0;
pub const GST_FLOW_NOT_LINKED: ::libc::c_int = -1;
pub const GST_FLOW_FLUSHING: ::libc::c_int = -2;
pub const GST_FLOW_EOS: ::libc::c_int = -3;
pub const GST_FLOW_NOT_NEGOTIATED: ::libc::c_int = -4;
pub const GST_FLOW_ERROR: ::libc::c_int = -5;
pub const GST_FLOW_NOT_SUPPORTED: ::libc::c_int = -6;
pub const GST_FLOW_CUSTOM_ERROR: ::libc::c_int = -100;
pub const GST_FLOW_CUSTOM_ERROR_1: ::libc::c_int = -101;
pub const GST_FLOW_CUSTOM_ERROR_2: ::libc::c_int = -102;
pub type GstFlowReturn = Enum_Unnamed168;
pub type Enum_Unnamed169 = ::libc::c_uint;
pub const GST_PAD_LINK_CHECK_NOTHING: ::libc::c_uint = 0;
pub const GST_PAD_LINK_CHECK_HIERARCHY: ::libc::c_uint = 1;
pub const GST_PAD_LINK_CHECK_TEMPLATE_CAPS: ::libc::c_uint = 2;
pub const GST_PAD_LINK_CHECK_CAPS: ::libc::c_uint = 4;
pub const GST_PAD_LINK_CHECK_DEFAULT: ::libc::c_uint = 5;
pub type GstPadLinkCheck = Enum_Unnamed169;
pub type GstPadActivateFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)
-> gboolean>;
pub type GstPadActivateModeFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
mode: GstPadMode, active: gboolean)
-> gboolean>;
pub type GstPadChainFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
buffer: *mut GstBuffer) -> GstFlowReturn>;
pub type GstPadChainListFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
list: *mut GstBufferList) -> GstFlowReturn>;
pub type GstPadGetRangeFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
offset: guint64, length: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn>;
pub type GstPadEventFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
event: *mut GstEvent) -> gboolean>;
pub type GstPadIterIntLinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)
-> *mut GstIterator>;
pub type GstPadQueryFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
query: *mut GstQuery) -> gboolean>;
pub type GstPadLinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject,
peer: *mut GstPad) -> GstPadLinkReturn>;
pub type GstPadUnlinkFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, parent: *mut GstObject)>;
pub type GstPadForwardFunction =
::std::option::Option<extern "C" fn(pad: *mut GstPad, user_data: gpointer)
-> gboolean>;
pub type Enum_Unnamed170 = ::libc::c_uint;
pub const GST_PAD_PROBE_TYPE_INVALID: ::libc::c_uint = 0;
pub const GST_PAD_PROBE_TYPE_IDLE: ::libc::c_uint = 1;
pub const GST_PAD_PROBE_TYPE_BLOCK: ::libc::c_uint = 2;
pub const GST_PAD_PROBE_TYPE_BUFFER: ::libc::c_uint = 16;
pub const GST_PAD_PROBE_TYPE_BUFFER_LIST: ::libc::c_uint = 32;
pub const GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM: ::libc::c_uint = 64;
pub const GST_PAD_PROBE_TYPE_EVENT_UPSTREAM: ::libc::c_uint = 128;
pub const GST_PAD_PROBE_TYPE_EVENT_FLUSH: ::libc::c_uint = 256;
pub const GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM: ::libc::c_uint = 512;
pub const GST_PAD_PROBE_TYPE_QUERY_UPSTREAM: ::libc::c_uint = 1024;
pub const GST_PAD_PROBE_TYPE_PUSH: ::libc::c_uint = 4096;
pub const GST_PAD_PROBE_TYPE_PULL: ::libc::c_uint = 8192;
pub const GST_PAD_PROBE_TYPE_BLOCKING: ::libc::c_uint = 3;
pub const GST_PAD_PROBE_TYPE_DATA_DOWNSTREAM: ::libc::c_uint = 112;
pub const GST_PAD_PROBE_TYPE_DATA_UPSTREAM: ::libc::c_uint = 128;
pub const GST_PAD_PROBE_TYPE_DATA_BOTH: ::libc::c_uint = 240;
pub const GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM: ::libc::c_uint = 114;
pub const GST_PAD_PROBE_TYPE_BLOCK_UPSTREAM: ::libc::c_uint = 130;
pub const GST_PAD_PROBE_TYPE_EVENT_BOTH: ::libc::c_uint = 192;
pub const GST_PAD_PROBE_TYPE_QUERY_BOTH: ::libc::c_uint = 1536;
pub const GST_PAD_PROBE_TYPE_ALL_BOTH: ::libc::c_uint = 1776;
pub const GST_PAD_PROBE_TYPE_SCHEDULING: ::libc::c_uint = 12288;
pub type GstPadProbeType = Enum_Unnamed170;
pub type Enum_Unnamed171 = ::libc::c_uint;
pub const GST_PAD_PROBE_DROP: ::libc::c_uint = 0;
pub const GST_PAD_PROBE_OK: ::libc::c_uint = 1;
pub const GST_PAD_PROBE_REMOVE: ::libc::c_uint = 2;
pub const GST_PAD_PROBE_PASS: ::libc::c_uint = 3;
pub type GstPadProbeReturn = Enum_Unnamed171;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadProbeInfo {
pub _type: GstPadProbeType,
pub id: gulong,
pub data: gpointer,
pub offset: guint64,
pub size: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadProbeInfo {
fn default() -> Struct__GstPadProbeInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPadProbeCallback =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, info: *mut GstPadProbeInfo,
user_data: gpointer) -> GstPadProbeReturn>;
pub type GstPadStickyEventsForeachFunction =
::std::option::Option<extern "C" fn
(pad: *mut GstPad, event: *mut *mut GstEvent,
user_data: gpointer) -> gboolean>;
pub type Enum_Unnamed172 = ::libc::c_uint;
pub const GST_PAD_FLAG_BLOCKED: ::libc::c_uint = 16;
pub const GST_PAD_FLAG_FLUSHING: ::libc::c_uint = 32;
pub const GST_PAD_FLAG_EOS: ::libc::c_uint = 64;
pub const GST_PAD_FLAG_BLOCKING: ::libc::c_uint = 128;
pub const GST_PAD_FLAG_NEED_PARENT: ::libc::c_uint = 256;
pub const GST_PAD_FLAG_NEED_RECONFIGURE: ::libc::c_uint = 512;
pub const GST_PAD_FLAG_PENDING_EVENTS: ::libc::c_uint = 1024;
pub const GST_PAD_FLAG_FIXED_CAPS: ::libc::c_uint = 2048;
pub const GST_PAD_FLAG_PROXY_CAPS: ::libc::c_uint = 4096;
pub const GST_PAD_FLAG_PROXY_ALLOCATION: ::libc::c_uint = 8192;
pub const GST_PAD_FLAG_PROXY_SCHEDULING: ::libc::c_uint = 16384;
pub const GST_PAD_FLAG_ACCEPT_INTERSECT: ::libc::c_uint = 32768;
pub const GST_PAD_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstPadFlags = Enum_Unnamed172;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPad {
pub object: GstObject,
pub element_private: gpointer,
pub padtemplate: *mut GstPadTemplate,
pub direction: GstPadDirection,
pub stream_rec_lock: GRecMutex,
pub task: *mut GstTask,
pub block_cond: GCond,
pub probes: GHookList,
pub mode: GstPadMode,
pub activatefunc: GstPadActivateFunction,
pub activatedata: gpointer,
pub activatenotify: GDestroyNotify,
pub activatemodefunc: GstPadActivateModeFunction,
pub activatemodedata: gpointer,
pub activatemodenotify: GDestroyNotify,
pub peer: *mut GstPad,
pub linkfunc: GstPadLinkFunction,
pub linkdata: gpointer,
pub linknotify: GDestroyNotify,
pub unlinkfunc: GstPadUnlinkFunction,
pub unlinkdata: gpointer,
pub unlinknotify: GDestroyNotify,
pub chainfunc: GstPadChainFunction,
pub chaindata: gpointer,
pub chainnotify: GDestroyNotify,
pub chainlistfunc: GstPadChainListFunction,
pub chainlistdata: gpointer,
pub chainlistnotify: GDestroyNotify,
pub getrangefunc: GstPadGetRangeFunction,
pub getrangedata: gpointer,
pub getrangenotify: GDestroyNotify,
pub eventfunc: GstPadEventFunction,
pub eventdata: gpointer,
pub eventnotify: GDestroyNotify,
pub offset: gint64,
pub queryfunc: GstPadQueryFunction,
pub querydata: gpointer,
pub querynotify: GDestroyNotify,
pub iterintlinkfunc: GstPadIterIntLinkFunction,
pub iterintlinkdata: gpointer,
pub iterintlinknotify: GDestroyNotify,
pub num_probes: gint,
pub num_blocked: gint,
pub _priv: *mut GstPadPrivate,
pub ABI: Union_Unnamed173,
}
impl ::std::default::Default for Struct__GstPad {
fn default() -> Struct__GstPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed173 {
pub _bindgen_data_: [u64; 4u],
}
impl Union_Unnamed173 {
pub unsafe fn _gst_reserved(&mut self) -> *mut [gpointer; 4u] {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn abi(&mut self) -> *mut Struct_Unnamed174 {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed173 {
fn default() -> Union_Unnamed173 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed174 {
pub last_flowret: GstFlowReturn,
}
impl ::std::default::Default for Struct_Unnamed174 {
fn default() -> Struct_Unnamed174 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPadClass {
pub parent_class: GstObjectClass,
pub linked: ::std::option::Option<extern "C" fn
(pad: *mut GstPad,
peer: *mut GstPad)>,
pub unlinked: ::std::option::Option<extern "C" fn
(pad: *mut GstPad,
peer: *mut GstPad)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPadClass {
fn default() -> Struct__GstPadClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstBus = Struct__GstBus;
pub enum Struct__GstBusPrivate { }
pub type GstBusPrivate = Struct__GstBusPrivate;
pub type GstBusClass = Struct__GstBusClass;
pub type Enum_Unnamed175 = ::libc::c_uint;
pub const GST_BUS_FLUSHING: ::libc::c_uint = 16;
pub const GST_BUS_FLAG_LAST: ::libc::c_uint = 32;
pub type GstBusFlags = Enum_Unnamed175;
pub type Enum_Unnamed176 = ::libc::c_uint;
pub const GST_BUS_DROP: ::libc::c_uint = 0;
pub const GST_BUS_PASS: ::libc::c_uint = 1;
pub const GST_BUS_ASYNC: ::libc::c_uint = 2;
pub type GstBusSyncReply = Enum_Unnamed176;
pub type GstBusSyncHandler =
::std::option::Option<extern "C" fn
(bus: *mut GstBus, message: *mut GstMessage,
user_data: gpointer) -> GstBusSyncReply>;
pub type GstBusFunc =
::std::option::Option<extern "C" fn
(bus: *mut GstBus, message: *mut GstMessage,
user_data: gpointer) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBus {
pub object: GstObject,
pub _priv: *mut GstBusPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBus {
fn default() -> Struct__GstBus { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBusClass {
pub parent_class: GstObjectClass,
pub message: ::std::option::Option<extern "C" fn
(bus: *mut GstBus,
message: *mut GstMessage)>,
pub sync_message: ::std::option::Option<extern "C" fn
(bus: *mut GstBus,
message: *mut GstMessage)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBusClass {
fn default() -> Struct__GstBusClass { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstElementFactory { }
pub type GstElementFactory = Struct__GstElementFactory;
pub enum Struct__GstElementFactoryClass { }
pub type GstElementFactoryClass = Struct__GstElementFactoryClass;
pub enum Struct__GstPlugin { }
pub type GstPlugin = Struct__GstPlugin;
pub enum Struct__GstPluginClass { }
pub type GstPluginClass = Struct__GstPluginClass;
pub type GstPluginDesc = Struct__GstPluginDesc;
pub type Enum_Unnamed177 = ::libc::c_uint;
pub const GST_PLUGIN_ERROR_MODULE: ::libc::c_uint = 0;
pub const GST_PLUGIN_ERROR_DEPENDENCIES: ::libc::c_uint = 1;
pub const GST_PLUGIN_ERROR_NAME_MISMATCH: ::libc::c_uint = 2;
pub type GstPluginError = Enum_Unnamed177;
pub type Enum_Unnamed178 = ::libc::c_uint;
pub const GST_PLUGIN_FLAG_CACHED: ::libc::c_uint = 16;
pub const GST_PLUGIN_FLAG_BLACKLISTED: ::libc::c_uint = 32;
pub type GstPluginFlags = Enum_Unnamed178;
pub type Enum_Unnamed179 = ::libc::c_uint;
pub const GST_PLUGIN_DEPENDENCY_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_PLUGIN_DEPENDENCY_FLAG_RECURSE: ::libc::c_uint = 1;
pub const GST_PLUGIN_DEPENDENCY_FLAG_PATHS_ARE_DEFAULT_ONLY: ::libc::c_uint =
2;
pub const GST_PLUGIN_DEPENDENCY_FLAG_FILE_NAME_IS_SUFFIX: ::libc::c_uint = 4;
pub type GstPluginDependencyFlags = Enum_Unnamed179;
pub type GstPluginInitFunc =
::std::option::Option<extern "C" fn(plugin: *mut GstPlugin) -> gboolean>;
pub type GstPluginInitFullFunc =
::std::option::Option<extern "C" fn
(plugin: *mut GstPlugin, user_data: gpointer)
-> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPluginDesc {
pub major_version: gint,
pub minor_version: gint,
pub name: *const gchar,
pub description: *const gchar,
pub plugin_init: GstPluginInitFunc,
pub version: *const gchar,
pub license: *const gchar,
pub source: *const gchar,
pub package: *const gchar,
pub origin: *const gchar,
pub release_datetime: *const gchar,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPluginDesc {
fn default() -> Struct__GstPluginDesc { unsafe { ::std::mem::zeroed() } }
}
pub type GstPluginFilter =
::std::option::Option<extern "C" fn
(plugin: *mut GstPlugin, user_data: gpointer)
-> gboolean>;
pub enum Struct__GstPluginFeature { }
pub type GstPluginFeature = Struct__GstPluginFeature;
pub enum Struct__GstPluginFeatureClass { }
pub type GstPluginFeatureClass = Struct__GstPluginFeatureClass;
pub type Enum_Unnamed180 = ::libc::c_uint;
pub const GST_RANK_NONE: ::libc::c_uint = 0;
pub const GST_RANK_MARGINAL: ::libc::c_uint = 64;
pub const GST_RANK_SECONDARY: ::libc::c_uint = 128;
pub const GST_RANK_PRIMARY: ::libc::c_uint = 256;
pub type GstRank = Enum_Unnamed180;
pub type GstPluginFeatureFilter =
::std::option::Option<extern "C" fn
(feature: *mut GstPluginFeature,
user_data: gpointer) -> gboolean>;
pub type Enum_Unnamed181 = ::libc::c_uint;
pub const GST_URI_ERROR_UNSUPPORTED_PROTOCOL: ::libc::c_uint = 0;
pub const GST_URI_ERROR_BAD_URI: ::libc::c_uint = 1;
pub const GST_URI_ERROR_BAD_STATE: ::libc::c_uint = 2;
pub const GST_URI_ERROR_BAD_REFERENCE: ::libc::c_uint = 3;
pub type GstURIError = Enum_Unnamed181;
pub type Enum_Unnamed182 = ::libc::c_uint;
pub const GST_URI_UNKNOWN: ::libc::c_uint = 0;
pub const GST_URI_SINK: ::libc::c_uint = 1;
pub const GST_URI_SRC: ::libc::c_uint = 2;
pub type GstURIType = Enum_Unnamed182;
pub enum Struct__GstURIHandler { }
pub type GstURIHandler = Struct__GstURIHandler;
pub type GstURIHandlerInterface = Struct__GstURIHandlerInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstURIHandlerInterface {
pub parent: GTypeInterface,
pub get_type: ::std::option::Option<extern "C" fn(_type: GType)
-> GstURIType>,
pub get_protocols: ::std::option::Option<extern "C" fn(_type: GType)
-> *const *const gchar>,
pub get_uri: ::std::option::Option<extern "C" fn
(handler: *mut GstURIHandler)
-> *mut gchar>,
pub set_uri: ::std::option::Option<extern "C" fn
(handler: *mut GstURIHandler,
uri: *const gchar,
error: *mut *mut GError)
-> gboolean>,
}
impl ::std::default::Default for Struct__GstURIHandlerInterface {
fn default() -> Struct__GstURIHandlerInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstElementFactoryListType = guint64;
pub type Enum_Unnamed183 = ::libc::c_uint;
pub const GST_STATE_CHANGE_FAILURE: ::libc::c_uint = 0;
pub const GST_STATE_CHANGE_SUCCESS: ::libc::c_uint = 1;
pub const GST_STATE_CHANGE_ASYNC: ::libc::c_uint = 2;
pub const GST_STATE_CHANGE_NO_PREROLL: ::libc::c_uint = 3;
pub type GstStateChangeReturn = Enum_Unnamed183;
pub type Enum_Unnamed184 = ::libc::c_uint;
pub const GST_STATE_CHANGE_NULL_TO_READY: ::libc::c_uint = 10;
pub const GST_STATE_CHANGE_READY_TO_PAUSED: ::libc::c_uint = 19;
pub const GST_STATE_CHANGE_PAUSED_TO_PLAYING: ::libc::c_uint = 28;
pub const GST_STATE_CHANGE_PLAYING_TO_PAUSED: ::libc::c_uint = 35;
pub const GST_STATE_CHANGE_PAUSED_TO_READY: ::libc::c_uint = 26;
pub const GST_STATE_CHANGE_READY_TO_NULL: ::libc::c_uint = 17;
pub type GstStateChange = Enum_Unnamed184;
pub type Enum_Unnamed185 = ::libc::c_uint;
pub const GST_ELEMENT_FLAG_LOCKED_STATE: ::libc::c_uint = 16;
pub const GST_ELEMENT_FLAG_SINK: ::libc::c_uint = 32;
pub const GST_ELEMENT_FLAG_SOURCE: ::libc::c_uint = 64;
pub const GST_ELEMENT_FLAG_PROVIDE_CLOCK: ::libc::c_uint = 128;
pub const GST_ELEMENT_FLAG_REQUIRE_CLOCK: ::libc::c_uint = 256;
pub const GST_ELEMENT_FLAG_INDEXABLE: ::libc::c_uint = 512;
pub const GST_ELEMENT_FLAG_LAST: ::libc::c_uint = 16384;
pub type GstElementFlags = Enum_Unnamed185;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstElement {
pub object: GstObject,
pub state_lock: GRecMutex,
pub state_cond: GCond,
pub state_cookie: guint32,
pub target_state: GstState,
pub current_state: GstState,
pub next_state: GstState,
pub pending_state: GstState,
pub last_return: GstStateChangeReturn,
pub bus: *mut GstBus,
pub clock: *mut GstClock,
pub base_time: GstClockTimeDiff,
pub start_time: GstClockTime,
pub numpads: guint16,
pub pads: *mut GList,
pub numsrcpads: guint16,
pub srcpads: *mut GList,
pub numsinkpads: guint16,
pub sinkpads: *mut GList,
pub pads_cookie: guint32,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstElement {
fn default() -> Struct__GstElement { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstElementClass {
pub parent_class: GstObjectClass,
pub metadata: gpointer,
pub elementfactory: *mut GstElementFactory,
pub padtemplates: *mut GList,
pub numpadtemplates: gint,
pub pad_templ_cookie: guint32,
pub pad_added: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub pad_removed: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub no_more_pads: ::std::option::Option<extern "C" fn
(element: *mut GstElement)>,
pub request_new_pad: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
templ:
*mut GstPadTemplate,
name: *const gchar,
caps: *const GstCaps)
-> *mut GstPad>,
pub release_pad: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
pad: *mut GstPad)>,
pub get_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
state: *mut GstState,
pending: *mut GstState,
timeout: GstClockTime)
-> GstStateChangeReturn>,
pub set_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
state: GstState)
-> GstStateChangeReturn>,
pub change_state: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
transition: GstStateChange)
-> GstStateChangeReturn>,
pub state_changed: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
oldstate: GstState,
newstate: GstState,
pending: GstState)>,
pub set_bus: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
bus: *mut GstBus)>,
pub provide_clock: ::std::option::Option<extern "C" fn
(element: *mut GstElement)
-> *mut GstClock>,
pub set_clock: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
clock: *mut GstClock)
-> gboolean>,
pub send_event: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
event: *mut GstEvent)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
query: *mut GstQuery) -> gboolean>,
pub post_message: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
message: *mut GstMessage)
-> gboolean>,
pub set_context: ::std::option::Option<extern "C" fn
(element: *mut GstElement,
context: *mut GstContext)>,
pub _gst_reserved: [gpointer; 18u],
}
impl ::std::default::Default for Struct__GstElementClass {
fn default() -> Struct__GstElementClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed186 = ::libc::c_uint;
pub const GST_BIN_FLAG_NO_RESYNC: ::libc::c_uint = 16384;
pub const GST_BIN_FLAG_LAST: ::libc::c_uint = 524288;
pub type GstBinFlags = Enum_Unnamed186;
pub type GstBin = Struct__GstBin;
pub type GstBinClass = Struct__GstBinClass;
pub enum Struct__GstBinPrivate { }
pub type GstBinPrivate = Struct__GstBinPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBin {
pub element: GstElement,
pub numchildren: gint,
pub children: *mut GList,
pub children_cookie: guint32,
pub child_bus: *mut GstBus,
pub messages: *mut GList,
pub polling: gboolean,
pub state_dirty: gboolean,
pub clock_dirty: gboolean,
pub provided_clock: *mut GstClock,
pub clock_provider: *mut GstElement,
pub _priv: *mut GstBinPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBin {
fn default() -> Struct__GstBin { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBinClass {
pub parent_class: GstElementClass,
pub pool: *mut GThreadPool,
pub element_added: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
child: *mut GstElement)>,
pub element_removed: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
child: *mut GstElement)>,
pub add_element: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
element: *mut GstElement)
-> gboolean>,
pub remove_element: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
element: *mut GstElement)
-> gboolean>,
pub handle_message: ::std::option::Option<extern "C" fn
(bin: *mut GstBin,
message: *mut GstMessage)>,
pub do_latency: ::std::option::Option<extern "C" fn(bin: *mut GstBin)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBinClass {
fn default() -> Struct__GstBinClass { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstBufferPoolPrivate { }
pub type GstBufferPoolPrivate = Struct__GstBufferPoolPrivate;
pub type GstBufferPoolClass = Struct__GstBufferPoolClass;
pub type Enum_Unnamed187 = ::libc::c_uint;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_KEY_UNIT: ::libc::c_uint = 1;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_DONTWAIT: ::libc::c_uint = 2;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_DISCONT: ::libc::c_uint = 4;
pub const GST_BUFFER_POOL_ACQUIRE_FLAG_LAST: ::libc::c_uint = 65536;
pub type GstBufferPoolAcquireFlags = Enum_Unnamed187;
pub type GstBufferPoolAcquireParams = Struct__GstBufferPoolAcquireParams;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPoolAcquireParams {
pub format: GstFormat,
pub start: gint64,
pub stop: gint64,
pub flags: GstBufferPoolAcquireFlags,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBufferPoolAcquireParams {
fn default() -> Struct__GstBufferPoolAcquireParams {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPool {
pub object: GstObject,
pub flushing: gint,
pub _priv: *mut GstBufferPoolPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstBufferPool {
fn default() -> Struct__GstBufferPool { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBufferPoolClass {
pub object_class: GstObjectClass,
pub get_options: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)
-> *mut *const gchar>,
pub set_config: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
config: *mut GstStructure)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(pool: *mut GstBufferPool)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(pool: *mut GstBufferPool)
-> gboolean>,
pub acquire_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer:
*mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn>,
pub alloc_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn>,
pub reset_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub release_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub free_buffer: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool,
buffer: *mut GstBuffer)>,
pub flush_start: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)>,
pub flush_stop: ::std::option::Option<extern "C" fn
(pool: *mut GstBufferPool)>,
pub _gst_reserved: [gpointer; 2u],
}
impl ::std::default::Default for Struct__GstBufferPoolClass {
fn default() -> Struct__GstBufferPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstChildProxy { }
pub type GstChildProxy = Struct__GstChildProxy;
pub type GstChildProxyInterface = Struct__GstChildProxyInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstChildProxyInterface {
pub parent: GTypeInterface,
pub get_child_by_name: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy,
name: *const gchar)
-> *mut GObject>,
pub get_child_by_index: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy,
index: guint)
-> *mut GObject>,
pub get_children_count: ::std::option::Option<extern "C" fn
(parent:
*mut GstChildProxy)
-> guint>,
pub child_added: ::std::option::Option<extern "C" fn
(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar)>,
pub child_removed: ::std::option::Option<extern "C" fn
(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstChildProxyInterface {
fn default() -> Struct__GstChildProxyInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed188 = ::libc::c_uint;
pub const GST_DEBUG_GRAPH_SHOW_MEDIA_TYPE: ::libc::c_uint = 1;
pub const GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS: ::libc::c_uint = 2;
pub const GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS: ::libc::c_uint = 4;
pub const GST_DEBUG_GRAPH_SHOW_STATES: ::libc::c_uint = 8;
pub const GST_DEBUG_GRAPH_SHOW_ALL: ::libc::c_uint = 15;
pub type GstDebugGraphDetails = Enum_Unnamed188;
pub enum Struct__GstDeviceProviderFactory { }
pub type GstDeviceProviderFactory = Struct__GstDeviceProviderFactory;
pub enum Struct__GstDeviceProviderFactoryClass { }
pub type GstDeviceProviderFactoryClass =
Struct__GstDeviceProviderFactoryClass;
pub type GstDeviceProvider = Struct__GstDeviceProvider;
pub type GstDeviceProviderClass = Struct__GstDeviceProviderClass;
pub enum Struct__GstDeviceProviderPrivate { }
pub type GstDeviceProviderPrivate = Struct__GstDeviceProviderPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceProvider {
pub parent: GstObject,
pub devices: *mut GList,
pub _priv: *mut GstDeviceProviderPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceProvider {
fn default() -> Struct__GstDeviceProvider {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceProviderClass {
pub parent_class: GstObjectClass,
pub factory: *mut GstDeviceProviderFactory,
pub probe: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)
-> *mut GList>,
pub start: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(provider: *mut GstDeviceProvider)>,
pub metadata: gpointer,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceProviderClass {
fn default() -> Struct__GstDeviceProviderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed189 = ::libc::c_uint;
pub const GST_CORE_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_CORE_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_CORE_ERROR_NOT_IMPLEMENTED: ::libc::c_uint = 3;
pub const GST_CORE_ERROR_STATE_CHANGE: ::libc::c_uint = 4;
pub const GST_CORE_ERROR_PAD: ::libc::c_uint = 5;
pub const GST_CORE_ERROR_THREAD: ::libc::c_uint = 6;
pub const GST_CORE_ERROR_NEGOTIATION: ::libc::c_uint = 7;
pub const GST_CORE_ERROR_EVENT: ::libc::c_uint = 8;
pub const GST_CORE_ERROR_SEEK: ::libc::c_uint = 9;
pub const GST_CORE_ERROR_CAPS: ::libc::c_uint = 10;
pub const GST_CORE_ERROR_TAG: ::libc::c_uint = 11;
pub const GST_CORE_ERROR_MISSING_PLUGIN: ::libc::c_uint = 12;
pub const GST_CORE_ERROR_CLOCK: ::libc::c_uint = 13;
pub const GST_CORE_ERROR_DISABLED: ::libc::c_uint = 14;
pub const GST_CORE_ERROR_NUM_ERRORS: ::libc::c_uint = 15;
pub type GstCoreError = Enum_Unnamed189;
pub type Enum_Unnamed190 = ::libc::c_uint;
pub const GST_LIBRARY_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_LIBRARY_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_LIBRARY_ERROR_INIT: ::libc::c_uint = 3;
pub const GST_LIBRARY_ERROR_SHUTDOWN: ::libc::c_uint = 4;
pub const GST_LIBRARY_ERROR_SETTINGS: ::libc::c_uint = 5;
pub const GST_LIBRARY_ERROR_ENCODE: ::libc::c_uint = 6;
pub const GST_LIBRARY_ERROR_NUM_ERRORS: ::libc::c_uint = 7;
pub type GstLibraryError = Enum_Unnamed190;
pub type Enum_Unnamed191 = ::libc::c_uint;
pub const GST_RESOURCE_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_RESOURCE_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_RESOURCE_ERROR_NOT_FOUND: ::libc::c_uint = 3;
pub const GST_RESOURCE_ERROR_BUSY: ::libc::c_uint = 4;
pub const GST_RESOURCE_ERROR_OPEN_READ: ::libc::c_uint = 5;
pub const GST_RESOURCE_ERROR_OPEN_WRITE: ::libc::c_uint = 6;
pub const GST_RESOURCE_ERROR_OPEN_READ_WRITE: ::libc::c_uint = 7;
pub const GST_RESOURCE_ERROR_CLOSE: ::libc::c_uint = 8;
pub const GST_RESOURCE_ERROR_READ: ::libc::c_uint = 9;
pub const GST_RESOURCE_ERROR_WRITE: ::libc::c_uint = 10;
pub const GST_RESOURCE_ERROR_SEEK: ::libc::c_uint = 11;
pub const GST_RESOURCE_ERROR_SYNC: ::libc::c_uint = 12;
pub const GST_RESOURCE_ERROR_SETTINGS: ::libc::c_uint = 13;
pub const GST_RESOURCE_ERROR_NO_SPACE_LEFT: ::libc::c_uint = 14;
pub const GST_RESOURCE_ERROR_NOT_AUTHORIZED: ::libc::c_uint = 15;
pub const GST_RESOURCE_ERROR_NUM_ERRORS: ::libc::c_uint = 16;
pub type GstResourceError = Enum_Unnamed191;
pub type Enum_Unnamed192 = ::libc::c_uint;
pub const GST_STREAM_ERROR_FAILED: ::libc::c_uint = 1;
pub const GST_STREAM_ERROR_TOO_LAZY: ::libc::c_uint = 2;
pub const GST_STREAM_ERROR_NOT_IMPLEMENTED: ::libc::c_uint = 3;
pub const GST_STREAM_ERROR_TYPE_NOT_FOUND: ::libc::c_uint = 4;
pub const GST_STREAM_ERROR_WRONG_TYPE: ::libc::c_uint = 5;
pub const GST_STREAM_ERROR_CODEC_NOT_FOUND: ::libc::c_uint = 6;
pub const GST_STREAM_ERROR_DECODE: ::libc::c_uint = 7;
pub const GST_STREAM_ERROR_ENCODE: ::libc::c_uint = 8;
pub const GST_STREAM_ERROR_DEMUX: ::libc::c_uint = 9;
pub const GST_STREAM_ERROR_MUX: ::libc::c_uint = 10;
pub const GST_STREAM_ERROR_FORMAT: ::libc::c_uint = 11;
pub const GST_STREAM_ERROR_DECRYPT: ::libc::c_uint = 12;
pub const GST_STREAM_ERROR_DECRYPT_NOKEY: ::libc::c_uint = 13;
pub const GST_STREAM_ERROR_NUM_ERRORS: ::libc::c_uint = 14;
pub type GstStreamError = Enum_Unnamed192;
pub type GstProxyPad = Struct__GstProxyPad;
pub enum Struct__GstProxyPadPrivate { }
pub type GstProxyPadPrivate = Struct__GstProxyPadPrivate;
pub type GstProxyPadClass = Struct__GstProxyPadClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstProxyPad {
pub pad: GstPad,
pub _priv: *mut GstProxyPadPrivate,
}
impl ::std::default::Default for Struct__GstProxyPad {
fn default() -> Struct__GstProxyPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstProxyPadClass {
pub parent_class: GstPadClass,
pub _gst_reserved: [gpointer; 1u],
}
impl ::std::default::Default for Struct__GstProxyPadClass {
fn default() -> Struct__GstProxyPadClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstGhostPad = Struct__GstGhostPad;
pub enum Struct__GstGhostPadPrivate { }
pub type GstGhostPadPrivate = Struct__GstGhostPadPrivate;
pub type GstGhostPadClass = Struct__GstGhostPadClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstGhostPad {
pub pad: GstProxyPad,
pub _priv: *mut GstGhostPadPrivate,
}
impl ::std::default::Default for Struct__GstGhostPad {
fn default() -> Struct__GstGhostPad { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstGhostPadClass {
pub parent_class: GstProxyPadClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstGhostPadClass {
fn default() -> Struct__GstGhostPadClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstDeviceMonitor = Struct__GstDeviceMonitor;
pub enum Struct__GstDeviceMonitorPrivate { }
pub type GstDeviceMonitorPrivate = Struct__GstDeviceMonitorPrivate;
pub type GstDeviceMonitorClass = Struct__GstDeviceMonitorClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceMonitor {
pub parent: GstObject,
pub _priv: *mut GstDeviceMonitorPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceMonitor {
fn default() -> Struct__GstDeviceMonitor {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDeviceMonitorClass {
pub parent_class: GstObjectClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstDeviceMonitorClass {
fn default() -> Struct__GstDeviceMonitorClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed193 = ::libc::c_uint;
pub const GST_LEVEL_NONE: ::libc::c_uint = 0;
pub const GST_LEVEL_ERROR: ::libc::c_uint = 1;
pub const GST_LEVEL_WARNING: ::libc::c_uint = 2;
pub const GST_LEVEL_FIXME: ::libc::c_uint = 3;
pub const GST_LEVEL_INFO: ::libc::c_uint = 4;
pub const GST_LEVEL_DEBUG: ::libc::c_uint = 5;
pub const GST_LEVEL_LOG: ::libc::c_uint = 6;
pub const GST_LEVEL_TRACE: ::libc::c_uint = 7;
pub const GST_LEVEL_MEMDUMP: ::libc::c_uint = 9;
pub const GST_LEVEL_COUNT: ::libc::c_uint = 10;
pub type GstDebugLevel = Enum_Unnamed193;
pub type Enum_Unnamed194 = ::libc::c_uint;
pub const GST_DEBUG_FG_BLACK: ::libc::c_uint = 0;
pub const GST_DEBUG_FG_RED: ::libc::c_uint = 1;
pub const GST_DEBUG_FG_GREEN: ::libc::c_uint = 2;
pub const GST_DEBUG_FG_YELLOW: ::libc::c_uint = 3;
pub const GST_DEBUG_FG_BLUE: ::libc::c_uint = 4;
pub const GST_DEBUG_FG_MAGENTA: ::libc::c_uint = 5;
pub const GST_DEBUG_FG_CYAN: ::libc::c_uint = 6;
pub const GST_DEBUG_FG_WHITE: ::libc::c_uint = 7;
pub const GST_DEBUG_BG_BLACK: ::libc::c_uint = 0;
pub const GST_DEBUG_BG_RED: ::libc::c_uint = 16;
pub const GST_DEBUG_BG_GREEN: ::libc::c_uint = 32;
pub const GST_DEBUG_BG_YELLOW: ::libc::c_uint = 48;
pub const GST_DEBUG_BG_BLUE: ::libc::c_uint = 64;
pub const GST_DEBUG_BG_MAGENTA: ::libc::c_uint = 80;
pub const GST_DEBUG_BG_CYAN: ::libc::c_uint = 96;
pub const GST_DEBUG_BG_WHITE: ::libc::c_uint = 112;
pub const GST_DEBUG_BOLD: ::libc::c_uint = 256;
pub const GST_DEBUG_UNDERLINE: ::libc::c_uint = 512;
pub type GstDebugColorFlags = Enum_Unnamed194;
pub type Enum_Unnamed195 = ::libc::c_uint;
pub const GST_DEBUG_COLOR_MODE_OFF: ::libc::c_uint = 0;
pub const GST_DEBUG_COLOR_MODE_ON: ::libc::c_uint = 1;
pub const GST_DEBUG_COLOR_MODE_UNIX: ::libc::c_uint = 2;
pub type GstDebugColorMode = Enum_Unnamed195;
pub type GstDebugCategory = Struct__GstDebugCategory;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstDebugCategory {
pub threshold: gint,
pub color: guint,
pub name: *const gchar,
pub description: *const gchar,
}
impl ::std::default::Default for Struct__GstDebugCategory {
fn default() -> Struct__GstDebugCategory {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstDebugMessage { }
pub type GstDebugMessage = Struct__GstDebugMessage;
pub type GstLogFunction =
::std::option::Option<extern "C" fn
(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject,
message: *mut GstDebugMessage,
user_data: gpointer)>;
pub type GstDebugFuncPtr = ::std::option::Option<extern "C" fn()>;
pub type GstValueCompareFunc =
::std::option::Option<extern "C" fn
(value1: *const GValue, value2: *const GValue)
-> gint>;
pub type GstValueSerializeFunc =
::std::option::Option<extern "C" fn(value1: *const GValue) -> *mut gchar>;
pub type GstValueDeserializeFunc =
::std::option::Option<extern "C" fn(dest: *mut GValue, s: *const gchar)
-> gboolean>;
pub type GstValueTable = Struct__GstValueTable;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstValueTable {
pub _type: GType,
pub compare: GstValueCompareFunc,
pub serialize: GstValueSerializeFunc,
pub deserialize: GstValueDeserializeFunc,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstValueTable {
fn default() -> Struct__GstValueTable { unsafe { ::std::mem::zeroed() } }
}
pub type GstParamSpecFraction = Struct__GstParamSpecFraction;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstParamSpecFraction {
pub parent_instance: GParamSpec,
pub min_num: gint,
pub min_den: gint,
pub max_num: gint,
pub max_den: gint,
pub def_num: gint,
pub def_den: gint,
}
impl ::std::default::Default for Struct__GstParamSpecFraction {
fn default() -> Struct__GstParamSpecFraction {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPipeline = Struct__GstPipeline;
pub type GstPipelineClass = Struct__GstPipelineClass;
pub enum Struct__GstPipelinePrivate { }
pub type GstPipelinePrivate = Struct__GstPipelinePrivate;
pub type Enum_Unnamed196 = ::libc::c_uint;
pub const GST_PIPELINE_FLAG_FIXED_CLOCK: ::libc::c_uint = 524288;
pub const GST_PIPELINE_FLAG_LAST: ::libc::c_uint = 8388608;
pub type GstPipelineFlags = Enum_Unnamed196;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPipeline {
pub bin: GstBin,
pub fixed_clock: *mut GstClock,
pub stream_time: GstClockTime,
pub delay: GstClockTime,
pub _priv: *mut GstPipelinePrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPipeline {
fn default() -> Struct__GstPipeline { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPipelineClass {
pub parent_class: GstBinClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPipelineClass {
fn default() -> Struct__GstPipelineClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstPoll { }
pub type GstPoll = Struct__GstPoll;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed197 {
pub fd: ::libc::c_int,
pub idx: gint,
}
impl ::std::default::Default for Struct_Unnamed197 {
fn default() -> Struct_Unnamed197 { unsafe { ::std::mem::zeroed() } }
}
pub type GstPollFD = Struct_Unnamed197;
pub enum Struct__GstPreset { }
pub type GstPreset = Struct__GstPreset;
pub type GstPresetInterface = Struct__GstPresetInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPresetInterface {
pub parent: GTypeInterface,
pub get_preset_names: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset)
-> *mut *mut gchar>,
pub get_property_names: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset)
-> *mut *mut gchar>,
pub load_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub save_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub rename_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
old_name: *const gchar,
new_name: *const gchar)
-> gboolean>,
pub delete_preset: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar)
-> gboolean>,
pub set_meta: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar,
tag: *const gchar,
value: *const gchar)
-> gboolean>,
pub get_meta: ::std::option::Option<extern "C" fn
(preset: *mut GstPreset,
name: *const gchar,
tag: *const gchar,
value: *mut *mut gchar)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPresetInterface {
fn default() -> Struct__GstPresetInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstRegistry = Struct__GstRegistry;
pub type GstRegistryClass = Struct__GstRegistryClass;
pub enum Struct__GstRegistryPrivate { }
pub type GstRegistryPrivate = Struct__GstRegistryPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstRegistry {
pub object: GstObject,
pub _priv: *mut GstRegistryPrivate,
}
impl ::std::default::Default for Struct__GstRegistry {
fn default() -> Struct__GstRegistry { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstRegistryClass {
pub parent_class: GstObjectClass,
}
impl ::std::default::Default for Struct__GstRegistryClass {
fn default() -> Struct__GstRegistryClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstSystemClock = Struct__GstSystemClock;
pub type GstSystemClockClass = Struct__GstSystemClockClass;
pub enum Struct__GstSystemClockPrivate { }
pub type GstSystemClockPrivate = Struct__GstSystemClockPrivate;
pub type Enum_Unnamed198 = ::libc::c_uint;
pub const GST_CLOCK_TYPE_REALTIME: ::libc::c_uint = 0;
pub const GST_CLOCK_TYPE_MONOTONIC: ::libc::c_uint = 1;
pub const GST_CLOCK_TYPE_OTHER: ::libc::c_uint = 2;
pub type GstClockType = Enum_Unnamed198;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSystemClock {
pub clock: GstClock,
pub _priv: *mut GstSystemClockPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSystemClock {
fn default() -> Struct__GstSystemClock { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstSystemClockClass {
pub parent_class: GstClockClass,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstSystemClockClass {
fn default() -> Struct__GstSystemClockClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstTagSetter { }
pub type GstTagSetter = Struct__GstTagSetter;
pub type GstTagSetterInterface = Struct__GstTagSetterInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTagSetterInterface {
pub g_iface: GTypeInterface,
}
impl ::std::default::Default for Struct__GstTagSetterInterface {
fn default() -> Struct__GstTagSetterInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstTocSetter { }
pub type GstTocSetter = Struct__GstTocSetter;
pub type GstTocSetterInterface = Struct__GstTocSetterInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTocSetterInterface {
pub g_iface: GTypeInterface,
}
impl ::std::default::Default for Struct__GstTocSetterInterface {
fn default() -> Struct__GstTocSetterInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstTypeFind = Struct__GstTypeFind;
pub type GstTypeFindFunction =
::std::option::Option<extern "C" fn
(find: *mut GstTypeFind, user_data: gpointer)>;
pub type Enum_Unnamed199 = ::libc::c_uint;
pub const GST_TYPE_FIND_NONE: ::libc::c_uint = 0;
pub const GST_TYPE_FIND_MINIMUM: ::libc::c_uint = 1;
pub const GST_TYPE_FIND_POSSIBLE: ::libc::c_uint = 50;
pub const GST_TYPE_FIND_LIKELY: ::libc::c_uint = 80;
pub const GST_TYPE_FIND_NEARLY_CERTAIN: ::libc::c_uint = 99;
pub const GST_TYPE_FIND_MAXIMUM: ::libc::c_uint = 100;
pub type GstTypeFindProbability = Enum_Unnamed199;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstTypeFind {
pub peek: ::std::option::Option<extern "C" fn
(data: gpointer, offset: gint64,
size: guint) -> *const guint8>,
pub suggest: ::std::option::Option<extern "C" fn
(data: gpointer,
probability: guint,
caps: *mut GstCaps)>,
pub data: gpointer,
pub get_length: ::std::option::Option<extern "C" fn(data: gpointer)
-> guint64>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstTypeFind {
fn default() -> Struct__GstTypeFind { unsafe { ::std::mem::zeroed() } }
}
pub enum Struct__GstTypeFindFactory { }
pub type GstTypeFindFactory = Struct__GstTypeFindFactory;
pub enum Struct__GstTypeFindFactoryClass { }
pub type GstTypeFindFactoryClass = Struct__GstTypeFindFactoryClass;
pub type Enum_Unnamed200 = ::libc::c_uint;
pub const GST_PARSE_ERROR_SYNTAX: ::libc::c_uint = 0;
pub const GST_PARSE_ERROR_NO_SUCH_ELEMENT: ::libc::c_uint = 1;
pub const GST_PARSE_ERROR_NO_SUCH_PROPERTY: ::libc::c_uint = 2;
pub const GST_PARSE_ERROR_LINK: ::libc::c_uint = 3;
pub const GST_PARSE_ERROR_COULD_NOT_SET_PROPERTY: ::libc::c_uint = 4;
pub const GST_PARSE_ERROR_EMPTY_BIN: ::libc::c_uint = 5;
pub const GST_PARSE_ERROR_EMPTY: ::libc::c_uint = 6;
pub type GstParseError = Enum_Unnamed200;
pub type Enum_Unnamed201 = ::libc::c_uint;
pub const GST_PARSE_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_PARSE_FLAG_FATAL_ERRORS: ::libc::c_uint = 1;
pub const GST_PARSE_FLAG_NO_SINGLE_ELEMENT_BINS: ::libc::c_uint = 2;
pub type GstParseFlags = Enum_Unnamed201;
pub enum Struct__GstParseContext { }
pub type GstParseContext = Struct__GstParseContext;
pub type Enum_Unnamed202 = ::libc::c_uint;
pub const GST_SEARCH_MODE_EXACT: ::libc::c_uint = 0;
pub const GST_SEARCH_MODE_BEFORE: ::libc::c_uint = 1;
pub const GST_SEARCH_MODE_AFTER: ::libc::c_uint = 2;
pub type GstSearchMode = Enum_Unnamed202;
pub type GstBaseSink = Struct__GstBaseSink;
pub type GstBaseSinkClass = Struct__GstBaseSinkClass;
pub enum Struct__GstBaseSinkPrivate { }
pub type GstBaseSinkPrivate = Struct__GstBaseSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSink {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub pad_mode: GstPadMode,
pub offset: guint64,
pub can_activate_pull: gboolean,
pub can_activate_push: gboolean,
pub preroll_lock: GMutex,
pub preroll_cond: GCond,
pub eos: gboolean,
pub need_preroll: gboolean,
pub have_preroll: gboolean,
pub playing_async: gboolean,
pub have_newsegment: gboolean,
pub segment: GstSegment,
pub clock_id: GstClockID,
pub sync: gboolean,
pub flushing: gboolean,
pub running: gboolean,
pub max_lateness: gint64,
pub _priv: *mut GstBaseSinkPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSink {
fn default() -> Struct__GstBaseSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSinkClass {
pub parent_class: GstElementClass,
pub get_caps: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub set_caps: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
caps: *mut GstCaps) -> gboolean>,
pub fixate: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
caps: *mut GstCaps)
-> *mut GstCaps>,
pub activate_pull: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
active: gboolean)
-> gboolean>,
pub get_times: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer,
start: *mut GstClockTime,
end: *mut GstClockTime)>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
query: *mut GstQuery)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub unlock: ::std::option::Option<extern "C" fn(sink: *mut GstBaseSink)
-> gboolean>,
pub unlock_stop: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
query: *mut GstQuery) -> gboolean>,
pub event: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
event: *mut GstEvent) -> gboolean>,
pub wait_event: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
event: *mut GstEvent)
-> GstFlowReturn>,
pub prepare: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub prepare_list: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer_list:
*mut GstBufferList)
-> GstFlowReturn>,
pub preroll: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub render: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub render_list: ::std::option::Option<extern "C" fn
(sink: *mut GstBaseSink,
buffer_list:
*mut GstBufferList)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSinkClass {
fn default() -> Struct__GstBaseSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstAppSink = Struct__GstAppSink;
pub type GstAppSinkClass = Struct__GstAppSinkClass;
pub enum Struct__GstAppSinkPrivate { }
pub type GstAppSinkPrivate = Struct__GstAppSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed203 {
pub eos: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)>,
pub new_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)
-> GstFlowReturn>,
pub new_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink,
user_data: gpointer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed203 {
fn default() -> Struct_Unnamed203 { unsafe { ::std::mem::zeroed() } }
}
pub type GstAppSinkCallbacks = Struct_Unnamed203;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSink {
pub basesink: GstBaseSink,
pub _priv: *mut GstAppSinkPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSink {
fn default() -> Struct__GstAppSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSinkClass {
pub basesink_class: GstBaseSinkClass,
pub eos: ::std::option::Option<extern "C" fn(appsink: *mut GstAppSink)>,
pub new_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> GstFlowReturn>,
pub new_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> GstFlowReturn>,
pub pull_preroll: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> *mut GstSample>,
pub pull_sample: ::std::option::Option<extern "C" fn
(appsink: *mut GstAppSink)
-> *mut GstSample>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSinkClass {
fn default() -> Struct__GstAppSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed204 = ::libc::c_uint;
pub const GST_BASE_SRC_FLAG_STARTING: ::libc::c_uint = 16384;
pub const GST_BASE_SRC_FLAG_STARTED: ::libc::c_uint = 32768;
pub const GST_BASE_SRC_FLAG_LAST: ::libc::c_uint = 1048576;
pub type GstBaseSrcFlags = Enum_Unnamed204;
pub type GstBaseSrc = Struct__GstBaseSrc;
pub type GstBaseSrcClass = Struct__GstBaseSrcClass;
pub enum Struct__GstBaseSrcPrivate { }
pub type GstBaseSrcPrivate = Struct__GstBaseSrcPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSrc {
pub element: GstElement,
pub srcpad: *mut GstPad,
pub live_lock: GMutex,
pub live_cond: GCond,
pub is_live: gboolean,
pub live_running: gboolean,
pub blocksize: guint,
pub can_activate_push: gboolean,
pub random_access: gboolean,
pub clock_id: GstClockID,
pub segment: GstSegment,
pub need_newsegment: gboolean,
pub num_buffers: gint,
pub num_buffers_left: gint,
pub typefind: gboolean,
pub running: gboolean,
pub pending_seek: *mut GstEvent,
pub _priv: *mut GstBaseSrcPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSrc {
fn default() -> Struct__GstBaseSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseSrcClass {
pub parent_class: GstElementClass,
pub get_caps: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub negotiate: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub fixate: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
caps: *mut GstCaps)
-> *mut GstCaps>,
pub set_caps: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
caps: *mut GstCaps) -> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
query: *mut GstQuery)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub get_times: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
buffer: *mut GstBuffer,
start: *mut GstClockTime,
end: *mut GstClockTime)>,
pub get_size: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
size: *mut guint64) -> gboolean>,
pub is_seekable: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub prepare_seek_segment: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
seek: *mut GstEvent,
segment:
*mut GstSegment)
-> gboolean>,
pub do_seek: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
segment: *mut GstSegment)
-> gboolean>,
pub unlock: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub unlock_stop: ::std::option::Option<extern "C" fn(src: *mut GstBaseSrc)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
query: *mut GstQuery) -> gboolean>,
pub event: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
event: *mut GstEvent) -> gboolean>,
pub create: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub alloc: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub fill: ::std::option::Option<extern "C" fn
(src: *mut GstBaseSrc,
offset: guint64, size: guint,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseSrcClass {
fn default() -> Struct__GstBaseSrcClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstPushSrc = Struct__GstPushSrc;
pub type GstPushSrcClass = Struct__GstPushSrcClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPushSrc {
pub parent: GstBaseSrc,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPushSrc {
fn default() -> Struct__GstPushSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstPushSrcClass {
pub parent_class: GstBaseSrcClass,
pub create: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub alloc: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut *mut GstBuffer)
-> GstFlowReturn>,
pub fill: ::std::option::Option<extern "C" fn
(src: *mut GstPushSrc,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstPushSrcClass {
fn default() -> Struct__GstPushSrcClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstAppSrc = Struct__GstAppSrc;
pub type GstAppSrcClass = Struct__GstAppSrcClass;
pub enum Struct__GstAppSrcPrivate { }
pub type GstAppSrcPrivate = Struct__GstAppSrcPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed205 {
pub need_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
length: guint,
user_data: gpointer)>,
pub enough_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
user_data: gpointer)>,
pub seek_data: ::std::option::Option<extern "C" fn
(src: *mut GstAppSrc,
offset: guint64,
user_data: gpointer)
-> gboolean>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct_Unnamed205 {
fn default() -> Struct_Unnamed205 { unsafe { ::std::mem::zeroed() } }
}
pub type GstAppSrcCallbacks = Struct_Unnamed205;
pub type Enum_Unnamed206 = ::libc::c_uint;
pub const GST_APP_STREAM_TYPE_STREAM: ::libc::c_uint = 0;
pub const GST_APP_STREAM_TYPE_SEEKABLE: ::libc::c_uint = 1;
pub const GST_APP_STREAM_TYPE_RANDOM_ACCESS: ::libc::c_uint = 2;
pub type GstAppStreamType = Enum_Unnamed206;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSrc {
pub basesrc: GstBaseSrc,
pub _priv: *mut GstAppSrcPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSrc {
fn default() -> Struct__GstAppSrc { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstAppSrcClass {
pub basesrc_class: GstBaseSrcClass,
pub need_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
length: guint)>,
pub enough_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc)>,
pub seek_data: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
offset: guint64) -> gboolean>,
pub push_buffer: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc,
buffer: *mut GstBuffer)
-> GstFlowReturn>,
pub end_of_stream: ::std::option::Option<extern "C" fn
(appsrc: *mut GstAppSrc)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstAppSrcClass {
fn default() -> Struct__GstAppSrcClass { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoAlignment = Struct__GstVideoAlignment;
pub type Enum_Unnamed207 = ::libc::c_uint;
pub const GST_VIDEO_TILE_TYPE_INDEXED: ::libc::c_uint = 0;
pub type GstVideoTileType = Enum_Unnamed207;
pub type Enum_Unnamed208 = ::libc::c_uint;
pub const GST_VIDEO_TILE_MODE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_TILE_MODE_ZFLIPZ_2X2: ::libc::c_uint = 65536;
pub type GstVideoTileMode = Enum_Unnamed208;
pub type Enum_Unnamed209 = ::libc::c_uint;
pub const GST_VIDEO_FORMAT_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_FORMAT_ENCODED: ::libc::c_uint = 1;
pub const GST_VIDEO_FORMAT_I420: ::libc::c_uint = 2;
pub const GST_VIDEO_FORMAT_YV12: ::libc::c_uint = 3;
pub const GST_VIDEO_FORMAT_YUY2: ::libc::c_uint = 4;
pub const GST_VIDEO_FORMAT_UYVY: ::libc::c_uint = 5;
pub const GST_VIDEO_FORMAT_AYUV: ::libc::c_uint = 6;
pub const GST_VIDEO_FORMAT_RGBx: ::libc::c_uint = 7;
pub const GST_VIDEO_FORMAT_BGRx: ::libc::c_uint = 8;
pub const GST_VIDEO_FORMAT_xRGB: ::libc::c_uint = 9;
pub const GST_VIDEO_FORMAT_xBGR: ::libc::c_uint = 10;
pub const GST_VIDEO_FORMAT_RGBA: ::libc::c_uint = 11;
pub const GST_VIDEO_FORMAT_BGRA: ::libc::c_uint = 12;
pub const GST_VIDEO_FORMAT_ARGB: ::libc::c_uint = 13;
pub const GST_VIDEO_FORMAT_ABGR: ::libc::c_uint = 14;
pub const GST_VIDEO_FORMAT_RGB: ::libc::c_uint = 15;
pub const GST_VIDEO_FORMAT_BGR: ::libc::c_uint = 16;
pub const GST_VIDEO_FORMAT_Y41B: ::libc::c_uint = 17;
pub const GST_VIDEO_FORMAT_Y42B: ::libc::c_uint = 18;
pub const GST_VIDEO_FORMAT_YVYU: ::libc::c_uint = 19;
pub const GST_VIDEO_FORMAT_Y444: ::libc::c_uint = 20;
pub const GST_VIDEO_FORMAT_v210: ::libc::c_uint = 21;
pub const GST_VIDEO_FORMAT_v216: ::libc::c_uint = 22;
pub const GST_VIDEO_FORMAT_NV12: ::libc::c_uint = 23;
pub const GST_VIDEO_FORMAT_NV21: ::libc::c_uint = 24;
pub const GST_VIDEO_FORMAT_GRAY8: ::libc::c_uint = 25;
pub const GST_VIDEO_FORMAT_GRAY16_BE: ::libc::c_uint = 26;
pub const GST_VIDEO_FORMAT_GRAY16_LE: ::libc::c_uint = 27;
pub const GST_VIDEO_FORMAT_v308: ::libc::c_uint = 28;
pub const GST_VIDEO_FORMAT_RGB16: ::libc::c_uint = 29;
pub const GST_VIDEO_FORMAT_BGR16: ::libc::c_uint = 30;
pub const GST_VIDEO_FORMAT_RGB15: ::libc::c_uint = 31;
pub const GST_VIDEO_FORMAT_BGR15: ::libc::c_uint = 32;
pub const GST_VIDEO_FORMAT_UYVP: ::libc::c_uint = 33;
pub const GST_VIDEO_FORMAT_A420: ::libc::c_uint = 34;
pub const GST_VIDEO_FORMAT_RGB8P: ::libc::c_uint = 35;
pub const GST_VIDEO_FORMAT_YUV9: ::libc::c_uint = 36;
pub const GST_VIDEO_FORMAT_YVU9: ::libc::c_uint = 37;
pub const GST_VIDEO_FORMAT_IYU1: ::libc::c_uint = 38;
pub const GST_VIDEO_FORMAT_ARGB64: ::libc::c_uint = 39;
pub const GST_VIDEO_FORMAT_AYUV64: ::libc::c_uint = 40;
pub const GST_VIDEO_FORMAT_r210: ::libc::c_uint = 41;
pub const GST_VIDEO_FORMAT_I420_10BE: ::libc::c_uint = 42;
pub const GST_VIDEO_FORMAT_I420_10LE: ::libc::c_uint = 43;
pub const GST_VIDEO_FORMAT_I422_10BE: ::libc::c_uint = 44;
pub const GST_VIDEO_FORMAT_I422_10LE: ::libc::c_uint = 45;
pub const GST_VIDEO_FORMAT_Y444_10BE: ::libc::c_uint = 46;
pub const GST_VIDEO_FORMAT_Y444_10LE: ::libc::c_uint = 47;
pub const GST_VIDEO_FORMAT_GBR: ::libc::c_uint = 48;
pub const GST_VIDEO_FORMAT_GBR_10BE: ::libc::c_uint = 49;
pub const GST_VIDEO_FORMAT_GBR_10LE: ::libc::c_uint = 50;
pub const GST_VIDEO_FORMAT_NV16: ::libc::c_uint = 51;
pub const GST_VIDEO_FORMAT_NV24: ::libc::c_uint = 52;
pub const GST_VIDEO_FORMAT_NV12_64Z32: ::libc::c_uint = 53;
pub type GstVideoFormat = Enum_Unnamed209;
pub type GstVideoFormatInfo = Struct__GstVideoFormatInfo;
pub type Enum_Unnamed210 = ::libc::c_uint;
pub const GST_VIDEO_FORMAT_FLAG_YUV: ::libc::c_uint = 1;
pub const GST_VIDEO_FORMAT_FLAG_RGB: ::libc::c_uint = 2;
pub const GST_VIDEO_FORMAT_FLAG_GRAY: ::libc::c_uint = 4;
pub const GST_VIDEO_FORMAT_FLAG_ALPHA: ::libc::c_uint = 8;
pub const GST_VIDEO_FORMAT_FLAG_LE: ::libc::c_uint = 16;
pub const GST_VIDEO_FORMAT_FLAG_PALETTE: ::libc::c_uint = 32;
pub const GST_VIDEO_FORMAT_FLAG_COMPLEX: ::libc::c_uint = 64;
pub const GST_VIDEO_FORMAT_FLAG_UNPACK: ::libc::c_uint = 128;
pub const GST_VIDEO_FORMAT_FLAG_TILED: ::libc::c_uint = 256;
pub type GstVideoFormatFlags = Enum_Unnamed210;
pub type Enum_Unnamed211 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_SITE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_SITE_NONE: ::libc::c_uint = 1;
pub const GST_VIDEO_CHROMA_SITE_H_COSITED: ::libc::c_uint = 2;
pub const GST_VIDEO_CHROMA_SITE_V_COSITED: ::libc::c_uint = 4;
pub const GST_VIDEO_CHROMA_SITE_ALT_LINE: ::libc::c_uint = 8;
pub const GST_VIDEO_CHROMA_SITE_COSITED: ::libc::c_uint = 6;
pub const GST_VIDEO_CHROMA_SITE_JPEG: ::libc::c_uint = 1;
pub const GST_VIDEO_CHROMA_SITE_MPEG2: ::libc::c_uint = 2;
pub const GST_VIDEO_CHROMA_SITE_DV: ::libc::c_uint = 14;
pub type GstVideoChromaSite = Enum_Unnamed211;
pub type Enum_Unnamed212 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_METHOD_NEAREST: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_METHOD_LINEAR: ::libc::c_uint = 1;
pub type GstVideoChromaMethod = Enum_Unnamed212;
pub type Enum_Unnamed213 = ::libc::c_uint;
pub const GST_VIDEO_CHROMA_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_CHROMA_FLAG_INTERLACED: ::libc::c_uint = 1;
pub type GstVideoChromaFlags = Enum_Unnamed213;
pub enum Struct__GstVideoChromaResample { }
pub type GstVideoChromaResample = Struct__GstVideoChromaResample;
pub type Enum_Unnamed214 = ::libc::c_uint;
pub const GST_VIDEO_PACK_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_PACK_FLAG_TRUNCATE_RANGE: ::libc::c_uint = 1;
pub const GST_VIDEO_PACK_FLAG_INTERLACED: ::libc::c_uint = 2;
pub type GstVideoPackFlags = Enum_Unnamed214;
pub type GstVideoFormatUnpack =
::std::option::Option<extern "C" fn
(info: *const GstVideoFormatInfo,
flags: GstVideoPackFlags, dest: gpointer,
data: *mut gpointer, stride: *mut gint,
x: gint, y: gint, width: gint)>;
pub type GstVideoFormatPack =
::std::option::Option<extern "C" fn
(info: *const GstVideoFormatInfo,
flags: GstVideoPackFlags, src: gpointer,
sstride: gint, data: *mut gpointer,
stride: *mut gint,
chroma_site: GstVideoChromaSite, y: gint,
width: gint)>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFormatInfo {
pub format: GstVideoFormat,
pub name: *const gchar,
pub description: *const gchar,
pub flags: GstVideoFormatFlags,
pub bits: guint,
pub n_components: guint,
pub shift: [guint; 4u],
pub depth: [guint; 4u],
pub pixel_stride: [gint; 4u],
pub n_planes: guint,
pub plane: [guint; 4u],
pub poffset: [guint; 4u],
pub w_sub: [guint; 4u],
pub h_sub: [guint; 4u],
pub unpack_format: GstVideoFormat,
pub unpack_func: GstVideoFormatUnpack,
pub pack_lines: gint,
pub pack_func: GstVideoFormatPack,
pub tile_mode: GstVideoTileMode,
pub tile_ws: guint,
pub tile_hs: guint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFormatInfo {
fn default() -> Struct__GstVideoFormatInfo {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed215 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_RANGE_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_RANGE_0_255: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_RANGE_16_235: ::libc::c_uint = 2;
pub type GstVideoColorRange = Enum_Unnamed215;
pub type Enum_Unnamed216 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_MATRIX_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_MATRIX_RGB: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_MATRIX_FCC: ::libc::c_uint = 2;
pub const GST_VIDEO_COLOR_MATRIX_BT709: ::libc::c_uint = 3;
pub const GST_VIDEO_COLOR_MATRIX_BT601: ::libc::c_uint = 4;
pub const GST_VIDEO_COLOR_MATRIX_SMPTE240M: ::libc::c_uint = 5;
pub type GstVideoColorMatrix = Enum_Unnamed216;
pub type Enum_Unnamed217 = ::libc::c_uint;
pub const GST_VIDEO_TRANSFER_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_TRANSFER_GAMMA10: ::libc::c_uint = 1;
pub const GST_VIDEO_TRANSFER_GAMMA18: ::libc::c_uint = 2;
pub const GST_VIDEO_TRANSFER_GAMMA20: ::libc::c_uint = 3;
pub const GST_VIDEO_TRANSFER_GAMMA22: ::libc::c_uint = 4;
pub const GST_VIDEO_TRANSFER_BT709: ::libc::c_uint = 5;
pub const GST_VIDEO_TRANSFER_SMPTE240M: ::libc::c_uint = 6;
pub const GST_VIDEO_TRANSFER_SRGB: ::libc::c_uint = 7;
pub const GST_VIDEO_TRANSFER_GAMMA28: ::libc::c_uint = 8;
pub const GST_VIDEO_TRANSFER_LOG100: ::libc::c_uint = 9;
pub const GST_VIDEO_TRANSFER_LOG316: ::libc::c_uint = 10;
pub type GstVideoTransferFunction = Enum_Unnamed217;
pub type Enum_Unnamed218 = ::libc::c_uint;
pub const GST_VIDEO_COLOR_PRIMARIES_UNKNOWN: ::libc::c_uint = 0;
pub const GST_VIDEO_COLOR_PRIMARIES_BT709: ::libc::c_uint = 1;
pub const GST_VIDEO_COLOR_PRIMARIES_BT470M: ::libc::c_uint = 2;
pub const GST_VIDEO_COLOR_PRIMARIES_BT470BG: ::libc::c_uint = 3;
pub const GST_VIDEO_COLOR_PRIMARIES_SMPTE170M: ::libc::c_uint = 4;
pub const GST_VIDEO_COLOR_PRIMARIES_SMPTE240M: ::libc::c_uint = 5;
pub const GST_VIDEO_COLOR_PRIMARIES_FILM: ::libc::c_uint = 6;
pub type GstVideoColorPrimaries = Enum_Unnamed218;
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed219 {
pub range: GstVideoColorRange,
pub matrix: GstVideoColorMatrix,
pub transfer: GstVideoTransferFunction,
pub primaries: GstVideoColorPrimaries,
}
impl ::std::default::Default for Struct_Unnamed219 {
fn default() -> Struct_Unnamed219 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoColorimetry = Struct_Unnamed219;
pub type GstVideoInfo = Struct__GstVideoInfo;
pub type Enum_Unnamed220 = ::libc::c_uint;
pub const GST_VIDEO_INTERLACE_MODE_PROGRESSIVE: ::libc::c_uint = 0;
pub const GST_VIDEO_INTERLACE_MODE_INTERLEAVED: ::libc::c_uint = 1;
pub const GST_VIDEO_INTERLACE_MODE_MIXED: ::libc::c_uint = 2;
pub const GST_VIDEO_INTERLACE_MODE_FIELDS: ::libc::c_uint = 3;
pub type GstVideoInterlaceMode = Enum_Unnamed220;
pub type Enum_Unnamed221 = ::libc::c_uint;
pub const GST_VIDEO_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_FLAG_VARIABLE_FPS: ::libc::c_uint = 1;
pub const GST_VIDEO_FLAG_PREMULTIPLIED_ALPHA: ::libc::c_uint = 2;
pub type GstVideoFlags = Enum_Unnamed221;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoInfo {
pub finfo: *const GstVideoFormatInfo,
pub interlace_mode: GstVideoInterlaceMode,
pub flags: GstVideoFlags,
pub width: gint,
pub height: gint,
pub size: gsize,
pub views: gint,
pub chroma_site: GstVideoChromaSite,
pub colorimetry: GstVideoColorimetry,
pub par_n: gint,
pub par_d: gint,
pub fps_n: gint,
pub fps_d: gint,
pub offset: [gsize; 4u],
pub stride: [gint; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoInfo {
fn default() -> Struct__GstVideoInfo { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoFrame = Struct__GstVideoFrame;
pub type Enum_Unnamed222 = ::libc::c_uint;
pub const GST_VIDEO_FRAME_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_FRAME_FLAG_INTERLACED: ::libc::c_uint = 1;
pub const GST_VIDEO_FRAME_FLAG_TFF: ::libc::c_uint = 2;
pub const GST_VIDEO_FRAME_FLAG_RFF: ::libc::c_uint = 4;
pub const GST_VIDEO_FRAME_FLAG_ONEFIELD: ::libc::c_uint = 8;
pub type GstVideoFrameFlags = Enum_Unnamed222;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFrame {
pub info: GstVideoInfo,
pub flags: GstVideoFrameFlags,
pub buffer: *mut GstBuffer,
pub meta: gpointer,
pub id: gint,
pub data: [gpointer; 4u],
pub map: [GstMapInfo; 4u],
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFrame {
fn default() -> Struct__GstVideoFrame { unsafe { ::std::mem::zeroed() } }
}
pub type Enum_Unnamed223 = ::libc::c_uint;
pub const GST_VIDEO_BUFFER_FLAG_INTERLACED: ::libc::c_uint = 1048576;
pub const GST_VIDEO_BUFFER_FLAG_TFF: ::libc::c_uint = 2097152;
pub const GST_VIDEO_BUFFER_FLAG_RFF: ::libc::c_uint = 4194304;
pub const GST_VIDEO_BUFFER_FLAG_ONEFIELD: ::libc::c_uint = 8388608;
pub const GST_VIDEO_BUFFER_FLAG_LAST: ::libc::c_uint = 268435456;
pub type GstVideoBufferFlags = Enum_Unnamed223;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoAlignment {
pub padding_top: guint,
pub padding_bottom: guint,
pub padding_left: guint,
pub padding_right: guint,
pub stride_align: [guint; 4u],
}
impl ::std::default::Default for Struct__GstVideoAlignment {
fn default() -> Struct__GstVideoAlignment {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoConvertSampleCallback =
::std::option::Option<extern "C" fn
(sample: *mut GstSample, error: *mut GError,
user_data: gpointer)>;
pub type GstColorBalanceChannel = Struct__GstColorBalanceChannel;
pub type GstColorBalanceChannelClass = Struct__GstColorBalanceChannelClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceChannel {
pub parent: GObject,
pub label: *mut gchar,
pub min_value: gint,
pub max_value: gint,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceChannel {
fn default() -> Struct__GstColorBalanceChannel {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceChannelClass {
pub parent: GObjectClass,
pub value_changed: ::std::option::Option<extern "C" fn
(channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceChannelClass {
fn default() -> Struct__GstColorBalanceChannelClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstColorBalance { }
pub type GstColorBalance = Struct__GstColorBalance;
pub type GstColorBalanceInterface = Struct__GstColorBalanceInterface;
pub type Enum_Unnamed224 = ::libc::c_uint;
pub const GST_COLOR_BALANCE_HARDWARE: ::libc::c_uint = 0;
pub const GST_COLOR_BALANCE_SOFTWARE: ::libc::c_uint = 1;
pub type GstColorBalanceType = Enum_Unnamed224;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstColorBalanceInterface {
pub iface: GTypeInterface,
pub list_channels: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance)
-> *const GList>,
pub set_value: ::std::option::Option<extern "C" fn
(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub get_value: ::std::option::Option<extern "C" fn
(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel)
-> gint>,
pub get_balance_type: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance)
-> GstColorBalanceType>,
pub value_changed: ::std::option::Option<extern "C" fn
(balance:
*mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint)>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstColorBalanceInterface {
fn default() -> Struct__GstColorBalanceInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstAdapter { }
pub type GstAdapter = Struct__GstAdapter;
pub enum Struct__GstAdapterClass { }
pub type GstAdapterClass = Struct__GstAdapterClass;
pub type GstVideoCodecState = Struct__GstVideoCodecState;
pub type GstVideoCodecFrame = Struct__GstVideoCodecFrame;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCodecState {
pub ref_count: gint,
pub info: GstVideoInfo,
pub caps: *mut GstCaps,
pub codec_data: *mut GstBuffer,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoCodecState {
fn default() -> Struct__GstVideoCodecState {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed225 = ::libc::c_uint;
pub const GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY: ::libc::c_uint = 1;
pub const GST_VIDEO_CODEC_FRAME_FLAG_SYNC_POINT: ::libc::c_uint = 2;
pub const GST_VIDEO_CODEC_FRAME_FLAG_FORCE_KEYFRAME: ::libc::c_uint = 4;
pub const GST_VIDEO_CODEC_FRAME_FLAG_FORCE_KEYFRAME_HEADERS: ::libc::c_uint =
8;
pub type GstVideoCodecFrameFlags = Enum_Unnamed225;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCodecFrame {
pub ref_count: gint,
pub flags: guint32,
pub system_frame_number: guint32,
pub decode_frame_number: guint32,
pub presentation_frame_number: guint32,
pub dts: GstClockTime,
pub pts: GstClockTime,
pub duration: GstClockTime,
pub distance_from_sync: ::libc::c_int,
pub input_buffer: *mut GstBuffer,
pub output_buffer: *mut GstBuffer,
pub deadline: GstClockTime,
pub events: *mut GList,
pub user_data: gpointer,
pub user_data_destroy_notify: GDestroyNotify,
pub abidata: Union_Unnamed226,
}
impl ::std::default::Default for Struct__GstVideoCodecFrame {
fn default() -> Struct__GstVideoCodecFrame {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Union_Unnamed226 {
pub _bindgen_data_: [u64; 20u],
}
impl Union_Unnamed226 {
pub unsafe fn ABI(&mut self) -> *mut Struct_Unnamed227 {
::std::mem::transmute(&self._bindgen_data_)
}
pub unsafe fn padding(&mut self) -> *mut [*mut ::libc::c_void; 20u] {
::std::mem::transmute(&self._bindgen_data_)
}
}
impl ::std::default::Default for Union_Unnamed226 {
fn default() -> Union_Unnamed226 { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed227 {
pub ts: GstClockTime,
pub ts2: GstClockTime,
}
impl ::std::default::Default for Struct_Unnamed227 {
fn default() -> Struct_Unnamed227 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoDecoder = Struct__GstVideoDecoder;
pub type GstVideoDecoderClass = Struct__GstVideoDecoderClass;
pub enum Struct__GstVideoDecoderPrivate { }
pub type GstVideoDecoderPrivate = Struct__GstVideoDecoderPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoDecoder {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub stream_lock: GRecMutex,
pub input_segment: GstSegment,
pub output_segment: GstSegment,
pub _priv: *mut GstVideoDecoderPrivate,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoDecoder {
fn default() -> Struct__GstVideoDecoder {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoDecoderClass {
pub element_class: GstElementClass,
pub open: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub close: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub parse: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame,
adapter: *mut GstAdapter,
at_eos: gboolean) -> GstFlowReturn>,
pub set_format: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
state: *mut GstVideoCodecState)
-> gboolean>,
pub reset: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
hard: gboolean) -> gboolean>,
pub finish: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> GstFlowReturn>,
pub handle_frame: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub sink_event: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
event: *mut GstEvent)
-> gboolean>,
pub negotiate: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(decoder:
*mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub flush: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder)
-> gboolean>,
pub sink_query: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub src_query: ::std::option::Option<extern "C" fn
(decoder: *mut GstVideoDecoder,
query: *mut GstQuery)
-> gboolean>,
pub padding: [*mut ::libc::c_void; 17u],
}
impl ::std::default::Default for Struct__GstVideoDecoderClass {
fn default() -> Struct__GstVideoDecoderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoEncoder = Struct__GstVideoEncoder;
pub enum Struct__GstVideoEncoderPrivate { }
pub type GstVideoEncoderPrivate = Struct__GstVideoEncoderPrivate;
pub type GstVideoEncoderClass = Struct__GstVideoEncoderClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoEncoder {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub stream_lock: GRecMutex,
pub input_segment: GstSegment,
pub output_segment: GstSegment,
pub _priv: *mut GstVideoEncoderPrivate,
pub padding: [*mut ::libc::c_void; 20u],
}
impl ::std::default::Default for Struct__GstVideoEncoder {
fn default() -> Struct__GstVideoEncoder {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoEncoderClass {
pub element_class: GstElementClass,
pub open: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub close: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub set_format: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
state: *mut GstVideoCodecState)
-> gboolean>,
pub handle_frame: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub reset: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
hard: gboolean) -> gboolean>,
pub finish: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> GstFlowReturn>,
pub pre_push: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn>,
pub getcaps: ::std::option::Option<extern "C" fn
(enc: *mut GstVideoEncoder,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub sink_event: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
event: *mut GstEvent)
-> gboolean>,
pub negotiate: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(encoder:
*mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub flush: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder)
-> gboolean>,
pub sink_query: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub src_query: ::std::option::Option<extern "C" fn
(encoder: *mut GstVideoEncoder,
query: *mut GstQuery)
-> gboolean>,
pub _gst_reserved: [gpointer; 17u],
}
impl ::std::default::Default for Struct__GstVideoEncoderClass {
fn default() -> Struct__GstVideoEncoderClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstBaseTransform = Struct__GstBaseTransform;
pub type GstBaseTransformClass = Struct__GstBaseTransformClass;
pub enum Struct__GstBaseTransformPrivate { }
pub type GstBaseTransformPrivate = Struct__GstBaseTransformPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseTransform {
pub element: GstElement,
pub sinkpad: *mut GstPad,
pub srcpad: *mut GstPad,
pub have_segment: gboolean,
pub segment: GstSegment,
pub _priv: *mut GstBaseTransformPrivate,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseTransform {
fn default() -> Struct__GstBaseTransform {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstBaseTransformClass {
pub parent_class: GstElementClass,
pub passthrough_on_same_caps: gboolean,
pub transform_ip_on_passthrough: gboolean,
pub transform_caps: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
filter: *mut GstCaps)
-> *mut GstCaps>,
pub fixate_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
othercaps: *mut GstCaps)
-> *mut GstCaps>,
pub accept_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps)
-> gboolean>,
pub set_caps: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
incaps: *mut GstCaps,
outcaps: *mut GstCaps)
-> gboolean>,
pub query: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
direction: GstPadDirection,
query: *mut GstQuery) -> gboolean>,
pub decide_allocation: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
query: *mut GstQuery)
-> gboolean>,
pub filter_meta: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
query: *mut GstQuery,
api: GType,
params: *const GstStructure)
-> gboolean>,
pub propose_allocation: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
decide_query:
*mut GstQuery,
query: *mut GstQuery)
-> gboolean>,
pub transform_size: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
direction: GstPadDirection,
caps: *mut GstCaps,
size: gsize,
othercaps: *mut GstCaps,
othersize: *mut gsize)
-> gboolean>,
pub get_unit_size: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
caps: *mut GstCaps,
size: *mut gsize)
-> gboolean>,
pub start: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform)
-> gboolean>,
pub stop: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform)
-> gboolean>,
pub sink_event: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
event: *mut GstEvent)
-> gboolean>,
pub src_event: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
event: *mut GstEvent)
-> gboolean>,
pub prepare_output_buffer: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
input:
*mut GstBuffer,
outbuf:
*mut *mut GstBuffer)
-> GstFlowReturn>,
pub copy_metadata: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
input: *mut GstBuffer,
outbuf: *mut GstBuffer)
-> gboolean>,
pub transform_meta: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
outbuf: *mut GstBuffer,
meta: *mut GstMeta,
inbuf: *mut GstBuffer)
-> gboolean>,
pub before_transform: ::std::option::Option<extern "C" fn
(trans:
*mut GstBaseTransform,
buffer: *mut GstBuffer)>,
pub transform: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
inbuf: *mut GstBuffer,
outbuf: *mut GstBuffer)
-> GstFlowReturn>,
pub transform_ip: ::std::option::Option<extern "C" fn
(trans: *mut GstBaseTransform,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 20u],
}
impl ::std::default::Default for Struct__GstBaseTransformClass {
fn default() -> Struct__GstBaseTransformClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoFilter = Struct__GstVideoFilter;
pub type GstVideoFilterClass = Struct__GstVideoFilterClass;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFilter {
pub element: GstBaseTransform,
pub negotiated: gboolean,
pub in_info: GstVideoInfo,
pub out_info: GstVideoInfo,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFilter {
fn default() -> Struct__GstVideoFilter { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoFilterClass {
pub parent_class: GstBaseTransformClass,
pub set_info: ::std::option::Option<extern "C" fn
(filter: *mut GstVideoFilter,
incaps: *mut GstCaps,
in_info: *mut GstVideoInfo,
outcaps: *mut GstCaps,
out_info: *mut GstVideoInfo)
-> gboolean>,
pub transform_frame: ::std::option::Option<extern "C" fn
(filter:
*mut GstVideoFilter,
inframe:
*mut GstVideoFrame,
outframe:
*mut GstVideoFrame)
-> GstFlowReturn>,
pub transform_frame_ip: ::std::option::Option<extern "C" fn
(trans:
*mut GstVideoFilter,
frame:
*mut GstVideoFrame)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoFilterClass {
fn default() -> Struct__GstVideoFilterClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoMeta = Struct__GstVideoMeta;
pub type GstVideoCropMeta = Struct__GstVideoCropMeta;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoMeta {
pub meta: GstMeta,
pub buffer: *mut GstBuffer,
pub flags: GstVideoFrameFlags,
pub format: GstVideoFormat,
pub id: gint,
pub width: guint,
pub height: guint,
pub n_planes: guint,
pub offset: [gsize; 4u],
pub stride: [gint; 4u],
pub map: ::std::option::Option<extern "C" fn
(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo,
data: *mut gpointer,
stride: *mut gint, flags: GstMapFlags)
-> gboolean>,
pub unmap: ::std::option::Option<extern "C" fn
(meta: *mut GstVideoMeta,
plane: guint, info: *mut GstMapInfo)
-> gboolean>,
}
impl ::std::default::Default for Struct__GstVideoMeta {
fn default() -> Struct__GstVideoMeta { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoCropMeta {
pub meta: GstMeta,
pub x: guint,
pub y: guint,
pub width: guint,
pub height: guint,
}
impl ::std::default::Default for Struct__GstVideoCropMeta {
fn default() -> Struct__GstVideoCropMeta {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed228 {
pub in_info: *mut GstVideoInfo,
pub out_info: *mut GstVideoInfo,
}
impl ::std::default::Default for Struct_Unnamed228 {
fn default() -> Struct_Unnamed228 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoMetaTransform = Struct_Unnamed228;
pub type Enum_Unnamed229 = ::libc::c_uint;
pub const GST_VIDEO_GL_TEXTURE_TYPE_LUMINANCE: ::libc::c_uint = 0;
pub const GST_VIDEO_GL_TEXTURE_TYPE_LUMINANCE_ALPHA: ::libc::c_uint = 1;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGB16: ::libc::c_uint = 2;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGB: ::libc::c_uint = 3;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RGBA: ::libc::c_uint = 4;
pub const GST_VIDEO_GL_TEXTURE_TYPE_R: ::libc::c_uint = 5;
pub const GST_VIDEO_GL_TEXTURE_TYPE_RG: ::libc::c_uint = 6;
pub type GstVideoGLTextureType = Enum_Unnamed229;
pub type Enum_Unnamed230 = ::libc::c_uint;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_NORMAL_Y_NORMAL: ::libc::c_uint =
0;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_NORMAL_Y_FLIP: ::libc::c_uint =
1;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_FLIP_Y_NORMAL: ::libc::c_uint =
2;
pub const GST_VIDEO_GL_TEXTURE_ORIENTATION_X_FLIP_Y_FLIP: ::libc::c_uint = 3;
pub type GstVideoGLTextureOrientation = Enum_Unnamed230;
pub type GstVideoGLTextureUploadMeta = Struct__GstVideoGLTextureUploadMeta;
pub type GstVideoGLTextureUpload =
::std::option::Option<extern "C" fn
(meta: *mut GstVideoGLTextureUploadMeta,
texture_id: *mut guint) -> gboolean>;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoGLTextureUploadMeta {
pub meta: GstMeta,
pub texture_orientation: GstVideoGLTextureOrientation,
pub n_textures: guint,
pub texture_type: [GstVideoGLTextureType; 4u],
pub buffer: *mut GstBuffer,
pub upload: GstVideoGLTextureUpload,
pub user_data: gpointer,
pub user_data_copy: GBoxedCopyFunc,
pub user_data_free: GBoxedFreeFunc,
}
impl ::std::default::Default for Struct__GstVideoGLTextureUploadMeta {
fn default() -> Struct__GstVideoGLTextureUploadMeta {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct_Unnamed231 {
pub meta: GstMeta,
pub roi_type: GQuark,
pub id: gint,
pub parent_id: gint,
pub x: guint,
pub y: guint,
pub w: guint,
pub h: guint,
}
impl ::std::default::Default for Struct_Unnamed231 {
fn default() -> Struct_Unnamed231 { unsafe { ::std::mem::zeroed() } }
}
pub type GstVideoRegionOfInterestMeta = Struct_Unnamed231;
pub type GstVideoBufferPool = Struct__GstVideoBufferPool;
pub type GstVideoBufferPoolClass = Struct__GstVideoBufferPoolClass;
pub enum Struct__GstVideoBufferPoolPrivate { }
pub type GstVideoBufferPoolPrivate = Struct__GstVideoBufferPoolPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoBufferPool {
pub bufferpool: GstBufferPool,
pub _priv: *mut GstVideoBufferPoolPrivate,
}
impl ::std::default::Default for Struct__GstVideoBufferPool {
fn default() -> Struct__GstVideoBufferPool {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoBufferPoolClass {
pub parent_class: GstBufferPoolClass,
}
impl ::std::default::Default for Struct__GstVideoBufferPoolClass {
fn default() -> Struct__GstVideoBufferPoolClass {
unsafe { ::std::mem::zeroed() }
}
}
pub type GstVideoSink = Struct__GstVideoSink;
pub type GstVideoSinkClass = Struct__GstVideoSinkClass;
pub type GstVideoRectangle = Struct__GstVideoRectangle;
pub enum Struct__GstVideoSinkPrivate { }
pub type GstVideoSinkPrivate = Struct__GstVideoSinkPrivate;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoRectangle {
pub x: gint,
pub y: gint,
pub w: gint,
pub h: gint,
}
impl ::std::default::Default for Struct__GstVideoRectangle {
fn default() -> Struct__GstVideoRectangle {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoSink {
pub element: GstBaseSink,
pub width: gint,
pub height: gint,
pub _priv: *mut GstVideoSinkPrivate,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoSink {
fn default() -> Struct__GstVideoSink { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoSinkClass {
pub parent_class: GstBaseSinkClass,
pub show_frame: ::std::option::Option<extern "C" fn
(video_sink: *mut GstVideoSink,
buf: *mut GstBuffer)
-> GstFlowReturn>,
pub _gst_reserved: [gpointer; 4u],
}
impl ::std::default::Default for Struct__GstVideoSinkClass {
fn default() -> Struct__GstVideoSinkClass {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstNavigation { }
pub type GstNavigation = Struct__GstNavigation;
pub type GstNavigationInterface = Struct__GstNavigationInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstNavigationInterface {
pub iface: GTypeInterface,
pub send_event: ::std::option::Option<extern "C" fn
(navigation: *mut GstNavigation,
structure: *mut GstStructure)>,
}
impl ::std::default::Default for Struct__GstNavigationInterface {
fn default() -> Struct__GstNavigationInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub type Enum_Unnamed232 = ::libc::c_uint;
pub const GST_NAVIGATION_COMMAND_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_COMMAND_MENU1: ::libc::c_uint = 1;
pub const GST_NAVIGATION_COMMAND_MENU2: ::libc::c_uint = 2;
pub const GST_NAVIGATION_COMMAND_MENU3: ::libc::c_uint = 3;
pub const GST_NAVIGATION_COMMAND_MENU4: ::libc::c_uint = 4;
pub const GST_NAVIGATION_COMMAND_MENU5: ::libc::c_uint = 5;
pub const GST_NAVIGATION_COMMAND_MENU6: ::libc::c_uint = 6;
pub const GST_NAVIGATION_COMMAND_MENU7: ::libc::c_uint = 7;
pub const GST_NAVIGATION_COMMAND_LEFT: ::libc::c_uint = 20;
pub const GST_NAVIGATION_COMMAND_RIGHT: ::libc::c_uint = 21;
pub const GST_NAVIGATION_COMMAND_UP: ::libc::c_uint = 22;
pub const GST_NAVIGATION_COMMAND_DOWN: ::libc::c_uint = 23;
pub const GST_NAVIGATION_COMMAND_ACTIVATE: ::libc::c_uint = 24;
pub const GST_NAVIGATION_COMMAND_PREV_ANGLE: ::libc::c_uint = 30;
pub const GST_NAVIGATION_COMMAND_NEXT_ANGLE: ::libc::c_uint = 31;
pub type GstNavigationCommand = Enum_Unnamed232;
pub type Enum_Unnamed233 = ::libc::c_uint;
pub const GST_NAVIGATION_QUERY_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_QUERY_COMMANDS: ::libc::c_uint = 1;
pub const GST_NAVIGATION_QUERY_ANGLES: ::libc::c_uint = 2;
pub type GstNavigationQueryType = Enum_Unnamed233;
pub type Enum_Unnamed234 = ::libc::c_uint;
pub const GST_NAVIGATION_MESSAGE_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_MESSAGE_MOUSE_OVER: ::libc::c_uint = 1;
pub const GST_NAVIGATION_MESSAGE_COMMANDS_CHANGED: ::libc::c_uint = 2;
pub const GST_NAVIGATION_MESSAGE_ANGLES_CHANGED: ::libc::c_uint = 3;
pub type GstNavigationMessageType = Enum_Unnamed234;
pub type Enum_Unnamed235 = ::libc::c_uint;
pub const GST_NAVIGATION_EVENT_INVALID: ::libc::c_uint = 0;
pub const GST_NAVIGATION_EVENT_KEY_PRESS: ::libc::c_uint = 1;
pub const GST_NAVIGATION_EVENT_KEY_RELEASE: ::libc::c_uint = 2;
pub const GST_NAVIGATION_EVENT_MOUSE_BUTTON_PRESS: ::libc::c_uint = 3;
pub const GST_NAVIGATION_EVENT_MOUSE_BUTTON_RELEASE: ::libc::c_uint = 4;
pub const GST_NAVIGATION_EVENT_MOUSE_MOVE: ::libc::c_uint = 5;
pub const GST_NAVIGATION_EVENT_COMMAND: ::libc::c_uint = 6;
pub type GstNavigationEventType = Enum_Unnamed235;
pub enum Struct__GstVideoOrientation { }
pub type GstVideoOrientation = Struct__GstVideoOrientation;
pub type GstVideoOrientationInterface = Struct__GstVideoOrientationInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOrientationInterface {
pub iface: GTypeInterface,
pub get_hflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean)
-> gboolean>,
pub get_vflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean)
-> gboolean>,
pub get_hcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: *mut gint)
-> gboolean>,
pub get_vcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: *mut gint)
-> gboolean>,
pub set_hflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean>,
pub set_vflip: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean>,
pub set_hcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean>,
pub set_vcenter: ::std::option::Option<extern "C" fn
(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean>,
}
impl ::std::default::Default for Struct__GstVideoOrientationInterface {
fn default() -> Struct__GstVideoOrientationInterface {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstVideoOverlayRectangle { }
pub type GstVideoOverlayRectangle = Struct__GstVideoOverlayRectangle;
pub type Enum_Unnamed236 = ::libc::c_uint;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_NONE: ::libc::c_uint = 0;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_PREMULTIPLIED_ALPHA: ::libc::c_uint =
1;
pub const GST_VIDEO_OVERLAY_FORMAT_FLAG_GLOBAL_ALPHA: ::libc::c_uint = 2;
pub type GstVideoOverlayFormatFlags = Enum_Unnamed236;
pub enum Struct__GstVideoOverlayComposition { }
pub type GstVideoOverlayComposition = Struct__GstVideoOverlayComposition;
pub type GstVideoOverlayCompositionMeta =
Struct__GstVideoOverlayCompositionMeta;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOverlayCompositionMeta {
pub meta: GstMeta,
pub overlay: *mut GstVideoOverlayComposition,
}
impl ::std::default::Default for Struct__GstVideoOverlayCompositionMeta {
fn default() -> Struct__GstVideoOverlayCompositionMeta {
unsafe { ::std::mem::zeroed() }
}
}
pub enum Struct__GstVideoOverlay { }
pub type GstVideoOverlay = Struct__GstVideoOverlay;
pub type GstVideoOverlayInterface = Struct__GstVideoOverlayInterface;
#[repr(C)]
#[derive(Copy)]
pub struct Struct__GstVideoOverlayInterface {
pub iface: GTypeInterface,
pub expose: ::std::option::Option<extern "C" fn
(overlay: *mut GstVideoOverlay)>,
pub handle_events: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
handle_events: gboolean)>,
pub set_render_rectangle: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
x: gint, y: gint,
width: gint,
height: gint)>,
pub set_window_handle: ::std::option::Option<extern "C" fn
(overlay:
*mut GstVideoOverlay,
handle: guintptr)>,
}
impl ::std::default::Default for Struct__GstVideoOverlayInterface {
fn default() -> Struct__GstVideoOverlayInterface {
unsafe { ::std::mem::zeroed() }
}
}
extern "C" {
pub static mut __tzname: [*mut ::libc::c_char; 2u];
pub static mut __daylight: ::libc::c_int;
pub static mut __timezone: ::libc::c_long;
pub static mut tzname: [*mut ::libc::c_char; 2u];
pub static mut daylight: ::libc::c_int;
pub static mut timezone: ::libc::c_long;
pub static mut _sys_siglist: [*const ::libc::c_char; 65u];
pub static mut sys_siglist: [*const ::libc::c_char; 65u];
pub static mut g_mem_gc_friendly: gboolean;
pub static mut glib_mem_profiler_table: *mut GMemVTable;
pub static mut g_timeout_funcs: GSourceFuncs;
pub static mut g_child_watch_funcs: GSourceFuncs;
pub static mut g_idle_funcs: GSourceFuncs;
pub static mut g_unix_signal_funcs: GSourceFuncs;
pub static mut g_unix_fd_source_funcs: GSourceFuncs;
pub static g_utf8_skip: *const gchar;
pub static mut g_io_watch_funcs: GSourceFuncs;
pub static g_ascii_table: *const guint16;
pub static g_test_config_vars: *const GTestConfig;
pub static glib_major_version: guint;
pub static glib_minor_version: guint;
pub static glib_micro_version: guint;
pub static glib_interface_age: guint;
pub static glib_binary_age: guint;
pub static mut g_thread_functions_for_glib_use: GThreadFunctions;
pub static mut g_thread_use_default_impl: gboolean;
pub static mut g_thread_gettime:
::std::option::Option<extern "C" fn() -> guint64>;
pub static mut g_threads_got_initialized: gboolean;
pub static mut g_param_spec_types: *mut GType;
pub static mut _gst_memory_type: GType;
pub static mut gst_memory_alignment: gsize;
pub static mut _gst_buffer_type: GType;
pub static mut _gst_meta_transform_copy: GQuark;
pub static mut _gst_meta_tag_memory: GQuark;
pub static mut _gst_buffer_list_type: GType;
pub static mut _gst_date_time_type: GType;
pub static mut _gst_structure_type: GType;
pub static mut _gst_caps_features_type: GType;
pub static mut _gst_caps_features_any: *mut GstCapsFeatures;
pub static mut _gst_caps_features_memory_system_memory:
*mut GstCapsFeatures;
pub static mut _gst_caps_type: GType;
pub static mut _gst_caps_any: *mut GstCaps;
pub static mut _gst_caps_none: *mut GstCaps;
pub static mut _gst_sample_type: GType;
pub static mut _gst_tag_list_type: GType;
pub static mut _gst_toc_type: GType;
pub static mut _gst_toc_entry_type: GType;
pub static mut _gst_context_type: GType;
pub static mut _gst_query_type: GType;
pub static mut _gst_message_type: GType;
pub static mut _gst_event_type: GType;
pub static mut GST_CAT_DEFAULT: *mut GstDebugCategory;
pub static mut _gst_debug_enabled: gboolean;
pub static mut _gst_debug_min: GstDebugLevel;
pub static mut _gst_int_range_type: GType;
pub static mut _gst_int64_range_type: GType;
pub static mut _gst_double_range_type: GType;
pub static mut _gst_fraction_range_type: GType;
pub static mut _gst_value_list_type: GType;
pub static mut _gst_value_array_type: GType;
pub static mut _gst_fraction_type: GType;
pub static mut _gst_bitmask_type: GType;
}
extern "C" {
pub fn clock() -> clock_t;
pub fn time(__timer: *mut time_t) -> time_t;
pub fn difftime(__time1: time_t, __time0: time_t) -> ::libc::c_double;
pub fn mktime(__tp: *mut Struct_tm) -> time_t;
pub fn strftime(__s: *mut ::libc::c_char, __maxsize: size_t,
__format: *const ::libc::c_char, __tp: *const Struct_tm)
-> size_t;
pub fn strftime_l(__s: *mut ::libc::c_char, __maxsize: size_t,
__format: *const ::libc::c_char, __tp: *const Struct_tm,
__loc: __locale_t) -> size_t;
pub fn gmtime(__timer: *const time_t) -> *mut Struct_tm;
pub fn localtime(__timer: *const time_t) -> *mut Struct_tm;
pub fn gmtime_r(__timer: *const time_t, __tp: *mut Struct_tm)
-> *mut Struct_tm;
pub fn localtime_r(__timer: *const time_t, __tp: *mut Struct_tm)
-> *mut Struct_tm;
pub fn asctime(__tp: *const Struct_tm) -> *mut ::libc::c_char;
pub fn ctime(__timer: *const time_t) -> *mut ::libc::c_char;
pub fn asctime_r(__tp: *const Struct_tm, __buf: *mut ::libc::c_char)
-> *mut ::libc::c_char;
pub fn ctime_r(__timer: *const time_t, __buf: *mut ::libc::c_char)
-> *mut ::libc::c_char;
pub fn tzset();
pub fn stime(__when: *const time_t) -> ::libc::c_int;
pub fn timegm(__tp: *mut Struct_tm) -> time_t;
pub fn timelocal(__tp: *mut Struct_tm) -> time_t;
pub fn dysize(__year: ::libc::c_int) -> ::libc::c_int;
pub fn nanosleep(__requested_time: *const Struct_timespec,
__remaining: *mut Struct_timespec) -> ::libc::c_int;
pub fn clock_getres(__clock_id: clockid_t, __res: *mut Struct_timespec)
-> ::libc::c_int;
pub fn clock_gettime(__clock_id: clockid_t, __tp: *mut Struct_timespec)
-> ::libc::c_int;
pub fn clock_settime(__clock_id: clockid_t, __tp: *const Struct_timespec)
-> ::libc::c_int;
pub fn clock_nanosleep(__clock_id: clockid_t, __flags: ::libc::c_int,
__req: *const Struct_timespec,
__rem: *mut Struct_timespec) -> ::libc::c_int;
pub fn clock_getcpuclockid(__pid: pid_t, __clock_id: *mut clockid_t)
-> ::libc::c_int;
pub fn timer_create(__clock_id: clockid_t, __evp: *mut Struct_sigevent,
__timerid: *mut timer_t) -> ::libc::c_int;
pub fn timer_delete(__timerid: timer_t) -> ::libc::c_int;
pub fn timer_settime(__timerid: timer_t, __flags: ::libc::c_int,
__value: *const Struct_itimerspec,
__ovalue: *mut Struct_itimerspec) -> ::libc::c_int;
pub fn timer_gettime(__timerid: timer_t, __value: *mut Struct_itimerspec)
-> ::libc::c_int;
pub fn timer_getoverrun(__timerid: timer_t) -> ::libc::c_int;
pub fn g_array_new(zero_terminated: gboolean, clear_: gboolean,
element_size: guint) -> *mut GArray;
pub fn g_array_sized_new(zero_terminated: gboolean, clear_: gboolean,
element_size: guint, reserved_size: guint)
-> *mut GArray;
pub fn g_array_free(array: *mut GArray, free_segment: gboolean)
-> *mut gchar;
pub fn g_array_ref(array: *mut GArray) -> *mut GArray;
pub fn g_array_unref(array: *mut GArray);
pub fn g_array_get_element_size(array: *mut GArray) -> guint;
pub fn g_array_append_vals(array: *mut GArray, data: gconstpointer,
len: guint) -> *mut GArray;
pub fn g_array_prepend_vals(array: *mut GArray, data: gconstpointer,
len: guint) -> *mut GArray;
pub fn g_array_insert_vals(array: *mut GArray, index_: guint,
data: gconstpointer, len: guint)
-> *mut GArray;
pub fn g_array_set_size(array: *mut GArray, length: guint) -> *mut GArray;
pub fn g_array_remove_index(array: *mut GArray, index_: guint)
-> *mut GArray;
pub fn g_array_remove_index_fast(array: *mut GArray, index_: guint)
-> *mut GArray;
pub fn g_array_remove_range(array: *mut GArray, index_: guint,
length: guint) -> *mut GArray;
pub fn g_array_sort(array: *mut GArray, compare_func: GCompareFunc);
pub fn g_array_sort_with_data(array: *mut GArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_array_set_clear_func(array: *mut GArray,
clear_func: GDestroyNotify);
pub fn g_ptr_array_new() -> *mut GPtrArray;
pub fn g_ptr_array_new_with_free_func(element_free_func: GDestroyNotify)
-> *mut GPtrArray;
pub fn g_ptr_array_sized_new(reserved_size: guint) -> *mut GPtrArray;
pub fn g_ptr_array_new_full(reserved_size: guint,
element_free_func: GDestroyNotify)
-> *mut GPtrArray;
pub fn g_ptr_array_free(array: *mut GPtrArray, free_seg: gboolean)
-> *mut gpointer;
pub fn g_ptr_array_ref(array: *mut GPtrArray) -> *mut GPtrArray;
pub fn g_ptr_array_unref(array: *mut GPtrArray);
pub fn g_ptr_array_set_free_func(array: *mut GPtrArray,
element_free_func: GDestroyNotify);
pub fn g_ptr_array_set_size(array: *mut GPtrArray, length: gint);
pub fn g_ptr_array_remove_index(array: *mut GPtrArray, index_: guint)
-> gpointer;
pub fn g_ptr_array_remove_index_fast(array: *mut GPtrArray, index_: guint)
-> gpointer;
pub fn g_ptr_array_remove(array: *mut GPtrArray, data: gpointer)
-> gboolean;
pub fn g_ptr_array_remove_fast(array: *mut GPtrArray, data: gpointer)
-> gboolean;
pub fn g_ptr_array_remove_range(array: *mut GPtrArray, index_: guint,
length: guint) -> *mut GPtrArray;
pub fn g_ptr_array_add(array: *mut GPtrArray, data: gpointer);
pub fn g_ptr_array_insert(array: *mut GPtrArray, index_: gint,
data: gpointer);
pub fn g_ptr_array_sort(array: *mut GPtrArray,
compare_func: GCompareFunc);
pub fn g_ptr_array_sort_with_data(array: *mut GPtrArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_ptr_array_foreach(array: *mut GPtrArray, func: GFunc,
user_data: gpointer);
pub fn g_byte_array_new() -> *mut GByteArray;
pub fn g_byte_array_new_take(data: *mut guint8, len: gsize)
-> *mut GByteArray;
pub fn g_byte_array_sized_new(reserved_size: guint) -> *mut GByteArray;
pub fn g_byte_array_free(array: *mut GByteArray, free_segment: gboolean)
-> *mut guint8;
pub fn g_byte_array_free_to_bytes(array: *mut GByteArray) -> *mut GBytes;
pub fn g_byte_array_ref(array: *mut GByteArray) -> *mut GByteArray;
pub fn g_byte_array_unref(array: *mut GByteArray);
pub fn g_byte_array_append(array: *mut GByteArray, data: *const guint8,
len: guint) -> *mut GByteArray;
pub fn g_byte_array_prepend(array: *mut GByteArray, data: *const guint8,
len: guint) -> *mut GByteArray;
pub fn g_byte_array_set_size(array: *mut GByteArray, length: guint)
-> *mut GByteArray;
pub fn g_byte_array_remove_index(array: *mut GByteArray, index_: guint)
-> *mut GByteArray;
pub fn g_byte_array_remove_index_fast(array: *mut GByteArray,
index_: guint) -> *mut GByteArray;
pub fn g_byte_array_remove_range(array: *mut GByteArray, index_: guint,
length: guint) -> *mut GByteArray;
pub fn g_byte_array_sort(array: *mut GByteArray,
compare_func: GCompareFunc);
pub fn g_byte_array_sort_with_data(array: *mut GByteArray,
compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_atomic_int_get(atomic: *const gint) -> gint;
pub fn g_atomic_int_set(atomic: *mut gint, newval: gint);
pub fn g_atomic_int_inc(atomic: *mut gint);
pub fn g_atomic_int_dec_and_test(atomic: *mut gint) -> gboolean;
pub fn g_atomic_int_compare_and_exchange(atomic: *mut gint, oldval: gint,
newval: gint) -> gboolean;
pub fn g_atomic_int_add(atomic: *mut gint, val: gint) -> gint;
pub fn g_atomic_int_and(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_int_or(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_int_xor(atomic: *mut guint, val: guint) -> guint;
pub fn g_atomic_pointer_get(atomic: *const ::libc::c_void) -> gpointer;
pub fn g_atomic_pointer_set(atomic: *mut ::libc::c_void,
newval: gpointer);
pub fn g_atomic_pointer_compare_and_exchange(atomic: *mut ::libc::c_void,
oldval: gpointer,
newval: gpointer)
-> gboolean;
pub fn g_atomic_pointer_add(atomic: *mut ::libc::c_void, val: gssize)
-> gssize;
pub fn g_atomic_pointer_and(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_pointer_or(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_pointer_xor(atomic: *mut ::libc::c_void, val: gsize)
-> gsize;
pub fn g_atomic_int_exchange_and_add(atomic: *mut gint, val: gint)
-> gint;
pub fn g_quark_try_string(string: *const gchar) -> GQuark;
pub fn g_quark_from_static_string(string: *const gchar) -> GQuark;
pub fn g_quark_from_string(string: *const gchar) -> GQuark;
pub fn g_quark_to_string(quark: GQuark) -> *const gchar;
pub fn g_intern_string(string: *const gchar) -> *const gchar;
pub fn g_intern_static_string(string: *const gchar) -> *const gchar;
pub fn g_error_new(domain: GQuark, code: gint, format: *const gchar, ...)
-> *mut GError;
pub fn g_error_new_literal(domain: GQuark, code: gint,
message: *const gchar) -> *mut GError;
pub fn g_error_new_valist(domain: GQuark, code: gint,
format: *const gchar, args: va_list)
-> *mut GError;
pub fn g_error_free(error: *mut GError);
pub fn g_error_copy(error: *const GError) -> *mut GError;
pub fn g_error_matches(error: *const GError, domain: GQuark, code: gint)
-> gboolean;
pub fn g_set_error(err: *mut *mut GError, domain: GQuark, code: gint,
format: *const gchar, ...);
pub fn g_set_error_literal(err: *mut *mut GError, domain: GQuark,
code: gint, message: *const gchar);
pub fn g_propagate_error(dest: *mut *mut GError, src: *mut GError);
pub fn g_clear_error(err: *mut *mut GError);
pub fn g_prefix_error(err: *mut *mut GError, format: *const gchar, ...);
pub fn g_propagate_prefixed_error(dest: *mut *mut GError,
src: *mut GError,
format: *const gchar, ...);
pub fn g_thread_error_quark() -> GQuark;
pub fn g_thread_ref(thread: *mut GThread) -> *mut GThread;
pub fn g_thread_unref(thread: *mut GThread);
pub fn g_thread_new(name: *const gchar, func: GThreadFunc, data: gpointer)
-> *mut GThread;
pub fn g_thread_try_new(name: *const gchar, func: GThreadFunc,
data: gpointer, error: *mut *mut GError)
-> *mut GThread;
pub fn g_thread_self() -> *mut GThread;
pub fn g_thread_exit(retval: gpointer);
pub fn g_thread_join(thread: *mut GThread) -> gpointer;
pub fn g_thread_yield();
pub fn g_mutex_init(mutex: *mut GMutex);
pub fn g_mutex_clear(mutex: *mut GMutex);
pub fn g_mutex_lock(mutex: *mut GMutex);
pub fn g_mutex_trylock(mutex: *mut GMutex) -> gboolean;
pub fn g_mutex_unlock(mutex: *mut GMutex);
pub fn g_rw_lock_init(rw_lock: *mut GRWLock);
pub fn g_rw_lock_clear(rw_lock: *mut GRWLock);
pub fn g_rw_lock_writer_lock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_writer_trylock(rw_lock: *mut GRWLock) -> gboolean;
pub fn g_rw_lock_writer_unlock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_reader_lock(rw_lock: *mut GRWLock);
pub fn g_rw_lock_reader_trylock(rw_lock: *mut GRWLock) -> gboolean;
pub fn g_rw_lock_reader_unlock(rw_lock: *mut GRWLock);
pub fn g_rec_mutex_init(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_clear(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_lock(rec_mutex: *mut GRecMutex);
pub fn g_rec_mutex_trylock(rec_mutex: *mut GRecMutex) -> gboolean;
pub fn g_rec_mutex_unlock(rec_mutex: *mut GRecMutex);
pub fn g_cond_init(cond: *mut GCond);
pub fn g_cond_clear(cond: *mut GCond);
pub fn g_cond_wait(cond: *mut GCond, mutex: *mut GMutex);
pub fn g_cond_signal(cond: *mut GCond);
pub fn g_cond_broadcast(cond: *mut GCond);
pub fn g_cond_wait_until(cond: *mut GCond, mutex: *mut GMutex,
end_time: gint64) -> gboolean;
pub fn g_private_get(key: *mut GPrivate) -> gpointer;
pub fn g_private_set(key: *mut GPrivate, value: gpointer);
pub fn g_private_replace(key: *mut GPrivate, value: gpointer);
pub fn g_once_impl(once: *mut GOnce, func: GThreadFunc, arg: gpointer)
-> gpointer;
pub fn g_once_init_enter(location: *mut ::libc::c_void) -> gboolean;
pub fn g_once_init_leave(location: *mut ::libc::c_void, result: gsize);
pub fn g_get_num_processors() -> guint;
pub fn g_async_queue_new() -> *mut GAsyncQueue;
pub fn g_async_queue_new_full(item_free_func: GDestroyNotify)
-> *mut GAsyncQueue;
pub fn g_async_queue_lock(queue: *mut GAsyncQueue);
pub fn g_async_queue_unlock(queue: *mut GAsyncQueue);
pub fn g_async_queue_ref(queue: *mut GAsyncQueue) -> *mut GAsyncQueue;
pub fn g_async_queue_unref(queue: *mut GAsyncQueue);
pub fn g_async_queue_ref_unlocked(queue: *mut GAsyncQueue);
pub fn g_async_queue_unref_and_unlock(queue: *mut GAsyncQueue);
pub fn g_async_queue_push(queue: *mut GAsyncQueue, data: gpointer);
pub fn g_async_queue_push_unlocked(queue: *mut GAsyncQueue,
data: gpointer);
pub fn g_async_queue_push_sorted(queue: *mut GAsyncQueue, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_push_sorted_unlocked(queue: *mut GAsyncQueue,
data: gpointer,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_pop(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_pop_unlocked(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_try_pop(queue: *mut GAsyncQueue) -> gpointer;
pub fn g_async_queue_try_pop_unlocked(queue: *mut GAsyncQueue)
-> gpointer;
pub fn g_async_queue_timeout_pop(queue: *mut GAsyncQueue,
timeout: guint64) -> gpointer;
pub fn g_async_queue_timeout_pop_unlocked(queue: *mut GAsyncQueue,
timeout: guint64) -> gpointer;
pub fn g_async_queue_length(queue: *mut GAsyncQueue) -> gint;
pub fn g_async_queue_length_unlocked(queue: *mut GAsyncQueue) -> gint;
pub fn g_async_queue_sort(queue: *mut GAsyncQueue, func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_sort_unlocked(queue: *mut GAsyncQueue,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_async_queue_timed_pop(queue: *mut GAsyncQueue,
end_time: *mut GTimeVal) -> gpointer;
pub fn g_async_queue_timed_pop_unlocked(queue: *mut GAsyncQueue,
end_time: *mut GTimeVal)
-> gpointer;
pub fn __sigismember(arg1: *const __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sigaddset(arg1: *mut __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sigdelset(arg1: *mut __sigset_t, arg2: ::libc::c_int)
-> ::libc::c_int;
pub fn __sysv_signal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn signal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn kill(__pid: __pid_t, __sig: ::libc::c_int) -> ::libc::c_int;
pub fn killpg(__pgrp: __pid_t, __sig: ::libc::c_int) -> ::libc::c_int;
pub fn raise(__sig: ::libc::c_int) -> ::libc::c_int;
pub fn ssignal(__sig: ::libc::c_int, __handler: __sighandler_t)
-> __sighandler_t;
pub fn gsignal(__sig: ::libc::c_int) -> ::libc::c_int;
pub fn psignal(__sig: ::libc::c_int, __s: *const ::libc::c_char);
pub fn psiginfo(__pinfo: *const siginfo_t, __s: *const ::libc::c_char);
pub fn __sigpause(__sig_or_mask: ::libc::c_int, __is_sig: ::libc::c_int)
-> ::libc::c_int;
pub fn sigblock(__mask: ::libc::c_int) -> ::libc::c_int;
pub fn sigsetmask(__mask: ::libc::c_int) -> ::libc::c_int;
pub fn siggetmask() -> ::libc::c_int;
pub fn sigemptyset(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigfillset(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigaddset(__set: *mut sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigdelset(__set: *mut sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigismember(__set: *const sigset_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn sigprocmask(__how: ::libc::c_int, __set: *const sigset_t,
__oset: *mut sigset_t) -> ::libc::c_int;
pub fn sigsuspend(__set: *const sigset_t) -> ::libc::c_int;
pub fn sigaction(__sig: ::libc::c_int, __act: *const Struct_sigaction,
__oact: *mut Struct_sigaction) -> ::libc::c_int;
pub fn sigpending(__set: *mut sigset_t) -> ::libc::c_int;
pub fn sigwait(__set: *const sigset_t, __sig: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn sigwaitinfo(__set: *const sigset_t, __info: *mut siginfo_t)
-> ::libc::c_int;
pub fn sigtimedwait(__set: *const sigset_t, __info: *mut siginfo_t,
__timeout: *const Struct_timespec) -> ::libc::c_int;
pub fn sigqueue(__pid: __pid_t, __sig: ::libc::c_int, __val: Union_sigval)
-> ::libc::c_int;
pub fn sigvec(__sig: ::libc::c_int, __vec: *const Struct_sigvec,
__ovec: *mut Struct_sigvec) -> ::libc::c_int;
pub fn sigreturn(__scp: *mut Struct_sigcontext) -> ::libc::c_int;
pub fn siginterrupt(__sig: ::libc::c_int, __interrupt: ::libc::c_int)
-> ::libc::c_int;
pub fn sigstack(__ss: *mut Struct_sigstack, __oss: *mut Struct_sigstack)
-> ::libc::c_int;
pub fn sigaltstack(__ss: *const Struct_sigaltstack,
__oss: *mut Struct_sigaltstack) -> ::libc::c_int;
pub fn pthread_sigmask(__how: ::libc::c_int, __newmask: *const __sigset_t,
__oldmask: *mut __sigset_t) -> ::libc::c_int;
pub fn pthread_kill(__threadid: pthread_t, __signo: ::libc::c_int)
-> ::libc::c_int;
pub fn __libc_current_sigrtmin() -> ::libc::c_int;
pub fn __libc_current_sigrtmax() -> ::libc::c_int;
pub fn g_on_error_query(prg_name: *const gchar);
pub fn g_on_error_stack_trace(prg_name: *const gchar);
pub fn g_base64_encode_step(_in: *const guchar, len: gsize,
break_lines: gboolean, out: *mut gchar,
state: *mut gint, save: *mut gint) -> gsize;
pub fn g_base64_encode_close(break_lines: gboolean, out: *mut gchar,
state: *mut gint, save: *mut gint) -> gsize;
pub fn g_base64_encode(data: *const guchar, len: gsize) -> *mut gchar;
pub fn g_base64_decode_step(_in: *const gchar, len: gsize,
out: *mut guchar, state: *mut gint,
save: *mut guint) -> gsize;
pub fn g_base64_decode(text: *const gchar, out_len: *mut gsize)
-> *mut guchar;
pub fn g_base64_decode_inplace(text: *mut gchar, out_len: *mut gsize)
-> *mut guchar;
pub fn g_bit_lock(address: *mut gint, lock_bit: gint);
pub fn g_bit_trylock(address: *mut gint, lock_bit: gint) -> gboolean;
pub fn g_bit_unlock(address: *mut gint, lock_bit: gint);
pub fn g_pointer_bit_lock(address: *mut ::libc::c_void, lock_bit: gint);
pub fn g_pointer_bit_trylock(address: *mut ::libc::c_void, lock_bit: gint)
-> gboolean;
pub fn g_pointer_bit_unlock(address: *mut ::libc::c_void, lock_bit: gint);
pub fn g_bookmark_file_error_quark() -> GQuark;
pub fn g_bookmark_file_new() -> *mut GBookmarkFile;
pub fn g_bookmark_file_free(bookmark: *mut GBookmarkFile);
pub fn g_bookmark_file_load_from_file(bookmark: *mut GBookmarkFile,
filename: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_load_from_data(bookmark: *mut GBookmarkFile,
data: *const gchar, length: gsize,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_load_from_data_dirs(bookmark: *mut GBookmarkFile,
file: *const gchar,
full_path: *mut *mut gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_to_data(bookmark: *mut GBookmarkFile,
length: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_bookmark_file_to_file(bookmark: *mut GBookmarkFile,
filename: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_title(bookmark: *mut GBookmarkFile,
uri: *const gchar, title: *const gchar);
pub fn g_bookmark_file_get_title(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_bookmark_file_set_description(bookmark: *mut GBookmarkFile,
uri: *const gchar,
description: *const gchar);
pub fn g_bookmark_file_get_description(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_bookmark_file_set_mime_type(bookmark: *mut GBookmarkFile,
uri: *const gchar,
mime_type: *const gchar);
pub fn g_bookmark_file_get_mime_type(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_bookmark_file_set_groups(bookmark: *mut GBookmarkFile,
uri: *const gchar,
groups: *mut *const gchar,
length: gsize);
pub fn g_bookmark_file_add_group(bookmark: *mut GBookmarkFile,
uri: *const gchar, group: *const gchar);
pub fn g_bookmark_file_has_group(bookmark: *mut GBookmarkFile,
uri: *const gchar, group: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_get_groups(bookmark: *mut GBookmarkFile,
uri: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_bookmark_file_add_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
exec: *const gchar);
pub fn g_bookmark_file_has_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_get_applications(bookmark: *mut GBookmarkFile,
uri: *const gchar,
length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_bookmark_file_set_app_info(bookmark: *mut GBookmarkFile,
uri: *const gchar, name: *const gchar,
exec: *const gchar, count: gint,
stamp: time_t,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_get_app_info(bookmark: *mut GBookmarkFile,
uri: *const gchar, name: *const gchar,
exec: *mut *mut gchar,
count: *mut guint, stamp: *mut time_t,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_is_private(bookmark: *mut GBookmarkFile,
uri: *const gchar,
is_private: gboolean);
pub fn g_bookmark_file_get_is_private(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_set_icon(bookmark: *mut GBookmarkFile,
uri: *const gchar, href: *const gchar,
mime_type: *const gchar);
pub fn g_bookmark_file_get_icon(bookmark: *mut GBookmarkFile,
uri: *const gchar, href: *mut *mut gchar,
mime_type: *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_set_added(bookmark: *mut GBookmarkFile,
uri: *const gchar, added: time_t);
pub fn g_bookmark_file_get_added(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_set_modified(bookmark: *mut GBookmarkFile,
uri: *const gchar, modified: time_t);
pub fn g_bookmark_file_get_modified(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_set_visited(bookmark: *mut GBookmarkFile,
uri: *const gchar, visited: time_t);
pub fn g_bookmark_file_get_visited(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> time_t;
pub fn g_bookmark_file_has_item(bookmark: *mut GBookmarkFile,
uri: *const gchar) -> gboolean;
pub fn g_bookmark_file_get_size(bookmark: *mut GBookmarkFile) -> gint;
pub fn g_bookmark_file_get_uris(bookmark: *mut GBookmarkFile,
length: *mut gsize) -> *mut *mut gchar;
pub fn g_bookmark_file_remove_group(bookmark: *mut GBookmarkFile,
uri: *const gchar,
group: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_remove_application(bookmark: *mut GBookmarkFile,
uri: *const gchar,
name: *const gchar,
error: *mut *mut GError)
-> gboolean;
pub fn g_bookmark_file_remove_item(bookmark: *mut GBookmarkFile,
uri: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bookmark_file_move_item(bookmark: *mut GBookmarkFile,
old_uri: *const gchar,
new_uri: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_bytes_new(data: gconstpointer, size: gsize) -> *mut GBytes;
pub fn g_bytes_new_take(data: gpointer, size: gsize) -> *mut GBytes;
pub fn g_bytes_new_static(data: gconstpointer, size: gsize)
-> *mut GBytes;
pub fn g_bytes_new_with_free_func(data: gconstpointer, size: gsize,
free_func: GDestroyNotify,
user_data: gpointer) -> *mut GBytes;
pub fn g_bytes_new_from_bytes(bytes: *mut GBytes, offset: gsize,
length: gsize) -> *mut GBytes;
pub fn g_bytes_get_data(bytes: *mut GBytes, size: *mut gsize)
-> gconstpointer;
pub fn g_bytes_get_size(bytes: *mut GBytes) -> gsize;
pub fn g_bytes_ref(bytes: *mut GBytes) -> *mut GBytes;
pub fn g_bytes_unref(bytes: *mut GBytes);
pub fn g_bytes_unref_to_data(bytes: *mut GBytes, size: *mut gsize)
-> gpointer;
pub fn g_bytes_unref_to_array(bytes: *mut GBytes) -> *mut GByteArray;
pub fn g_bytes_hash(bytes: gconstpointer) -> guint;
pub fn g_bytes_equal(bytes1: gconstpointer, bytes2: gconstpointer)
-> gboolean;
pub fn g_bytes_compare(bytes1: gconstpointer, bytes2: gconstpointer)
-> gint;
pub fn g_get_charset(charset: *mut *const ::libc::c_char) -> gboolean;
pub fn g_get_codeset() -> *mut gchar;
pub fn g_get_language_names() -> *const *const gchar;
pub fn g_get_locale_variants(locale: *const gchar) -> *mut *mut gchar;
pub fn g_checksum_type_get_length(checksum_type: GChecksumType) -> gssize;
pub fn g_checksum_new(checksum_type: GChecksumType) -> *mut GChecksum;
pub fn g_checksum_reset(checksum: *mut GChecksum);
pub fn g_checksum_copy(checksum: *const GChecksum) -> *mut GChecksum;
pub fn g_checksum_free(checksum: *mut GChecksum);
pub fn g_checksum_update(checksum: *mut GChecksum, data: *const guchar,
length: gssize);
pub fn g_checksum_get_string(checksum: *mut GChecksum) -> *const gchar;
pub fn g_checksum_get_digest(checksum: *mut GChecksum,
buffer: *mut guint8, digest_len: *mut gsize);
pub fn g_compute_checksum_for_data(checksum_type: GChecksumType,
data: *const guchar, length: gsize)
-> *mut gchar;
pub fn g_compute_checksum_for_string(checksum_type: GChecksumType,
str: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_compute_checksum_for_bytes(checksum_type: GChecksumType,
data: *mut GBytes) -> *mut gchar;
pub fn g_convert_error_quark() -> GQuark;
pub fn g_iconv_open(to_codeset: *const gchar, from_codeset: *const gchar)
-> GIConv;
pub fn g_iconv(converter: GIConv, inbuf: *mut *mut gchar,
inbytes_left: *mut gsize, outbuf: *mut *mut gchar,
outbytes_left: *mut gsize) -> gsize;
pub fn g_iconv_close(converter: GIConv) -> gint;
pub fn g_convert(str: *const gchar, len: gssize, to_codeset: *const gchar,
from_codeset: *const gchar, bytes_read: *mut gsize,
bytes_written: *mut gsize, error: *mut *mut GError)
-> *mut gchar;
pub fn g_convert_with_iconv(str: *const gchar, len: gssize,
converter: GIConv, bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_convert_with_fallback(str: *const gchar, len: gssize,
to_codeset: *const gchar,
from_codeset: *const gchar,
fallback: *const gchar,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_locale_to_utf8(opsysstring: *const gchar, len: gssize,
bytes_read: *mut gsize, bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_locale_from_utf8(utf8string: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_to_utf8(opsysstring: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_from_utf8(utf8string: *const gchar, len: gssize,
bytes_read: *mut gsize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_from_uri(uri: *const gchar, hostname: *mut *mut gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_to_uri(filename: *const gchar, hostname: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_filename_display_name(filename: *const gchar) -> *mut gchar;
pub fn g_get_filename_charsets(charsets: *mut *mut *const gchar)
-> gboolean;
pub fn g_filename_display_basename(filename: *const gchar) -> *mut gchar;
pub fn g_uri_list_extract_uris(uri_list: *const gchar) -> *mut *mut gchar;
pub fn g_datalist_init(datalist: *mut *mut GData);
pub fn g_datalist_clear(datalist: *mut *mut GData);
pub fn g_datalist_id_get_data(datalist: *mut *mut GData, key_id: GQuark)
-> gpointer;
pub fn g_datalist_id_set_data_full(datalist: *mut *mut GData,
key_id: GQuark, data: gpointer,
destroy_func: GDestroyNotify);
pub fn g_datalist_id_dup_data(datalist: *mut *mut GData, key_id: GQuark,
dup_func: GDuplicateFunc,
user_data: gpointer) -> gpointer;
pub fn g_datalist_id_replace_data(datalist: *mut *mut GData,
key_id: GQuark, oldval: gpointer,
newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_datalist_id_remove_no_notify(datalist: *mut *mut GData,
key_id: GQuark) -> gpointer;
pub fn g_datalist_foreach(datalist: *mut *mut GData,
func: GDataForeachFunc, user_data: gpointer);
pub fn g_datalist_set_flags(datalist: *mut *mut GData, flags: guint);
pub fn g_datalist_unset_flags(datalist: *mut *mut GData, flags: guint);
pub fn g_datalist_get_flags(datalist: *mut *mut GData) -> guint;
pub fn g_dataset_destroy(dataset_location: gconstpointer);
pub fn g_dataset_id_get_data(dataset_location: gconstpointer,
key_id: GQuark) -> gpointer;
pub fn g_datalist_get_data(datalist: *mut *mut GData, key: *const gchar)
-> gpointer;
pub fn g_dataset_id_set_data_full(dataset_location: gconstpointer,
key_id: GQuark, data: gpointer,
destroy_func: GDestroyNotify);
pub fn g_dataset_id_remove_no_notify(dataset_location: gconstpointer,
key_id: GQuark) -> gpointer;
pub fn g_dataset_foreach(dataset_location: gconstpointer,
func: GDataForeachFunc, user_data: gpointer);
pub fn g_date_new() -> *mut GDate;
pub fn g_date_new_dmy(day: GDateDay, month: GDateMonth, year: GDateYear)
-> *mut GDate;
pub fn g_date_new_julian(julian_day: guint32) -> *mut GDate;
pub fn g_date_free(date: *mut GDate);
pub fn g_date_valid(date: *const GDate) -> gboolean;
pub fn g_date_valid_day(day: GDateDay) -> gboolean;
pub fn g_date_valid_month(month: GDateMonth) -> gboolean;
pub fn g_date_valid_year(year: GDateYear) -> gboolean;
pub fn g_date_valid_weekday(weekday: GDateWeekday) -> gboolean;
pub fn g_date_valid_julian(julian_date: guint32) -> gboolean;
pub fn g_date_valid_dmy(day: GDateDay, month: GDateMonth, year: GDateYear)
-> gboolean;
pub fn g_date_get_weekday(date: *const GDate) -> GDateWeekday;
pub fn g_date_get_month(date: *const GDate) -> GDateMonth;
pub fn g_date_get_year(date: *const GDate) -> GDateYear;
pub fn g_date_get_day(date: *const GDate) -> GDateDay;
pub fn g_date_get_julian(date: *const GDate) -> guint32;
pub fn g_date_get_day_of_year(date: *const GDate) -> guint;
pub fn g_date_get_monday_week_of_year(date: *const GDate) -> guint;
pub fn g_date_get_sunday_week_of_year(date: *const GDate) -> guint;
pub fn g_date_get_iso8601_week_of_year(date: *const GDate) -> guint;
pub fn g_date_clear(date: *mut GDate, n_dates: guint);
pub fn g_date_set_parse(date: *mut GDate, str: *const gchar);
pub fn g_date_set_time_t(date: *mut GDate, timet: time_t);
pub fn g_date_set_time_val(date: *mut GDate, timeval: *mut GTimeVal);
pub fn g_date_set_time(date: *mut GDate, time_: GTime);
pub fn g_date_set_month(date: *mut GDate, month: GDateMonth);
pub fn g_date_set_day(date: *mut GDate, day: GDateDay);
pub fn g_date_set_year(date: *mut GDate, year: GDateYear);
pub fn g_date_set_dmy(date: *mut GDate, day: GDateDay, month: GDateMonth,
y: GDateYear);
pub fn g_date_set_julian(date: *mut GDate, julian_date: guint32);
pub fn g_date_is_first_of_month(date: *const GDate) -> gboolean;
pub fn g_date_is_last_of_month(date: *const GDate) -> gboolean;
pub fn g_date_add_days(date: *mut GDate, n_days: guint);
pub fn g_date_subtract_days(date: *mut GDate, n_days: guint);
pub fn g_date_add_months(date: *mut GDate, n_months: guint);
pub fn g_date_subtract_months(date: *mut GDate, n_months: guint);
pub fn g_date_add_years(date: *mut GDate, n_years: guint);
pub fn g_date_subtract_years(date: *mut GDate, n_years: guint);
pub fn g_date_is_leap_year(year: GDateYear) -> gboolean;
pub fn g_date_get_days_in_month(month: GDateMonth, year: GDateYear)
-> guint8;
pub fn g_date_get_monday_weeks_in_year(year: GDateYear) -> guint8;
pub fn g_date_get_sunday_weeks_in_year(year: GDateYear) -> guint8;
pub fn g_date_days_between(date1: *const GDate, date2: *const GDate)
-> gint;
pub fn g_date_compare(lhs: *const GDate, rhs: *const GDate) -> gint;
pub fn g_date_to_struct_tm(date: *const GDate, tm: *mut Struct_tm);
pub fn g_date_clamp(date: *mut GDate, min_date: *const GDate,
max_date: *const GDate);
pub fn g_date_order(date1: *mut GDate, date2: *mut GDate);
pub fn g_date_strftime(s: *mut gchar, slen: gsize, format: *const gchar,
date: *const GDate) -> gsize;
pub fn g_time_zone_new(identifier: *const gchar) -> *mut GTimeZone;
pub fn g_time_zone_new_utc() -> *mut GTimeZone;
pub fn g_time_zone_new_local() -> *mut GTimeZone;
pub fn g_time_zone_ref(tz: *mut GTimeZone) -> *mut GTimeZone;
pub fn g_time_zone_unref(tz: *mut GTimeZone);
pub fn g_time_zone_find_interval(tz: *mut GTimeZone, _type: GTimeType,
time_: gint64) -> gint;
pub fn g_time_zone_adjust_time(tz: *mut GTimeZone, _type: GTimeType,
time_: *mut gint64) -> gint;
pub fn g_time_zone_get_abbreviation(tz: *mut GTimeZone, interval: gint)
-> *const gchar;
pub fn g_time_zone_get_offset(tz: *mut GTimeZone, interval: gint)
-> gint32;
pub fn g_time_zone_is_dst(tz: *mut GTimeZone, interval: gint) -> gboolean;
pub fn g_date_time_unref(datetime: *mut GDateTime);
pub fn g_date_time_ref(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_new_now(tz: *mut GTimeZone) -> *mut GDateTime;
pub fn g_date_time_new_now_local() -> *mut GDateTime;
pub fn g_date_time_new_now_utc() -> *mut GDateTime;
pub fn g_date_time_new_from_unix_local(t: gint64) -> *mut GDateTime;
pub fn g_date_time_new_from_unix_utc(t: gint64) -> *mut GDateTime;
pub fn g_date_time_new_from_timeval_local(tv: *const GTimeVal)
-> *mut GDateTime;
pub fn g_date_time_new_from_timeval_utc(tv: *const GTimeVal)
-> *mut GDateTime;
pub fn g_date_time_new(tz: *mut GTimeZone, year: gint, month: gint,
day: gint, hour: gint, minute: gint,
seconds: gdouble) -> *mut GDateTime;
pub fn g_date_time_new_local(year: gint, month: gint, day: gint,
hour: gint, minute: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_new_utc(year: gint, month: gint, day: gint, hour: gint,
minute: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_add(datetime: *mut GDateTime, timespan: GTimeSpan)
-> *mut GDateTime;
pub fn g_date_time_add_years(datetime: *mut GDateTime, years: gint)
-> *mut GDateTime;
pub fn g_date_time_add_months(datetime: *mut GDateTime, months: gint)
-> *mut GDateTime;
pub fn g_date_time_add_weeks(datetime: *mut GDateTime, weeks: gint)
-> *mut GDateTime;
pub fn g_date_time_add_days(datetime: *mut GDateTime, days: gint)
-> *mut GDateTime;
pub fn g_date_time_add_hours(datetime: *mut GDateTime, hours: gint)
-> *mut GDateTime;
pub fn g_date_time_add_minutes(datetime: *mut GDateTime, minutes: gint)
-> *mut GDateTime;
pub fn g_date_time_add_seconds(datetime: *mut GDateTime, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_add_full(datetime: *mut GDateTime, years: gint,
months: gint, days: gint, hours: gint,
minutes: gint, seconds: gdouble)
-> *mut GDateTime;
pub fn g_date_time_compare(dt1: gconstpointer, dt2: gconstpointer)
-> gint;
pub fn g_date_time_difference(end: *mut GDateTime, begin: *mut GDateTime)
-> GTimeSpan;
pub fn g_date_time_hash(datetime: gconstpointer) -> guint;
pub fn g_date_time_equal(dt1: gconstpointer, dt2: gconstpointer)
-> gboolean;
pub fn g_date_time_get_ymd(datetime: *mut GDateTime, year: *mut gint,
month: *mut gint, day: *mut gint);
pub fn g_date_time_get_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_month(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_month(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_week_numbering_year(datetime: *mut GDateTime)
-> gint;
pub fn g_date_time_get_week_of_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_week(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_day_of_year(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_hour(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_minute(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_second(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_microsecond(datetime: *mut GDateTime) -> gint;
pub fn g_date_time_get_seconds(datetime: *mut GDateTime) -> gdouble;
pub fn g_date_time_to_unix(datetime: *mut GDateTime) -> gint64;
pub fn g_date_time_to_timeval(datetime: *mut GDateTime, tv: *mut GTimeVal)
-> gboolean;
pub fn g_date_time_get_utc_offset(datetime: *mut GDateTime) -> GTimeSpan;
pub fn g_date_time_get_timezone_abbreviation(datetime: *mut GDateTime)
-> *const gchar;
pub fn g_date_time_is_daylight_savings(datetime: *mut GDateTime)
-> gboolean;
pub fn g_date_time_to_timezone(datetime: *mut GDateTime,
tz: *mut GTimeZone) -> *mut GDateTime;
pub fn g_date_time_to_local(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_to_utc(datetime: *mut GDateTime) -> *mut GDateTime;
pub fn g_date_time_format(datetime: *mut GDateTime, format: *const gchar)
-> *mut gchar;
pub fn opendir(__name: *const ::libc::c_char) -> *mut DIR;
pub fn fdopendir(__fd: ::libc::c_int) -> *mut DIR;
pub fn closedir(__dirp: *mut DIR) -> ::libc::c_int;
pub fn readdir(__dirp: *mut DIR) -> *mut Struct_dirent;
pub fn readdir_r(__dirp: *mut DIR, __entry: *mut Struct_dirent,
__result: *mut *mut Struct_dirent) -> ::libc::c_int;
pub fn rewinddir(__dirp: *mut DIR);
pub fn seekdir(__dirp: *mut DIR, __pos: ::libc::c_long);
pub fn telldir(__dirp: *mut DIR) -> ::libc::c_long;
pub fn dirfd(__dirp: *mut DIR) -> ::libc::c_int;
pub fn scandir(__dir: *const ::libc::c_char,
__namelist: *mut *mut *mut Struct_dirent,
__selector:
::std::option::Option<extern "C" fn
(arg1: *const Struct_dirent)
-> ::libc::c_int>,
__cmp:
::std::option::Option<extern "C" fn
(arg1:
*mut *const Struct_dirent,
arg2:
*mut *const Struct_dirent)
-> ::libc::c_int>)
-> ::libc::c_int;
pub fn alphasort(__e1: *mut *const Struct_dirent,
__e2: *mut *const Struct_dirent) -> ::libc::c_int;
pub fn getdirentries(__fd: ::libc::c_int, __buf: *mut ::libc::c_char,
__nbytes: size_t, __basep: *mut __off_t)
-> __ssize_t;
pub fn g_dir_open(path: *const gchar, flags: guint,
error: *mut *mut GError) -> *mut GDir;
pub fn g_dir_read_name(dir: *mut GDir) -> *const gchar;
pub fn g_dir_rewind(dir: *mut GDir);
pub fn g_dir_close(dir: *mut GDir);
pub fn g_getenv(variable: *const gchar) -> *const gchar;
pub fn g_setenv(variable: *const gchar, value: *const gchar,
overwrite: gboolean) -> gboolean;
pub fn g_unsetenv(variable: *const gchar);
pub fn g_listenv() -> *mut *mut gchar;
pub fn g_get_environ() -> *mut *mut gchar;
pub fn g_environ_getenv(envp: *mut *mut gchar, variable: *const gchar)
-> *const gchar;
pub fn g_environ_setenv(envp: *mut *mut gchar, variable: *const gchar,
value: *const gchar, overwrite: gboolean)
-> *mut *mut gchar;
pub fn g_environ_unsetenv(envp: *mut *mut gchar, variable: *const gchar)
-> *mut *mut gchar;
pub fn g_file_error_quark() -> GQuark;
pub fn g_file_error_from_errno(err_no: gint) -> GFileError;
pub fn g_file_test(filename: *const gchar, test: GFileTest) -> gboolean;
pub fn g_file_get_contents(filename: *const gchar,
contents: *mut *mut gchar, length: *mut gsize,
error: *mut *mut GError) -> gboolean;
pub fn g_file_set_contents(filename: *const gchar, contents: *const gchar,
length: gssize, error: *mut *mut GError)
-> gboolean;
pub fn g_file_read_link(filename: *const gchar, error: *mut *mut GError)
-> *mut gchar;
pub fn g_mkdtemp(tmpl: *mut gchar) -> *mut gchar;
pub fn g_mkdtemp_full(tmpl: *mut gchar, mode: gint) -> *mut gchar;
pub fn g_mkstemp(tmpl: *mut gchar) -> gint;
pub fn g_mkstemp_full(tmpl: *mut gchar, flags: gint, mode: gint) -> gint;
pub fn g_file_open_tmp(tmpl: *const gchar, name_used: *mut *mut gchar,
error: *mut *mut GError) -> gint;
pub fn g_dir_make_tmp(tmpl: *const gchar, error: *mut *mut GError)
-> *mut gchar;
pub fn g_build_path(separator: *const gchar,
first_element: *const gchar, ...) -> *mut gchar;
pub fn g_build_pathv(separator: *const gchar, args: *mut *mut gchar)
-> *mut gchar;
pub fn g_build_filename(first_element: *const gchar, ...) -> *mut gchar;
pub fn g_build_filenamev(args: *mut *mut gchar) -> *mut gchar;
pub fn g_mkdir_with_parents(pathname: *const gchar, mode: gint) -> gint;
pub fn g_path_is_absolute(file_name: *const gchar) -> gboolean;
pub fn g_path_skip_root(file_name: *const gchar) -> *const gchar;
pub fn g_basename(file_name: *const gchar) -> *const gchar;
pub fn g_get_current_dir() -> *mut gchar;
pub fn g_path_get_basename(file_name: *const gchar) -> *mut gchar;
pub fn g_path_get_dirname(file_name: *const gchar) -> *mut gchar;
pub fn g_strip_context(msgid: *const gchar, msgval: *const gchar)
-> *const gchar;
pub fn g_dgettext(domain: *const gchar, msgid: *const gchar)
-> *const gchar;
pub fn g_dcgettext(domain: *const gchar, msgid: *const gchar,
category: gint) -> *const gchar;
pub fn g_dngettext(domain: *const gchar, msgid: *const gchar,
msgid_plural: *const gchar, n: gulong) -> *const gchar;
pub fn g_dpgettext(domain: *const gchar, msgctxtid: *const gchar,
msgidoffset: gsize) -> *const gchar;
pub fn g_dpgettext2(domain: *const gchar, context: *const gchar,
msgid: *const gchar) -> *const gchar;
pub fn g_free(mem: gpointer);
pub fn g_clear_pointer(pp: *mut gpointer, destroy: GDestroyNotify);
pub fn g_malloc(n_bytes: gsize) -> gpointer;
pub fn g_malloc0(n_bytes: gsize) -> gpointer;
pub fn g_realloc(mem: gpointer, n_bytes: gsize) -> gpointer;
pub fn g_try_malloc(n_bytes: gsize) -> gpointer;
pub fn g_try_malloc0(n_bytes: gsize) -> gpointer;
pub fn g_try_realloc(mem: gpointer, n_bytes: gsize) -> gpointer;
pub fn g_malloc_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_malloc0_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_realloc_n(mem: gpointer, n_blocks: gsize, n_block_bytes: gsize)
-> gpointer;
pub fn g_try_malloc_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_try_malloc0_n(n_blocks: gsize, n_block_bytes: gsize) -> gpointer;
pub fn g_try_realloc_n(mem: gpointer, n_blocks: gsize,
n_block_bytes: gsize) -> gpointer;
pub fn g_mem_set_vtable(vtable: *mut GMemVTable);
pub fn g_mem_is_system_malloc() -> gboolean;
pub fn g_mem_profile();
pub fn g_node_new(data: gpointer) -> *mut GNode;
pub fn g_node_destroy(root: *mut GNode);
pub fn g_node_unlink(node: *mut GNode);
pub fn g_node_copy_deep(node: *mut GNode, copy_func: GCopyFunc,
data: gpointer) -> *mut GNode;
pub fn g_node_copy(node: *mut GNode) -> *mut GNode;
pub fn g_node_insert(parent: *mut GNode, position: gint, node: *mut GNode)
-> *mut GNode;
pub fn g_node_insert_before(parent: *mut GNode, sibling: *mut GNode,
node: *mut GNode) -> *mut GNode;
pub fn g_node_insert_after(parent: *mut GNode, sibling: *mut GNode,
node: *mut GNode) -> *mut GNode;
pub fn g_node_prepend(parent: *mut GNode, node: *mut GNode) -> *mut GNode;
pub fn g_node_n_nodes(root: *mut GNode, flags: GTraverseFlags) -> guint;
pub fn g_node_get_root(node: *mut GNode) -> *mut GNode;
pub fn g_node_is_ancestor(node: *mut GNode, descendant: *mut GNode)
-> gboolean;
pub fn g_node_depth(node: *mut GNode) -> guint;
pub fn g_node_find(root: *mut GNode, order: GTraverseType,
flags: GTraverseFlags, data: gpointer) -> *mut GNode;
pub fn g_node_traverse(root: *mut GNode, order: GTraverseType,
flags: GTraverseFlags, max_depth: gint,
func: GNodeTraverseFunc, data: gpointer);
pub fn g_node_max_height(root: *mut GNode) -> guint;
pub fn g_node_children_foreach(node: *mut GNode, flags: GTraverseFlags,
func: GNodeForeachFunc, data: gpointer);
pub fn g_node_reverse_children(node: *mut GNode);
pub fn g_node_n_children(node: *mut GNode) -> guint;
pub fn g_node_nth_child(node: *mut GNode, n: guint) -> *mut GNode;
pub fn g_node_last_child(node: *mut GNode) -> *mut GNode;
pub fn g_node_find_child(node: *mut GNode, flags: GTraverseFlags,
data: gpointer) -> *mut GNode;
pub fn g_node_child_position(node: *mut GNode, child: *mut GNode) -> gint;
pub fn g_node_child_index(node: *mut GNode, data: gpointer) -> gint;
pub fn g_node_first_sibling(node: *mut GNode) -> *mut GNode;
pub fn g_node_last_sibling(node: *mut GNode) -> *mut GNode;
pub fn g_list_alloc() -> *mut GList;
pub fn g_list_free(list: *mut GList);
pub fn g_list_free_1(list: *mut GList);
pub fn g_list_free_full(list: *mut GList, free_func: GDestroyNotify);
pub fn g_list_append(list: *mut GList, data: gpointer) -> *mut GList;
pub fn g_list_prepend(list: *mut GList, data: gpointer) -> *mut GList;
pub fn g_list_insert(list: *mut GList, data: gpointer, position: gint)
-> *mut GList;
pub fn g_list_insert_sorted(list: *mut GList, data: gpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_list_insert_sorted_with_data(list: *mut GList, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_insert_before(list: *mut GList, sibling: *mut GList,
data: gpointer) -> *mut GList;
pub fn g_list_concat(list1: *mut GList, list2: *mut GList) -> *mut GList;
pub fn g_list_remove(list: *mut GList, data: gconstpointer) -> *mut GList;
pub fn g_list_remove_all(list: *mut GList, data: gconstpointer)
-> *mut GList;
pub fn g_list_remove_link(list: *mut GList, llink: *mut GList)
-> *mut GList;
pub fn g_list_delete_link(list: *mut GList, link_: *mut GList)
-> *mut GList;
pub fn g_list_reverse(list: *mut GList) -> *mut GList;
pub fn g_list_copy(list: *mut GList) -> *mut GList;
pub fn g_list_copy_deep(list: *mut GList, func: GCopyFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_nth(list: *mut GList, n: guint) -> *mut GList;
pub fn g_list_nth_prev(list: *mut GList, n: guint) -> *mut GList;
pub fn g_list_find(list: *mut GList, data: gconstpointer) -> *mut GList;
pub fn g_list_find_custom(list: *mut GList, data: gconstpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_list_position(list: *mut GList, llink: *mut GList) -> gint;
pub fn g_list_index(list: *mut GList, data: gconstpointer) -> gint;
pub fn g_list_last(list: *mut GList) -> *mut GList;
pub fn g_list_first(list: *mut GList) -> *mut GList;
pub fn g_list_length(list: *mut GList) -> guint;
pub fn g_list_foreach(list: *mut GList, func: GFunc, user_data: gpointer);
pub fn g_list_sort(list: *mut GList, compare_func: GCompareFunc)
-> *mut GList;
pub fn g_list_sort_with_data(list: *mut GList,
compare_func: GCompareDataFunc,
user_data: gpointer) -> *mut GList;
pub fn g_list_nth_data(list: *mut GList, n: guint) -> gpointer;
pub fn g_hash_table_new(hash_func: GHashFunc, key_equal_func: GEqualFunc)
-> *mut GHashTable;
pub fn g_hash_table_new_full(hash_func: GHashFunc,
key_equal_func: GEqualFunc,
key_destroy_func: GDestroyNotify,
value_destroy_func: GDestroyNotify)
-> *mut GHashTable;
pub fn g_hash_table_destroy(hash_table: *mut GHashTable);
pub fn g_hash_table_insert(hash_table: *mut GHashTable, key: gpointer,
value: gpointer) -> gboolean;
pub fn g_hash_table_replace(hash_table: *mut GHashTable, key: gpointer,
value: gpointer) -> gboolean;
pub fn g_hash_table_add(hash_table: *mut GHashTable, key: gpointer)
-> gboolean;
pub fn g_hash_table_remove(hash_table: *mut GHashTable,
key: gconstpointer) -> gboolean;
pub fn g_hash_table_remove_all(hash_table: *mut GHashTable);
pub fn g_hash_table_steal(hash_table: *mut GHashTable, key: gconstpointer)
-> gboolean;
pub fn g_hash_table_steal_all(hash_table: *mut GHashTable);
pub fn g_hash_table_lookup(hash_table: *mut GHashTable,
key: gconstpointer) -> gpointer;
pub fn g_hash_table_contains(hash_table: *mut GHashTable,
key: gconstpointer) -> gboolean;
pub fn g_hash_table_lookup_extended(hash_table: *mut GHashTable,
lookup_key: gconstpointer,
orig_key: *mut gpointer,
value: *mut gpointer) -> gboolean;
pub fn g_hash_table_foreach(hash_table: *mut GHashTable, func: GHFunc,
user_data: gpointer);
pub fn g_hash_table_find(hash_table: *mut GHashTable, predicate: GHRFunc,
user_data: gpointer) -> gpointer;
pub fn g_hash_table_foreach_remove(hash_table: *mut GHashTable,
func: GHRFunc, user_data: gpointer)
-> guint;
pub fn g_hash_table_foreach_steal(hash_table: *mut GHashTable,
func: GHRFunc, user_data: gpointer)
-> guint;
pub fn g_hash_table_size(hash_table: *mut GHashTable) -> guint;
pub fn g_hash_table_get_keys(hash_table: *mut GHashTable) -> *mut GList;
pub fn g_hash_table_get_values(hash_table: *mut GHashTable) -> *mut GList;
pub fn g_hash_table_get_keys_as_array(hash_table: *mut GHashTable,
length: *mut guint)
-> *mut gpointer;
pub fn g_hash_table_iter_init(iter: *mut GHashTableIter,
hash_table: *mut GHashTable);
pub fn g_hash_table_iter_next(iter: *mut GHashTableIter,
key: *mut gpointer, value: *mut gpointer)
-> gboolean;
pub fn g_hash_table_iter_get_hash_table(iter: *mut GHashTableIter)
-> *mut GHashTable;
pub fn g_hash_table_iter_remove(iter: *mut GHashTableIter);
pub fn g_hash_table_iter_replace(iter: *mut GHashTableIter,
value: gpointer);
pub fn g_hash_table_iter_steal(iter: *mut GHashTableIter);
pub fn g_hash_table_ref(hash_table: *mut GHashTable) -> *mut GHashTable;
pub fn g_hash_table_unref(hash_table: *mut GHashTable);
pub fn g_str_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_str_hash(v: gconstpointer) -> guint;
pub fn g_int_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_int_hash(v: gconstpointer) -> guint;
pub fn g_int64_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_int64_hash(v: gconstpointer) -> guint;
pub fn g_double_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_double_hash(v: gconstpointer) -> guint;
pub fn g_direct_hash(v: gconstpointer) -> guint;
pub fn g_direct_equal(v1: gconstpointer, v2: gconstpointer) -> gboolean;
pub fn g_hmac_new(digest_type: GChecksumType, key: *const guchar,
key_len: gsize) -> *mut GHmac;
pub fn g_hmac_copy(hmac: *const GHmac) -> *mut GHmac;
pub fn g_hmac_ref(hmac: *mut GHmac) -> *mut GHmac;
pub fn g_hmac_unref(hmac: *mut GHmac);
pub fn g_hmac_update(hmac: *mut GHmac, data: *const guchar,
length: gssize);
pub fn g_hmac_get_string(hmac: *mut GHmac) -> *const gchar;
pub fn g_hmac_get_digest(hmac: *mut GHmac, buffer: *mut guint8,
digest_len: *mut gsize);
pub fn g_compute_hmac_for_data(digest_type: GChecksumType,
key: *const guchar, key_len: gsize,
data: *const guchar, length: gsize)
-> *mut gchar;
pub fn g_compute_hmac_for_string(digest_type: GChecksumType,
key: *const guchar, key_len: gsize,
str: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_hook_list_init(hook_list: *mut GHookList, hook_size: guint);
pub fn g_hook_list_clear(hook_list: *mut GHookList);
pub fn g_hook_alloc(hook_list: *mut GHookList) -> *mut GHook;
pub fn g_hook_free(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_ref(hook_list: *mut GHookList, hook: *mut GHook)
-> *mut GHook;
pub fn g_hook_unref(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_destroy(hook_list: *mut GHookList, hook_id: gulong)
-> gboolean;
pub fn g_hook_destroy_link(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_prepend(hook_list: *mut GHookList, hook: *mut GHook);
pub fn g_hook_insert_before(hook_list: *mut GHookList,
sibling: *mut GHook, hook: *mut GHook);
pub fn g_hook_insert_sorted(hook_list: *mut GHookList, hook: *mut GHook,
func: GHookCompareFunc);
pub fn g_hook_get(hook_list: *mut GHookList, hook_id: gulong)
-> *mut GHook;
pub fn g_hook_find(hook_list: *mut GHookList, need_valids: gboolean,
func: GHookFindFunc, data: gpointer) -> *mut GHook;
pub fn g_hook_find_data(hook_list: *mut GHookList, need_valids: gboolean,
data: gpointer) -> *mut GHook;
pub fn g_hook_find_func(hook_list: *mut GHookList, need_valids: gboolean,
func: gpointer) -> *mut GHook;
pub fn g_hook_find_func_data(hook_list: *mut GHookList,
need_valids: gboolean, func: gpointer,
data: gpointer) -> *mut GHook;
pub fn g_hook_first_valid(hook_list: *mut GHookList,
may_be_in_call: gboolean) -> *mut GHook;
pub fn g_hook_next_valid(hook_list: *mut GHookList, hook: *mut GHook,
may_be_in_call: gboolean) -> *mut GHook;
pub fn g_hook_compare_ids(new_hook: *mut GHook, sibling: *mut GHook)
-> gint;
pub fn g_hook_list_invoke(hook_list: *mut GHookList,
may_recurse: gboolean);
pub fn g_hook_list_invoke_check(hook_list: *mut GHookList,
may_recurse: gboolean);
pub fn g_hook_list_marshal(hook_list: *mut GHookList,
may_recurse: gboolean,
marshaller: GHookMarshaller,
marshal_data: gpointer);
pub fn g_hook_list_marshal_check(hook_list: *mut GHookList,
may_recurse: gboolean,
marshaller: GHookCheckMarshaller,
marshal_data: gpointer);
pub fn g_hostname_is_non_ascii(hostname: *const gchar) -> gboolean;
pub fn g_hostname_is_ascii_encoded(hostname: *const gchar) -> gboolean;
pub fn g_hostname_is_ip_address(hostname: *const gchar) -> gboolean;
pub fn g_hostname_to_ascii(hostname: *const gchar) -> *mut gchar;
pub fn g_hostname_to_unicode(hostname: *const gchar) -> *mut gchar;
pub fn g_poll(fds: *mut GPollFD, nfds: guint, timeout: gint) -> gint;
pub fn g_slist_alloc() -> *mut GSList;
pub fn g_slist_free(list: *mut GSList);
pub fn g_slist_free_1(list: *mut GSList);
pub fn g_slist_free_full(list: *mut GSList, free_func: GDestroyNotify);
pub fn g_slist_append(list: *mut GSList, data: gpointer) -> *mut GSList;
pub fn g_slist_prepend(list: *mut GSList, data: gpointer) -> *mut GSList;
pub fn g_slist_insert(list: *mut GSList, data: gpointer, position: gint)
-> *mut GSList;
pub fn g_slist_insert_sorted(list: *mut GSList, data: gpointer,
func: GCompareFunc) -> *mut GSList;
pub fn g_slist_insert_sorted_with_data(list: *mut GSList, data: gpointer,
func: GCompareDataFunc,
user_data: gpointer)
-> *mut GSList;
pub fn g_slist_insert_before(slist: *mut GSList, sibling: *mut GSList,
data: gpointer) -> *mut GSList;
pub fn g_slist_concat(list1: *mut GSList, list2: *mut GSList)
-> *mut GSList;
pub fn g_slist_remove(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_remove_all(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_remove_link(list: *mut GSList, link_: *mut GSList)
-> *mut GSList;
pub fn g_slist_delete_link(list: *mut GSList, link_: *mut GSList)
-> *mut GSList;
pub fn g_slist_reverse(list: *mut GSList) -> *mut GSList;
pub fn g_slist_copy(list: *mut GSList) -> *mut GSList;
pub fn g_slist_copy_deep(list: *mut GSList, func: GCopyFunc,
user_data: gpointer) -> *mut GSList;
pub fn g_slist_nth(list: *mut GSList, n: guint) -> *mut GSList;
pub fn g_slist_find(list: *mut GSList, data: gconstpointer)
-> *mut GSList;
pub fn g_slist_find_custom(list: *mut GSList, data: gconstpointer,
func: GCompareFunc) -> *mut GSList;
pub fn g_slist_position(list: *mut GSList, llink: *mut GSList) -> gint;
pub fn g_slist_index(list: *mut GSList, data: gconstpointer) -> gint;
pub fn g_slist_last(list: *mut GSList) -> *mut GSList;
pub fn g_slist_length(list: *mut GSList) -> guint;
pub fn g_slist_foreach(list: *mut GSList, func: GFunc,
user_data: gpointer);
pub fn g_slist_sort(list: *mut GSList, compare_func: GCompareFunc)
-> *mut GSList;
pub fn g_slist_sort_with_data(list: *mut GSList,
compare_func: GCompareDataFunc,
user_data: gpointer) -> *mut GSList;
pub fn g_slist_nth_data(list: *mut GSList, n: guint) -> gpointer;
pub fn g_main_context_new() -> *mut GMainContext;
pub fn g_main_context_ref(context: *mut GMainContext)
-> *mut GMainContext;
pub fn g_main_context_unref(context: *mut GMainContext);
pub fn g_main_context_default() -> *mut GMainContext;
pub fn g_main_context_iteration(context: *mut GMainContext,
may_block: gboolean) -> gboolean;
pub fn g_main_context_pending(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_find_source_by_id(context: *mut GMainContext,
source_id: guint) -> *mut GSource;
pub fn g_main_context_find_source_by_user_data(context: *mut GMainContext,
user_data: gpointer)
-> *mut GSource;
pub fn g_main_context_find_source_by_funcs_user_data(context:
*mut GMainContext,
funcs:
*mut GSourceFuncs,
user_data: gpointer)
-> *mut GSource;
pub fn g_main_context_wakeup(context: *mut GMainContext);
pub fn g_main_context_acquire(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_release(context: *mut GMainContext);
pub fn g_main_context_is_owner(context: *mut GMainContext) -> gboolean;
pub fn g_main_context_wait(context: *mut GMainContext, cond: *mut GCond,
mutex: *mut GMutex) -> gboolean;
pub fn g_main_context_prepare(context: *mut GMainContext,
priority: *mut gint) -> gboolean;
pub fn g_main_context_query(context: *mut GMainContext,
max_priority: gint, timeout_: *mut gint,
fds: *mut GPollFD, n_fds: gint) -> gint;
pub fn g_main_context_check(context: *mut GMainContext,
max_priority: gint, fds: *mut GPollFD,
n_fds: gint) -> gint;
pub fn g_main_context_dispatch(context: *mut GMainContext);
pub fn g_main_context_set_poll_func(context: *mut GMainContext,
func: GPollFunc);
pub fn g_main_context_get_poll_func(context: *mut GMainContext)
-> GPollFunc;
pub fn g_main_context_add_poll(context: *mut GMainContext,
fd: *mut GPollFD, priority: gint);
pub fn g_main_context_remove_poll(context: *mut GMainContext,
fd: *mut GPollFD);
pub fn g_main_depth() -> gint;
pub fn g_main_current_source() -> *mut GSource;
pub fn g_main_context_push_thread_default(context: *mut GMainContext);
pub fn g_main_context_pop_thread_default(context: *mut GMainContext);
pub fn g_main_context_get_thread_default() -> *mut GMainContext;
pub fn g_main_context_ref_thread_default() -> *mut GMainContext;
pub fn g_main_loop_new(context: *mut GMainContext, is_running: gboolean)
-> *mut GMainLoop;
pub fn g_main_loop_run(_loop: *mut GMainLoop);
pub fn g_main_loop_quit(_loop: *mut GMainLoop);
pub fn g_main_loop_ref(_loop: *mut GMainLoop) -> *mut GMainLoop;
pub fn g_main_loop_unref(_loop: *mut GMainLoop);
pub fn g_main_loop_is_running(_loop: *mut GMainLoop) -> gboolean;
pub fn g_main_loop_get_context(_loop: *mut GMainLoop)
-> *mut GMainContext;
pub fn g_source_new(source_funcs: *mut GSourceFuncs, struct_size: guint)
-> *mut GSource;
pub fn g_source_ref(source: *mut GSource) -> *mut GSource;
pub fn g_source_unref(source: *mut GSource);
pub fn g_source_attach(source: *mut GSource, context: *mut GMainContext)
-> guint;
pub fn g_source_destroy(source: *mut GSource);
pub fn g_source_set_priority(source: *mut GSource, priority: gint);
pub fn g_source_get_priority(source: *mut GSource) -> gint;
pub fn g_source_set_can_recurse(source: *mut GSource,
can_recurse: gboolean);
pub fn g_source_get_can_recurse(source: *mut GSource) -> gboolean;
pub fn g_source_get_id(source: *mut GSource) -> guint;
pub fn g_source_get_context(source: *mut GSource) -> *mut GMainContext;
pub fn g_source_set_callback(source: *mut GSource, func: GSourceFunc,
data: gpointer, notify: GDestroyNotify);
pub fn g_source_set_funcs(source: *mut GSource, funcs: *mut GSourceFuncs);
pub fn g_source_is_destroyed(source: *mut GSource) -> gboolean;
pub fn g_source_set_name(source: *mut GSource,
name: *const ::libc::c_char);
pub fn g_source_get_name(source: *mut GSource) -> *const ::libc::c_char;
pub fn g_source_set_name_by_id(tag: guint, name: *const ::libc::c_char);
pub fn g_source_set_ready_time(source: *mut GSource, ready_time: gint64);
pub fn g_source_get_ready_time(source: *mut GSource) -> gint64;
pub fn g_source_add_unix_fd(source: *mut GSource, fd: gint,
events: GIOCondition) -> gpointer;
pub fn g_source_modify_unix_fd(source: *mut GSource, tag: gpointer,
new_events: GIOCondition);
pub fn g_source_remove_unix_fd(source: *mut GSource, tag: gpointer);
pub fn g_source_query_unix_fd(source: *mut GSource, tag: gpointer)
-> GIOCondition;
pub fn g_source_set_callback_indirect(source: *mut GSource,
callback_data: gpointer,
callback_funcs:
*mut GSourceCallbackFuncs);
pub fn g_source_add_poll(source: *mut GSource, fd: *mut GPollFD);
pub fn g_source_remove_poll(source: *mut GSource, fd: *mut GPollFD);
pub fn g_source_add_child_source(source: *mut GSource,
child_source: *mut GSource);
pub fn g_source_remove_child_source(source: *mut GSource,
child_source: *mut GSource);
pub fn g_source_get_current_time(source: *mut GSource,
timeval: *mut GTimeVal);
pub fn g_source_get_time(source: *mut GSource) -> gint64;
pub fn g_idle_source_new() -> *mut GSource;
pub fn g_child_watch_source_new(pid: GPid) -> *mut GSource;
pub fn g_timeout_source_new(interval: guint) -> *mut GSource;
pub fn g_timeout_source_new_seconds(interval: guint) -> *mut GSource;
pub fn g_get_current_time(result: *mut GTimeVal);
pub fn g_get_monotonic_time() -> gint64;
pub fn g_get_real_time() -> gint64;
pub fn g_source_remove(tag: guint) -> gboolean;
pub fn g_source_remove_by_user_data(user_data: gpointer) -> gboolean;
pub fn g_source_remove_by_funcs_user_data(funcs: *mut GSourceFuncs,
user_data: gpointer)
-> gboolean;
pub fn g_timeout_add_full(priority: gint, interval: guint,
function: GSourceFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_timeout_add(interval: guint, function: GSourceFunc,
data: gpointer) -> guint;
pub fn g_timeout_add_seconds_full(priority: gint, interval: guint,
function: GSourceFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_timeout_add_seconds(interval: guint, function: GSourceFunc,
data: gpointer) -> guint;
pub fn g_child_watch_add_full(priority: gint, pid: GPid,
function: GChildWatchFunc, data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn g_child_watch_add(pid: GPid, function: GChildWatchFunc,
data: gpointer) -> guint;
pub fn g_idle_add(function: GSourceFunc, data: gpointer) -> guint;
pub fn g_idle_add_full(priority: gint, function: GSourceFunc,
data: gpointer, notify: GDestroyNotify) -> guint;
pub fn g_idle_remove_by_data(data: gpointer) -> gboolean;
pub fn g_main_context_invoke_full(context: *mut GMainContext,
priority: gint, function: GSourceFunc,
data: gpointer, notify: GDestroyNotify);
pub fn g_main_context_invoke(context: *mut GMainContext,
function: GSourceFunc, data: gpointer);
pub fn g_unicode_script_to_iso15924(script: GUnicodeScript) -> guint32;
pub fn g_unicode_script_from_iso15924(iso15924: guint32)
-> GUnicodeScript;
pub fn g_unichar_isalnum(c: gunichar) -> gboolean;
pub fn g_unichar_isalpha(c: gunichar) -> gboolean;
pub fn g_unichar_iscntrl(c: gunichar) -> gboolean;
pub fn g_unichar_isdigit(c: gunichar) -> gboolean;
pub fn g_unichar_isgraph(c: gunichar) -> gboolean;
pub fn g_unichar_islower(c: gunichar) -> gboolean;
pub fn g_unichar_isprint(c: gunichar) -> gboolean;
pub fn g_unichar_ispunct(c: gunichar) -> gboolean;
pub fn g_unichar_isspace(c: gunichar) -> gboolean;
pub fn g_unichar_isupper(c: gunichar) -> gboolean;
pub fn g_unichar_isxdigit(c: gunichar) -> gboolean;
pub fn g_unichar_istitle(c: gunichar) -> gboolean;
pub fn g_unichar_isdefined(c: gunichar) -> gboolean;
pub fn g_unichar_iswide(c: gunichar) -> gboolean;
pub fn g_unichar_iswide_cjk(c: gunichar) -> gboolean;
pub fn g_unichar_iszerowidth(c: gunichar) -> gboolean;
pub fn g_unichar_ismark(c: gunichar) -> gboolean;
pub fn g_unichar_toupper(c: gunichar) -> gunichar;
pub fn g_unichar_tolower(c: gunichar) -> gunichar;
pub fn g_unichar_totitle(c: gunichar) -> gunichar;
pub fn g_unichar_digit_value(c: gunichar) -> gint;
pub fn g_unichar_xdigit_value(c: gunichar) -> gint;
pub fn g_unichar_type(c: gunichar) -> GUnicodeType;
pub fn g_unichar_break_type(c: gunichar) -> GUnicodeBreakType;
pub fn g_unichar_combining_class(uc: gunichar) -> gint;
pub fn g_unichar_get_mirror_char(ch: gunichar, mirrored_ch: *mut gunichar)
-> gboolean;
pub fn g_unichar_get_script(ch: gunichar) -> GUnicodeScript;
pub fn g_unichar_validate(ch: gunichar) -> gboolean;
pub fn g_unichar_compose(a: gunichar, b: gunichar, ch: *mut gunichar)
-> gboolean;
pub fn g_unichar_decompose(ch: gunichar, a: *mut gunichar,
b: *mut gunichar) -> gboolean;
pub fn g_unichar_fully_decompose(ch: gunichar, compat: gboolean,
result: *mut gunichar, result_len: gsize)
-> gsize;
pub fn g_unicode_canonical_ordering(string: *mut gunichar, len: gsize);
pub fn g_unicode_canonical_decomposition(ch: gunichar,
result_len: *mut gsize)
-> *mut gunichar;
pub fn g_utf8_get_char(p: *const gchar) -> gunichar;
pub fn g_utf8_get_char_validated(p: *const gchar, max_len: gssize)
-> gunichar;
pub fn g_utf8_offset_to_pointer(str: *const gchar, offset: glong)
-> *mut gchar;
pub fn g_utf8_pointer_to_offset(str: *const gchar, pos: *const gchar)
-> glong;
pub fn g_utf8_prev_char(p: *const gchar) -> *mut gchar;
pub fn g_utf8_find_next_char(p: *const gchar, end: *const gchar)
-> *mut gchar;
pub fn g_utf8_find_prev_char(str: *const gchar, p: *const gchar)
-> *mut gchar;
pub fn g_utf8_strlen(p: *const gchar, max: gssize) -> glong;
pub fn g_utf8_substring(str: *const gchar, start_pos: glong,
end_pos: glong) -> *mut gchar;
pub fn g_utf8_strncpy(dest: *mut gchar, src: *const gchar, n: gsize)
-> *mut gchar;
pub fn g_utf8_strchr(p: *const gchar, len: gssize, c: gunichar)
-> *mut gchar;
pub fn g_utf8_strrchr(p: *const gchar, len: gssize, c: gunichar)
-> *mut gchar;
pub fn g_utf8_strreverse(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_to_utf16(str: *const gchar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar2;
pub fn g_utf8_to_ucs4(str: *const gchar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar;
pub fn g_utf8_to_ucs4_fast(str: *const gchar, len: glong,
items_written: *mut glong) -> *mut gunichar;
pub fn g_utf16_to_ucs4(str: *const gunichar2, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar;
pub fn g_utf16_to_utf8(str: *const gunichar2, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gchar;
pub fn g_ucs4_to_utf16(str: *const gunichar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gunichar2;
pub fn g_ucs4_to_utf8(str: *const gunichar, len: glong,
items_read: *mut glong, items_written: *mut glong,
error: *mut *mut GError) -> *mut gchar;
pub fn g_unichar_to_utf8(c: gunichar, outbuf: *mut gchar) -> gint;
pub fn g_utf8_validate(str: *const gchar, max_len: gssize,
end: *mut *const gchar) -> gboolean;
pub fn g_utf8_strup(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_strdown(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_casefold(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_normalize(str: *const gchar, len: gssize,
mode: GNormalizeMode) -> *mut gchar;
pub fn g_utf8_collate(str1: *const gchar, str2: *const gchar) -> gint;
pub fn g_utf8_collate_key(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_utf8_collate_key_for_filename(str: *const gchar, len: gssize)
-> *mut gchar;
pub fn _g_utf8_make_valid(name: *const gchar) -> *mut gchar;
pub fn g_get_user_name() -> *const gchar;
pub fn g_get_real_name() -> *const gchar;
pub fn g_get_home_dir() -> *const gchar;
pub fn g_get_tmp_dir() -> *const gchar;
pub fn g_get_host_name() -> *const gchar;
pub fn g_get_prgname() -> *const gchar;
pub fn g_set_prgname(prgname: *const gchar);
pub fn g_get_application_name() -> *const gchar;
pub fn g_set_application_name(application_name: *const gchar);
pub fn g_reload_user_special_dirs_cache();
pub fn g_get_user_data_dir() -> *const gchar;
pub fn g_get_user_config_dir() -> *const gchar;
pub fn g_get_user_cache_dir() -> *const gchar;
pub fn g_get_system_data_dirs() -> *const *const gchar;
pub fn g_get_system_config_dirs() -> *const *const gchar;
pub fn g_get_user_runtime_dir() -> *const gchar;
pub fn g_get_user_special_dir(directory: GUserDirectory) -> *const gchar;
pub fn g_parse_debug_string(string: *const gchar, keys: *const GDebugKey,
nkeys: guint) -> guint;
pub fn g_snprintf(string: *mut gchar, n: gulong,
format: *const gchar, ...) -> gint;
pub fn g_vsnprintf(string: *mut gchar, n: gulong, format: *const gchar,
args: va_list) -> gint;
pub fn g_nullify_pointer(nullify_location: *mut gpointer);
pub fn g_format_size_full(size: guint64, flags: GFormatSizeFlags)
-> *mut gchar;
pub fn g_format_size(size: guint64) -> *mut gchar;
pub fn g_format_size_for_display(size: goffset) -> *mut gchar;
pub fn g_atexit(func: GVoidFunc);
pub fn g_find_program_in_path(program: *const gchar) -> *mut gchar;
pub fn g_string_new(init: *const gchar) -> *mut GString;
pub fn g_string_new_len(init: *const gchar, len: gssize) -> *mut GString;
pub fn g_string_sized_new(dfl_size: gsize) -> *mut GString;
pub fn g_string_free(string: *mut GString, free_segment: gboolean)
-> *mut gchar;
pub fn g_string_free_to_bytes(string: *mut GString) -> *mut GBytes;
pub fn g_string_equal(v: *const GString, v2: *const GString) -> gboolean;
pub fn g_string_hash(str: *const GString) -> guint;
pub fn g_string_assign(string: *mut GString, rval: *const gchar)
-> *mut GString;
pub fn g_string_truncate(string: *mut GString, len: gsize)
-> *mut GString;
pub fn g_string_set_size(string: *mut GString, len: gsize)
-> *mut GString;
pub fn g_string_insert_len(string: *mut GString, pos: gssize,
val: *const gchar, len: gssize)
-> *mut GString;
pub fn g_string_append(string: *mut GString, val: *const gchar)
-> *mut GString;
pub fn g_string_append_len(string: *mut GString, val: *const gchar,
len: gssize) -> *mut GString;
pub fn g_string_append_c(string: *mut GString, c: gchar) -> *mut GString;
pub fn g_string_append_unichar(string: *mut GString, wc: gunichar)
-> *mut GString;
pub fn g_string_prepend(string: *mut GString, val: *const gchar)
-> *mut GString;
pub fn g_string_prepend_c(string: *mut GString, c: gchar) -> *mut GString;
pub fn g_string_prepend_unichar(string: *mut GString, wc: gunichar)
-> *mut GString;
pub fn g_string_prepend_len(string: *mut GString, val: *const gchar,
len: gssize) -> *mut GString;
pub fn g_string_insert(string: *mut GString, pos: gssize,
val: *const gchar) -> *mut GString;
pub fn g_string_insert_c(string: *mut GString, pos: gssize, c: gchar)
-> *mut GString;
pub fn g_string_insert_unichar(string: *mut GString, pos: gssize,
wc: gunichar) -> *mut GString;
pub fn g_string_overwrite(string: *mut GString, pos: gsize,
val: *const gchar) -> *mut GString;
pub fn g_string_overwrite_len(string: *mut GString, pos: gsize,
val: *const gchar, len: gssize)
-> *mut GString;
pub fn g_string_erase(string: *mut GString, pos: gssize, len: gssize)
-> *mut GString;
pub fn g_string_ascii_down(string: *mut GString) -> *mut GString;
pub fn g_string_ascii_up(string: *mut GString) -> *mut GString;
pub fn g_string_vprintf(string: *mut GString, format: *const gchar,
args: va_list);
pub fn g_string_printf(string: *mut GString, format: *const gchar, ...);
pub fn g_string_append_vprintf(string: *mut GString, format: *const gchar,
args: va_list);
pub fn g_string_append_printf(string: *mut GString,
format: *const gchar, ...);
pub fn g_string_append_uri_escaped(string: *mut GString,
unescaped: *const gchar,
reserved_chars_allowed: *const gchar,
allow_utf8: gboolean) -> *mut GString;
pub fn g_string_down(string: *mut GString) -> *mut GString;
pub fn g_string_up(string: *mut GString) -> *mut GString;
pub fn g_io_channel_init(channel: *mut GIOChannel);
pub fn g_io_channel_ref(channel: *mut GIOChannel) -> *mut GIOChannel;
pub fn g_io_channel_unref(channel: *mut GIOChannel);
pub fn g_io_channel_read(channel: *mut GIOChannel, buf: *mut gchar,
count: gsize, bytes_read: *mut gsize)
-> GIOError;
pub fn g_io_channel_write(channel: *mut GIOChannel, buf: *const gchar,
count: gsize, bytes_written: *mut gsize)
-> GIOError;
pub fn g_io_channel_seek(channel: *mut GIOChannel, offset: gint64,
_type: GSeekType) -> GIOError;
pub fn g_io_channel_close(channel: *mut GIOChannel);
pub fn g_io_channel_shutdown(channel: *mut GIOChannel, flush: gboolean,
err: *mut *mut GError) -> GIOStatus;
pub fn g_io_add_watch_full(channel: *mut GIOChannel, priority: gint,
condition: GIOCondition, func: GIOFunc,
user_data: gpointer, notify: GDestroyNotify)
-> guint;
pub fn g_io_create_watch(channel: *mut GIOChannel,
condition: GIOCondition) -> *mut GSource;
pub fn g_io_add_watch(channel: *mut GIOChannel, condition: GIOCondition,
func: GIOFunc, user_data: gpointer) -> guint;
pub fn g_io_channel_set_buffer_size(channel: *mut GIOChannel,
size: gsize);
pub fn g_io_channel_get_buffer_size(channel: *mut GIOChannel) -> gsize;
pub fn g_io_channel_get_buffer_condition(channel: *mut GIOChannel)
-> GIOCondition;
pub fn g_io_channel_set_flags(channel: *mut GIOChannel, flags: GIOFlags,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_get_flags(channel: *mut GIOChannel) -> GIOFlags;
pub fn g_io_channel_set_line_term(channel: *mut GIOChannel,
line_term: *const gchar, length: gint);
pub fn g_io_channel_get_line_term(channel: *mut GIOChannel,
length: *mut gint) -> *const gchar;
pub fn g_io_channel_set_buffered(channel: *mut GIOChannel,
buffered: gboolean);
pub fn g_io_channel_get_buffered(channel: *mut GIOChannel) -> gboolean;
pub fn g_io_channel_set_encoding(channel: *mut GIOChannel,
encoding: *const gchar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_get_encoding(channel: *mut GIOChannel)
-> *const gchar;
pub fn g_io_channel_set_close_on_unref(channel: *mut GIOChannel,
do_close: gboolean);
pub fn g_io_channel_get_close_on_unref(channel: *mut GIOChannel)
-> gboolean;
pub fn g_io_channel_flush(channel: *mut GIOChannel,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_line(channel: *mut GIOChannel,
str_return: *mut *mut gchar,
length: *mut gsize,
terminator_pos: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_line_string(channel: *mut GIOChannel,
buffer: *mut GString,
terminator_pos: *mut gsize,
error: *mut *mut GError)
-> GIOStatus;
pub fn g_io_channel_read_to_end(channel: *mut GIOChannel,
str_return: *mut *mut gchar,
length: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_chars(channel: *mut GIOChannel, buf: *mut gchar,
count: gsize, bytes_read: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_read_unichar(channel: *mut GIOChannel,
thechar: *mut gunichar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_write_chars(channel: *mut GIOChannel,
buf: *const gchar, count: gssize,
bytes_written: *mut gsize,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_write_unichar(channel: *mut GIOChannel,
thechar: gunichar,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_seek_position(channel: *mut GIOChannel,
offset: gint64, _type: GSeekType,
error: *mut *mut GError) -> GIOStatus;
pub fn g_io_channel_new_file(filename: *const gchar, mode: *const gchar,
error: *mut *mut GError) -> *mut GIOChannel;
pub fn g_io_channel_error_quark() -> GQuark;
pub fn g_io_channel_error_from_errno(en: gint) -> GIOChannelError;
pub fn g_io_channel_unix_new(fd: ::libc::c_int) -> *mut GIOChannel;
pub fn g_io_channel_unix_get_fd(channel: *mut GIOChannel) -> gint;
pub fn g_key_file_error_quark() -> GQuark;
pub fn g_key_file_new() -> *mut GKeyFile;
pub fn g_key_file_ref(key_file: *mut GKeyFile) -> *mut GKeyFile;
pub fn g_key_file_unref(key_file: *mut GKeyFile);
pub fn g_key_file_free(key_file: *mut GKeyFile);
pub fn g_key_file_set_list_separator(key_file: *mut GKeyFile,
separator: gchar);
pub fn g_key_file_load_from_file(key_file: *mut GKeyFile,
file: *const gchar, flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_data(key_file: *mut GKeyFile,
data: *const gchar, length: gsize,
flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_dirs(key_file: *mut GKeyFile,
file: *const gchar,
search_dirs: *mut *const gchar,
full_path: *mut *mut gchar,
flags: GKeyFileFlags,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_load_from_data_dirs(key_file: *mut GKeyFile,
file: *const gchar,
full_path: *mut *mut gchar,
flags: GKeyFileFlags,
error: *mut *mut GError)
-> gboolean;
pub fn g_key_file_to_data(key_file: *mut GKeyFile, length: *mut gsize,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_save_to_file(key_file: *mut GKeyFile,
filename: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_start_group(key_file: *mut GKeyFile) -> *mut gchar;
pub fn g_key_file_get_groups(key_file: *mut GKeyFile, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_key_file_get_keys(key_file: *mut GKeyFile,
group_name: *const gchar, length: *mut gsize,
error: *mut *mut GError) -> *mut *mut gchar;
pub fn g_key_file_has_group(key_file: *mut GKeyFile,
group_name: *const gchar) -> gboolean;
pub fn g_key_file_has_key(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_value(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_set_value(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: *const gchar);
pub fn g_key_file_get_string(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_set_string(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
string: *const gchar);
pub fn g_key_file_get_locale_string(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_key_file_set_locale_string(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
string: *const gchar);
pub fn g_key_file_get_boolean(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_set_boolean(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gboolean);
pub fn g_key_file_get_integer(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gint;
pub fn g_key_file_set_integer(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gint);
pub fn g_key_file_get_int64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gint64;
pub fn g_key_file_set_int64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gint64);
pub fn g_key_file_get_uint64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> guint64;
pub fn g_key_file_set_uint64(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: guint64);
pub fn g_key_file_get_double(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gdouble;
pub fn g_key_file_set_double(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
value: gdouble);
pub fn g_key_file_get_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_key_file_set_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
list: *const *const gchar,
length: gsize);
pub fn g_key_file_get_locale_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
length: *mut gsize,
error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_key_file_set_locale_string_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
locale: *const gchar,
list: *const *const gchar,
length: gsize);
pub fn g_key_file_get_boolean_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut gboolean;
pub fn g_key_file_set_boolean_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gboolean,
length: gsize);
pub fn g_key_file_get_integer_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError) -> *mut gint;
pub fn g_key_file_set_double_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gdouble,
length: gsize);
pub fn g_key_file_get_double_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, length: *mut gsize,
error: *mut *mut GError)
-> *mut gdouble;
pub fn g_key_file_set_integer_list(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar, list: *mut gint,
length: gsize);
pub fn g_key_file_set_comment(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
comment: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_get_comment(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_key_file_remove_comment(key_file: *mut GKeyFile,
group_name: *const gchar,
key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_remove_key(key_file: *mut GKeyFile,
group_name: *const gchar, key: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_key_file_remove_group(key_file: *mut GKeyFile,
group_name: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_mapped_file_new(filename: *const gchar, writable: gboolean,
error: *mut *mut GError) -> *mut GMappedFile;
pub fn g_mapped_file_new_from_fd(fd: gint, writable: gboolean,
error: *mut *mut GError)
-> *mut GMappedFile;
pub fn g_mapped_file_get_length(file: *mut GMappedFile) -> gsize;
pub fn g_mapped_file_get_contents(file: *mut GMappedFile) -> *mut gchar;
pub fn g_mapped_file_get_bytes(file: *mut GMappedFile) -> *mut GBytes;
pub fn g_mapped_file_ref(file: *mut GMappedFile) -> *mut GMappedFile;
pub fn g_mapped_file_unref(file: *mut GMappedFile);
pub fn g_mapped_file_free(file: *mut GMappedFile);
pub fn g_markup_error_quark() -> GQuark;
pub fn g_markup_parse_context_new(parser: *const GMarkupParser,
flags: GMarkupParseFlags,
user_data: gpointer,
user_data_dnotify: GDestroyNotify)
-> *mut GMarkupParseContext;
pub fn g_markup_parse_context_ref(context: *mut GMarkupParseContext)
-> *mut GMarkupParseContext;
pub fn g_markup_parse_context_unref(context: *mut GMarkupParseContext);
pub fn g_markup_parse_context_free(context: *mut GMarkupParseContext);
pub fn g_markup_parse_context_parse(context: *mut GMarkupParseContext,
text: *const gchar, text_len: gssize,
error: *mut *mut GError) -> gboolean;
pub fn g_markup_parse_context_push(context: *mut GMarkupParseContext,
parser: *const GMarkupParser,
user_data: gpointer);
pub fn g_markup_parse_context_pop(context: *mut GMarkupParseContext)
-> gpointer;
pub fn g_markup_parse_context_end_parse(context: *mut GMarkupParseContext,
error: *mut *mut GError)
-> gboolean;
pub fn g_markup_parse_context_get_element(context:
*mut GMarkupParseContext)
-> *const gchar;
pub fn g_markup_parse_context_get_element_stack(context:
*mut GMarkupParseContext)
-> *const GSList;
pub fn g_markup_parse_context_get_position(context:
*mut GMarkupParseContext,
line_number: *mut gint,
char_number: *mut gint);
pub fn g_markup_parse_context_get_user_data(context:
*mut GMarkupParseContext)
-> gpointer;
pub fn g_markup_escape_text(text: *const gchar, length: gssize)
-> *mut gchar;
pub fn g_markup_printf_escaped(format: *const ::libc::c_char, ...)
-> *mut gchar;
pub fn g_markup_vprintf_escaped(format: *const ::libc::c_char,
args: va_list) -> *mut gchar;
pub fn g_markup_collect_attributes(element_name: *const gchar,
attribute_names: *mut *const gchar,
attribute_values: *mut *const gchar,
error: *mut *mut GError,
first_type: GMarkupCollectType,
first_attr: *const gchar, ...)
-> gboolean;
pub fn g_printf_string_upper_bound(format: *const gchar, args: va_list)
-> gsize;
pub fn g_log_set_handler(log_domain: *const gchar,
log_levels: GLogLevelFlags, log_func: GLogFunc,
user_data: gpointer) -> guint;
pub fn g_log_remove_handler(log_domain: *const gchar, handler_id: guint);
pub fn g_log_default_handler(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar,
unused_data: gpointer);
pub fn g_log_set_default_handler(log_func: GLogFunc, user_data: gpointer)
-> GLogFunc;
pub fn g_log(log_domain: *const gchar, log_level: GLogLevelFlags,
format: *const gchar, ...);
pub fn g_logv(log_domain: *const gchar, log_level: GLogLevelFlags,
format: *const gchar, args: va_list);
pub fn g_log_set_fatal_mask(log_domain: *const gchar,
fatal_mask: GLogLevelFlags) -> GLogLevelFlags;
pub fn g_log_set_always_fatal(fatal_mask: GLogLevelFlags)
-> GLogLevelFlags;
pub fn _g_log_fallback_handler(log_domain: *const gchar,
log_level: GLogLevelFlags,
message: *const gchar,
unused_data: gpointer);
pub fn g_return_if_fail_warning(log_domain: *const ::libc::c_char,
pretty_function: *const ::libc::c_char,
expression: *const ::libc::c_char);
pub fn g_warn_message(domain: *const ::libc::c_char,
file: *const ::libc::c_char, line: ::libc::c_int,
func: *const ::libc::c_char,
warnexpr: *const ::libc::c_char);
pub fn g_assert_warning(log_domain: *const ::libc::c_char,
file: *const ::libc::c_char, line: ::libc::c_int,
pretty_function: *const ::libc::c_char,
expression: *const ::libc::c_char);
pub fn g_print(format: *const gchar, ...);
pub fn g_set_print_handler(func: GPrintFunc) -> GPrintFunc;
pub fn g_printerr(format: *const gchar, ...);
pub fn g_set_printerr_handler(func: GPrintFunc) -> GPrintFunc;
pub fn g_option_error_quark() -> GQuark;
pub fn g_option_context_new(parameter_string: *const gchar)
-> *mut GOptionContext;
pub fn g_option_context_set_summary(context: *mut GOptionContext,
summary: *const gchar);
pub fn g_option_context_get_summary(context: *mut GOptionContext)
-> *const gchar;
pub fn g_option_context_set_description(context: *mut GOptionContext,
description: *const gchar);
pub fn g_option_context_get_description(context: *mut GOptionContext)
-> *const gchar;
pub fn g_option_context_free(context: *mut GOptionContext);
pub fn g_option_context_set_help_enabled(context: *mut GOptionContext,
help_enabled: gboolean);
pub fn g_option_context_get_help_enabled(context: *mut GOptionContext)
-> gboolean;
pub fn g_option_context_set_ignore_unknown_options(context:
*mut GOptionContext,
ignore_unknown:
gboolean);
pub fn g_option_context_get_ignore_unknown_options(context:
*mut GOptionContext)
-> gboolean;
pub fn g_option_context_add_main_entries(context: *mut GOptionContext,
entries: *const GOptionEntry,
translation_domain:
*const gchar);
pub fn g_option_context_parse(context: *mut GOptionContext,
argc: *mut gint, argv: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_option_context_parse_strv(context: *mut GOptionContext,
arguments: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_option_context_set_translate_func(context: *mut GOptionContext,
func: GTranslateFunc,
data: gpointer,
destroy_notify:
GDestroyNotify);
pub fn g_option_context_set_translation_domain(context:
*mut GOptionContext,
domain: *const gchar);
pub fn g_option_context_add_group(context: *mut GOptionContext,
group: *mut GOptionGroup);
pub fn g_option_context_set_main_group(context: *mut GOptionContext,
group: *mut GOptionGroup);
pub fn g_option_context_get_main_group(context: *mut GOptionContext)
-> *mut GOptionGroup;
pub fn g_option_context_get_help(context: *mut GOptionContext,
main_help: gboolean,
group: *mut GOptionGroup) -> *mut gchar;
pub fn g_option_group_new(name: *const gchar, description: *const gchar,
help_description: *const gchar,
user_data: gpointer, destroy: GDestroyNotify)
-> *mut GOptionGroup;
pub fn g_option_group_set_parse_hooks(group: *mut GOptionGroup,
pre_parse_func: GOptionParseFunc,
post_parse_func: GOptionParseFunc);
pub fn g_option_group_set_error_hook(group: *mut GOptionGroup,
error_func: GOptionErrorFunc);
pub fn g_option_group_free(group: *mut GOptionGroup);
pub fn g_option_group_add_entries(group: *mut GOptionGroup,
entries: *const GOptionEntry);
pub fn g_option_group_set_translate_func(group: *mut GOptionGroup,
func: GTranslateFunc,
data: gpointer,
destroy_notify: GDestroyNotify);
pub fn g_option_group_set_translation_domain(group: *mut GOptionGroup,
domain: *const gchar);
pub fn g_pattern_spec_new(pattern: *const gchar) -> *mut GPatternSpec;
pub fn g_pattern_spec_free(pspec: *mut GPatternSpec);
pub fn g_pattern_spec_equal(pspec1: *mut GPatternSpec,
pspec2: *mut GPatternSpec) -> gboolean;
pub fn g_pattern_match(pspec: *mut GPatternSpec, string_length: guint,
string: *const gchar,
string_reversed: *const gchar) -> gboolean;
pub fn g_pattern_match_string(pspec: *mut GPatternSpec,
string: *const gchar) -> gboolean;
pub fn g_pattern_match_simple(pattern: *const gchar, string: *const gchar)
-> gboolean;
pub fn g_spaced_primes_closest(num: guint) -> guint;
pub fn g_qsort_with_data(pbase: gconstpointer, total_elems: gint,
size: gsize, compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_queue_new() -> *mut GQueue;
pub fn g_queue_free(queue: *mut GQueue);
pub fn g_queue_free_full(queue: *mut GQueue, free_func: GDestroyNotify);
pub fn g_queue_init(queue: *mut GQueue);
pub fn g_queue_clear(queue: *mut GQueue);
pub fn g_queue_is_empty(queue: *mut GQueue) -> gboolean;
pub fn g_queue_get_length(queue: *mut GQueue) -> guint;
pub fn g_queue_reverse(queue: *mut GQueue);
pub fn g_queue_copy(queue: *mut GQueue) -> *mut GQueue;
pub fn g_queue_foreach(queue: *mut GQueue, func: GFunc,
user_data: gpointer);
pub fn g_queue_find(queue: *mut GQueue, data: gconstpointer)
-> *mut GList;
pub fn g_queue_find_custom(queue: *mut GQueue, data: gconstpointer,
func: GCompareFunc) -> *mut GList;
pub fn g_queue_sort(queue: *mut GQueue, compare_func: GCompareDataFunc,
user_data: gpointer);
pub fn g_queue_push_head(queue: *mut GQueue, data: gpointer);
pub fn g_queue_push_tail(queue: *mut GQueue, data: gpointer);
pub fn g_queue_push_nth(queue: *mut GQueue, data: gpointer, n: gint);
pub fn g_queue_pop_head(queue: *mut GQueue) -> gpointer;
pub fn g_queue_pop_tail(queue: *mut GQueue) -> gpointer;
pub fn g_queue_pop_nth(queue: *mut GQueue, n: guint) -> gpointer;
pub fn g_queue_peek_head(queue: *mut GQueue) -> gpointer;
pub fn g_queue_peek_tail(queue: *mut GQueue) -> gpointer;
pub fn g_queue_peek_nth(queue: *mut GQueue, n: guint) -> gpointer;
pub fn g_queue_index(queue: *mut GQueue, data: gconstpointer) -> gint;
pub fn g_queue_remove(queue: *mut GQueue, data: gconstpointer)
-> gboolean;
pub fn g_queue_remove_all(queue: *mut GQueue, data: gconstpointer)
-> guint;
pub fn g_queue_insert_before(queue: *mut GQueue, sibling: *mut GList,
data: gpointer);
pub fn g_queue_insert_after(queue: *mut GQueue, sibling: *mut GList,
data: gpointer);
pub fn g_queue_insert_sorted(queue: *mut GQueue, data: gpointer,
func: GCompareDataFunc, user_data: gpointer);
pub fn g_queue_push_head_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_push_tail_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_push_nth_link(queue: *mut GQueue, n: gint,
link_: *mut GList);
pub fn g_queue_pop_head_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_pop_tail_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_pop_nth_link(queue: *mut GQueue, n: guint) -> *mut GList;
pub fn g_queue_peek_head_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_peek_tail_link(queue: *mut GQueue) -> *mut GList;
pub fn g_queue_peek_nth_link(queue: *mut GQueue, n: guint) -> *mut GList;
pub fn g_queue_link_index(queue: *mut GQueue, link_: *mut GList) -> gint;
pub fn g_queue_unlink(queue: *mut GQueue, link_: *mut GList);
pub fn g_queue_delete_link(queue: *mut GQueue, link_: *mut GList);
pub fn g_rand_new_with_seed(seed: guint32) -> *mut GRand;
pub fn g_rand_new_with_seed_array(seed: *const guint32,
seed_length: guint) -> *mut GRand;
pub fn g_rand_new() -> *mut GRand;
pub fn g_rand_free(rand_: *mut GRand);
pub fn g_rand_copy(rand_: *mut GRand) -> *mut GRand;
pub fn g_rand_set_seed(rand_: *mut GRand, seed: guint32);
pub fn g_rand_set_seed_array(rand_: *mut GRand, seed: *const guint32,
seed_length: guint);
pub fn g_rand_int(rand_: *mut GRand) -> guint32;
pub fn g_rand_int_range(rand_: *mut GRand, begin: gint32, end: gint32)
-> gint32;
pub fn g_rand_double(rand_: *mut GRand) -> gdouble;
pub fn g_rand_double_range(rand_: *mut GRand, begin: gdouble,
end: gdouble) -> gdouble;
pub fn g_random_set_seed(seed: guint32);
pub fn g_random_int() -> guint32;
pub fn g_random_int_range(begin: gint32, end: gint32) -> gint32;
pub fn g_random_double() -> gdouble;
pub fn g_random_double_range(begin: gdouble, end: gdouble) -> gdouble;
pub fn g_regex_error_quark() -> GQuark;
pub fn g_regex_new(pattern: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut GRegex;
pub fn g_regex_ref(regex: *mut GRegex) -> *mut GRegex;
pub fn g_regex_unref(regex: *mut GRegex);
pub fn g_regex_get_pattern(regex: *const GRegex) -> *const gchar;
pub fn g_regex_get_max_backref(regex: *const GRegex) -> gint;
pub fn g_regex_get_capture_count(regex: *const GRegex) -> gint;
pub fn g_regex_get_has_cr_or_lf(regex: *const GRegex) -> gboolean;
pub fn g_regex_get_max_lookbehind(regex: *const GRegex) -> gint;
pub fn g_regex_get_string_number(regex: *const GRegex, name: *const gchar)
-> gint;
pub fn g_regex_escape_string(string: *const gchar, length: gint)
-> *mut gchar;
pub fn g_regex_escape_nul(string: *const gchar, length: gint)
-> *mut gchar;
pub fn g_regex_get_compile_flags(regex: *const GRegex)
-> GRegexCompileFlags;
pub fn g_regex_get_match_flags(regex: *const GRegex) -> GRegexMatchFlags;
pub fn g_regex_match_simple(pattern: *const gchar, string: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags) -> gboolean;
pub fn g_regex_match(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo) -> gboolean;
pub fn g_regex_match_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_regex_match_all(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo) -> gboolean;
pub fn g_regex_match_all_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
match_info: *mut *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_regex_split_simple(pattern: *const gchar, string: *const gchar,
compile_options: GRegexCompileFlags,
match_options: GRegexMatchFlags)
-> *mut *mut gchar;
pub fn g_regex_split(regex: *const GRegex, string: *const gchar,
match_options: GRegexMatchFlags) -> *mut *mut gchar;
pub fn g_regex_split_full(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
max_tokens: gint, error: *mut *mut GError)
-> *mut *mut gchar;
pub fn g_regex_replace(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
replacement: *const gchar,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_replace_literal(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
replacement: *const gchar,
match_options: GRegexMatchFlags,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_replace_eval(regex: *const GRegex, string: *const gchar,
string_len: gssize, start_position: gint,
match_options: GRegexMatchFlags,
eval: GRegexEvalCallback, user_data: gpointer,
error: *mut *mut GError) -> *mut gchar;
pub fn g_regex_check_replacement(replacement: *const gchar,
has_references: *mut gboolean,
error: *mut *mut GError) -> gboolean;
pub fn g_match_info_get_regex(match_info: *const GMatchInfo)
-> *mut GRegex;
pub fn g_match_info_get_string(match_info: *const GMatchInfo)
-> *const gchar;
pub fn g_match_info_ref(match_info: *mut GMatchInfo) -> *mut GMatchInfo;
pub fn g_match_info_unref(match_info: *mut GMatchInfo);
pub fn g_match_info_free(match_info: *mut GMatchInfo);
pub fn g_match_info_next(match_info: *mut GMatchInfo,
error: *mut *mut GError) -> gboolean;
pub fn g_match_info_matches(match_info: *const GMatchInfo) -> gboolean;
pub fn g_match_info_get_match_count(match_info: *const GMatchInfo)
-> gint;
pub fn g_match_info_is_partial_match(match_info: *const GMatchInfo)
-> gboolean;
pub fn g_match_info_expand_references(match_info: *const GMatchInfo,
string_to_expand: *const gchar,
error: *mut *mut GError)
-> *mut gchar;
pub fn g_match_info_fetch(match_info: *const GMatchInfo, match_num: gint)
-> *mut gchar;
pub fn g_match_info_fetch_pos(match_info: *const GMatchInfo,
match_num: gint, start_pos: *mut gint,
end_pos: *mut gint) -> gboolean;
pub fn g_match_info_fetch_named(match_info: *const GMatchInfo,
name: *const gchar) -> *mut gchar;
pub fn g_match_info_fetch_named_pos(match_info: *const GMatchInfo,
name: *const gchar,
start_pos: *mut gint,
end_pos: *mut gint) -> gboolean;
pub fn g_match_info_fetch_all(match_info: *const GMatchInfo)
-> *mut *mut gchar;
pub fn g_scanner_new(config_templ: *const GScannerConfig)
-> *mut GScanner;
pub fn g_scanner_destroy(scanner: *mut GScanner);
pub fn g_scanner_input_file(scanner: *mut GScanner, input_fd: gint);
pub fn g_scanner_sync_file_offset(scanner: *mut GScanner);
pub fn g_scanner_input_text(scanner: *mut GScanner, text: *const gchar,
text_len: guint);
pub fn g_scanner_get_next_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_peek_next_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_cur_token(scanner: *mut GScanner) -> GTokenType;
pub fn g_scanner_cur_value(scanner: *mut GScanner) -> GTokenValue;
pub fn g_scanner_cur_line(scanner: *mut GScanner) -> guint;
pub fn g_scanner_cur_position(scanner: *mut GScanner) -> guint;
pub fn g_scanner_eof(scanner: *mut GScanner) -> gboolean;
pub fn g_scanner_set_scope(scanner: *mut GScanner, scope_id: guint)
-> guint;
pub fn g_scanner_scope_add_symbol(scanner: *mut GScanner, scope_id: guint,
symbol: *const gchar, value: gpointer);
pub fn g_scanner_scope_remove_symbol(scanner: *mut GScanner,
scope_id: guint,
symbol: *const gchar);
pub fn g_scanner_scope_lookup_symbol(scanner: *mut GScanner,
scope_id: guint,
symbol: *const gchar) -> gpointer;
pub fn g_scanner_scope_foreach_symbol(scanner: *mut GScanner,
scope_id: guint, func: GHFunc,
user_data: gpointer);
pub fn g_scanner_lookup_symbol(scanner: *mut GScanner,
symbol: *const gchar) -> gpointer;
pub fn g_scanner_unexp_token(scanner: *mut GScanner,
expected_token: GTokenType,
identifier_spec: *const gchar,
symbol_spec: *const gchar,
symbol_name: *const gchar,
message: *const gchar, is_error: gint);
pub fn g_scanner_error(scanner: *mut GScanner, format: *const gchar, ...);
pub fn g_scanner_warn(scanner: *mut GScanner, format: *const gchar, ...);
pub fn g_sequence_new(data_destroy: GDestroyNotify) -> *mut GSequence;
pub fn g_sequence_free(seq: *mut GSequence);
pub fn g_sequence_get_length(seq: *mut GSequence) -> gint;
pub fn g_sequence_foreach(seq: *mut GSequence, func: GFunc,
user_data: gpointer);
pub fn g_sequence_foreach_range(begin: *mut GSequenceIter,
end: *mut GSequenceIter, func: GFunc,
user_data: gpointer);
pub fn g_sequence_sort(seq: *mut GSequence, cmp_func: GCompareDataFunc,
cmp_data: gpointer);
pub fn g_sequence_sort_iter(seq: *mut GSequence,
cmp_func: GSequenceIterCompareFunc,
cmp_data: gpointer);
pub fn g_sequence_get_begin_iter(seq: *mut GSequence)
-> *mut GSequenceIter;
pub fn g_sequence_get_end_iter(seq: *mut GSequence) -> *mut GSequenceIter;
pub fn g_sequence_get_iter_at_pos(seq: *mut GSequence, pos: gint)
-> *mut GSequenceIter;
pub fn g_sequence_append(seq: *mut GSequence, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_prepend(seq: *mut GSequence, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_insert_before(iter: *mut GSequenceIter, data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_move(src: *mut GSequenceIter, dest: *mut GSequenceIter);
pub fn g_sequence_swap(a: *mut GSequenceIter, b: *mut GSequenceIter);
pub fn g_sequence_insert_sorted(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_insert_sorted_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_sort_changed(iter: *mut GSequenceIter,
cmp_func: GCompareDataFunc,
cmp_data: gpointer);
pub fn g_sequence_sort_changed_iter(iter: *mut GSequenceIter,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer);
pub fn g_sequence_remove(iter: *mut GSequenceIter);
pub fn g_sequence_remove_range(begin: *mut GSequenceIter,
end: *mut GSequenceIter);
pub fn g_sequence_move_range(dest: *mut GSequenceIter,
begin: *mut GSequenceIter,
end: *mut GSequenceIter);
pub fn g_sequence_search(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc, cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_search_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_lookup(seq: *mut GSequence, data: gpointer,
cmp_func: GCompareDataFunc, cmp_data: gpointer)
-> *mut GSequenceIter;
pub fn g_sequence_lookup_iter(seq: *mut GSequence, data: gpointer,
iter_cmp: GSequenceIterCompareFunc,
cmp_data: gpointer) -> *mut GSequenceIter;
pub fn g_sequence_get(iter: *mut GSequenceIter) -> gpointer;
pub fn g_sequence_set(iter: *mut GSequenceIter, data: gpointer);
pub fn g_sequence_iter_is_begin(iter: *mut GSequenceIter) -> gboolean;
pub fn g_sequence_iter_is_end(iter: *mut GSequenceIter) -> gboolean;
pub fn g_sequence_iter_next(iter: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_sequence_iter_prev(iter: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_sequence_iter_get_position(iter: *mut GSequenceIter) -> gint;
pub fn g_sequence_iter_move(iter: *mut GSequenceIter, delta: gint)
-> *mut GSequenceIter;
pub fn g_sequence_iter_get_sequence(iter: *mut GSequenceIter)
-> *mut GSequence;
pub fn g_sequence_iter_compare(a: *mut GSequenceIter,
b: *mut GSequenceIter) -> gint;
pub fn g_sequence_range_get_midpoint(begin: *mut GSequenceIter,
end: *mut GSequenceIter)
-> *mut GSequenceIter;
pub fn g_shell_error_quark() -> GQuark;
pub fn g_shell_quote(unquoted_string: *const gchar) -> *mut gchar;
pub fn g_shell_unquote(quoted_string: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn g_shell_parse_argv(command_line: *const gchar, argcp: *mut gint,
argvp: *mut *mut *mut gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_slice_alloc(block_size: gsize) -> gpointer;
pub fn g_slice_alloc0(block_size: gsize) -> gpointer;
pub fn g_slice_copy(block_size: gsize, mem_block: gconstpointer)
-> gpointer;
pub fn g_slice_free1(block_size: gsize, mem_block: gpointer);
pub fn g_slice_free_chain_with_offset(block_size: gsize,
mem_chain: gpointer,
next_offset: gsize);
pub fn g_slice_set_config(ckey: GSliceConfig, value: gint64);
pub fn g_slice_get_config(ckey: GSliceConfig) -> gint64;
pub fn g_slice_get_config_state(ckey: GSliceConfig, address: gint64,
n_values: *mut guint) -> *mut gint64;
pub fn g_spawn_error_quark() -> GQuark;
pub fn g_spawn_exit_error_quark() -> GQuark;
pub fn g_spawn_async(working_directory: *const gchar,
argv: *mut *mut gchar, envp: *mut *mut gchar,
flags: GSpawnFlags,
child_setup: GSpawnChildSetupFunc,
user_data: gpointer, child_pid: *mut GPid,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_async_with_pipes(working_directory: *const gchar,
argv: *mut *mut gchar,
envp: *mut *mut gchar, flags: GSpawnFlags,
child_setup: GSpawnChildSetupFunc,
user_data: gpointer, child_pid: *mut GPid,
standard_input: *mut gint,
standard_output: *mut gint,
standard_error: *mut gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_sync(working_directory: *const gchar,
argv: *mut *mut gchar, envp: *mut *mut gchar,
flags: GSpawnFlags, child_setup: GSpawnChildSetupFunc,
user_data: gpointer, standard_output: *mut *mut gchar,
standard_error: *mut *mut gchar,
exit_status: *mut gint, error: *mut *mut GError)
-> gboolean;
pub fn g_spawn_command_line_sync(command_line: *const gchar,
standard_output: *mut *mut gchar,
standard_error: *mut *mut gchar,
exit_status: *mut gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_command_line_async(command_line: *const gchar,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_check_exit_status(exit_status: gint,
error: *mut *mut GError) -> gboolean;
pub fn g_spawn_close_pid(pid: GPid);
pub fn g_ascii_tolower(c: gchar) -> gchar;
pub fn g_ascii_toupper(c: gchar) -> gchar;
pub fn g_ascii_digit_value(c: gchar) -> gint;
pub fn g_ascii_xdigit_value(c: gchar) -> gint;
pub fn g_strdelimit(string: *mut gchar, delimiters: *const gchar,
new_delimiter: gchar) -> *mut gchar;
pub fn g_strcanon(string: *mut gchar, valid_chars: *const gchar,
substitutor: gchar) -> *mut gchar;
pub fn g_strerror(errnum: gint) -> *const gchar;
pub fn g_strsignal(signum: gint) -> *const gchar;
pub fn g_strreverse(string: *mut gchar) -> *mut gchar;
pub fn g_strlcpy(dest: *mut gchar, src: *const gchar, dest_size: gsize)
-> gsize;
pub fn g_strlcat(dest: *mut gchar, src: *const gchar, dest_size: gsize)
-> gsize;
pub fn g_strstr_len(haystack: *const gchar, haystack_len: gssize,
needle: *const gchar) -> *mut gchar;
pub fn g_strrstr(haystack: *const gchar, needle: *const gchar)
-> *mut gchar;
pub fn g_strrstr_len(haystack: *const gchar, haystack_len: gssize,
needle: *const gchar) -> *mut gchar;
pub fn g_str_has_suffix(str: *const gchar, suffix: *const gchar)
-> gboolean;
pub fn g_str_has_prefix(str: *const gchar, prefix: *const gchar)
-> gboolean;
pub fn g_strtod(nptr: *const gchar, endptr: *mut *mut gchar) -> gdouble;
pub fn g_ascii_strtod(nptr: *const gchar, endptr: *mut *mut gchar)
-> gdouble;
pub fn g_ascii_strtoull(nptr: *const gchar, endptr: *mut *mut gchar,
base: guint) -> guint64;
pub fn g_ascii_strtoll(nptr: *const gchar, endptr: *mut *mut gchar,
base: guint) -> gint64;
pub fn g_ascii_dtostr(buffer: *mut gchar, buf_len: gint, d: gdouble)
-> *mut gchar;
pub fn g_ascii_formatd(buffer: *mut gchar, buf_len: gint,
format: *const gchar, d: gdouble) -> *mut gchar;
pub fn g_strchug(string: *mut gchar) -> *mut gchar;
pub fn g_strchomp(string: *mut gchar) -> *mut gchar;
pub fn g_ascii_strcasecmp(s1: *const gchar, s2: *const gchar) -> gint;
pub fn g_ascii_strncasecmp(s1: *const gchar, s2: *const gchar, n: gsize)
-> gint;
pub fn g_ascii_strdown(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_ascii_strup(str: *const gchar, len: gssize) -> *mut gchar;
pub fn g_str_is_ascii(str: *const gchar) -> gboolean;
pub fn g_strcasecmp(s1: *const gchar, s2: *const gchar) -> gint;
pub fn g_strncasecmp(s1: *const gchar, s2: *const gchar, n: guint)
-> gint;
pub fn g_strdown(string: *mut gchar) -> *mut gchar;
pub fn g_strup(string: *mut gchar) -> *mut gchar;
pub fn g_strdup(str: *const gchar) -> *mut gchar;
pub fn g_strdup_printf(format: *const gchar, ...) -> *mut gchar;
pub fn g_strdup_vprintf(format: *const gchar, args: va_list)
-> *mut gchar;
pub fn g_strndup(str: *const gchar, n: gsize) -> *mut gchar;
pub fn g_strnfill(length: gsize, fill_char: gchar) -> *mut gchar;
pub fn g_strconcat(string1: *const gchar, ...) -> *mut gchar;
pub fn g_strjoin(separator: *const gchar, ...) -> *mut gchar;
pub fn g_strcompress(source: *const gchar) -> *mut gchar;
pub fn g_strescape(source: *const gchar, exceptions: *const gchar)
-> *mut gchar;
pub fn g_memdup(mem: gconstpointer, byte_size: guint) -> gpointer;
pub fn g_strsplit(string: *const gchar, delimiter: *const gchar,
max_tokens: gint) -> *mut *mut gchar;
pub fn g_strsplit_set(string: *const gchar, delimiters: *const gchar,
max_tokens: gint) -> *mut *mut gchar;
pub fn g_strjoinv(separator: *const gchar, str_array: *mut *mut gchar)
-> *mut gchar;
pub fn g_strfreev(str_array: *mut *mut gchar);
pub fn g_strdupv(str_array: *mut *mut gchar) -> *mut *mut gchar;
pub fn g_strv_length(str_array: *mut *mut gchar) -> guint;
pub fn g_stpcpy(dest: *mut gchar, src: *const ::libc::c_char)
-> *mut gchar;
pub fn g_str_to_ascii(str: *const gchar, from_locale: *const gchar)
-> *mut gchar;
pub fn g_str_tokenize_and_fold(string: *const gchar,
translit_locale: *const gchar,
ascii_alternates: *mut *mut *mut gchar)
-> *mut *mut gchar;
pub fn g_str_match_string(search_term: *const gchar,
potential_hit: *const gchar,
accept_alternates: gboolean) -> gboolean;
pub fn g_string_chunk_new(size: gsize) -> *mut GStringChunk;
pub fn g_string_chunk_free(chunk: *mut GStringChunk);
pub fn g_string_chunk_clear(chunk: *mut GStringChunk);
pub fn g_string_chunk_insert(chunk: *mut GStringChunk,
string: *const gchar) -> *mut gchar;
pub fn g_string_chunk_insert_len(chunk: *mut GStringChunk,
string: *const gchar, len: gssize)
-> *mut gchar;
pub fn g_string_chunk_insert_const(chunk: *mut GStringChunk,
string: *const gchar) -> *mut gchar;
pub fn g_strcmp0(str1: *const ::libc::c_char, str2: *const ::libc::c_char)
-> ::libc::c_int;
pub fn g_test_minimized_result(minimized_quantity: ::libc::c_double,
format: *const ::libc::c_char, ...);
pub fn g_test_maximized_result(maximized_quantity: ::libc::c_double,
format: *const ::libc::c_char, ...);
pub fn g_test_init(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char, ...);
pub fn g_test_subprocess() -> gboolean;
pub fn g_test_run() -> ::libc::c_int;
pub fn g_test_add_func(testpath: *const ::libc::c_char,
test_func: GTestFunc);
pub fn g_test_add_data_func(testpath: *const ::libc::c_char,
test_data: gconstpointer,
test_func: GTestDataFunc);
pub fn g_test_add_data_func_full(testpath: *const ::libc::c_char,
test_data: gpointer,
test_func: GTestDataFunc,
data_free_func: GDestroyNotify);
pub fn g_test_fail();
pub fn g_test_incomplete(msg: *const gchar);
pub fn g_test_skip(msg: *const gchar);
pub fn g_test_failed() -> gboolean;
pub fn g_test_set_nonfatal_assertions();
pub fn g_test_message(format: *const ::libc::c_char, ...);
pub fn g_test_bug_base(uri_pattern: *const ::libc::c_char);
pub fn g_test_bug(bug_uri_snippet: *const ::libc::c_char);
pub fn g_test_timer_start();
pub fn g_test_timer_elapsed() -> ::libc::c_double;
pub fn g_test_timer_last() -> ::libc::c_double;
pub fn g_test_queue_free(gfree_pointer: gpointer);
pub fn g_test_queue_destroy(destroy_func: GDestroyNotify,
destroy_data: gpointer);
pub fn g_test_trap_fork(usec_timeout: guint64,
test_trap_flags: GTestTrapFlags) -> gboolean;
pub fn g_test_trap_subprocess(test_path: *const ::libc::c_char,
usec_timeout: guint64,
test_flags: GTestSubprocessFlags);
pub fn g_test_trap_has_passed() -> gboolean;
pub fn g_test_trap_reached_timeout() -> gboolean;
pub fn g_test_rand_int() -> gint32;
pub fn g_test_rand_int_range(begin: gint32, end: gint32) -> gint32;
pub fn g_test_rand_double() -> ::libc::c_double;
pub fn g_test_rand_double_range(range_start: ::libc::c_double,
range_end: ::libc::c_double)
-> ::libc::c_double;
pub fn g_test_create_case(test_name: *const ::libc::c_char,
data_size: gsize, test_data: gconstpointer,
data_setup: GTestFixtureFunc,
data_test: GTestFixtureFunc,
data_teardown: GTestFixtureFunc)
-> *mut GTestCase;
pub fn g_test_create_suite(suite_name: *const ::libc::c_char)
-> *mut GTestSuite;
pub fn g_test_get_root() -> *mut GTestSuite;
pub fn g_test_suite_add(suite: *mut GTestSuite,
test_case: *mut GTestCase);
pub fn g_test_suite_add_suite(suite: *mut GTestSuite,
nestedsuite: *mut GTestSuite);
pub fn g_test_run_suite(suite: *mut GTestSuite) -> ::libc::c_int;
pub fn g_test_trap_assertions(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
assertion_flags: guint64,
pattern: *const ::libc::c_char);
pub fn g_assertion_message(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
message: *const ::libc::c_char);
pub fn g_assertion_message_expr(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char);
pub fn g_assertion_message_cmpstr(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
arg1: *const ::libc::c_char,
cmp: *const ::libc::c_char,
arg2: *const ::libc::c_char);
pub fn g_assertion_message_cmpnum(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
arg1: ::libc::c_double,
cmp: *const ::libc::c_char,
arg2: ::libc::c_double,
numtype: ::libc::c_char);
pub fn g_assertion_message_error(domain: *const ::libc::c_char,
file: *const ::libc::c_char,
line: ::libc::c_int,
func: *const ::libc::c_char,
expr: *const ::libc::c_char,
error: *const GError,
error_domain: GQuark,
error_code: ::libc::c_int);
pub fn g_test_add_vtable(testpath: *const ::libc::c_char,
data_size: gsize, test_data: gconstpointer,
data_setup: GTestFixtureFunc,
data_test: GTestFixtureFunc,
data_teardown: GTestFixtureFunc);
pub fn g_test_log_type_name(log_type: GTestLogType)
-> *const ::libc::c_char;
pub fn g_test_log_buffer_new() -> *mut GTestLogBuffer;
pub fn g_test_log_buffer_free(tbuffer: *mut GTestLogBuffer);
pub fn g_test_log_buffer_push(tbuffer: *mut GTestLogBuffer,
n_bytes: guint, bytes: *const guint8);
pub fn g_test_log_buffer_pop(tbuffer: *mut GTestLogBuffer)
-> *mut GTestLogMsg;
pub fn g_test_log_msg_free(tmsg: *mut GTestLogMsg);
pub fn g_test_log_set_fatal_handler(log_func: GTestLogFatalFunc,
user_data: gpointer);
pub fn g_test_expect_message(log_domain: *const gchar,
log_level: GLogLevelFlags,
pattern: *const gchar);
pub fn g_test_assert_expected_messages_internal(domain:
*const ::libc::c_char,
file:
*const ::libc::c_char,
line: ::libc::c_int,
func:
*const ::libc::c_char);
pub fn g_test_build_filename(file_type: GTestFileType,
first_path: *const gchar, ...) -> *mut gchar;
pub fn g_test_get_dir(file_type: GTestFileType) -> *const gchar;
pub fn g_test_get_filename(file_type: GTestFileType,
first_path: *const gchar, ...) -> *const gchar;
pub fn g_thread_pool_new(func: GFunc, user_data: gpointer,
max_threads: gint, exclusive: gboolean,
error: *mut *mut GError) -> *mut GThreadPool;
pub fn g_thread_pool_free(pool: *mut GThreadPool, immediate: gboolean,
wait_: gboolean);
pub fn g_thread_pool_push(pool: *mut GThreadPool, data: gpointer,
error: *mut *mut GError) -> gboolean;
pub fn g_thread_pool_unprocessed(pool: *mut GThreadPool) -> guint;
pub fn g_thread_pool_set_sort_function(pool: *mut GThreadPool,
func: GCompareDataFunc,
user_data: gpointer);
pub fn g_thread_pool_set_max_threads(pool: *mut GThreadPool,
max_threads: gint,
error: *mut *mut GError) -> gboolean;
pub fn g_thread_pool_get_max_threads(pool: *mut GThreadPool) -> gint;
pub fn g_thread_pool_get_num_threads(pool: *mut GThreadPool) -> guint;
pub fn g_thread_pool_set_max_unused_threads(max_threads: gint);
pub fn g_thread_pool_get_max_unused_threads() -> gint;
pub fn g_thread_pool_get_num_unused_threads() -> guint;
pub fn g_thread_pool_stop_unused_threads();
pub fn g_thread_pool_set_max_idle_time(interval: guint);
pub fn g_thread_pool_get_max_idle_time() -> guint;
pub fn g_timer_new() -> *mut GTimer;
pub fn g_timer_destroy(timer: *mut GTimer);
pub fn g_timer_start(timer: *mut GTimer);
pub fn g_timer_stop(timer: *mut GTimer);
pub fn g_timer_reset(timer: *mut GTimer);
pub fn g_timer_continue(timer: *mut GTimer);
pub fn g_timer_elapsed(timer: *mut GTimer, microseconds: *mut gulong)
-> gdouble;
pub fn g_usleep(microseconds: gulong);
pub fn g_time_val_add(time_: *mut GTimeVal, microseconds: glong);
pub fn g_time_val_from_iso8601(iso_date: *const gchar,
time_: *mut GTimeVal) -> gboolean;
pub fn g_time_val_to_iso8601(time_: *mut GTimeVal) -> *mut gchar;
pub fn g_tree_new(key_compare_func: GCompareFunc) -> *mut GTree;
pub fn g_tree_new_with_data(key_compare_func: GCompareDataFunc,
key_compare_data: gpointer) -> *mut GTree;
pub fn g_tree_new_full(key_compare_func: GCompareDataFunc,
key_compare_data: gpointer,
key_destroy_func: GDestroyNotify,
value_destroy_func: GDestroyNotify) -> *mut GTree;
pub fn g_tree_ref(tree: *mut GTree) -> *mut GTree;
pub fn g_tree_unref(tree: *mut GTree);
pub fn g_tree_destroy(tree: *mut GTree);
pub fn g_tree_insert(tree: *mut GTree, key: gpointer, value: gpointer);
pub fn g_tree_replace(tree: *mut GTree, key: gpointer, value: gpointer);
pub fn g_tree_remove(tree: *mut GTree, key: gconstpointer) -> gboolean;
pub fn g_tree_steal(tree: *mut GTree, key: gconstpointer) -> gboolean;
pub fn g_tree_lookup(tree: *mut GTree, key: gconstpointer) -> gpointer;
pub fn g_tree_lookup_extended(tree: *mut GTree, lookup_key: gconstpointer,
orig_key: *mut gpointer,
value: *mut gpointer) -> gboolean;
pub fn g_tree_foreach(tree: *mut GTree, func: GTraverseFunc,
user_data: gpointer);
pub fn g_tree_traverse(tree: *mut GTree, traverse_func: GTraverseFunc,
traverse_type: GTraverseType, user_data: gpointer);
pub fn g_tree_search(tree: *mut GTree, search_func: GCompareFunc,
user_data: gconstpointer) -> gpointer;
pub fn g_tree_height(tree: *mut GTree) -> gint;
pub fn g_tree_nnodes(tree: *mut GTree) -> gint;
pub fn g_uri_unescape_string(escaped_string: *const ::libc::c_char,
illegal_characters: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_unescape_segment(escaped_string: *const ::libc::c_char,
escaped_string_end: *const ::libc::c_char,
illegal_characters: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_parse_scheme(uri: *const ::libc::c_char)
-> *mut ::libc::c_char;
pub fn g_uri_escape_string(unescaped: *const ::libc::c_char,
reserved_chars_allowed: *const ::libc::c_char,
allow_utf8: gboolean) -> *mut ::libc::c_char;
pub fn g_variant_type_string_is_valid(type_string: *const gchar)
-> gboolean;
pub fn g_variant_type_string_scan(string: *const gchar,
limit: *const gchar,
endptr: *mut *const gchar) -> gboolean;
pub fn g_variant_type_free(_type: *mut GVariantType);
pub fn g_variant_type_copy(_type: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new(type_string: *const gchar) -> *mut GVariantType;
pub fn g_variant_type_get_string_length(_type: *const GVariantType)
-> gsize;
pub fn g_variant_type_peek_string(_type: *const GVariantType)
-> *const gchar;
pub fn g_variant_type_dup_string(_type: *const GVariantType)
-> *mut gchar;
pub fn g_variant_type_is_definite(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_container(_type: *const GVariantType)
-> gboolean;
pub fn g_variant_type_is_basic(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_maybe(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_array(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_tuple(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_is_dict_entry(_type: *const GVariantType)
-> gboolean;
pub fn g_variant_type_is_variant(_type: *const GVariantType) -> gboolean;
pub fn g_variant_type_hash(_type: gconstpointer) -> guint;
pub fn g_variant_type_equal(type1: gconstpointer, type2: gconstpointer)
-> gboolean;
pub fn g_variant_type_is_subtype_of(_type: *const GVariantType,
supertype: *const GVariantType)
-> gboolean;
pub fn g_variant_type_element(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_first(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_next(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_n_items(_type: *const GVariantType) -> gsize;
pub fn g_variant_type_key(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_value(_type: *const GVariantType)
-> *const GVariantType;
pub fn g_variant_type_new_array(element: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new_maybe(element: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_new_tuple(items: *const *const GVariantType,
length: gint) -> *mut GVariantType;
pub fn g_variant_type_new_dict_entry(key: *const GVariantType,
value: *const GVariantType)
-> *mut GVariantType;
pub fn g_variant_type_checked_(arg1: *const gchar) -> *const GVariantType;
pub fn g_variant_unref(value: *mut GVariant);
pub fn g_variant_ref(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_ref_sink(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_is_floating(value: *mut GVariant) -> gboolean;
pub fn g_variant_take_ref(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_get_type(value: *mut GVariant) -> *const GVariantType;
pub fn g_variant_get_type_string(value: *mut GVariant) -> *const gchar;
pub fn g_variant_is_of_type(value: *mut GVariant,
_type: *const GVariantType) -> gboolean;
pub fn g_variant_is_container(value: *mut GVariant) -> gboolean;
pub fn g_variant_classify(value: *mut GVariant) -> GVariantClass;
pub fn g_variant_new_boolean(value: gboolean) -> *mut GVariant;
pub fn g_variant_new_byte(value: guchar) -> *mut GVariant;
pub fn g_variant_new_int16(value: gint16) -> *mut GVariant;
pub fn g_variant_new_uint16(value: guint16) -> *mut GVariant;
pub fn g_variant_new_int32(value: gint32) -> *mut GVariant;
pub fn g_variant_new_uint32(value: guint32) -> *mut GVariant;
pub fn g_variant_new_int64(value: gint64) -> *mut GVariant;
pub fn g_variant_new_uint64(value: guint64) -> *mut GVariant;
pub fn g_variant_new_handle(value: gint32) -> *mut GVariant;
pub fn g_variant_new_double(value: gdouble) -> *mut GVariant;
pub fn g_variant_new_string(string: *const gchar) -> *mut GVariant;
pub fn g_variant_new_take_string(string: *mut gchar) -> *mut GVariant;
pub fn g_variant_new_printf(format_string: *const gchar, ...)
-> *mut GVariant;
pub fn g_variant_new_object_path(object_path: *const gchar)
-> *mut GVariant;
pub fn g_variant_is_object_path(string: *const gchar) -> gboolean;
pub fn g_variant_new_signature(signature: *const gchar) -> *mut GVariant;
pub fn g_variant_is_signature(string: *const gchar) -> gboolean;
pub fn g_variant_new_variant(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_strv(strv: *const *const gchar, length: gssize)
-> *mut GVariant;
pub fn g_variant_new_objv(strv: *const *const gchar, length: gssize)
-> *mut GVariant;
pub fn g_variant_new_bytestring(string: *const gchar) -> *mut GVariant;
pub fn g_variant_new_bytestring_array(strv: *const *const gchar,
length: gssize) -> *mut GVariant;
pub fn g_variant_new_fixed_array(element_type: *const GVariantType,
elements: gconstpointer,
n_elements: gsize, element_size: gsize)
-> *mut GVariant;
pub fn g_variant_get_boolean(value: *mut GVariant) -> gboolean;
pub fn g_variant_get_byte(value: *mut GVariant) -> guchar;
pub fn g_variant_get_int16(value: *mut GVariant) -> gint16;
pub fn g_variant_get_uint16(value: *mut GVariant) -> guint16;
pub fn g_variant_get_int32(value: *mut GVariant) -> gint32;
pub fn g_variant_get_uint32(value: *mut GVariant) -> guint32;
pub fn g_variant_get_int64(value: *mut GVariant) -> gint64;
pub fn g_variant_get_uint64(value: *mut GVariant) -> guint64;
pub fn g_variant_get_handle(value: *mut GVariant) -> gint32;
pub fn g_variant_get_double(value: *mut GVariant) -> gdouble;
pub fn g_variant_get_variant(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_get_string(value: *mut GVariant, length: *mut gsize)
-> *const gchar;
pub fn g_variant_dup_string(value: *mut GVariant, length: *mut gsize)
-> *mut gchar;
pub fn g_variant_get_strv(value: *mut GVariant, length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_strv(value: *mut GVariant, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_get_objv(value: *mut GVariant, length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_objv(value: *mut GVariant, length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_get_bytestring(value: *mut GVariant) -> *const gchar;
pub fn g_variant_dup_bytestring(value: *mut GVariant, length: *mut gsize)
-> *mut gchar;
pub fn g_variant_get_bytestring_array(value: *mut GVariant,
length: *mut gsize)
-> *mut *const gchar;
pub fn g_variant_dup_bytestring_array(value: *mut GVariant,
length: *mut gsize)
-> *mut *mut gchar;
pub fn g_variant_new_maybe(child_type: *const GVariantType,
child: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_array(child_type: *const GVariantType,
children: *const *mut GVariant,
n_children: gsize) -> *mut GVariant;
pub fn g_variant_new_tuple(children: *const *mut GVariant,
n_children: gsize) -> *mut GVariant;
pub fn g_variant_new_dict_entry(key: *mut GVariant, value: *mut GVariant)
-> *mut GVariant;
pub fn g_variant_get_maybe(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_n_children(value: *mut GVariant) -> gsize;
pub fn g_variant_get_child(value: *mut GVariant, index_: gsize,
format_string: *const gchar, ...);
pub fn g_variant_get_child_value(value: *mut GVariant, index_: gsize)
-> *mut GVariant;
pub fn g_variant_lookup(dictionary: *mut GVariant, key: *const gchar,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_lookup_value(dictionary: *mut GVariant,
key: *const gchar,
expected_type: *const GVariantType)
-> *mut GVariant;
pub fn g_variant_get_fixed_array(value: *mut GVariant,
n_elements: *mut gsize,
element_size: gsize) -> gconstpointer;
pub fn g_variant_get_size(value: *mut GVariant) -> gsize;
pub fn g_variant_get_data(value: *mut GVariant) -> gconstpointer;
pub fn g_variant_get_data_as_bytes(value: *mut GVariant) -> *mut GBytes;
pub fn g_variant_store(value: *mut GVariant, data: gpointer);
pub fn g_variant_print(value: *mut GVariant, type_annotate: gboolean)
-> *mut gchar;
pub fn g_variant_print_string(value: *mut GVariant, string: *mut GString,
type_annotate: gboolean) -> *mut GString;
pub fn g_variant_hash(value: gconstpointer) -> guint;
pub fn g_variant_equal(one: gconstpointer, two: gconstpointer)
-> gboolean;
pub fn g_variant_get_normal_form(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_is_normal_form(value: *mut GVariant) -> gboolean;
pub fn g_variant_byteswap(value: *mut GVariant) -> *mut GVariant;
pub fn g_variant_new_from_bytes(_type: *const GVariantType,
bytes: *mut GBytes, trusted: gboolean)
-> *mut GVariant;
pub fn g_variant_new_from_data(_type: *const GVariantType,
data: gconstpointer, size: gsize,
trusted: gboolean, notify: GDestroyNotify,
user_data: gpointer) -> *mut GVariant;
pub fn g_variant_iter_new(value: *mut GVariant) -> *mut GVariantIter;
pub fn g_variant_iter_init(iter: *mut GVariantIter, value: *mut GVariant)
-> gsize;
pub fn g_variant_iter_copy(iter: *mut GVariantIter) -> *mut GVariantIter;
pub fn g_variant_iter_n_children(iter: *mut GVariantIter) -> gsize;
pub fn g_variant_iter_free(iter: *mut GVariantIter);
pub fn g_variant_iter_next_value(iter: *mut GVariantIter)
-> *mut GVariant;
pub fn g_variant_iter_next(iter: *mut GVariantIter,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_iter_loop(iter: *mut GVariantIter,
format_string: *const gchar, ...) -> gboolean;
pub fn g_variant_parser_get_error_quark() -> GQuark;
pub fn g_variant_parse_error_quark() -> GQuark;
pub fn g_variant_builder_new(_type: *const GVariantType)
-> *mut GVariantBuilder;
pub fn g_variant_builder_unref(builder: *mut GVariantBuilder);
pub fn g_variant_builder_ref(builder: *mut GVariantBuilder)
-> *mut GVariantBuilder;
pub fn g_variant_builder_init(builder: *mut GVariantBuilder,
_type: *const GVariantType);
pub fn g_variant_builder_end(builder: *mut GVariantBuilder)
-> *mut GVariant;
pub fn g_variant_builder_clear(builder: *mut GVariantBuilder);
pub fn g_variant_builder_open(builder: *mut GVariantBuilder,
_type: *const GVariantType);
pub fn g_variant_builder_close(builder: *mut GVariantBuilder);
pub fn g_variant_builder_add_value(builder: *mut GVariantBuilder,
value: *mut GVariant);
pub fn g_variant_builder_add(builder: *mut GVariantBuilder,
format_string: *const gchar, ...);
pub fn g_variant_builder_add_parsed(builder: *mut GVariantBuilder,
format: *const gchar, ...);
pub fn g_variant_new(format_string: *const gchar, ...) -> *mut GVariant;
pub fn g_variant_get(value: *mut GVariant,
format_string: *const gchar, ...);
pub fn g_variant_new_va(format_string: *const gchar,
endptr: *mut *const gchar, app: *mut va_list)
-> *mut GVariant;
pub fn g_variant_get_va(value: *mut GVariant, format_string: *const gchar,
endptr: *mut *const gchar, app: *mut va_list);
pub fn g_variant_check_format_string(value: *mut GVariant,
format_string: *const gchar,
copy_only: gboolean) -> gboolean;
pub fn g_variant_parse(_type: *const GVariantType, text: *const gchar,
limit: *const gchar, endptr: *mut *const gchar,
error: *mut *mut GError) -> *mut GVariant;
pub fn g_variant_new_parsed(format: *const gchar, ...) -> *mut GVariant;
pub fn g_variant_new_parsed_va(format: *const gchar, app: *mut va_list)
-> *mut GVariant;
pub fn g_variant_parse_error_print_context(error: *mut GError,
source_str: *const gchar)
-> *mut gchar;
pub fn g_variant_compare(one: gconstpointer, two: gconstpointer) -> gint;
pub fn g_variant_dict_new(from_asv: *mut GVariant) -> *mut GVariantDict;
pub fn g_variant_dict_init(dict: *mut GVariantDict,
from_asv: *mut GVariant);
pub fn g_variant_dict_lookup(dict: *mut GVariantDict, key: *const gchar,
format_string: *const gchar, ...)
-> gboolean;
pub fn g_variant_dict_lookup_value(dict: *mut GVariantDict,
key: *const gchar,
expected_type: *const GVariantType)
-> *mut GVariant;
pub fn g_variant_dict_contains(dict: *mut GVariantDict, key: *const gchar)
-> gboolean;
pub fn g_variant_dict_insert(dict: *mut GVariantDict, key: *const gchar,
format_string: *const gchar, ...);
pub fn g_variant_dict_insert_value(dict: *mut GVariantDict,
key: *const gchar,
value: *mut GVariant);
pub fn g_variant_dict_remove(dict: *mut GVariantDict, key: *const gchar)
-> gboolean;
pub fn g_variant_dict_clear(dict: *mut GVariantDict);
pub fn g_variant_dict_end(dict: *mut GVariantDict) -> *mut GVariant;
pub fn g_variant_dict_ref(dict: *mut GVariantDict) -> *mut GVariantDict;
pub fn g_variant_dict_unref(dict: *mut GVariantDict);
pub fn glib_check_version(required_major: guint, required_minor: guint,
required_micro: guint) -> *const gchar;
pub fn g_mem_chunk_new(name: *const gchar, atom_size: gint,
area_size: gsize, _type: gint) -> *mut GMemChunk;
pub fn g_mem_chunk_destroy(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_alloc(mem_chunk: *mut GMemChunk) -> gpointer;
pub fn g_mem_chunk_alloc0(mem_chunk: *mut GMemChunk) -> gpointer;
pub fn g_mem_chunk_free(mem_chunk: *mut GMemChunk, mem: gpointer);
pub fn g_mem_chunk_clean(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_reset(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_print(mem_chunk: *mut GMemChunk);
pub fn g_mem_chunk_info();
pub fn g_blow_chunks();
pub fn g_allocator_new(name: *const gchar, n_preallocs: guint)
-> *mut GAllocator;
pub fn g_allocator_free(allocator: *mut GAllocator);
pub fn g_list_push_allocator(allocator: *mut GAllocator);
pub fn g_list_pop_allocator();
pub fn g_slist_push_allocator(allocator: *mut GAllocator);
pub fn g_slist_pop_allocator();
pub fn g_node_push_allocator(allocator: *mut GAllocator);
pub fn g_node_pop_allocator();
pub fn g_cache_new(value_new_func: GCacheNewFunc,
value_destroy_func: GCacheDestroyFunc,
key_dup_func: GCacheDupFunc,
key_destroy_func: GCacheDestroyFunc,
hash_key_func: GHashFunc, hash_value_func: GHashFunc,
key_equal_func: GEqualFunc) -> *mut GCache;
pub fn g_cache_destroy(cache: *mut GCache);
pub fn g_cache_insert(cache: *mut GCache, key: gpointer) -> gpointer;
pub fn g_cache_remove(cache: *mut GCache, value: gconstpointer);
pub fn g_cache_key_foreach(cache: *mut GCache, func: GHFunc,
user_data: gpointer);
pub fn g_cache_value_foreach(cache: *mut GCache, func: GHFunc,
user_data: gpointer);
pub fn g_completion_new(func: GCompletionFunc) -> *mut GCompletion;
pub fn g_completion_add_items(cmp: *mut GCompletion, items: *mut GList);
pub fn g_completion_remove_items(cmp: *mut GCompletion,
items: *mut GList);
pub fn g_completion_clear_items(cmp: *mut GCompletion);
pub fn g_completion_complete(cmp: *mut GCompletion, prefix: *const gchar,
new_prefix: *mut *mut gchar) -> *mut GList;
pub fn g_completion_complete_utf8(cmp: *mut GCompletion,
prefix: *const gchar,
new_prefix: *mut *mut gchar)
-> *mut GList;
pub fn g_completion_set_compare(cmp: *mut GCompletion,
strncmp_func: GCompletionStrncmpFunc);
pub fn g_completion_free(cmp: *mut GCompletion);
pub fn g_relation_new(fields: gint) -> *mut GRelation;
pub fn g_relation_destroy(relation: *mut GRelation);
pub fn g_relation_index(relation: *mut GRelation, field: gint,
hash_func: GHashFunc, key_equal_func: GEqualFunc);
pub fn g_relation_insert(relation: *mut GRelation, ...);
pub fn g_relation_delete(relation: *mut GRelation, key: gconstpointer,
field: gint) -> gint;
pub fn g_relation_select(relation: *mut GRelation, key: gconstpointer,
field: gint) -> *mut GTuples;
pub fn g_relation_count(relation: *mut GRelation, key: gconstpointer,
field: gint) -> gint;
pub fn g_relation_exists(relation: *mut GRelation, ...) -> gboolean;
pub fn g_relation_print(relation: *mut GRelation);
pub fn g_tuples_destroy(tuples: *mut GTuples);
pub fn g_tuples_index(tuples: *mut GTuples, index_: gint, field: gint)
-> gpointer;
pub fn g_thread_create(func: GThreadFunc, data: gpointer,
joinable: gboolean, error: *mut *mut GError)
-> *mut GThread;
pub fn g_thread_create_full(func: GThreadFunc, data: gpointer,
stack_size: gulong, joinable: gboolean,
bound: gboolean, priority: GThreadPriority,
error: *mut *mut GError) -> *mut GThread;
pub fn g_thread_set_priority(thread: *mut GThread,
priority: GThreadPriority);
pub fn g_thread_foreach(thread_func: GFunc, user_data: gpointer);
pub fn select(__nfds: ::libc::c_int, __readfds: *mut fd_set,
__writefds: *mut fd_set, __exceptfds: *mut fd_set,
__timeout: *mut Struct_timeval) -> ::libc::c_int;
pub fn pselect(__nfds: ::libc::c_int, __readfds: *mut fd_set,
__writefds: *mut fd_set, __exceptfds: *mut fd_set,
__timeout: *const Struct_timespec,
__sigmask: *const __sigset_t) -> ::libc::c_int;
pub fn gnu_dev_major(__dev: ::libc::c_ulonglong) -> ::libc::c_uint;
pub fn gnu_dev_minor(__dev: ::libc::c_ulonglong) -> ::libc::c_uint;
pub fn gnu_dev_makedev(__major: ::libc::c_uint, __minor: ::libc::c_uint)
-> ::libc::c_ulonglong;
pub fn __sched_cpucount(__setsize: size_t, __setp: *const cpu_set_t)
-> ::libc::c_int;
pub fn __sched_cpualloc(__count: size_t) -> *mut cpu_set_t;
pub fn __sched_cpufree(__set: *mut cpu_set_t);
pub fn sched_setparam(__pid: __pid_t, __param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn sched_getparam(__pid: __pid_t, __param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn sched_setscheduler(__pid: __pid_t, __policy: ::libc::c_int,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn sched_getscheduler(__pid: __pid_t) -> ::libc::c_int;
pub fn sched_yield() -> ::libc::c_int;
pub fn sched_get_priority_max(__algorithm: ::libc::c_int)
-> ::libc::c_int;
pub fn sched_get_priority_min(__algorithm: ::libc::c_int)
-> ::libc::c_int;
pub fn sched_rr_get_interval(__pid: __pid_t, __t: *mut Struct_timespec)
-> ::libc::c_int;
pub fn pthread_create(__newthread: *mut pthread_t,
__attr: *const pthread_attr_t,
__start_routine:
::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)
->
*mut ::libc::c_void>,
__arg: *mut ::libc::c_void) -> ::libc::c_int;
pub fn pthread_exit(__retval: *mut ::libc::c_void);
pub fn pthread_join(__th: pthread_t,
__thread_return: *mut *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_detach(__th: pthread_t) -> ::libc::c_int;
pub fn pthread_self() -> pthread_t;
pub fn pthread_equal(__thread1: pthread_t, __thread2: pthread_t)
-> ::libc::c_int;
pub fn pthread_attr_init(__attr: *mut pthread_attr_t) -> ::libc::c_int;
pub fn pthread_attr_destroy(__attr: *mut pthread_attr_t) -> ::libc::c_int;
pub fn pthread_attr_getdetachstate(__attr: *const pthread_attr_t,
__detachstate: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setdetachstate(__attr: *mut pthread_attr_t,
__detachstate: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getguardsize(__attr: *const pthread_attr_t,
__guardsize: *mut size_t)
-> ::libc::c_int;
pub fn pthread_attr_setguardsize(__attr: *mut pthread_attr_t,
__guardsize: size_t) -> ::libc::c_int;
pub fn pthread_attr_getschedparam(__attr: *const pthread_attr_t,
__param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_attr_setschedparam(__attr: *mut pthread_attr_t,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_attr_getschedpolicy(__attr: *const pthread_attr_t,
__policy: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setschedpolicy(__attr: *mut pthread_attr_t,
__policy: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getinheritsched(__attr: *const pthread_attr_t,
__inherit: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setinheritsched(__attr: *mut pthread_attr_t,
__inherit: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_getscope(__attr: *const pthread_attr_t,
__scope: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_attr_setscope(__attr: *mut pthread_attr_t,
__scope: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_attr_getstackaddr(__attr: *const pthread_attr_t,
__stackaddr: *mut *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_attr_setstackaddr(__attr: *mut pthread_attr_t,
__stackaddr: *mut ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_attr_getstacksize(__attr: *const pthread_attr_t,
__stacksize: *mut size_t)
-> ::libc::c_int;
pub fn pthread_attr_setstacksize(__attr: *mut pthread_attr_t,
__stacksize: size_t) -> ::libc::c_int;
pub fn pthread_attr_getstack(__attr: *const pthread_attr_t,
__stackaddr: *mut *mut ::libc::c_void,
__stacksize: *mut size_t) -> ::libc::c_int;
pub fn pthread_attr_setstack(__attr: *mut pthread_attr_t,
__stackaddr: *mut ::libc::c_void,
__stacksize: size_t) -> ::libc::c_int;
pub fn pthread_setschedparam(__target_thread: pthread_t,
__policy: ::libc::c_int,
__param: *const Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_getschedparam(__target_thread: pthread_t,
__policy: *mut ::libc::c_int,
__param: *mut Struct_sched_param)
-> ::libc::c_int;
pub fn pthread_setschedprio(__target_thread: pthread_t,
__prio: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_once(__once_control: *mut pthread_once_t,
__init_routine:
::std::option::Option<extern "C" fn()>)
-> ::libc::c_int;
pub fn pthread_setcancelstate(__state: ::libc::c_int,
__oldstate: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_setcanceltype(__type: ::libc::c_int,
__oldtype: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_cancel(__th: pthread_t) -> ::libc::c_int;
pub fn pthread_testcancel();
pub fn __pthread_register_cancel(__buf: *mut __pthread_unwind_buf_t);
pub fn __pthread_unregister_cancel(__buf: *mut __pthread_unwind_buf_t);
pub fn __pthread_unwind_next(__buf: *mut __pthread_unwind_buf_t);
pub fn __sigsetjmp(__env: *mut Struct___jmp_buf_tag,
__savemask: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_mutex_init(__mutex: *mut pthread_mutex_t,
__mutexattr: *const pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutex_destroy(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_trylock(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_lock(__mutex: *mut pthread_mutex_t) -> ::libc::c_int;
pub fn pthread_mutex_timedlock(__mutex: *mut pthread_mutex_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_mutex_unlock(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutex_getprioceiling(__mutex: *const pthread_mutex_t,
__prioceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutex_setprioceiling(__mutex: *mut pthread_mutex_t,
__prioceiling: ::libc::c_int,
__old_ceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutex_consistent(__mutex: *mut pthread_mutex_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_init(__attr: *mut pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_destroy(__attr: *mut pthread_mutexattr_t)
-> ::libc::c_int;
pub fn pthread_mutexattr_getpshared(__attr: *const pthread_mutexattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setpshared(__attr: *mut pthread_mutexattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_gettype(__attr: *const pthread_mutexattr_t,
__kind: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_settype(__attr: *mut pthread_mutexattr_t,
__kind: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_mutexattr_getprotocol(__attr: *const pthread_mutexattr_t,
__protocol: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setprotocol(__attr: *mut pthread_mutexattr_t,
__protocol: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_getprioceiling(__attr:
*const pthread_mutexattr_t,
__prioceiling: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setprioceiling(__attr: *mut pthread_mutexattr_t,
__prioceiling: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_getrobust(__attr: *const pthread_mutexattr_t,
__robustness: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_mutexattr_setrobust(__attr: *mut pthread_mutexattr_t,
__robustness: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlock_init(__rwlock: *mut pthread_rwlock_t,
__attr: *const pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlock_destroy(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_rdlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_tryrdlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_timedrdlock(__rwlock: *mut pthread_rwlock_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_rwlock_wrlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_trywrlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlock_timedwrlock(__rwlock: *mut pthread_rwlock_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_rwlock_unlock(__rwlock: *mut pthread_rwlock_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_init(__attr: *mut pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_destroy(__attr: *mut pthread_rwlockattr_t)
-> ::libc::c_int;
pub fn pthread_rwlockattr_getpshared(__attr: *const pthread_rwlockattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_setpshared(__attr: *mut pthread_rwlockattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_getkind_np(__attr: *const pthread_rwlockattr_t,
__pref: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_rwlockattr_setkind_np(__attr: *mut pthread_rwlockattr_t,
__pref: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_cond_init(__cond: *mut pthread_cond_t,
__cond_attr: *const pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_cond_destroy(__cond: *mut pthread_cond_t) -> ::libc::c_int;
pub fn pthread_cond_signal(__cond: *mut pthread_cond_t) -> ::libc::c_int;
pub fn pthread_cond_broadcast(__cond: *mut pthread_cond_t)
-> ::libc::c_int;
pub fn pthread_cond_wait(__cond: *mut pthread_cond_t,
__mutex: *mut pthread_mutex_t) -> ::libc::c_int;
pub fn pthread_cond_timedwait(__cond: *mut pthread_cond_t,
__mutex: *mut pthread_mutex_t,
__abstime: *const Struct_timespec)
-> ::libc::c_int;
pub fn pthread_condattr_init(__attr: *mut pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_condattr_destroy(__attr: *mut pthread_condattr_t)
-> ::libc::c_int;
pub fn pthread_condattr_getpshared(__attr: *const pthread_condattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_condattr_setpshared(__attr: *mut pthread_condattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_condattr_getclock(__attr: *const pthread_condattr_t,
__clock_id: *mut __clockid_t)
-> ::libc::c_int;
pub fn pthread_condattr_setclock(__attr: *mut pthread_condattr_t,
__clock_id: __clockid_t)
-> ::libc::c_int;
pub fn pthread_spin_init(__lock: *mut pthread_spinlock_t,
__pshared: ::libc::c_int) -> ::libc::c_int;
pub fn pthread_spin_destroy(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_lock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_trylock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_spin_unlock(__lock: *mut pthread_spinlock_t)
-> ::libc::c_int;
pub fn pthread_barrier_init(__barrier: *mut pthread_barrier_t,
__attr: *const pthread_barrierattr_t,
__count: ::libc::c_uint) -> ::libc::c_int;
pub fn pthread_barrier_destroy(__barrier: *mut pthread_barrier_t)
-> ::libc::c_int;
pub fn pthread_barrier_wait(__barrier: *mut pthread_barrier_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_init(__attr: *mut pthread_barrierattr_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_destroy(__attr: *mut pthread_barrierattr_t)
-> ::libc::c_int;
pub fn pthread_barrierattr_getpshared(__attr:
*const pthread_barrierattr_t,
__pshared: *mut ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_barrierattr_setpshared(__attr: *mut pthread_barrierattr_t,
__pshared: ::libc::c_int)
-> ::libc::c_int;
pub fn pthread_key_create(__key: *mut pthread_key_t,
__destr_function:
::std::option::Option<extern "C" fn
(arg1:
*mut ::libc::c_void)>)
-> ::libc::c_int;
pub fn pthread_key_delete(__key: pthread_key_t) -> ::libc::c_int;
pub fn pthread_getspecific(__key: pthread_key_t) -> *mut ::libc::c_void;
pub fn pthread_setspecific(__key: pthread_key_t,
__pointer: *const ::libc::c_void)
-> ::libc::c_int;
pub fn pthread_getcpuclockid(__thread_id: pthread_t,
__clock_id: *mut __clockid_t)
-> ::libc::c_int;
pub fn pthread_atfork(__prepare: ::std::option::Option<extern "C" fn()>,
__parent: ::std::option::Option<extern "C" fn()>,
__child: ::std::option::Option<extern "C" fn()>)
-> ::libc::c_int;
pub fn g_static_mutex_init(mutex: *mut GStaticMutex);
pub fn g_static_mutex_free(mutex: *mut GStaticMutex);
pub fn g_static_mutex_get_mutex_impl(mutex: *mut GStaticMutex)
-> *mut GMutex;
pub fn g_static_rec_mutex_init(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_lock(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_trylock(mutex: *mut GStaticRecMutex)
-> gboolean;
pub fn g_static_rec_mutex_unlock(mutex: *mut GStaticRecMutex);
pub fn g_static_rec_mutex_lock_full(mutex: *mut GStaticRecMutex,
depth: guint);
pub fn g_static_rec_mutex_unlock_full(mutex: *mut GStaticRecMutex)
-> guint;
pub fn g_static_rec_mutex_free(mutex: *mut GStaticRecMutex);
pub fn g_static_rw_lock_init(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_reader_lock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_reader_trylock(lock: *mut GStaticRWLock)
-> gboolean;
pub fn g_static_rw_lock_reader_unlock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_writer_lock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_writer_trylock(lock: *mut GStaticRWLock)
-> gboolean;
pub fn g_static_rw_lock_writer_unlock(lock: *mut GStaticRWLock);
pub fn g_static_rw_lock_free(lock: *mut GStaticRWLock);
pub fn g_private_new(notify: GDestroyNotify) -> *mut GPrivate;
pub fn g_static_private_init(private_key: *mut GStaticPrivate);
pub fn g_static_private_get(private_key: *mut GStaticPrivate) -> gpointer;
pub fn g_static_private_set(private_key: *mut GStaticPrivate,
data: gpointer, notify: GDestroyNotify);
pub fn g_static_private_free(private_key: *mut GStaticPrivate);
pub fn g_once_init_enter_impl(location: *mut gsize) -> gboolean;
pub fn g_thread_init(vtable: gpointer);
pub fn g_thread_init_with_errorcheck_mutexes(vtable: gpointer);
pub fn g_thread_get_initialized() -> gboolean;
pub fn g_mutex_new() -> *mut GMutex;
pub fn g_mutex_free(mutex: *mut GMutex);
pub fn g_cond_new() -> *mut GCond;
pub fn g_cond_free(cond: *mut GCond);
pub fn g_cond_timed_wait(cond: *mut GCond, mutex: *mut GMutex,
timeval: *mut GTimeVal) -> gboolean;
pub fn g_type_init();
pub fn g_type_init_with_debug_flags(debug_flags: GTypeDebugFlags);
pub fn g_type_name(_type: GType) -> *const gchar;
pub fn g_type_qname(_type: GType) -> GQuark;
pub fn g_type_from_name(name: *const gchar) -> GType;
pub fn g_type_parent(_type: GType) -> GType;
pub fn g_type_depth(_type: GType) -> guint;
pub fn g_type_next_base(leaf_type: GType, root_type: GType) -> GType;
pub fn g_type_is_a(_type: GType, is_a_type: GType) -> gboolean;
pub fn g_type_class_ref(_type: GType) -> gpointer;
pub fn g_type_class_peek(_type: GType) -> gpointer;
pub fn g_type_class_peek_static(_type: GType) -> gpointer;
pub fn g_type_class_unref(g_class: gpointer);
pub fn g_type_class_peek_parent(g_class: gpointer) -> gpointer;
pub fn g_type_interface_peek(instance_class: gpointer, iface_type: GType)
-> gpointer;
pub fn g_type_interface_peek_parent(g_iface: gpointer) -> gpointer;
pub fn g_type_default_interface_ref(g_type: GType) -> gpointer;
pub fn g_type_default_interface_peek(g_type: GType) -> gpointer;
pub fn g_type_default_interface_unref(g_iface: gpointer);
pub fn g_type_children(_type: GType, n_children: *mut guint)
-> *mut GType;
pub fn g_type_interfaces(_type: GType, n_interfaces: *mut guint)
-> *mut GType;
pub fn g_type_set_qdata(_type: GType, quark: GQuark, data: gpointer);
pub fn g_type_get_qdata(_type: GType, quark: GQuark) -> gpointer;
pub fn g_type_query(_type: GType, query: *mut GTypeQuery);
pub fn g_type_register_static(parent_type: GType, type_name: *const gchar,
info: *const GTypeInfo, flags: GTypeFlags)
-> GType;
pub fn g_type_register_static_simple(parent_type: GType,
type_name: *const gchar,
class_size: guint,
class_init: GClassInitFunc,
instance_size: guint,
instance_init: GInstanceInitFunc,
flags: GTypeFlags) -> GType;
pub fn g_type_register_dynamic(parent_type: GType,
type_name: *const gchar,
plugin: *mut GTypePlugin,
flags: GTypeFlags) -> GType;
pub fn g_type_register_fundamental(type_id: GType,
type_name: *const gchar,
info: *const GTypeInfo,
finfo: *const GTypeFundamentalInfo,
flags: GTypeFlags) -> GType;
pub fn g_type_add_interface_static(instance_type: GType,
interface_type: GType,
info: *const GInterfaceInfo);
pub fn g_type_add_interface_dynamic(instance_type: GType,
interface_type: GType,
plugin: *mut GTypePlugin);
pub fn g_type_interface_add_prerequisite(interface_type: GType,
prerequisite_type: GType);
pub fn g_type_interface_prerequisites(interface_type: GType,
n_prerequisites: *mut guint)
-> *mut GType;
pub fn g_type_class_add_private(g_class: gpointer, private_size: gsize);
pub fn g_type_add_instance_private(class_type: GType, private_size: gsize)
-> gint;
pub fn g_type_instance_get_private(instance: *mut GTypeInstance,
private_type: GType) -> gpointer;
pub fn g_type_class_adjust_private_offset(g_class: gpointer,
private_size_or_offset:
*mut gint);
pub fn g_type_add_class_private(class_type: GType, private_size: gsize);
pub fn g_type_class_get_private(klass: *mut GTypeClass,
private_type: GType) -> gpointer;
pub fn g_type_class_get_instance_private_offset(g_class: gpointer)
-> gint;
pub fn g_type_ensure(_type: GType);
pub fn g_type_get_type_registration_serial() -> guint;
pub fn g_type_get_plugin(_type: GType) -> *mut GTypePlugin;
pub fn g_type_interface_get_plugin(instance_type: GType,
interface_type: GType)
-> *mut GTypePlugin;
pub fn g_type_fundamental_next() -> GType;
pub fn g_type_fundamental(type_id: GType) -> GType;
pub fn g_type_create_instance(_type: GType) -> *mut GTypeInstance;
pub fn g_type_free_instance(instance: *mut GTypeInstance);
pub fn g_type_add_class_cache_func(cache_data: gpointer,
cache_func: GTypeClassCacheFunc);
pub fn g_type_remove_class_cache_func(cache_data: gpointer,
cache_func: GTypeClassCacheFunc);
pub fn g_type_class_unref_uncached(g_class: gpointer);
pub fn g_type_add_interface_check(check_data: gpointer,
check_func: GTypeInterfaceCheckFunc);
pub fn g_type_remove_interface_check(check_data: gpointer,
check_func: GTypeInterfaceCheckFunc);
pub fn g_type_value_table_peek(_type: GType) -> *mut GTypeValueTable;
pub fn g_type_check_instance(instance: *mut GTypeInstance) -> gboolean;
pub fn g_type_check_instance_cast(instance: *mut GTypeInstance,
iface_type: GType)
-> *mut GTypeInstance;
pub fn g_type_check_instance_is_a(instance: *mut GTypeInstance,
iface_type: GType) -> gboolean;
pub fn g_type_check_instance_is_fundamentally_a(instance:
*mut GTypeInstance,
fundamental_type: GType)
-> gboolean;
pub fn g_type_check_class_cast(g_class: *mut GTypeClass, is_a_type: GType)
-> *mut GTypeClass;
pub fn g_type_check_class_is_a(g_class: *mut GTypeClass, is_a_type: GType)
-> gboolean;
pub fn g_type_check_is_value_type(_type: GType) -> gboolean;
pub fn g_type_check_value(value: *mut GValue) -> gboolean;
pub fn g_type_check_value_holds(value: *mut GValue, _type: GType)
-> gboolean;
pub fn g_type_test_flags(_type: GType, flags: guint) -> gboolean;
pub fn g_type_name_from_instance(instance: *mut GTypeInstance)
-> *const gchar;
pub fn g_type_name_from_class(g_class: *mut GTypeClass) -> *const gchar;
pub fn g_value_init(value: *mut GValue, g_type: GType) -> *mut GValue;
pub fn g_value_copy(src_value: *const GValue, dest_value: *mut GValue);
pub fn g_value_reset(value: *mut GValue) -> *mut GValue;
pub fn g_value_unset(value: *mut GValue);
pub fn g_value_set_instance(value: *mut GValue, instance: gpointer);
pub fn g_value_init_from_instance(value: *mut GValue, instance: gpointer);
pub fn g_value_fits_pointer(value: *const GValue) -> gboolean;
pub fn g_value_peek_pointer(value: *const GValue) -> gpointer;
pub fn g_value_type_compatible(src_type: GType, dest_type: GType)
-> gboolean;
pub fn g_value_type_transformable(src_type: GType, dest_type: GType)
-> gboolean;
pub fn g_value_transform(src_value: *const GValue,
dest_value: *mut GValue) -> gboolean;
pub fn g_value_register_transform_func(src_type: GType, dest_type: GType,
transform_func: GValueTransform);
pub fn g_param_spec_ref(pspec: *mut GParamSpec) -> *mut GParamSpec;
pub fn g_param_spec_unref(pspec: *mut GParamSpec);
pub fn g_param_spec_sink(pspec: *mut GParamSpec);
pub fn g_param_spec_ref_sink(pspec: *mut GParamSpec) -> *mut GParamSpec;
pub fn g_param_spec_get_qdata(pspec: *mut GParamSpec, quark: GQuark)
-> gpointer;
pub fn g_param_spec_set_qdata(pspec: *mut GParamSpec, quark: GQuark,
data: gpointer);
pub fn g_param_spec_set_qdata_full(pspec: *mut GParamSpec, quark: GQuark,
data: gpointer,
destroy: GDestroyNotify);
pub fn g_param_spec_steal_qdata(pspec: *mut GParamSpec, quark: GQuark)
-> gpointer;
pub fn g_param_spec_get_redirect_target(pspec: *mut GParamSpec)
-> *mut GParamSpec;
pub fn g_param_value_set_default(pspec: *mut GParamSpec,
value: *mut GValue);
pub fn g_param_value_defaults(pspec: *mut GParamSpec, value: *mut GValue)
-> gboolean;
pub fn g_param_value_validate(pspec: *mut GParamSpec, value: *mut GValue)
-> gboolean;
pub fn g_param_value_convert(pspec: *mut GParamSpec,
src_value: *const GValue,
dest_value: *mut GValue,
strict_validation: gboolean) -> gboolean;
pub fn g_param_values_cmp(pspec: *mut GParamSpec, value1: *const GValue,
value2: *const GValue) -> gint;
pub fn g_param_spec_get_name(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_param_spec_get_nick(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_param_spec_get_blurb(pspec: *mut GParamSpec) -> *const gchar;
pub fn g_value_set_param(value: *mut GValue, param: *mut GParamSpec);
pub fn g_value_get_param(value: *const GValue) -> *mut GParamSpec;
pub fn g_value_dup_param(value: *const GValue) -> *mut GParamSpec;
pub fn g_value_take_param(value: *mut GValue, param: *mut GParamSpec);
pub fn g_value_set_param_take_ownership(value: *mut GValue,
param: *mut GParamSpec);
pub fn g_param_spec_get_default_value(param: *mut GParamSpec)
-> *const GValue;
pub fn g_param_type_register_static(name: *const gchar,
pspec_info: *const GParamSpecTypeInfo)
-> GType;
pub fn _g_param_type_register_static_constant(name: *const gchar,
pspec_info:
*const GParamSpecTypeInfo,
opt_type: GType) -> GType;
pub fn g_param_spec_internal(param_type: GType, name: *const gchar,
nick: *const gchar, blurb: *const gchar,
flags: GParamFlags) -> gpointer;
pub fn g_param_spec_pool_new(type_prefixing: gboolean)
-> *mut GParamSpecPool;
pub fn g_param_spec_pool_insert(pool: *mut GParamSpecPool,
pspec: *mut GParamSpec,
owner_type: GType);
pub fn g_param_spec_pool_remove(pool: *mut GParamSpecPool,
pspec: *mut GParamSpec);
pub fn g_param_spec_pool_lookup(pool: *mut GParamSpecPool,
param_name: *const gchar,
owner_type: GType,
walk_ancestors: gboolean)
-> *mut GParamSpec;
pub fn g_param_spec_pool_list_owned(pool: *mut GParamSpecPool,
owner_type: GType) -> *mut GList;
pub fn g_param_spec_pool_list(pool: *mut GParamSpecPool,
owner_type: GType, n_pspecs_p: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_cclosure_new(callback_func: GCallback, user_data: gpointer,
destroy_data: GClosureNotify) -> *mut GClosure;
pub fn g_cclosure_new_swap(callback_func: GCallback, user_data: gpointer,
destroy_data: GClosureNotify) -> *mut GClosure;
pub fn g_signal_type_cclosure_new(itype: GType, struct_offset: guint)
-> *mut GClosure;
pub fn g_closure_ref(closure: *mut GClosure) -> *mut GClosure;
pub fn g_closure_sink(closure: *mut GClosure);
pub fn g_closure_unref(closure: *mut GClosure);
pub fn g_closure_new_simple(sizeof_closure: guint, data: gpointer)
-> *mut GClosure;
pub fn g_closure_add_finalize_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_remove_finalize_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_add_invalidate_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_remove_invalidate_notifier(closure: *mut GClosure,
notify_data: gpointer,
notify_func: GClosureNotify);
pub fn g_closure_add_marshal_guards(closure: *mut GClosure,
pre_marshal_data: gpointer,
pre_marshal_notify: GClosureNotify,
post_marshal_data: gpointer,
post_marshal_notify: GClosureNotify);
pub fn g_closure_set_marshal(closure: *mut GClosure,
marshal: GClosureMarshal);
pub fn g_closure_set_meta_marshal(closure: *mut GClosure,
marshal_data: gpointer,
meta_marshal: GClosureMarshal);
pub fn g_closure_invalidate(closure: *mut GClosure);
pub fn g_closure_invoke(closure: *mut GClosure, return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer);
pub fn g_cclosure_marshal_generic(closure: *mut GClosure,
return_gvalue: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_generic_va(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args_list: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__VOID(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__VOIDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__BOOLEAN(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__BOOLEANv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__CHAR(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__CHARv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UCHAR(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UCHARv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__INT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__INTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UINT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UINTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__LONG(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__LONGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__ULONG(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__ULONGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__ENUM(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__ENUMv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__FLAGS(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__FLAGSv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__FLOAT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__FLOATv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__DOUBLE(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__DOUBLEv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__STRING(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__STRINGv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__PARAM(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__PARAMv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__BOXED(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__BOXEDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__POINTER(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__POINTERv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__OBJECT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__OBJECTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer, args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__VARIANT(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__VARIANTv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_VOID__UINT_POINTER(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_VOID__UINT_POINTERv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_BOOLEAN__FLAGS(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values: *const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_BOOLEAN__FLAGSv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_cclosure_marshal_STRING__OBJECT_POINTER(closure: *mut GClosure,
return_value:
*mut GValue,
n_param_values: guint,
param_values:
*const GValue,
invocation_hint:
gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_STRING__OBJECT_POINTERv(closure: *mut GClosure,
return_value:
*mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types:
*mut GType);
pub fn g_cclosure_marshal_BOOLEAN__BOXED_BOXED(closure: *mut GClosure,
return_value: *mut GValue,
n_param_values: guint,
param_values:
*const GValue,
invocation_hint: gpointer,
marshal_data: gpointer);
pub fn g_cclosure_marshal_BOOLEAN__BOXED_BOXEDv(closure: *mut GClosure,
return_value: *mut GValue,
instance: gpointer,
args: va_list,
marshal_data: gpointer,
n_params: ::libc::c_int,
param_types: *mut GType);
pub fn g_signal_newv(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_closure: *mut GClosure,
accumulator: GSignalAccumulator, accu_data: gpointer,
c_marshaller: GSignalCMarshaller, return_type: GType,
n_params: guint, param_types: *mut GType) -> guint;
pub fn g_signal_new_valist(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_closure: *mut GClosure,
accumulator: GSignalAccumulator,
accu_data: gpointer,
c_marshaller: GSignalCMarshaller,
return_type: GType, n_params: guint,
args: va_list) -> guint;
pub fn g_signal_new(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags, class_offset: guint,
accumulator: GSignalAccumulator, accu_data: gpointer,
c_marshaller: GSignalCMarshaller, return_type: GType,
n_params: guint, ...) -> guint;
pub fn g_signal_new_class_handler(signal_name: *const gchar, itype: GType,
signal_flags: GSignalFlags,
class_handler: GCallback,
accumulator: GSignalAccumulator,
accu_data: gpointer,
c_marshaller: GSignalCMarshaller,
return_type: GType,
n_params: guint, ...) -> guint;
pub fn g_signal_set_va_marshaller(signal_id: guint, instance_type: GType,
va_marshaller: GSignalCVaMarshaller);
pub fn g_signal_emitv(instance_and_params: *const GValue,
signal_id: guint, detail: GQuark,
return_value: *mut GValue);
pub fn g_signal_emit_valist(instance: gpointer, signal_id: guint,
detail: GQuark, var_args: va_list);
pub fn g_signal_emit(instance: gpointer, signal_id: guint,
detail: GQuark, ...);
pub fn g_signal_emit_by_name(instance: gpointer,
detailed_signal: *const gchar, ...);
pub fn g_signal_lookup(name: *const gchar, itype: GType) -> guint;
pub fn g_signal_name(signal_id: guint) -> *const gchar;
pub fn g_signal_query(signal_id: guint, query: *mut GSignalQuery);
pub fn g_signal_list_ids(itype: GType, n_ids: *mut guint) -> *mut guint;
pub fn g_signal_parse_name(detailed_signal: *const gchar, itype: GType,
signal_id_p: *mut guint, detail_p: *mut GQuark,
force_detail_quark: gboolean) -> gboolean;
pub fn g_signal_get_invocation_hint(instance: gpointer)
-> *mut GSignalInvocationHint;
pub fn g_signal_stop_emission(instance: gpointer, signal_id: guint,
detail: GQuark);
pub fn g_signal_stop_emission_by_name(instance: gpointer,
detailed_signal: *const gchar);
pub fn g_signal_add_emission_hook(signal_id: guint, detail: GQuark,
hook_func: GSignalEmissionHook,
hook_data: gpointer,
data_destroy: GDestroyNotify) -> gulong;
pub fn g_signal_remove_emission_hook(signal_id: guint, hook_id: gulong);
pub fn g_signal_has_handler_pending(instance: gpointer, signal_id: guint,
detail: GQuark,
may_be_blocked: gboolean) -> gboolean;
pub fn g_signal_connect_closure_by_id(instance: gpointer,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
after: gboolean) -> gulong;
pub fn g_signal_connect_closure(instance: gpointer,
detailed_signal: *const gchar,
closure: *mut GClosure, after: gboolean)
-> gulong;
pub fn g_signal_connect_data(instance: gpointer,
detailed_signal: *const gchar,
c_handler: GCallback, data: gpointer,
destroy_data: GClosureNotify,
connect_flags: GConnectFlags) -> gulong;
pub fn g_signal_handler_block(instance: gpointer, handler_id: gulong);
pub fn g_signal_handler_unblock(instance: gpointer, handler_id: gulong);
pub fn g_signal_handler_disconnect(instance: gpointer,
handler_id: gulong);
pub fn g_signal_handler_is_connected(instance: gpointer,
handler_id: gulong) -> gboolean;
pub fn g_signal_handler_find(instance: gpointer, mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure, func: gpointer,
data: gpointer) -> gulong;
pub fn g_signal_handlers_block_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
func: gpointer, data: gpointer)
-> guint;
pub fn g_signal_handlers_unblock_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint, detail: GQuark,
closure: *mut GClosure,
func: gpointer, data: gpointer)
-> guint;
pub fn g_signal_handlers_disconnect_matched(instance: gpointer,
mask: GSignalMatchType,
signal_id: guint,
detail: GQuark,
closure: *mut GClosure,
func: gpointer,
data: gpointer) -> guint;
pub fn g_signal_override_class_closure(signal_id: guint,
instance_type: GType,
class_closure: *mut GClosure);
pub fn g_signal_override_class_handler(signal_name: *const gchar,
instance_type: GType,
class_handler: GCallback);
pub fn g_signal_chain_from_overridden(instance_and_params: *const GValue,
return_value: *mut GValue);
pub fn g_signal_chain_from_overridden_handler(instance: gpointer, ...);
pub fn g_signal_accumulator_true_handled(ihint:
*mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue,
dummy: gpointer) -> gboolean;
pub fn g_signal_accumulator_first_wins(ihint: *mut GSignalInvocationHint,
return_accu: *mut GValue,
handler_return: *const GValue,
dummy: gpointer) -> gboolean;
pub fn g_signal_handlers_destroy(instance: gpointer);
pub fn _g_signals_destroy(itype: GType);
pub fn g_date_get_type() -> GType;
pub fn g_strv_get_type() -> GType;
pub fn g_gstring_get_type() -> GType;
pub fn g_hash_table_get_type() -> GType;
pub fn g_array_get_type() -> GType;
pub fn g_byte_array_get_type() -> GType;
pub fn g_ptr_array_get_type() -> GType;
pub fn g_bytes_get_type() -> GType;
pub fn g_variant_type_get_gtype() -> GType;
pub fn g_regex_get_type() -> GType;
pub fn g_match_info_get_type() -> GType;
pub fn g_error_get_type() -> GType;
pub fn g_date_time_get_type() -> GType;
pub fn g_time_zone_get_type() -> GType;
pub fn g_io_channel_get_type() -> GType;
pub fn g_io_condition_get_type() -> GType;
pub fn g_variant_builder_get_type() -> GType;
pub fn g_variant_dict_get_type() -> GType;
pub fn g_key_file_get_type() -> GType;
pub fn g_main_loop_get_type() -> GType;
pub fn g_main_context_get_type() -> GType;
pub fn g_source_get_type() -> GType;
pub fn g_pollfd_get_type() -> GType;
pub fn g_thread_get_type() -> GType;
pub fn g_checksum_get_type() -> GType;
pub fn g_markup_parse_context_get_type() -> GType;
pub fn g_mapped_file_get_type() -> GType;
pub fn g_variant_get_gtype() -> GType;
pub fn g_boxed_copy(boxed_type: GType, src_boxed: gconstpointer)
-> gpointer;
pub fn g_boxed_free(boxed_type: GType, boxed: gpointer);
pub fn g_value_set_boxed(value: *mut GValue, v_boxed: gconstpointer);
pub fn g_value_set_static_boxed(value: *mut GValue,
v_boxed: gconstpointer);
pub fn g_value_take_boxed(value: *mut GValue, v_boxed: gconstpointer);
pub fn g_value_set_boxed_take_ownership(value: *mut GValue,
v_boxed: gconstpointer);
pub fn g_value_get_boxed(value: *const GValue) -> gpointer;
pub fn g_value_dup_boxed(value: *const GValue) -> gpointer;
pub fn g_boxed_type_register_static(name: *const gchar,
boxed_copy: GBoxedCopyFunc,
boxed_free: GBoxedFreeFunc) -> GType;
pub fn g_closure_get_type() -> GType;
pub fn g_value_get_type() -> GType;
pub fn g_initially_unowned_get_type() -> GType;
pub fn g_object_class_install_property(oclass: *mut GObjectClass,
property_id: guint,
pspec: *mut GParamSpec);
pub fn g_object_class_find_property(oclass: *mut GObjectClass,
property_name: *const gchar)
-> *mut GParamSpec;
pub fn g_object_class_list_properties(oclass: *mut GObjectClass,
n_properties: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_object_class_override_property(oclass: *mut GObjectClass,
property_id: guint,
name: *const gchar);
pub fn g_object_class_install_properties(oclass: *mut GObjectClass,
n_pspecs: guint,
pspecs: *mut *mut GParamSpec);
pub fn g_object_interface_install_property(g_iface: gpointer,
pspec: *mut GParamSpec);
pub fn g_object_interface_find_property(g_iface: gpointer,
property_name: *const gchar)
-> *mut GParamSpec;
pub fn g_object_interface_list_properties(g_iface: gpointer,
n_properties_p: *mut guint)
-> *mut *mut GParamSpec;
pub fn g_object_get_type() -> GType;
pub fn g_object_new(object_type: GType,
first_property_name: *const gchar, ...) -> gpointer;
pub fn g_object_newv(object_type: GType, n_parameters: guint,
parameters: *mut GParameter) -> gpointer;
pub fn g_object_new_valist(object_type: GType,
first_property_name: *const gchar,
var_args: va_list) -> *mut GObject;
pub fn g_object_set(object: gpointer,
first_property_name: *const gchar, ...);
pub fn g_object_get(object: gpointer,
first_property_name: *const gchar, ...);
pub fn g_object_connect(object: gpointer, signal_spec: *const gchar, ...)
-> gpointer;
pub fn g_object_disconnect(object: gpointer,
signal_spec: *const gchar, ...);
pub fn g_object_set_valist(object: *mut GObject,
first_property_name: *const gchar,
var_args: va_list);
pub fn g_object_get_valist(object: *mut GObject,
first_property_name: *const gchar,
var_args: va_list);
pub fn g_object_set_property(object: *mut GObject,
property_name: *const gchar,
value: *const GValue);
pub fn g_object_get_property(object: *mut GObject,
property_name: *const gchar,
value: *mut GValue);
pub fn g_object_freeze_notify(object: *mut GObject);
pub fn g_object_notify(object: *mut GObject, property_name: *const gchar);
pub fn g_object_notify_by_pspec(object: *mut GObject,
pspec: *mut GParamSpec);
pub fn g_object_thaw_notify(object: *mut GObject);
pub fn g_object_is_floating(object: gpointer) -> gboolean;
pub fn g_object_ref_sink(object: gpointer) -> gpointer;
pub fn g_object_ref(object: gpointer) -> gpointer;
pub fn g_object_unref(object: gpointer);
pub fn g_object_weak_ref(object: *mut GObject, notify: GWeakNotify,
data: gpointer);
pub fn g_object_weak_unref(object: *mut GObject, notify: GWeakNotify,
data: gpointer);
pub fn g_object_add_weak_pointer(object: *mut GObject,
weak_pointer_location: *mut gpointer);
pub fn g_object_remove_weak_pointer(object: *mut GObject,
weak_pointer_location: *mut gpointer);
pub fn g_object_add_toggle_ref(object: *mut GObject,
notify: GToggleNotify, data: gpointer);
pub fn g_object_remove_toggle_ref(object: *mut GObject,
notify: GToggleNotify, data: gpointer);
pub fn g_object_get_qdata(object: *mut GObject, quark: GQuark)
-> gpointer;
pub fn g_object_set_qdata(object: *mut GObject, quark: GQuark,
data: gpointer);
pub fn g_object_set_qdata_full(object: *mut GObject, quark: GQuark,
data: gpointer, destroy: GDestroyNotify);
pub fn g_object_steal_qdata(object: *mut GObject, quark: GQuark)
-> gpointer;
pub fn g_object_dup_qdata(object: *mut GObject, quark: GQuark,
dup_func: GDuplicateFunc, user_data: gpointer)
-> gpointer;
pub fn g_object_replace_qdata(object: *mut GObject, quark: GQuark,
oldval: gpointer, newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_object_get_data(object: *mut GObject, key: *const gchar)
-> gpointer;
pub fn g_object_set_data(object: *mut GObject, key: *const gchar,
data: gpointer);
pub fn g_object_set_data_full(object: *mut GObject, key: *const gchar,
data: gpointer, destroy: GDestroyNotify);
pub fn g_object_steal_data(object: *mut GObject, key: *const gchar)
-> gpointer;
pub fn g_object_dup_data(object: *mut GObject, key: *const gchar,
dup_func: GDuplicateFunc, user_data: gpointer)
-> gpointer;
pub fn g_object_replace_data(object: *mut GObject, key: *const gchar,
oldval: gpointer, newval: gpointer,
destroy: GDestroyNotify,
old_destroy: *mut GDestroyNotify)
-> gboolean;
pub fn g_object_watch_closure(object: *mut GObject,
closure: *mut GClosure);
pub fn g_cclosure_new_object(callback_func: GCallback,
object: *mut GObject) -> *mut GClosure;
pub fn g_cclosure_new_object_swap(callback_func: GCallback,
object: *mut GObject) -> *mut GClosure;
pub fn g_closure_new_object(sizeof_closure: guint, object: *mut GObject)
-> *mut GClosure;
pub fn g_value_set_object(value: *mut GValue, v_object: gpointer);
pub fn g_value_get_object(value: *const GValue) -> gpointer;
pub fn g_value_dup_object(value: *const GValue) -> gpointer;
pub fn g_signal_connect_object(instance: gpointer,
detailed_signal: *const gchar,
c_handler: GCallback, gobject: gpointer,
connect_flags: GConnectFlags) -> gulong;
pub fn g_object_force_floating(object: *mut GObject);
pub fn g_object_run_dispose(object: *mut GObject);
pub fn g_value_take_object(value: *mut GValue, v_object: gpointer);
pub fn g_value_set_object_take_ownership(value: *mut GValue,
v_object: gpointer);
pub fn g_object_compat_control(what: gsize, data: gpointer) -> gsize;
pub fn g_clear_object(object_ptr: *mut *mut GObject);
pub fn g_weak_ref_init(weak_ref: *mut GWeakRef, object: gpointer);
pub fn g_weak_ref_clear(weak_ref: *mut GWeakRef);
pub fn g_weak_ref_get(weak_ref: *mut GWeakRef) -> gpointer;
pub fn g_weak_ref_set(weak_ref: *mut GWeakRef, object: gpointer);
pub fn g_binding_flags_get_type() -> GType;
pub fn g_binding_get_type() -> GType;
pub fn g_binding_get_flags(binding: *mut GBinding) -> GBindingFlags;
pub fn g_binding_get_source(binding: *mut GBinding) -> *mut GObject;
pub fn g_binding_get_target(binding: *mut GBinding) -> *mut GObject;
pub fn g_binding_get_source_property(binding: *mut GBinding)
-> *const gchar;
pub fn g_binding_get_target_property(binding: *mut GBinding)
-> *const gchar;
pub fn g_binding_unbind(binding: *mut GBinding);
pub fn g_object_bind_property(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags) -> *mut GBinding;
pub fn g_object_bind_property_full(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags,
transform_to: GBindingTransformFunc,
transform_from: GBindingTransformFunc,
user_data: gpointer,
notify: GDestroyNotify)
-> *mut GBinding;
pub fn g_object_bind_property_with_closures(source: gpointer,
source_property: *const gchar,
target: gpointer,
target_property: *const gchar,
flags: GBindingFlags,
transform_to: *mut GClosure,
transform_from: *mut GClosure)
-> *mut GBinding;
pub fn g_enum_get_value(enum_class: *mut GEnumClass, value: gint)
-> *mut GEnumValue;
pub fn g_enum_get_value_by_name(enum_class: *mut GEnumClass,
name: *const gchar) -> *mut GEnumValue;
pub fn g_enum_get_value_by_nick(enum_class: *mut GEnumClass,
nick: *const gchar) -> *mut GEnumValue;
pub fn g_flags_get_first_value(flags_class: *mut GFlagsClass,
value: guint) -> *mut GFlagsValue;
pub fn g_flags_get_value_by_name(flags_class: *mut GFlagsClass,
name: *const gchar) -> *mut GFlagsValue;
pub fn g_flags_get_value_by_nick(flags_class: *mut GFlagsClass,
nick: *const gchar) -> *mut GFlagsValue;
pub fn g_value_set_enum(value: *mut GValue, v_enum: gint);
pub fn g_value_get_enum(value: *const GValue) -> gint;
pub fn g_value_set_flags(value: *mut GValue, v_flags: guint);
pub fn g_value_get_flags(value: *const GValue) -> guint;
pub fn g_enum_register_static(name: *const gchar,
const_static_values: *const GEnumValue)
-> GType;
pub fn g_flags_register_static(name: *const gchar,
const_static_values: *const GFlagsValue)
-> GType;
pub fn g_enum_complete_type_info(g_enum_type: GType, info: *mut GTypeInfo,
const_values: *const GEnumValue);
pub fn g_flags_complete_type_info(g_flags_type: GType,
info: *mut GTypeInfo,
const_values: *const GFlagsValue);
pub fn g_param_spec_char(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint8,
maximum: gint8, default_value: gint8,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_uchar(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint8,
maximum: guint8, default_value: guint8,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_boolean(name: *const gchar, nick: *const gchar,
blurb: *const gchar, default_value: gboolean,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_int(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint, maximum: gint,
default_value: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_uint(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint,
maximum: guint, default_value: guint,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_long(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: glong,
maximum: glong, default_value: glong,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_ulong(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gulong,
maximum: gulong, default_value: gulong,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_int64(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gint64,
maximum: gint64, default_value: gint64,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_uint64(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: guint64,
maximum: guint64, default_value: guint64,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_unichar(name: *const gchar, nick: *const gchar,
blurb: *const gchar, default_value: gunichar,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_enum(name: *const gchar, nick: *const gchar,
blurb: *const gchar, enum_type: GType,
default_value: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_flags(name: *const gchar, nick: *const gchar,
blurb: *const gchar, flags_type: GType,
default_value: guint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_float(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gfloat,
maximum: gfloat, default_value: gfloat,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_double(name: *const gchar, nick: *const gchar,
blurb: *const gchar, minimum: gdouble,
maximum: gdouble, default_value: gdouble,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_string(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
default_value: *const gchar,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_param(name: *const gchar, nick: *const gchar,
blurb: *const gchar, param_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_boxed(name: *const gchar, nick: *const gchar,
blurb: *const gchar, boxed_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_pointer(name: *const gchar, nick: *const gchar,
blurb: *const gchar, flags: GParamFlags)
-> *mut GParamSpec;
pub fn g_param_spec_value_array(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
element_spec: *mut GParamSpec,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_object(name: *const gchar, nick: *const gchar,
blurb: *const gchar, object_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_override(name: *const gchar,
overridden: *mut GParamSpec)
-> *mut GParamSpec;
pub fn g_param_spec_gtype(name: *const gchar, nick: *const gchar,
blurb: *const gchar, is_a_type: GType,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_param_spec_variant(name: *const gchar, nick: *const gchar,
blurb: *const gchar,
_type: *const GVariantType,
default_value: *mut GVariant,
flags: GParamFlags) -> *mut GParamSpec;
pub fn g_source_set_closure(source: *mut GSource, closure: *mut GClosure);
pub fn g_source_set_dummy_callback(source: *mut GSource);
pub fn g_type_module_get_type() -> GType;
pub fn g_type_module_use(module: *mut GTypeModule) -> gboolean;
pub fn g_type_module_unuse(module: *mut GTypeModule);
pub fn g_type_module_set_name(module: *mut GTypeModule,
name: *const gchar);
pub fn g_type_module_register_type(module: *mut GTypeModule,
parent_type: GType,
type_name: *const gchar,
type_info: *const GTypeInfo,
flags: GTypeFlags) -> GType;
pub fn g_type_module_add_interface(module: *mut GTypeModule,
instance_type: GType,
interface_type: GType,
interface_info: *const GInterfaceInfo);
pub fn g_type_module_register_enum(module: *mut GTypeModule,
name: *const gchar,
const_static_values: *const GEnumValue)
-> GType;
pub fn g_type_module_register_flags(module: *mut GTypeModule,
name: *const gchar,
const_static_values:
*const GFlagsValue) -> GType;
pub fn g_type_plugin_get_type() -> GType;
pub fn g_type_plugin_use(plugin: *mut GTypePlugin);
pub fn g_type_plugin_unuse(plugin: *mut GTypePlugin);
pub fn g_type_plugin_complete_type_info(plugin: *mut GTypePlugin,
g_type: GType,
info: *mut GTypeInfo,
value_table:
*mut GTypeValueTable);
pub fn g_type_plugin_complete_interface_info(plugin: *mut GTypePlugin,
instance_type: GType,
interface_type: GType,
info: *mut GInterfaceInfo);
pub fn g_value_array_get_type() -> GType;
pub fn g_value_array_get_nth(value_array: *mut GValueArray, index_: guint)
-> *mut GValue;
pub fn g_value_array_new(n_prealloced: guint) -> *mut GValueArray;
pub fn g_value_array_free(value_array: *mut GValueArray);
pub fn g_value_array_copy(value_array: *const GValueArray)
-> *mut GValueArray;
pub fn g_value_array_prepend(value_array: *mut GValueArray,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_append(value_array: *mut GValueArray,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_insert(value_array: *mut GValueArray, index_: guint,
value: *const GValue) -> *mut GValueArray;
pub fn g_value_array_remove(value_array: *mut GValueArray, index_: guint)
-> *mut GValueArray;
pub fn g_value_array_sort(value_array: *mut GValueArray,
compare_func: GCompareFunc) -> *mut GValueArray;
pub fn g_value_array_sort_with_data(value_array: *mut GValueArray,
compare_func: GCompareDataFunc,
user_data: gpointer)
-> *mut GValueArray;
pub fn g_value_set_char(value: *mut GValue, v_char: gchar);
pub fn g_value_get_char(value: *const GValue) -> gchar;
pub fn g_value_set_schar(value: *mut GValue, v_char: gint8);
pub fn g_value_get_schar(value: *const GValue) -> gint8;
pub fn g_value_set_uchar(value: *mut GValue, v_uchar: guchar);
pub fn g_value_get_uchar(value: *const GValue) -> guchar;
pub fn g_value_set_boolean(value: *mut GValue, v_boolean: gboolean);
pub fn g_value_get_boolean(value: *const GValue) -> gboolean;
pub fn g_value_set_int(value: *mut GValue, v_int: gint);
pub fn g_value_get_int(value: *const GValue) -> gint;
pub fn g_value_set_uint(value: *mut GValue, v_uint: guint);
pub fn g_value_get_uint(value: *const GValue) -> guint;
pub fn g_value_set_long(value: *mut GValue, v_long: glong);
pub fn g_value_get_long(value: *const GValue) -> glong;
pub fn g_value_set_ulong(value: *mut GValue, v_ulong: gulong);
pub fn g_value_get_ulong(value: *const GValue) -> gulong;
pub fn g_value_set_int64(value: *mut GValue, v_int64: gint64);
pub fn g_value_get_int64(value: *const GValue) -> gint64;
pub fn g_value_set_uint64(value: *mut GValue, v_uint64: guint64);
pub fn g_value_get_uint64(value: *const GValue) -> guint64;
pub fn g_value_set_float(value: *mut GValue, v_float: gfloat);
pub fn g_value_get_float(value: *const GValue) -> gfloat;
pub fn g_value_set_double(value: *mut GValue, v_double: gdouble);
pub fn g_value_get_double(value: *const GValue) -> gdouble;
pub fn g_value_set_string(value: *mut GValue, v_string: *const gchar);
pub fn g_value_set_static_string(value: *mut GValue,
v_string: *const gchar);
pub fn g_value_get_string(value: *const GValue) -> *const gchar;
pub fn g_value_dup_string(value: *const GValue) -> *mut gchar;
pub fn g_value_set_pointer(value: *mut GValue, v_pointer: gpointer);
pub fn g_value_get_pointer(value: *const GValue) -> gpointer;
pub fn g_gtype_get_type() -> GType;
pub fn g_value_set_gtype(value: *mut GValue, v_gtype: GType);
pub fn g_value_get_gtype(value: *const GValue) -> GType;
pub fn g_value_set_variant(value: *mut GValue, variant: *mut GVariant);
pub fn g_value_take_variant(value: *mut GValue, variant: *mut GVariant);
pub fn g_value_get_variant(value: *const GValue) -> *mut GVariant;
pub fn g_value_dup_variant(value: *const GValue) -> *mut GVariant;
pub fn g_pointer_type_register_static(name: *const gchar) -> GType;
pub fn g_strdup_value_contents(value: *const GValue) -> *mut gchar;
pub fn g_value_take_string(value: *mut GValue, v_string: *mut gchar);
pub fn g_value_set_string_take_ownership(value: *mut GValue,
v_string: *mut gchar);
pub fn gst_object_flags_get_type() -> GType;
pub fn gst_allocator_flags_get_type() -> GType;
pub fn gst_bin_flags_get_type() -> GType;
pub fn gst_buffer_flags_get_type() -> GType;
pub fn gst_buffer_copy_flags_get_type() -> GType;
pub fn gst_buffer_pool_acquire_flags_get_type() -> GType;
pub fn gst_bus_flags_get_type() -> GType;
pub fn gst_bus_sync_reply_get_type() -> GType;
pub fn gst_caps_flags_get_type() -> GType;
pub fn gst_caps_intersect_mode_get_type() -> GType;
pub fn gst_clock_return_get_type() -> GType;
pub fn gst_clock_entry_type_get_type() -> GType;
pub fn gst_clock_flags_get_type() -> GType;
pub fn gst_debug_graph_details_get_type() -> GType;
pub fn gst_state_get_type() -> GType;
pub fn gst_state_change_return_get_type() -> GType;
pub fn gst_state_change_get_type() -> GType;
pub fn gst_element_flags_get_type() -> GType;
pub fn gst_core_error_get_type() -> GType;
pub fn gst_library_error_get_type() -> GType;
pub fn gst_resource_error_get_type() -> GType;
pub fn gst_stream_error_get_type() -> GType;
pub fn gst_event_type_flags_get_type() -> GType;
pub fn gst_event_type_get_type() -> GType;
pub fn gst_qos_type_get_type() -> GType;
pub fn gst_stream_flags_get_type() -> GType;
pub fn gst_format_get_type() -> GType;
pub fn gst_debug_level_get_type() -> GType;
pub fn gst_debug_color_flags_get_type() -> GType;
pub fn gst_debug_color_mode_get_type() -> GType;
pub fn gst_iterator_result_get_type() -> GType;
pub fn gst_iterator_item_get_type() -> GType;
pub fn gst_message_type_get_type() -> GType;
pub fn gst_structure_change_type_get_type() -> GType;
pub fn gst_stream_status_type_get_type() -> GType;
pub fn gst_progress_type_get_type() -> GType;
pub fn gst_meta_flags_get_type() -> GType;
pub fn gst_memory_flags_get_type() -> GType;
pub fn gst_map_flags_get_type() -> GType;
pub fn gst_mini_object_flags_get_type() -> GType;
pub fn gst_lock_flags_get_type() -> GType;
pub fn gst_pad_direction_get_type() -> GType;
pub fn gst_pad_mode_get_type() -> GType;
pub fn gst_pad_link_return_get_type() -> GType;
pub fn gst_flow_return_get_type() -> GType;
pub fn gst_pad_link_check_get_type() -> GType;
pub fn gst_pad_probe_type_get_type() -> GType;
pub fn gst_pad_probe_return_get_type() -> GType;
pub fn gst_pad_flags_get_type() -> GType;
pub fn gst_pad_presence_get_type() -> GType;
pub fn gst_pad_template_flags_get_type() -> GType;
pub fn gst_pipeline_flags_get_type() -> GType;
pub fn gst_plugin_error_get_type() -> GType;
pub fn gst_plugin_flags_get_type() -> GType;
pub fn gst_plugin_dependency_flags_get_type() -> GType;
pub fn gst_rank_get_type() -> GType;
pub fn gst_query_type_flags_get_type() -> GType;
pub fn gst_query_type_get_type() -> GType;
pub fn gst_buffering_mode_get_type() -> GType;
pub fn gst_scheduling_flags_get_type() -> GType;
pub fn gst_seek_type_get_type() -> GType;
pub fn gst_seek_flags_get_type() -> GType;
pub fn gst_segment_flags_get_type() -> GType;
pub fn gst_clock_type_get_type() -> GType;
pub fn gst_tag_merge_mode_get_type() -> GType;
pub fn gst_tag_flag_get_type() -> GType;
pub fn gst_tag_scope_get_type() -> GType;
pub fn gst_task_state_get_type() -> GType;
pub fn gst_toc_scope_get_type() -> GType;
pub fn gst_toc_entry_type_get_type() -> GType;
pub fn gst_toc_loop_type_get_type() -> GType;
pub fn gst_type_find_probability_get_type() -> GType;
pub fn gst_uri_error_get_type() -> GType;
pub fn gst_uri_type_get_type() -> GType;
pub fn gst_search_mode_get_type() -> GType;
pub fn gst_parse_error_get_type() -> GType;
pub fn gst_parse_flags_get_type() -> GType;
pub fn gst_atomic_queue_get_type() -> GType;
pub fn gst_atomic_queue_new(initial_size: guint) -> *mut GstAtomicQueue;
pub fn gst_atomic_queue_ref(queue: *mut GstAtomicQueue);
pub fn gst_atomic_queue_unref(queue: *mut GstAtomicQueue);
pub fn gst_atomic_queue_push(queue: *mut GstAtomicQueue, data: gpointer);
pub fn gst_atomic_queue_pop(queue: *mut GstAtomicQueue) -> gpointer;
pub fn gst_atomic_queue_peek(queue: *mut GstAtomicQueue) -> gpointer;
pub fn gst_atomic_queue_length(queue: *mut GstAtomicQueue) -> guint;
pub fn gst_object_get_type() -> GType;
pub fn gst_object_set_name(object: *mut GstObject, name: *const gchar)
-> gboolean;
pub fn gst_object_get_name(object: *mut GstObject) -> *mut gchar;
pub fn gst_object_set_parent(object: *mut GstObject,
parent: *mut GstObject) -> gboolean;
pub fn gst_object_get_parent(object: *mut GstObject) -> *mut GstObject;
pub fn gst_object_unparent(object: *mut GstObject);
pub fn gst_object_has_ancestor(object: *mut GstObject,
ancestor: *mut GstObject) -> gboolean;
pub fn gst_object_default_deep_notify(object: *mut GObject,
orig: *mut GstObject,
pspec: *mut GParamSpec,
excluded_props: *mut *mut gchar);
pub fn gst_object_ref(object: gpointer) -> gpointer;
pub fn gst_object_unref(object: gpointer);
pub fn gst_object_ref_sink(object: gpointer) -> gpointer;
pub fn gst_object_replace(oldobj: *mut *mut GstObject,
newobj: *mut GstObject) -> gboolean;
pub fn gst_object_get_path_string(object: *mut GstObject) -> *mut gchar;
pub fn gst_object_check_uniqueness(list: *mut GList, name: *const gchar)
-> gboolean;
pub fn gst_clock_get_type() -> GType;
pub fn gst_clock_set_resolution(clock: *mut GstClock,
resolution: GstClockTime) -> GstClockTime;
pub fn gst_clock_get_resolution(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_get_time(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_set_calibration(clock: *mut GstClock,
internal: GstClockTime,
external: GstClockTime,
rate_num: GstClockTime,
rate_denom: GstClockTime);
pub fn gst_clock_get_calibration(clock: *mut GstClock,
internal: *mut GstClockTime,
external: *mut GstClockTime,
rate_num: *mut GstClockTime,
rate_denom: *mut GstClockTime);
pub fn gst_clock_set_master(clock: *mut GstClock, master: *mut GstClock)
-> gboolean;
pub fn gst_clock_get_master(clock: *mut GstClock) -> *mut GstClock;
pub fn gst_clock_set_timeout(clock: *mut GstClock, timeout: GstClockTime);
pub fn gst_clock_get_timeout(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_add_observation(clock: *mut GstClock,
slave: GstClockTime,
master: GstClockTime,
r_squared: *mut gdouble) -> gboolean;
pub fn gst_clock_get_internal_time(clock: *mut GstClock) -> GstClockTime;
pub fn gst_clock_adjust_unlocked(clock: *mut GstClock,
internal: GstClockTime) -> GstClockTime;
pub fn gst_clock_unadjust_unlocked(clock: *mut GstClock,
external: GstClockTime)
-> GstClockTime;
pub fn gst_clock_new_single_shot_id(clock: *mut GstClock,
time: GstClockTime) -> GstClockID;
pub fn gst_clock_new_periodic_id(clock: *mut GstClock,
start_time: GstClockTime,
interval: GstClockTime) -> GstClockID;
pub fn gst_clock_id_ref(id: GstClockID) -> GstClockID;
pub fn gst_clock_id_unref(id: GstClockID);
pub fn gst_clock_id_compare_func(id1: gconstpointer, id2: gconstpointer)
-> gint;
pub fn gst_clock_id_get_time(id: GstClockID) -> GstClockTime;
pub fn gst_clock_id_wait(id: GstClockID, jitter: *mut GstClockTimeDiff)
-> GstClockReturn;
pub fn gst_clock_id_wait_async(id: GstClockID, func: GstClockCallback,
user_data: gpointer,
destroy_data: GDestroyNotify)
-> GstClockReturn;
pub fn gst_clock_id_unschedule(id: GstClockID);
pub fn gst_clock_single_shot_id_reinit(clock: *mut GstClock,
id: GstClockID, time: GstClockTime)
-> gboolean;
pub fn gst_clock_periodic_id_reinit(clock: *mut GstClock, id: GstClockID,
start_time: GstClockTime,
interval: GstClockTime) -> gboolean;
pub fn gst_control_source_get_type() -> GType;
pub fn gst_control_source_get_value(_self: *mut GstControlSource,
timestamp: GstClockTime,
value: *mut gdouble) -> gboolean;
pub fn gst_control_source_get_value_array(_self: *mut GstControlSource,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut gdouble)
-> gboolean;
pub fn gst_control_binding_get_type() -> GType;
pub fn gst_control_binding_sync_values(binding: *mut GstControlBinding,
object: *mut GstObject,
timestamp: GstClockTime,
last_sync: GstClockTime)
-> gboolean;
pub fn gst_control_binding_get_value(binding: *mut GstControlBinding,
timestamp: GstClockTime)
-> *mut GValue;
pub fn gst_control_binding_get_value_array(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: gpointer) -> gboolean;
pub fn gst_control_binding_get_g_value_array(binding:
*mut GstControlBinding,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint,
values: *mut GValue)
-> gboolean;
pub fn gst_control_binding_set_disabled(binding: *mut GstControlBinding,
disabled: gboolean);
pub fn gst_control_binding_is_disabled(binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_suggest_next_sync(object: *mut GstObject)
-> GstClockTime;
pub fn gst_object_sync_values(object: *mut GstObject,
timestamp: GstClockTime) -> gboolean;
pub fn gst_object_has_active_control_bindings(object: *mut GstObject)
-> gboolean;
pub fn gst_object_set_control_bindings_disabled(object: *mut GstObject,
disabled: gboolean);
pub fn gst_object_set_control_binding_disabled(object: *mut GstObject,
property_name:
*const gchar,
disabled: gboolean);
pub fn gst_object_add_control_binding(object: *mut GstObject,
binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_get_control_binding(object: *mut GstObject,
property_name: *const gchar)
-> *mut GstControlBinding;
pub fn gst_object_remove_control_binding(object: *mut GstObject,
binding: *mut GstControlBinding)
-> gboolean;
pub fn gst_object_get_value(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime) -> *mut GValue;
pub fn gst_object_get_value_array(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime,
interval: GstClockTime, n_values: guint,
values: gpointer) -> gboolean;
pub fn gst_object_get_g_value_array(object: *mut GstObject,
property_name: *const gchar,
timestamp: GstClockTime,
interval: GstClockTime,
n_values: guint, values: *mut GValue)
-> gboolean;
pub fn gst_object_get_control_rate(object: *mut GstObject)
-> GstClockTime;
pub fn gst_object_set_control_rate(object: *mut GstObject,
control_rate: GstClockTime);
pub fn gst_pad_mode_get_name(mode: GstPadMode) -> *const gchar;
pub fn gst_mini_object_init(mini_object: *mut GstMiniObject, flags: guint,
_type: GType,
copy_func: GstMiniObjectCopyFunction,
dispose_func: GstMiniObjectDisposeFunction,
free_func: GstMiniObjectFreeFunction);
pub fn gst_mini_object_ref(mini_object: *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_unref(mini_object: *mut GstMiniObject);
pub fn gst_mini_object_weak_ref(object: *mut GstMiniObject,
notify: GstMiniObjectNotify,
data: gpointer);
pub fn gst_mini_object_weak_unref(object: *mut GstMiniObject,
notify: GstMiniObjectNotify,
data: gpointer);
pub fn gst_mini_object_lock(object: *mut GstMiniObject,
flags: GstLockFlags) -> gboolean;
pub fn gst_mini_object_unlock(object: *mut GstMiniObject,
flags: GstLockFlags);
pub fn gst_mini_object_is_writable(mini_object: *const GstMiniObject)
-> gboolean;
pub fn gst_mini_object_make_writable(mini_object: *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_copy(mini_object: *const GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_mini_object_set_qdata(object: *mut GstMiniObject,
quark: GQuark, data: gpointer,
destroy: GDestroyNotify);
pub fn gst_mini_object_get_qdata(object: *mut GstMiniObject,
quark: GQuark) -> gpointer;
pub fn gst_mini_object_steal_qdata(object: *mut GstMiniObject,
quark: GQuark) -> gpointer;
pub fn gst_mini_object_replace(olddata: *mut *mut GstMiniObject,
newdata: *mut GstMiniObject) -> gboolean;
pub fn gst_mini_object_take(olddata: *mut *mut GstMiniObject,
newdata: *mut GstMiniObject) -> gboolean;
pub fn gst_mini_object_steal(olddata: *mut *mut GstMiniObject)
-> *mut GstMiniObject;
pub fn gst_memory_get_type() -> GType;
pub fn gst_memory_init(mem: *mut GstMemory, flags: GstMemoryFlags,
allocator: *mut GstAllocator,
parent: *mut GstMemory, maxsize: gsize,
align: gsize, offset: gsize, size: gsize);
pub fn gst_memory_is_type(mem: *mut GstMemory, mem_type: *const gchar)
-> gboolean;
pub fn gst_memory_get_sizes(mem: *mut GstMemory, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_memory_resize(mem: *mut GstMemory, offset: gssize,
size: gsize);
pub fn gst_memory_make_mapped(mem: *mut GstMemory, info: *mut GstMapInfo,
flags: GstMapFlags) -> *mut GstMemory;
pub fn gst_memory_map(mem: *mut GstMemory, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_memory_unmap(mem: *mut GstMemory, info: *mut GstMapInfo);
pub fn gst_memory_copy(mem: *mut GstMemory, offset: gssize, size: gssize)
-> *mut GstMemory;
pub fn gst_memory_share(mem: *mut GstMemory, offset: gssize, size: gssize)
-> *mut GstMemory;
pub fn gst_memory_is_span(mem1: *mut GstMemory, mem2: *mut GstMemory,
offset: *mut gsize) -> gboolean;
pub fn gst_allocation_params_get_type() -> GType;
pub fn gst_allocator_get_type() -> GType;
pub fn gst_allocator_register(name: *const gchar,
allocator: *mut GstAllocator);
pub fn gst_allocator_find(name: *const gchar) -> *mut GstAllocator;
pub fn gst_allocator_set_default(allocator: *mut GstAllocator);
pub fn gst_allocation_params_init(params: *mut GstAllocationParams);
pub fn gst_allocation_params_copy(params: *const GstAllocationParams)
-> *mut GstAllocationParams;
pub fn gst_allocation_params_free(params: *mut GstAllocationParams);
pub fn gst_allocator_alloc(allocator: *mut GstAllocator, size: gsize,
params: *mut GstAllocationParams)
-> *mut GstMemory;
pub fn gst_allocator_free(allocator: *mut GstAllocator,
memory: *mut GstMemory);
pub fn gst_memory_new_wrapped(flags: GstMemoryFlags, data: gpointer,
maxsize: gsize, offset: gsize, size: gsize,
user_data: gpointer, notify: GDestroyNotify)
-> *mut GstMemory;
pub fn gst_buffer_get_type() -> GType;
pub fn gst_buffer_get_max_memory() -> guint;
pub fn gst_buffer_new() -> *mut GstBuffer;
pub fn gst_buffer_new_allocate(allocator: *mut GstAllocator, size: gsize,
params: *mut GstAllocationParams)
-> *mut GstBuffer;
pub fn gst_buffer_new_wrapped_full(flags: GstMemoryFlags, data: gpointer,
maxsize: gsize, offset: gsize,
size: gsize, user_data: gpointer,
notify: GDestroyNotify)
-> *mut GstBuffer;
pub fn gst_buffer_new_wrapped(data: gpointer, size: gsize)
-> *mut GstBuffer;
pub fn gst_buffer_n_memory(buffer: *mut GstBuffer) -> guint;
pub fn gst_buffer_insert_memory(buffer: *mut GstBuffer, idx: gint,
mem: *mut GstMemory);
pub fn gst_buffer_replace_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint, mem: *mut GstMemory);
pub fn gst_buffer_peek_memory(buffer: *mut GstBuffer, idx: guint)
-> *mut GstMemory;
pub fn gst_buffer_get_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint) -> *mut GstMemory;
pub fn gst_buffer_remove_memory_range(buffer: *mut GstBuffer, idx: guint,
length: gint);
pub fn gst_buffer_prepend_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_append_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_replace_memory(buffer: *mut GstBuffer, idx: guint,
mem: *mut GstMemory);
pub fn gst_buffer_replace_all_memory(buffer: *mut GstBuffer,
mem: *mut GstMemory);
pub fn gst_buffer_get_memory(buffer: *mut GstBuffer, idx: guint)
-> *mut GstMemory;
pub fn gst_buffer_get_all_memory(buffer: *mut GstBuffer)
-> *mut GstMemory;
pub fn gst_buffer_remove_memory(buffer: *mut GstBuffer, idx: guint);
pub fn gst_buffer_remove_all_memory(buffer: *mut GstBuffer);
pub fn gst_buffer_find_memory(buffer: *mut GstBuffer, offset: gsize,
size: gsize, idx: *mut guint,
length: *mut guint, skip: *mut gsize)
-> gboolean;
pub fn gst_buffer_is_memory_range_writable(buffer: *mut GstBuffer,
idx: guint, length: gint)
-> gboolean;
pub fn gst_buffer_is_all_memory_writable(buffer: *mut GstBuffer)
-> gboolean;
pub fn gst_buffer_fill(buffer: *mut GstBuffer, offset: gsize,
src: gconstpointer, size: gsize) -> gsize;
pub fn gst_buffer_extract(buffer: *mut GstBuffer, offset: gsize,
dest: gpointer, size: gsize) -> gsize;
pub fn gst_buffer_memcmp(buffer: *mut GstBuffer, offset: gsize,
mem: gconstpointer, size: gsize) -> gint;
pub fn gst_buffer_memset(buffer: *mut GstBuffer, offset: gsize,
val: guint8, size: gsize) -> gsize;
pub fn gst_buffer_get_sizes_range(buffer: *mut GstBuffer, idx: guint,
length: gint, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_buffer_resize_range(buffer: *mut GstBuffer, idx: guint,
length: gint, offset: gssize, size: gssize)
-> gboolean;
pub fn gst_buffer_get_sizes(buffer: *mut GstBuffer, offset: *mut gsize,
maxsize: *mut gsize) -> gsize;
pub fn gst_buffer_get_size(buffer: *mut GstBuffer) -> gsize;
pub fn gst_buffer_resize(buffer: *mut GstBuffer, offset: gssize,
size: gssize);
pub fn gst_buffer_set_size(buffer: *mut GstBuffer, size: gssize);
pub fn gst_buffer_map_range(buffer: *mut GstBuffer, idx: guint,
length: gint, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_buffer_map(buffer: *mut GstBuffer, info: *mut GstMapInfo,
flags: GstMapFlags) -> gboolean;
pub fn gst_buffer_unmap(buffer: *mut GstBuffer, info: *mut GstMapInfo);
pub fn gst_buffer_extract_dup(buffer: *mut GstBuffer, offset: gsize,
size: gsize, dest: *mut gpointer,
dest_size: *mut gsize);
pub fn gst_buffer_copy_into(dest: *mut GstBuffer, src: *mut GstBuffer,
flags: GstBufferCopyFlags, offset: gsize,
size: gsize) -> gboolean;
pub fn gst_buffer_copy_region(parent: *mut GstBuffer,
flags: GstBufferCopyFlags, offset: gsize,
size: gsize) -> *mut GstBuffer;
pub fn gst_buffer_append_region(buf1: *mut GstBuffer,
buf2: *mut GstBuffer, offset: gssize,
size: gssize) -> *mut GstBuffer;
pub fn gst_buffer_append(buf1: *mut GstBuffer, buf2: *mut GstBuffer)
-> *mut GstBuffer;
pub fn gst_meta_api_type_register(api: *const gchar,
tags: *mut *const gchar) -> GType;
pub fn gst_meta_api_type_has_tag(api: GType, tag: GQuark) -> gboolean;
pub fn gst_meta_register(api: GType, _impl: *const gchar, size: gsize,
init_func: GstMetaInitFunction,
free_func: GstMetaFreeFunction,
transform_func: GstMetaTransformFunction)
-> *const GstMetaInfo;
pub fn gst_meta_get_info(_impl: *const gchar) -> *const GstMetaInfo;
pub fn gst_meta_api_type_get_tags(api: GType) -> *const *const gchar;
pub fn gst_buffer_get_meta(buffer: *mut GstBuffer, api: GType)
-> *mut GstMeta;
pub fn gst_buffer_add_meta(buffer: *mut GstBuffer,
info: *const GstMetaInfo, params: gpointer)
-> *mut GstMeta;
pub fn gst_buffer_remove_meta(buffer: *mut GstBuffer, meta: *mut GstMeta)
-> gboolean;
pub fn gst_buffer_iterate_meta(buffer: *mut GstBuffer,
state: *mut gpointer) -> *mut GstMeta;
pub fn gst_buffer_foreach_meta(buffer: *mut GstBuffer,
func: GstBufferForeachMetaFunc,
user_data: gpointer) -> gboolean;
pub fn gst_buffer_list_get_type() -> GType;
pub fn gst_buffer_list_new() -> *mut GstBufferList;
pub fn gst_buffer_list_new_sized(size: guint) -> *mut GstBufferList;
pub fn gst_buffer_list_length(list: *mut GstBufferList) -> guint;
pub fn gst_buffer_list_get(list: *mut GstBufferList, idx: guint)
-> *mut GstBuffer;
pub fn gst_buffer_list_insert(list: *mut GstBufferList, idx: gint,
buffer: *mut GstBuffer);
pub fn gst_buffer_list_remove(list: *mut GstBufferList, idx: guint,
length: guint);
pub fn gst_buffer_list_foreach(list: *mut GstBufferList,
func: GstBufferListFunc,
user_data: gpointer) -> gboolean;
pub fn gst_date_time_get_type() -> GType;
pub fn gst_date_time_has_year(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_month(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_day(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_time(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_has_second(datetime: *const GstDateTime) -> gboolean;
pub fn gst_date_time_get_year(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_month(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_day(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_hour(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_minute(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_second(datetime: *const GstDateTime) -> gint;
pub fn gst_date_time_get_microsecond(datetime: *const GstDateTime)
-> gint;
pub fn gst_date_time_get_time_zone_offset(datetime: *const GstDateTime)
-> gfloat;
pub fn gst_date_time_new_from_unix_epoch_local_time(secs: gint64)
-> *mut GstDateTime;
pub fn gst_date_time_new_from_unix_epoch_utc(secs: gint64)
-> *mut GstDateTime;
pub fn gst_date_time_new_local_time(year: gint, month: gint, day: gint,
hour: gint, minute: gint,
seconds: gdouble) -> *mut GstDateTime;
pub fn gst_date_time_new_y(year: gint) -> *mut GstDateTime;
pub fn gst_date_time_new_ym(year: gint, month: gint) -> *mut GstDateTime;
pub fn gst_date_time_new_ymd(year: gint, month: gint, day: gint)
-> *mut GstDateTime;
pub fn gst_date_time_new(tzoffset: gfloat, year: gint, month: gint,
day: gint, hour: gint, minute: gint,
seconds: gdouble) -> *mut GstDateTime;
pub fn gst_date_time_new_now_local_time() -> *mut GstDateTime;
pub fn gst_date_time_new_now_utc() -> *mut GstDateTime;
pub fn gst_date_time_to_iso8601_string(datetime: *mut GstDateTime)
-> *mut gchar;
pub fn gst_date_time_new_from_iso8601_string(string: *const gchar)
-> *mut GstDateTime;
pub fn gst_date_time_to_g_date_time(datetime: *mut GstDateTime)
-> *mut GDateTime;
pub fn gst_date_time_new_from_g_date_time(dt: *mut GDateTime)
-> *mut GstDateTime;
pub fn gst_date_time_ref(datetime: *mut GstDateTime) -> *mut GstDateTime;
pub fn gst_date_time_unref(datetime: *mut GstDateTime);
pub fn gst_structure_get_type() -> GType;
pub fn gst_structure_new_empty(name: *const gchar) -> *mut GstStructure;
pub fn gst_structure_new_id_empty(quark: GQuark) -> *mut GstStructure;
pub fn gst_structure_new(name: *const gchar,
firstfield: *const gchar, ...)
-> *mut GstStructure;
pub fn gst_structure_new_valist(name: *const gchar,
firstfield: *const gchar,
varargs: va_list) -> *mut GstStructure;
pub fn gst_structure_new_id(name_quark: GQuark, field_quark: GQuark, ...)
-> *mut GstStructure;
pub fn gst_structure_new_from_string(string: *const gchar)
-> *mut GstStructure;
pub fn gst_structure_copy(structure: *const GstStructure)
-> *mut GstStructure;
pub fn gst_structure_set_parent_refcount(structure: *mut GstStructure,
refcount: *mut gint) -> gboolean;
pub fn gst_structure_free(structure: *mut GstStructure);
pub fn gst_structure_get_name(structure: *const GstStructure)
-> *const gchar;
pub fn gst_structure_get_name_id(structure: *const GstStructure)
-> GQuark;
pub fn gst_structure_has_name(structure: *const GstStructure,
name: *const gchar) -> gboolean;
pub fn gst_structure_set_name(structure: *mut GstStructure,
name: *const gchar);
pub fn gst_structure_id_set_value(structure: *mut GstStructure,
field: GQuark, value: *const GValue);
pub fn gst_structure_set_value(structure: *mut GstStructure,
fieldname: *const gchar,
value: *const GValue);
pub fn gst_structure_id_take_value(structure: *mut GstStructure,
field: GQuark, value: *mut GValue);
pub fn gst_structure_take_value(structure: *mut GstStructure,
fieldname: *const gchar,
value: *mut GValue);
pub fn gst_structure_set(structure: *mut GstStructure,
fieldname: *const gchar, ...);
pub fn gst_structure_set_valist(structure: *mut GstStructure,
fieldname: *const gchar,
varargs: va_list);
pub fn gst_structure_id_set(structure: *mut GstStructure,
fieldname: GQuark, ...);
pub fn gst_structure_id_set_valist(structure: *mut GstStructure,
fieldname: GQuark, varargs: va_list);
pub fn gst_structure_get_valist(structure: *const GstStructure,
first_fieldname: *const ::libc::c_char,
args: va_list) -> gboolean;
pub fn gst_structure_get(structure: *const GstStructure,
first_fieldname: *const ::libc::c_char, ...)
-> gboolean;
pub fn gst_structure_id_get_valist(structure: *const GstStructure,
first_field_id: GQuark, args: va_list)
-> gboolean;
pub fn gst_structure_id_get(structure: *const GstStructure,
first_field_id: GQuark, ...) -> gboolean;
pub fn gst_structure_id_get_value(structure: *const GstStructure,
field: GQuark) -> *const GValue;
pub fn gst_structure_get_value(structure: *const GstStructure,
fieldname: *const gchar) -> *const GValue;
pub fn gst_structure_remove_field(structure: *mut GstStructure,
fieldname: *const gchar);
pub fn gst_structure_remove_fields(structure: *mut GstStructure,
fieldname: *const gchar, ...);
pub fn gst_structure_remove_fields_valist(structure: *mut GstStructure,
fieldname: *const gchar,
varargs: va_list);
pub fn gst_structure_remove_all_fields(structure: *mut GstStructure);
pub fn gst_structure_get_field_type(structure: *const GstStructure,
fieldname: *const gchar) -> GType;
pub fn gst_structure_foreach(structure: *const GstStructure,
func: GstStructureForeachFunc,
user_data: gpointer) -> gboolean;
pub fn gst_structure_map_in_place(structure: *mut GstStructure,
func: GstStructureMapFunc,
user_data: gpointer) -> gboolean;
pub fn gst_structure_n_fields(structure: *const GstStructure) -> gint;
pub fn gst_structure_nth_field_name(structure: *const GstStructure,
index: guint) -> *const gchar;
pub fn gst_structure_id_has_field(structure: *const GstStructure,
field: GQuark) -> gboolean;
pub fn gst_structure_id_has_field_typed(structure: *const GstStructure,
field: GQuark, _type: GType)
-> gboolean;
pub fn gst_structure_has_field(structure: *const GstStructure,
fieldname: *const gchar) -> gboolean;
pub fn gst_structure_has_field_typed(structure: *const GstStructure,
fieldname: *const gchar,
_type: GType) -> gboolean;
pub fn gst_structure_get_boolean(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gboolean) -> gboolean;
pub fn gst_structure_get_int(structure: *const GstStructure,
fieldname: *const gchar, value: *mut gint)
-> gboolean;
pub fn gst_structure_get_uint(structure: *const GstStructure,
fieldname: *const gchar, value: *mut guint)
-> gboolean;
pub fn gst_structure_get_int64(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gint64) -> gboolean;
pub fn gst_structure_get_uint64(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut guint64) -> gboolean;
pub fn gst_structure_get_double(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut gdouble) -> gboolean;
pub fn gst_structure_get_date(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut *mut GDate) -> gboolean;
pub fn gst_structure_get_date_time(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_structure_get_clock_time(structure: *const GstStructure,
fieldname: *const gchar,
value: *mut GstClockTime) -> gboolean;
pub fn gst_structure_get_string(structure: *const GstStructure,
fieldname: *const gchar) -> *const gchar;
pub fn gst_structure_get_enum(structure: *const GstStructure,
fieldname: *const gchar, enumtype: GType,
value: *mut gint) -> gboolean;
pub fn gst_structure_get_fraction(structure: *const GstStructure,
fieldname: *const gchar,
value_numerator: *mut gint,
value_denominator: *mut gint)
-> gboolean;
pub fn gst_structure_to_string(structure: *const GstStructure)
-> *mut gchar;
pub fn gst_structure_from_string(string: *const gchar,
end: *mut *mut gchar)
-> *mut GstStructure;
pub fn gst_structure_fixate_field_nearest_int(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target: ::libc::c_int)
-> gboolean;
pub fn gst_structure_fixate_field_nearest_double(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target: ::libc::c_double)
-> gboolean;
pub fn gst_structure_fixate_field_boolean(structure: *mut GstStructure,
field_name:
*const ::libc::c_char,
target: gboolean) -> gboolean;
pub fn gst_structure_fixate_field_string(structure: *mut GstStructure,
field_name:
*const ::libc::c_char,
target: *const gchar)
-> gboolean;
pub fn gst_structure_fixate_field_nearest_fraction(structure:
*mut GstStructure,
field_name:
*const ::libc::c_char,
target_numerator: gint,
target_denominator:
gint) -> gboolean;
pub fn gst_structure_fixate_field(structure: *mut GstStructure,
field_name: *const ::libc::c_char)
-> gboolean;
pub fn gst_structure_fixate(structure: *mut GstStructure);
pub fn gst_structure_is_equal(structure1: *const GstStructure,
structure2: *const GstStructure)
-> gboolean;
pub fn gst_structure_is_subset(subset: *const GstStructure,
superset: *const GstStructure) -> gboolean;
pub fn gst_structure_can_intersect(struct1: *const GstStructure,
struct2: *const GstStructure)
-> gboolean;
pub fn gst_structure_intersect(struct1: *const GstStructure,
struct2: *const GstStructure)
-> *mut GstStructure;
pub fn gst_caps_features_get_type() -> GType;
pub fn gst_is_caps_features(obj: gconstpointer) -> gboolean;
pub fn gst_caps_features_new_empty() -> *mut GstCapsFeatures;
pub fn gst_caps_features_new_any() -> *mut GstCapsFeatures;
pub fn gst_caps_features_new(feature1: *const gchar, ...)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_valist(feature1: *const gchar,
varargs: va_list)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_id(feature1: GQuark, ...)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_new_id_valist(feature1: GQuark, varargs: va_list)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_set_parent_refcount(features:
*mut GstCapsFeatures,
refcount: *mut gint)
-> gboolean;
pub fn gst_caps_features_copy(features: *const GstCapsFeatures)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_free(features: *mut GstCapsFeatures);
pub fn gst_caps_features_to_string(features: *const GstCapsFeatures)
-> *mut gchar;
pub fn gst_caps_features_from_string(features: *const gchar)
-> *mut GstCapsFeatures;
pub fn gst_caps_features_get_size(features: *const GstCapsFeatures)
-> guint;
pub fn gst_caps_features_get_nth(features: *const GstCapsFeatures,
i: guint) -> *const gchar;
pub fn gst_caps_features_get_nth_id(features: *const GstCapsFeatures,
i: guint) -> GQuark;
pub fn gst_caps_features_contains(features: *const GstCapsFeatures,
feature: *const gchar) -> gboolean;
pub fn gst_caps_features_contains_id(features: *const GstCapsFeatures,
feature: GQuark) -> gboolean;
pub fn gst_caps_features_is_equal(features1: *const GstCapsFeatures,
features2: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_features_is_any(features: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_features_add(features: *mut GstCapsFeatures,
feature: *const gchar);
pub fn gst_caps_features_add_id(features: *mut GstCapsFeatures,
feature: GQuark);
pub fn gst_caps_features_remove(features: *mut GstCapsFeatures,
feature: *const gchar);
pub fn gst_caps_features_remove_id(features: *mut GstCapsFeatures,
feature: GQuark);
pub fn gst_caps_get_type() -> GType;
pub fn gst_caps_new_empty() -> *mut GstCaps;
pub fn gst_caps_new_any() -> *mut GstCaps;
pub fn gst_caps_new_empty_simple(media_type: *const ::libc::c_char)
-> *mut GstCaps;
pub fn gst_caps_new_simple(media_type: *const ::libc::c_char,
fieldname: *const ::libc::c_char, ...)
-> *mut GstCaps;
pub fn gst_caps_new_full(struct1: *mut GstStructure, ...) -> *mut GstCaps;
pub fn gst_caps_new_full_valist(structure: *mut GstStructure,
var_args: va_list) -> *mut GstCaps;
pub fn gst_static_caps_get_type() -> GType;
pub fn gst_static_caps_get(static_caps: *mut GstStaticCaps)
-> *mut GstCaps;
pub fn gst_static_caps_cleanup(static_caps: *mut GstStaticCaps);
pub fn gst_caps_append(caps1: *mut GstCaps, caps2: *mut GstCaps);
pub fn gst_caps_append_structure(caps: *mut GstCaps,
structure: *mut GstStructure);
pub fn gst_caps_append_structure_full(caps: *mut GstCaps,
structure: *mut GstStructure,
features: *mut GstCapsFeatures);
pub fn gst_caps_remove_structure(caps: *mut GstCaps, idx: guint);
pub fn gst_caps_merge(caps1: *mut GstCaps, caps2: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_merge_structure(caps: *mut GstCaps,
structure: *mut GstStructure)
-> *mut GstCaps;
pub fn gst_caps_merge_structure_full(caps: *mut GstCaps,
structure: *mut GstStructure,
features: *mut GstCapsFeatures)
-> *mut GstCaps;
pub fn gst_caps_get_size(caps: *const GstCaps) -> guint;
pub fn gst_caps_get_structure(caps: *const GstCaps, index: guint)
-> *mut GstStructure;
pub fn gst_caps_steal_structure(caps: *mut GstCaps, index: guint)
-> *mut GstStructure;
pub fn gst_caps_set_features(caps: *mut GstCaps, index: guint,
features: *mut GstCapsFeatures);
pub fn gst_caps_get_features(caps: *const GstCaps, index: guint)
-> *mut GstCapsFeatures;
pub fn gst_caps_copy_nth(caps: *const GstCaps, nth: guint)
-> *mut GstCaps;
pub fn gst_caps_truncate(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_set_value(caps: *mut GstCaps,
field: *const ::libc::c_char,
value: *const GValue);
pub fn gst_caps_set_simple(caps: *mut GstCaps,
field: *const ::libc::c_char, ...);
pub fn gst_caps_set_simple_valist(caps: *mut GstCaps,
field: *const ::libc::c_char,
varargs: va_list);
pub fn gst_caps_is_any(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_empty(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_fixed(caps: *const GstCaps) -> gboolean;
pub fn gst_caps_is_always_compatible(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_is_subset(subset: *const GstCaps,
superset: *const GstCaps) -> gboolean;
pub fn gst_caps_is_subset_structure(caps: *const GstCaps,
structure: *const GstStructure)
-> gboolean;
pub fn gst_caps_is_subset_structure_full(caps: *const GstCaps,
structure: *const GstStructure,
features: *const GstCapsFeatures)
-> gboolean;
pub fn gst_caps_is_equal(caps1: *const GstCaps, caps2: *const GstCaps)
-> gboolean;
pub fn gst_caps_is_equal_fixed(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_can_intersect(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_is_strictly_equal(caps1: *const GstCaps,
caps2: *const GstCaps) -> gboolean;
pub fn gst_caps_intersect(caps1: *mut GstCaps, caps2: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_intersect_full(caps1: *mut GstCaps, caps2: *mut GstCaps,
mode: GstCapsIntersectMode)
-> *mut GstCaps;
pub fn gst_caps_subtract(minuend: *mut GstCaps, subtrahend: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_caps_normalize(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_simplify(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_fixate(caps: *mut GstCaps) -> *mut GstCaps;
pub fn gst_caps_to_string(caps: *const GstCaps) -> *mut gchar;
pub fn gst_caps_from_string(string: *const gchar) -> *mut GstCaps;
pub fn gst_iterator_get_type() -> GType;
pub fn gst_iterator_new(size: guint, _type: GType, lock: *mut GMutex,
master_cookie: *mut guint32,
copy: GstIteratorCopyFunction,
next: GstIteratorNextFunction,
item: GstIteratorItemFunction,
resync: GstIteratorResyncFunction,
free: GstIteratorFreeFunction)
-> *mut GstIterator;
pub fn gst_iterator_new_list(_type: GType, lock: *mut GMutex,
master_cookie: *mut guint32,
list: *mut *mut GList, owner: *mut GObject,
item: GstIteratorItemFunction)
-> *mut GstIterator;
pub fn gst_iterator_new_single(_type: GType, object: *const GValue)
-> *mut GstIterator;
pub fn gst_iterator_copy(it: *const GstIterator) -> *mut GstIterator;
pub fn gst_iterator_next(it: *mut GstIterator, elem: *mut GValue)
-> GstIteratorResult;
pub fn gst_iterator_resync(it: *mut GstIterator);
pub fn gst_iterator_free(it: *mut GstIterator);
pub fn gst_iterator_push(it: *mut GstIterator, other: *mut GstIterator);
pub fn gst_iterator_filter(it: *mut GstIterator, func: GCompareFunc,
user_data: *const GValue) -> *mut GstIterator;
pub fn gst_iterator_fold(it: *mut GstIterator,
func: GstIteratorFoldFunction, ret: *mut GValue,
user_data: gpointer) -> GstIteratorResult;
pub fn gst_iterator_foreach(it: *mut GstIterator,
func: GstIteratorForeachFunction,
user_data: gpointer) -> GstIteratorResult;
pub fn gst_iterator_find_custom(it: *mut GstIterator, func: GCompareFunc,
elem: *mut GValue, user_data: gpointer)
-> gboolean;
pub fn gst_format_get_name(format: GstFormat) -> *const gchar;
pub fn gst_format_to_quark(format: GstFormat) -> GQuark;
pub fn gst_format_register(nick: *const gchar, description: *const gchar)
-> GstFormat;
pub fn gst_format_get_by_nick(nick: *const gchar) -> GstFormat;
pub fn gst_formats_contains(formats: *const GstFormat, format: GstFormat)
-> gboolean;
pub fn gst_format_get_details(format: GstFormat)
-> *const GstFormatDefinition;
pub fn gst_format_iterate_definitions() -> *mut GstIterator;
pub fn gst_segment_get_type() -> GType;
pub fn gst_segment_new() -> *mut GstSegment;
pub fn gst_segment_copy(segment: *const GstSegment) -> *mut GstSegment;
pub fn gst_segment_copy_into(src: *const GstSegment,
dest: *mut GstSegment);
pub fn gst_segment_free(segment: *mut GstSegment);
pub fn gst_segment_init(segment: *mut GstSegment, format: GstFormat);
pub fn gst_segment_to_stream_time(segment: *const GstSegment,
format: GstFormat, position: guint64)
-> guint64;
pub fn gst_segment_to_running_time(segment: *const GstSegment,
format: GstFormat, position: guint64)
-> guint64;
pub fn gst_segment_to_position(segment: *const GstSegment,
format: GstFormat, running_time: guint64)
-> guint64;
pub fn gst_segment_set_running_time(segment: *mut GstSegment,
format: GstFormat,
running_time: guint64) -> gboolean;
pub fn gst_segment_offset_running_time(segment: *mut GstSegment,
format: GstFormat, offset: gint64)
-> gboolean;
pub fn gst_segment_clip(segment: *const GstSegment, format: GstFormat,
start: guint64, stop: guint64,
clip_start: *mut guint64, clip_stop: *mut guint64)
-> gboolean;
pub fn gst_segment_do_seek(segment: *mut GstSegment, rate: gdouble,
format: GstFormat, flags: GstSeekFlags,
start_type: GstSeekType, start: guint64,
stop_type: GstSeekType, stop: guint64,
update: *mut gboolean) -> gboolean;
pub fn gst_sample_get_type() -> GType;
pub fn gst_sample_new(buffer: *mut GstBuffer, caps: *mut GstCaps,
segment: *const GstSegment, info: *mut GstStructure)
-> *mut GstSample;
pub fn gst_sample_get_buffer(sample: *mut GstSample) -> *mut GstBuffer;
pub fn gst_sample_get_caps(sample: *mut GstSample) -> *mut GstCaps;
pub fn gst_sample_get_segment(sample: *mut GstSample) -> *mut GstSegment;
pub fn gst_sample_get_info(sample: *mut GstSample) -> *const GstStructure;
pub fn gst_tag_list_get_type() -> GType;
pub fn gst_tag_register(name: *const gchar, flag: GstTagFlag,
_type: GType, nick: *const gchar,
blurb: *const gchar, func: GstTagMergeFunc);
pub fn gst_tag_register_static(name: *const gchar, flag: GstTagFlag,
_type: GType, nick: *const gchar,
blurb: *const gchar,
func: GstTagMergeFunc);
pub fn gst_tag_merge_use_first(dest: *mut GValue, src: *const GValue);
pub fn gst_tag_merge_strings_with_comma(dest: *mut GValue,
src: *const GValue);
pub fn gst_tag_exists(tag: *const gchar) -> gboolean;
pub fn gst_tag_get_type(tag: *const gchar) -> GType;
pub fn gst_tag_get_nick(tag: *const gchar) -> *const gchar;
pub fn gst_tag_get_description(tag: *const gchar) -> *const gchar;
pub fn gst_tag_get_flag(tag: *const gchar) -> GstTagFlag;
pub fn gst_tag_is_fixed(tag: *const gchar) -> gboolean;
pub fn gst_tag_list_new_empty() -> *mut GstTagList;
pub fn gst_tag_list_new(tag: *const gchar, ...) -> *mut GstTagList;
pub fn gst_tag_list_new_valist(var_args: va_list) -> *mut GstTagList;
pub fn gst_tag_list_set_scope(list: *mut GstTagList, scope: GstTagScope);
pub fn gst_tag_list_get_scope(list: *const GstTagList) -> GstTagScope;
pub fn gst_tag_list_to_string(list: *const GstTagList) -> *mut gchar;
pub fn gst_tag_list_new_from_string(str: *const gchar) -> *mut GstTagList;
pub fn gst_tag_list_n_tags(list: *const GstTagList) -> gint;
pub fn gst_tag_list_nth_tag_name(list: *const GstTagList, index: guint)
-> *const gchar;
pub fn gst_tag_list_is_empty(list: *const GstTagList) -> gboolean;
pub fn gst_tag_list_is_equal(list1: *const GstTagList,
list2: *const GstTagList) -> gboolean;
pub fn gst_tag_list_insert(into: *mut GstTagList, from: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_tag_list_merge(list1: *const GstTagList,
list2: *const GstTagList, mode: GstTagMergeMode)
-> *mut GstTagList;
pub fn gst_tag_list_get_tag_size(list: *const GstTagList,
tag: *const gchar) -> guint;
pub fn gst_tag_list_add(list: *mut GstTagList, mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_list_add_values(list: *mut GstTagList,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_list_add_valist(list: *mut GstTagList,
mode: GstTagMergeMode, tag: *const gchar,
var_args: va_list);
pub fn gst_tag_list_add_valist_values(list: *mut GstTagList,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_list_add_value(list: *mut GstTagList,
mode: GstTagMergeMode, tag: *const gchar,
value: *const GValue);
pub fn gst_tag_list_remove_tag(list: *mut GstTagList, tag: *const gchar);
pub fn gst_tag_list_foreach(list: *const GstTagList,
func: GstTagForeachFunc, user_data: gpointer);
pub fn gst_tag_list_get_value_index(list: *const GstTagList,
tag: *const gchar, index: guint)
-> *const GValue;
pub fn gst_tag_list_copy_value(dest: *mut GValue, list: *const GstTagList,
tag: *const gchar) -> gboolean;
pub fn gst_tag_list_get_boolean(list: *const GstTagList,
tag: *const gchar, value: *mut gboolean)
-> gboolean;
pub fn gst_tag_list_get_boolean_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gboolean) -> gboolean;
pub fn gst_tag_list_get_int(list: *const GstTagList, tag: *const gchar,
value: *mut gint) -> gboolean;
pub fn gst_tag_list_get_int_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gint) -> gboolean;
pub fn gst_tag_list_get_uint(list: *const GstTagList, tag: *const gchar,
value: *mut guint) -> gboolean;
pub fn gst_tag_list_get_uint_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut guint) -> gboolean;
pub fn gst_tag_list_get_int64(list: *const GstTagList, tag: *const gchar,
value: *mut gint64) -> gboolean;
pub fn gst_tag_list_get_int64_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gint64) -> gboolean;
pub fn gst_tag_list_get_uint64(list: *const GstTagList, tag: *const gchar,
value: *mut guint64) -> gboolean;
pub fn gst_tag_list_get_uint64_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut guint64) -> gboolean;
pub fn gst_tag_list_get_float(list: *const GstTagList, tag: *const gchar,
value: *mut gfloat) -> gboolean;
pub fn gst_tag_list_get_float_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gfloat) -> gboolean;
pub fn gst_tag_list_get_double(list: *const GstTagList, tag: *const gchar,
value: *mut gdouble) -> gboolean;
pub fn gst_tag_list_get_double_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gdouble) -> gboolean;
pub fn gst_tag_list_get_string(list: *const GstTagList, tag: *const gchar,
value: *mut *mut gchar) -> gboolean;
pub fn gst_tag_list_get_string_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut gchar) -> gboolean;
pub fn gst_tag_list_peek_string_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *const gchar)
-> gboolean;
pub fn gst_tag_list_get_pointer(list: *const GstTagList,
tag: *const gchar, value: *mut gpointer)
-> gboolean;
pub fn gst_tag_list_get_pointer_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut gpointer) -> gboolean;
pub fn gst_tag_list_get_date(list: *const GstTagList, tag: *const gchar,
value: *mut *mut GDate) -> gboolean;
pub fn gst_tag_list_get_date_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut GDate) -> gboolean;
pub fn gst_tag_list_get_date_time(list: *const GstTagList,
tag: *const gchar,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_tag_list_get_date_time_index(list: *const GstTagList,
tag: *const gchar, index: guint,
value: *mut *mut GstDateTime)
-> gboolean;
pub fn gst_tag_list_get_sample(list: *const GstTagList, tag: *const gchar,
sample: *mut *mut GstSample) -> gboolean;
pub fn gst_tag_list_get_sample_index(list: *const GstTagList,
tag: *const gchar, index: guint,
sample: *mut *mut GstSample)
-> gboolean;
pub fn gst_toc_get_type() -> GType;
pub fn gst_toc_entry_get_type() -> GType;
pub fn gst_toc_new(scope: GstTocScope) -> *mut GstToc;
pub fn gst_toc_get_scope(toc: *const GstToc) -> GstTocScope;
pub fn gst_toc_set_tags(toc: *mut GstToc, tags: *mut GstTagList);
pub fn gst_toc_merge_tags(toc: *mut GstToc, tags: *mut GstTagList,
mode: GstTagMergeMode);
pub fn gst_toc_get_tags(toc: *const GstToc) -> *mut GstTagList;
pub fn gst_toc_append_entry(toc: *mut GstToc, entry: *mut GstTocEntry);
pub fn gst_toc_get_entries(toc: *const GstToc) -> *mut GList;
pub fn gst_toc_dump(toc: *mut GstToc);
pub fn gst_toc_entry_new(_type: GstTocEntryType, uid: *const gchar)
-> *mut GstTocEntry;
pub fn gst_toc_find_entry(toc: *const GstToc, uid: *const gchar)
-> *mut GstTocEntry;
pub fn gst_toc_entry_get_entry_type(entry: *const GstTocEntry)
-> GstTocEntryType;
pub fn gst_toc_entry_get_uid(entry: *const GstTocEntry) -> *const gchar;
pub fn gst_toc_entry_append_sub_entry(entry: *mut GstTocEntry,
subentry: *mut GstTocEntry);
pub fn gst_toc_entry_get_sub_entries(entry: *const GstTocEntry)
-> *mut GList;
pub fn gst_toc_entry_set_tags(entry: *mut GstTocEntry,
tags: *mut GstTagList);
pub fn gst_toc_entry_merge_tags(entry: *mut GstTocEntry,
tags: *mut GstTagList,
mode: GstTagMergeMode);
pub fn gst_toc_entry_get_tags(entry: *const GstTocEntry)
-> *mut GstTagList;
pub fn gst_toc_entry_is_alternative(entry: *const GstTocEntry)
-> gboolean;
pub fn gst_toc_entry_is_sequence(entry: *const GstTocEntry) -> gboolean;
pub fn gst_toc_entry_set_start_stop_times(entry: *mut GstTocEntry,
start: gint64, stop: gint64);
pub fn gst_toc_entry_get_start_stop_times(entry: *const GstTocEntry,
start: *mut gint64,
stop: *mut gint64) -> gboolean;
pub fn gst_toc_entry_set_loop(entry: *mut GstTocEntry,
loop_type: GstTocLoopType,
repeat_count: gint);
pub fn gst_toc_entry_get_loop(entry: *const GstTocEntry,
loop_type: *mut GstTocLoopType,
repeat_count: *mut gint) -> gboolean;
pub fn gst_toc_entry_get_toc(entry: *mut GstTocEntry) -> *mut GstToc;
pub fn gst_toc_entry_get_parent(entry: *mut GstTocEntry)
-> *mut GstTocEntry;
pub fn gst_toc_entry_type_get_nick(_type: GstTocEntryType)
-> *const gchar;
pub fn gst_context_get_type() -> GType;
pub fn gst_context_new(context_type: *const gchar, persistent: gboolean)
-> *mut GstContext;
pub fn gst_context_get_context_type(context: *const GstContext)
-> *const gchar;
pub fn gst_context_has_context_type(context: *const GstContext,
context_type: *const gchar)
-> gboolean;
pub fn gst_context_get_structure(context: *const GstContext)
-> *const GstStructure;
pub fn gst_context_writable_structure(context: *mut GstContext)
-> *mut GstStructure;
pub fn gst_context_is_persistent(context: *const GstContext) -> gboolean;
pub fn gst_query_type_get_name(_type: GstQueryType) -> *const gchar;
pub fn gst_query_type_to_quark(_type: GstQueryType) -> GQuark;
pub fn gst_query_type_get_flags(_type: GstQueryType) -> GstQueryTypeFlags;
pub fn gst_query_get_type() -> GType;
pub fn gst_query_new_custom(_type: GstQueryType,
structure: *mut GstStructure)
-> *mut GstQuery;
pub fn gst_query_get_structure(query: *mut GstQuery)
-> *const GstStructure;
pub fn gst_query_writable_structure(query: *mut GstQuery)
-> *mut GstStructure;
pub fn gst_query_new_position(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_position(query: *mut GstQuery, format: GstFormat,
cur: gint64);
pub fn gst_query_parse_position(query: *mut GstQuery,
format: *mut GstFormat, cur: *mut gint64);
pub fn gst_query_new_duration(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_duration(query: *mut GstQuery, format: GstFormat,
duration: gint64);
pub fn gst_query_parse_duration(query: *mut GstQuery,
format: *mut GstFormat,
duration: *mut gint64);
pub fn gst_query_new_latency() -> *mut GstQuery;
pub fn gst_query_set_latency(query: *mut GstQuery, live: gboolean,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_query_parse_latency(query: *mut GstQuery, live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_query_new_convert(src_format: GstFormat, value: gint64,
dest_format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_convert(query: *mut GstQuery, src_format: GstFormat,
src_value: gint64, dest_format: GstFormat,
dest_value: gint64);
pub fn gst_query_parse_convert(query: *mut GstQuery,
src_format: *mut GstFormat,
src_value: *mut gint64,
dest_format: *mut GstFormat,
dest_value: *mut gint64);
pub fn gst_query_new_segment(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_segment(query: *mut GstQuery, rate: gdouble,
format: GstFormat, start_value: gint64,
stop_value: gint64);
pub fn gst_query_parse_segment(query: *mut GstQuery, rate: *mut gdouble,
format: *mut GstFormat,
start_value: *mut gint64,
stop_value: *mut gint64);
pub fn gst_query_new_seeking(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_seeking(query: *mut GstQuery, format: GstFormat,
seekable: gboolean, segment_start: gint64,
segment_end: gint64);
pub fn gst_query_parse_seeking(query: *mut GstQuery,
format: *mut GstFormat,
seekable: *mut gboolean,
segment_start: *mut gint64,
segment_end: *mut gint64);
pub fn gst_query_new_formats() -> *mut GstQuery;
pub fn gst_query_set_formats(query: *mut GstQuery, n_formats: gint, ...);
pub fn gst_query_set_formatsv(query: *mut GstQuery, n_formats: gint,
formats: *const GstFormat);
pub fn gst_query_parse_n_formats(query: *mut GstQuery,
n_formats: *mut guint);
pub fn gst_query_parse_nth_format(query: *mut GstQuery, nth: guint,
format: *mut GstFormat);
pub fn gst_query_new_buffering(format: GstFormat) -> *mut GstQuery;
pub fn gst_query_set_buffering_percent(query: *mut GstQuery,
busy: gboolean, percent: gint);
pub fn gst_query_parse_buffering_percent(query: *mut GstQuery,
busy: *mut gboolean,
percent: *mut gint);
pub fn gst_query_set_buffering_stats(query: *mut GstQuery,
mode: GstBufferingMode, avg_in: gint,
avg_out: gint,
buffering_left: gint64);
pub fn gst_query_parse_buffering_stats(query: *mut GstQuery,
mode: *mut GstBufferingMode,
avg_in: *mut gint,
avg_out: *mut gint,
buffering_left: *mut gint64);
pub fn gst_query_set_buffering_range(query: *mut GstQuery,
format: GstFormat, start: gint64,
stop: gint64,
estimated_total: gint64);
pub fn gst_query_parse_buffering_range(query: *mut GstQuery,
format: *mut GstFormat,
start: *mut gint64,
stop: *mut gint64,
estimated_total: *mut gint64);
pub fn gst_query_add_buffering_range(query: *mut GstQuery, start: gint64,
stop: gint64) -> gboolean;
pub fn gst_query_get_n_buffering_ranges(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_buffering_range(query: *mut GstQuery,
index: guint,
start: *mut gint64,
stop: *mut gint64) -> gboolean;
pub fn gst_query_new_uri() -> *mut GstQuery;
pub fn gst_query_parse_uri(query: *mut GstQuery, uri: *mut *mut gchar);
pub fn gst_query_set_uri(query: *mut GstQuery, uri: *const gchar);
pub fn gst_query_parse_uri_redirection(query: *mut GstQuery,
uri: *mut *mut gchar);
pub fn gst_query_set_uri_redirection(query: *mut GstQuery,
uri: *const gchar);
pub fn gst_query_parse_uri_redirection_permanent(query: *mut GstQuery,
permanent:
*mut gboolean);
pub fn gst_query_set_uri_redirection_permanent(query: *mut GstQuery,
permanent: gboolean);
pub fn gst_query_new_allocation(caps: *mut GstCaps, need_pool: gboolean)
-> *mut GstQuery;
pub fn gst_query_parse_allocation(query: *mut GstQuery,
caps: *mut *mut GstCaps,
need_pool: *mut gboolean);
pub fn gst_query_add_allocation_pool(query: *mut GstQuery,
pool: *mut GstBufferPool,
size: guint, min_buffers: guint,
max_buffers: guint);
pub fn gst_query_get_n_allocation_pools(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_pool(query: *mut GstQuery,
index: guint,
pool: *mut *mut GstBufferPool,
size: *mut guint,
min_buffers: *mut guint,
max_buffers: *mut guint);
pub fn gst_query_set_nth_allocation_pool(query: *mut GstQuery,
index: guint,
pool: *mut GstBufferPool,
size: guint, min_buffers: guint,
max_buffers: guint);
pub fn gst_query_remove_nth_allocation_pool(query: *mut GstQuery,
index: guint);
pub fn gst_query_add_allocation_param(query: *mut GstQuery,
allocator: *mut GstAllocator,
params: *const GstAllocationParams);
pub fn gst_query_get_n_allocation_params(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_param(query: *mut GstQuery,
index: guint,
allocator:
*mut *mut GstAllocator,
params:
*mut GstAllocationParams);
pub fn gst_query_set_nth_allocation_param(query: *mut GstQuery,
index: guint,
allocator: *mut GstAllocator,
params:
*const GstAllocationParams);
pub fn gst_query_remove_nth_allocation_param(query: *mut GstQuery,
index: guint);
pub fn gst_query_add_allocation_meta(query: *mut GstQuery, api: GType,
params: *const GstStructure);
pub fn gst_query_get_n_allocation_metas(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_allocation_meta(query: *mut GstQuery,
index: guint,
params:
*mut *const GstStructure)
-> GType;
pub fn gst_query_remove_nth_allocation_meta(query: *mut GstQuery,
index: guint);
pub fn gst_query_find_allocation_meta(query: *mut GstQuery, api: GType,
index: *mut guint) -> gboolean;
pub fn gst_query_new_scheduling() -> *mut GstQuery;
pub fn gst_query_set_scheduling(query: *mut GstQuery,
flags: GstSchedulingFlags, minsize: gint,
maxsize: gint, align: gint);
pub fn gst_query_parse_scheduling(query: *mut GstQuery,
flags: *mut GstSchedulingFlags,
minsize: *mut gint, maxsize: *mut gint,
align: *mut gint);
pub fn gst_query_add_scheduling_mode(query: *mut GstQuery,
mode: GstPadMode);
pub fn gst_query_get_n_scheduling_modes(query: *mut GstQuery) -> guint;
pub fn gst_query_parse_nth_scheduling_mode(query: *mut GstQuery,
index: guint) -> GstPadMode;
pub fn gst_query_has_scheduling_mode(query: *mut GstQuery,
mode: GstPadMode) -> gboolean;
pub fn gst_query_has_scheduling_mode_with_flags(query: *mut GstQuery,
mode: GstPadMode,
flags: GstSchedulingFlags)
-> gboolean;
pub fn gst_query_new_accept_caps(caps: *mut GstCaps) -> *mut GstQuery;
pub fn gst_query_parse_accept_caps(query: *mut GstQuery,
caps: *mut *mut GstCaps);
pub fn gst_query_set_accept_caps_result(query: *mut GstQuery,
result: gboolean);
pub fn gst_query_parse_accept_caps_result(query: *mut GstQuery,
result: *mut gboolean);
pub fn gst_query_new_caps(filter: *mut GstCaps) -> *mut GstQuery;
pub fn gst_query_parse_caps(query: *mut GstQuery,
filter: *mut *mut GstCaps);
pub fn gst_query_set_caps_result(query: *mut GstQuery,
caps: *mut GstCaps);
pub fn gst_query_parse_caps_result(query: *mut GstQuery,
caps: *mut *mut GstCaps);
pub fn gst_query_new_drain() -> *mut GstQuery;
pub fn gst_query_new_context(context_type: *const gchar) -> *mut GstQuery;
pub fn gst_query_parse_context_type(query: *mut GstQuery,
context_type: *mut *const gchar)
-> gboolean;
pub fn gst_query_set_context(query: *mut GstQuery,
context: *mut GstContext);
pub fn gst_query_parse_context(query: *mut GstQuery,
context: *mut *mut GstContext);
pub fn gst_device_get_type() -> GType;
pub fn gst_device_create_element(device: *mut GstDevice,
name: *const gchar) -> *mut GstElement;
pub fn gst_device_get_caps(device: *mut GstDevice) -> *mut GstCaps;
pub fn gst_device_get_display_name(device: *mut GstDevice) -> *mut gchar;
pub fn gst_device_get_device_class(device: *mut GstDevice) -> *mut gchar;
pub fn gst_device_reconfigure_element(device: *mut GstDevice,
element: *mut GstElement)
-> gboolean;
pub fn gst_device_has_classesv(device: *mut GstDevice,
classes: *mut *mut gchar) -> gboolean;
pub fn gst_device_has_classes(device: *mut GstDevice,
classes: *const gchar) -> gboolean;
pub fn gst_message_get_type() -> GType;
pub fn gst_message_type_get_name(_type: GstMessageType) -> *const gchar;
pub fn gst_message_type_to_quark(_type: GstMessageType) -> GQuark;
pub fn gst_message_new_custom(_type: GstMessageType, src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_get_structure(message: *mut GstMessage)
-> *const GstStructure;
pub fn gst_message_has_name(message: *mut GstMessage, name: *const gchar)
-> gboolean;
pub fn gst_message_get_seqnum(message: *mut GstMessage) -> guint32;
pub fn gst_message_set_seqnum(message: *mut GstMessage, seqnum: guint32);
pub fn gst_message_new_eos(src: *mut GstObject) -> *mut GstMessage;
pub fn gst_message_new_error(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_error(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_warning(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_warning(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_info(src: *mut GstObject, error: *mut GError,
debug: *const gchar) -> *mut GstMessage;
pub fn gst_message_parse_info(message: *mut GstMessage,
gerror: *mut *mut GError,
debug: *mut *mut gchar);
pub fn gst_message_new_tag(src: *mut GstObject, tag_list: *mut GstTagList)
-> *mut GstMessage;
pub fn gst_message_parse_tag(message: *mut GstMessage,
tag_list: *mut *mut GstTagList);
pub fn gst_message_new_buffering(src: *mut GstObject, percent: gint)
-> *mut GstMessage;
pub fn gst_message_parse_buffering(message: *mut GstMessage,
percent: *mut gint);
pub fn gst_message_set_buffering_stats(message: *mut GstMessage,
mode: GstBufferingMode,
avg_in: gint, avg_out: gint,
buffering_left: gint64);
pub fn gst_message_parse_buffering_stats(message: *mut GstMessage,
mode: *mut GstBufferingMode,
avg_in: *mut gint,
avg_out: *mut gint,
buffering_left: *mut gint64);
pub fn gst_message_new_state_changed(src: *mut GstObject,
oldstate: GstState,
newstate: GstState,
pending: GstState)
-> *mut GstMessage;
pub fn gst_message_parse_state_changed(message: *mut GstMessage,
oldstate: *mut GstState,
newstate: *mut GstState,
pending: *mut GstState);
pub fn gst_message_new_state_dirty(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_step_done(src: *mut GstObject, format: GstFormat,
amount: guint64, rate: gdouble,
flush: gboolean, intermediate: gboolean,
duration: guint64, eos: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_step_done(message: *mut GstMessage,
format: *mut GstFormat,
amount: *mut guint64,
rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean,
duration: *mut guint64,
eos: *mut gboolean);
pub fn gst_message_new_clock_provide(src: *mut GstObject,
clock: *mut GstClock,
ready: gboolean) -> *mut GstMessage;
pub fn gst_message_parse_clock_provide(message: *mut GstMessage,
clock: *mut *mut GstClock,
ready: *mut gboolean);
pub fn gst_message_new_clock_lost(src: *mut GstObject,
clock: *mut GstClock)
-> *mut GstMessage;
pub fn gst_message_parse_clock_lost(message: *mut GstMessage,
clock: *mut *mut GstClock);
pub fn gst_message_new_new_clock(src: *mut GstObject,
clock: *mut GstClock) -> *mut GstMessage;
pub fn gst_message_parse_new_clock(message: *mut GstMessage,
clock: *mut *mut GstClock);
pub fn gst_message_new_application(src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_new_element(src: *mut GstObject,
structure: *mut GstStructure)
-> *mut GstMessage;
pub fn gst_message_new_segment_start(src: *mut GstObject,
format: GstFormat, position: gint64)
-> *mut GstMessage;
pub fn gst_message_parse_segment_start(message: *mut GstMessage,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_message_new_segment_done(src: *mut GstObject,
format: GstFormat, position: gint64)
-> *mut GstMessage;
pub fn gst_message_parse_segment_done(message: *mut GstMessage,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_message_new_duration_changed(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_latency(src: *mut GstObject) -> *mut GstMessage;
pub fn gst_message_new_async_start(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_new_async_done(src: *mut GstObject,
running_time: GstClockTime)
-> *mut GstMessage;
pub fn gst_message_parse_async_done(message: *mut GstMessage,
running_time: *mut GstClockTime);
pub fn gst_message_new_structure_change(src: *mut GstObject,
_type: GstStructureChangeType,
owner: *mut GstElement,
busy: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_structure_change(message: *mut GstMessage,
_type:
*mut GstStructureChangeType,
owner: *mut *mut GstElement,
busy: *mut gboolean);
pub fn gst_message_new_stream_status(src: *mut GstObject,
_type: GstStreamStatusType,
owner: *mut GstElement)
-> *mut GstMessage;
pub fn gst_message_parse_stream_status(message: *mut GstMessage,
_type: *mut GstStreamStatusType,
owner: *mut *mut GstElement);
pub fn gst_message_set_stream_status_object(message: *mut GstMessage,
object: *const GValue);
pub fn gst_message_get_stream_status_object(message: *mut GstMessage)
-> *const GValue;
pub fn gst_message_new_request_state(src: *mut GstObject, state: GstState)
-> *mut GstMessage;
pub fn gst_message_parse_request_state(message: *mut GstMessage,
state: *mut GstState);
pub fn gst_message_new_step_start(src: *mut GstObject, active: gboolean,
format: GstFormat, amount: guint64,
rate: gdouble, flush: gboolean,
intermediate: gboolean)
-> *mut GstMessage;
pub fn gst_message_parse_step_start(message: *mut GstMessage,
active: *mut gboolean,
format: *mut GstFormat,
amount: *mut guint64,
rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean);
pub fn gst_message_new_qos(src: *mut GstObject, live: gboolean,
running_time: guint64, stream_time: guint64,
timestamp: guint64, duration: guint64)
-> *mut GstMessage;
pub fn gst_message_copy (msg: *const GstMessage) -> *mut GstMessage;
pub fn gst_message_set_qos_values(message: *mut GstMessage,
jitter: gint64, proportion: gdouble,
quality: gint);
pub fn gst_message_set_qos_stats(message: *mut GstMessage,
format: GstFormat, processed: guint64,
dropped: guint64);
pub fn gst_message_parse_qos(message: *mut GstMessage,
live: *mut gboolean,
running_time: *mut guint64,
stream_time: *mut guint64,
timestamp: *mut guint64,
duration: *mut guint64);
pub fn gst_message_parse_qos_values(message: *mut GstMessage,
jitter: *mut gint64,
proportion: *mut gdouble,
quality: *mut gint);
pub fn gst_message_parse_qos_stats(message: *mut GstMessage,
format: *mut GstFormat,
processed: *mut guint64,
dropped: *mut guint64);
pub fn gst_message_new_progress(src: *mut GstObject,
_type: GstProgressType,
code: *const gchar, text: *const gchar)
-> *mut GstMessage;
pub fn gst_message_parse_progress(message: *mut GstMessage,
_type: *mut GstProgressType,
code: *mut *mut gchar,
text: *mut *mut gchar);
pub fn gst_message_new_toc(src: *mut GstObject, toc: *mut GstToc,
updated: gboolean) -> *mut GstMessage;
pub fn gst_message_parse_toc(message: *mut GstMessage,
toc: *mut *mut GstToc,
updated: *mut gboolean);
pub fn gst_message_new_reset_time(src: *mut GstObject,
running_time: GstClockTime)
-> *mut GstMessage;
pub fn gst_message_parse_reset_time(message: *mut GstMessage,
running_time: *mut GstClockTime);
pub fn gst_message_new_stream_start(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_message_set_group_id(message: *mut GstMessage,
group_id: guint);
pub fn gst_message_parse_group_id(message: *mut GstMessage,
group_id: *mut guint) -> gboolean;
pub fn gst_message_new_need_context(src: *mut GstObject,
context_type: *const gchar)
-> *mut GstMessage;
pub fn gst_message_parse_context_type(message: *mut GstMessage,
context_type: *mut *const gchar)
-> gboolean;
pub fn gst_message_new_have_context(src: *mut GstObject,
context: *mut GstContext)
-> *mut GstMessage;
pub fn gst_message_parse_have_context(message: *mut GstMessage,
context: *mut *mut GstContext);
pub fn gst_message_new_device_added(src: *mut GstObject,
device: *mut GstDevice)
-> *mut GstMessage;
pub fn gst_message_parse_device_added(message: *mut GstMessage,
device: *mut *mut GstDevice);
pub fn gst_message_new_device_removed(src: *mut GstObject,
device: *mut GstDevice)
-> *mut GstMessage;
pub fn gst_message_parse_device_removed(message: *mut GstMessage,
device: *mut *mut GstDevice);
pub fn gst_event_type_get_name(_type: GstEventType) -> *const gchar;
pub fn gst_event_type_to_quark(_type: GstEventType) -> GQuark;
pub fn gst_event_type_get_flags(_type: GstEventType) -> GstEventTypeFlags;
pub fn gst_event_get_type() -> GType;
pub fn gst_event_new_custom(_type: GstEventType,
structure: *mut GstStructure)
-> *mut GstEvent;
pub fn gst_event_get_structure(event: *mut GstEvent)
-> *const GstStructure;
pub fn gst_event_writable_structure(event: *mut GstEvent)
-> *mut GstStructure;
pub fn gst_event_has_name(event: *mut GstEvent, name: *const gchar)
-> gboolean;
pub fn gst_event_get_seqnum(event: *mut GstEvent) -> guint32;
pub fn gst_event_set_seqnum(event: *mut GstEvent, seqnum: guint32);
pub fn gst_event_get_running_time_offset(event: *mut GstEvent) -> gint64;
pub fn gst_event_set_running_time_offset(event: *mut GstEvent,
offset: gint64);
pub fn gst_event_new_stream_start(stream_id: *const gchar)
-> *mut GstEvent;
pub fn gst_event_parse_stream_start(event: *mut GstEvent,
stream_id: *mut *const gchar);
pub fn gst_event_set_stream_flags(event: *mut GstEvent,
flags: GstStreamFlags);
pub fn gst_event_parse_stream_flags(event: *mut GstEvent,
flags: *mut GstStreamFlags);
pub fn gst_event_set_group_id(event: *mut GstEvent, group_id: guint);
pub fn gst_event_parse_group_id(event: *mut GstEvent,
group_id: *mut guint) -> gboolean;
pub fn gst_event_new_flush_start() -> *mut GstEvent;
pub fn gst_event_new_flush_stop(reset_time: gboolean) -> *mut GstEvent;
pub fn gst_event_parse_flush_stop(event: *mut GstEvent,
reset_time: *mut gboolean);
pub fn gst_event_new_eos() -> *mut GstEvent;
pub fn gst_event_new_gap(timestamp: GstClockTime, duration: GstClockTime)
-> *mut GstEvent;
pub fn gst_event_parse_gap(event: *mut GstEvent,
timestamp: *mut GstClockTime,
duration: *mut GstClockTime);
pub fn gst_event_new_caps(caps: *mut GstCaps) -> *mut GstEvent;
pub fn gst_event_parse_caps(event: *mut GstEvent,
caps: *mut *mut GstCaps);
pub fn gst_event_new_segment(segment: *const GstSegment) -> *mut GstEvent;
pub fn gst_event_parse_segment(event: *mut GstEvent,
segment: *mut *const GstSegment);
pub fn gst_event_copy_segment(event: *mut GstEvent,
segment: *mut GstSegment);
pub fn gst_event_new_tag(taglist: *mut GstTagList) -> *mut GstEvent;
pub fn gst_event_parse_tag(event: *mut GstEvent,
taglist: *mut *mut GstTagList);
pub fn gst_event_new_toc(toc: *mut GstToc, updated: gboolean)
-> *mut GstEvent;
pub fn gst_event_parse_toc(event: *mut GstEvent, toc: *mut *mut GstToc,
updated: *mut gboolean);
pub fn gst_event_new_buffer_size(format: GstFormat, minsize: gint64,
maxsize: gint64, async: gboolean)
-> *mut GstEvent;
pub fn gst_event_parse_buffer_size(event: *mut GstEvent,
format: *mut GstFormat,
minsize: *mut gint64,
maxsize: *mut gint64,
async: *mut gboolean);
pub fn gst_event_new_sink_message(name: *const gchar,
msg: *mut GstMessage) -> *mut GstEvent;
pub fn gst_event_parse_sink_message(event: *mut GstEvent,
msg: *mut *mut GstMessage);
pub fn gst_event_new_qos(_type: GstQOSType, proportion: gdouble,
diff: GstClockTimeDiff, timestamp: GstClockTime)
-> *mut GstEvent;
pub fn gst_event_parse_qos(event: *mut GstEvent, _type: *mut GstQOSType,
proportion: *mut gdouble,
diff: *mut GstClockTimeDiff,
timestamp: *mut GstClockTime);
pub fn gst_event_new_seek(rate: gdouble, format: GstFormat,
flags: GstSeekFlags, start_type: GstSeekType,
start: gint64, stop_type: GstSeekType,
stop: gint64) -> *mut GstEvent;
pub fn gst_event_parse_seek(event: *mut GstEvent, rate: *mut gdouble,
format: *mut GstFormat,
flags: *mut GstSeekFlags,
start_type: *mut GstSeekType,
start: *mut gint64,
stop_type: *mut GstSeekType,
stop: *mut gint64);
pub fn gst_event_new_navigation(structure: *mut GstStructure)
-> *mut GstEvent;
pub fn gst_event_new_latency(latency: GstClockTime) -> *mut GstEvent;
pub fn gst_event_parse_latency(event: *mut GstEvent,
latency: *mut GstClockTime);
pub fn gst_event_new_step(format: GstFormat, amount: guint64,
rate: gdouble, flush: gboolean,
intermediate: gboolean) -> *mut GstEvent;
pub fn gst_event_parse_step(event: *mut GstEvent, format: *mut GstFormat,
amount: *mut guint64, rate: *mut gdouble,
flush: *mut gboolean,
intermediate: *mut gboolean);
pub fn gst_event_new_reconfigure() -> *mut GstEvent;
pub fn gst_event_new_toc_select(uid: *const gchar) -> *mut GstEvent;
pub fn gst_event_parse_toc_select(event: *mut GstEvent,
uid: *mut *mut gchar);
pub fn gst_event_new_segment_done(format: GstFormat, position: gint64)
-> *mut GstEvent;
pub fn gst_event_parse_segment_done(event: *mut GstEvent,
format: *mut GstFormat,
position: *mut gint64);
pub fn gst_task_pool_get_type() -> GType;
pub fn gst_task_pool_new() -> *mut GstTaskPool;
pub fn gst_task_pool_prepare(pool: *mut GstTaskPool,
error: *mut *mut GError);
pub fn gst_task_pool_push(pool: *mut GstTaskPool,
func: GstTaskPoolFunction, user_data: gpointer,
error: *mut *mut GError) -> gpointer;
pub fn gst_task_pool_join(pool: *mut GstTaskPool, id: gpointer);
pub fn gst_task_pool_cleanup(pool: *mut GstTaskPool);
pub fn gst_task_cleanup_all();
pub fn gst_task_get_type() -> GType;
pub fn gst_task_new(func: GstTaskFunction, user_data: gpointer,
notify: GDestroyNotify) -> *mut GstTask;
pub fn gst_task_set_lock(task: *mut GstTask, mutex: *mut GRecMutex);
pub fn gst_task_get_pool(task: *mut GstTask) -> *mut GstTaskPool;
pub fn gst_task_set_pool(task: *mut GstTask, pool: *mut GstTaskPool);
pub fn gst_task_set_enter_callback(task: *mut GstTask,
enter_func: GstTaskThreadFunc,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_task_set_leave_callback(task: *mut GstTask,
leave_func: GstTaskThreadFunc,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_task_get_state(task: *mut GstTask) -> GstTaskState;
pub fn gst_task_set_state(task: *mut GstTask, state: GstTaskState)
-> gboolean;
pub fn gst_task_start(task: *mut GstTask) -> gboolean;
pub fn gst_task_stop(task: *mut GstTask) -> gboolean;
pub fn gst_task_pause(task: *mut GstTask) -> gboolean;
pub fn gst_task_join(task: *mut GstTask) -> gboolean;
pub fn gst_pad_template_get_type() -> GType;
pub fn gst_static_pad_template_get_type() -> GType;
pub fn gst_pad_template_new(name_template: *const gchar,
direction: GstPadDirection,
presence: GstPadPresence, caps: *mut GstCaps)
-> *mut GstPadTemplate;
pub fn gst_static_pad_template_get(pad_template:
*mut GstStaticPadTemplate)
-> *mut GstPadTemplate;
pub fn gst_static_pad_template_get_caps(templ: *mut GstStaticPadTemplate)
-> *mut GstCaps;
pub fn gst_pad_template_get_caps(templ: *mut GstPadTemplate)
-> *mut GstCaps;
pub fn gst_pad_template_pad_created(templ: *mut GstPadTemplate,
pad: *mut GstPad);
pub fn gst_flow_get_name(ret: GstFlowReturn) -> *const gchar;
pub fn gst_flow_to_quark(ret: GstFlowReturn) -> GQuark;
pub fn gst_pad_link_get_name(ret: GstPadLinkReturn) -> *const gchar;
pub fn gst_pad_probe_info_get_event(info: *mut GstPadProbeInfo)
-> *mut GstEvent;
pub fn gst_pad_probe_info_get_query(info: *mut GstPadProbeInfo)
-> *mut GstQuery;
pub fn gst_pad_probe_info_get_buffer(info: *mut GstPadProbeInfo)
-> *mut GstBuffer;
pub fn gst_pad_probe_info_get_buffer_list(info: *mut GstPadProbeInfo)
-> *mut GstBufferList;
pub fn gst_pad_get_type() -> GType;
pub fn gst_pad_new(name: *const gchar, direction: GstPadDirection)
-> *mut GstPad;
pub fn gst_pad_new_from_template(templ: *mut GstPadTemplate,
name: *const gchar) -> *mut GstPad;
pub fn gst_pad_new_from_static_template(templ: *mut GstStaticPadTemplate,
name: *const gchar)
-> *mut GstPad;
pub fn gst_pad_get_direction(pad: *mut GstPad) -> GstPadDirection;
pub fn gst_pad_set_active(pad: *mut GstPad, active: gboolean) -> gboolean;
pub fn gst_pad_is_active(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_activate_mode(pad: *mut GstPad, mode: GstPadMode,
active: gboolean) -> gboolean;
pub fn gst_pad_add_probe(pad: *mut GstPad, mask: GstPadProbeType,
callback: GstPadProbeCallback,
user_data: gpointer,
destroy_data: GDestroyNotify) -> gulong;
pub fn gst_pad_remove_probe(pad: *mut GstPad, id: gulong);
pub fn gst_pad_is_blocked(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_is_blocking(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_mark_reconfigure(pad: *mut GstPad);
pub fn gst_pad_needs_reconfigure(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_check_reconfigure(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_set_element_private(pad: *mut GstPad, _priv: gpointer);
pub fn gst_pad_get_element_private(pad: *mut GstPad) -> gpointer;
pub fn gst_pad_get_pad_template(pad: *mut GstPad) -> *mut GstPadTemplate;
pub fn gst_pad_store_sticky_event(pad: *mut GstPad, event: *mut GstEvent)
-> GstFlowReturn;
pub fn gst_pad_get_sticky_event(pad: *mut GstPad,
event_type: GstEventType, idx: guint)
-> *mut GstEvent;
pub fn gst_pad_sticky_events_foreach(pad: *mut GstPad,
foreach_func:
GstPadStickyEventsForeachFunction,
user_data: gpointer);
pub fn gst_pad_set_activate_function_full(pad: *mut GstPad,
activate:
GstPadActivateFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_activatemode_function_full(pad: *mut GstPad,
activatemode:
GstPadActivateModeFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_chain_function_full(pad: *mut GstPad,
chain: GstPadChainFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_chain_list_function_full(pad: *mut GstPad,
chainlist:
GstPadChainListFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_getrange_function_full(pad: *mut GstPad,
get: GstPadGetRangeFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_event_function_full(pad: *mut GstPad,
event: GstPadEventFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_link_function_full(pad: *mut GstPad,
link: GstPadLinkFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_set_unlink_function_full(pad: *mut GstPad,
unlink: GstPadUnlinkFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_can_link(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> gboolean;
pub fn gst_pad_link(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> GstPadLinkReturn;
pub fn gst_pad_link_full(srcpad: *mut GstPad, sinkpad: *mut GstPad,
flags: GstPadLinkCheck) -> GstPadLinkReturn;
pub fn gst_pad_unlink(srcpad: *mut GstPad, sinkpad: *mut GstPad)
-> gboolean;
pub fn gst_pad_is_linked(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_get_peer(pad: *mut GstPad) -> *mut GstPad;
pub fn gst_pad_get_pad_template_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_get_current_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_has_current_caps(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_get_allowed_caps(pad: *mut GstPad) -> *mut GstCaps;
pub fn gst_pad_get_offset(pad: *mut GstPad) -> gint64;
pub fn gst_pad_set_offset(pad: *mut GstPad, offset: gint64);
pub fn gst_pad_push(pad: *mut GstPad, buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_pad_push_list(pad: *mut GstPad, list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_pad_pull_range(pad: *mut GstPad, offset: guint64, size: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn;
pub fn gst_pad_push_event(pad: *mut GstPad, event: *mut GstEvent)
-> gboolean;
pub fn gst_pad_event_default(pad: *mut GstPad, parent: *mut GstObject,
event: *mut GstEvent) -> gboolean;
pub fn gst_pad_get_last_flow_return(pad: *mut GstPad) -> GstFlowReturn;
pub fn gst_pad_chain(pad: *mut GstPad, buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_pad_chain_list(pad: *mut GstPad, list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_pad_get_range(pad: *mut GstPad, offset: guint64, size: guint,
buffer: *mut *mut GstBuffer) -> GstFlowReturn;
pub fn gst_pad_send_event(pad: *mut GstPad, event: *mut GstEvent)
-> gboolean;
pub fn gst_pad_start_task(pad: *mut GstPad, func: GstTaskFunction,
user_data: gpointer, notify: GDestroyNotify)
-> gboolean;
pub fn gst_pad_pause_task(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_stop_task(pad: *mut GstPad) -> gboolean;
pub fn gst_pad_set_iterate_internal_links_function_full(pad: *mut GstPad,
iterintlink:
GstPadIterIntLinkFunction,
user_data:
gpointer,
notify:
GDestroyNotify);
pub fn gst_pad_iterate_internal_links(pad: *mut GstPad)
-> *mut GstIterator;
pub fn gst_pad_iterate_internal_links_default(pad: *mut GstPad,
parent: *mut GstObject)
-> *mut GstIterator;
pub fn gst_pad_query(pad: *mut GstPad, query: *mut GstQuery) -> gboolean;
pub fn gst_pad_peer_query(pad: *mut GstPad, query: *mut GstQuery)
-> gboolean;
pub fn gst_pad_set_query_function_full(pad: *mut GstPad,
query: GstPadQueryFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_pad_query_default(pad: *mut GstPad, parent: *mut GstObject,
query: *mut GstQuery) -> gboolean;
pub fn gst_pad_forward(pad: *mut GstPad, forward: GstPadForwardFunction,
user_data: gpointer) -> gboolean;
pub fn gst_bus_get_type() -> GType;
pub fn gst_bus_new() -> *mut GstBus;
pub fn gst_bus_post(bus: *mut GstBus, message: *mut GstMessage)
-> gboolean;
pub fn gst_bus_have_pending(bus: *mut GstBus) -> gboolean;
pub fn gst_bus_peek(bus: *mut GstBus) -> *mut GstMessage;
pub fn gst_bus_pop(bus: *mut GstBus) -> *mut GstMessage;
pub fn gst_bus_pop_filtered(bus: *mut GstBus, types: GstMessageType)
-> *mut GstMessage;
pub fn gst_bus_timed_pop(bus: *mut GstBus, timeout: GstClockTime)
-> *mut GstMessage;
pub fn gst_bus_timed_pop_filtered(bus: *mut GstBus, timeout: GstClockTime,
types: GstMessageType)
-> *mut GstMessage;
pub fn gst_bus_set_flushing(bus: *mut GstBus, flushing: gboolean);
pub fn gst_bus_set_sync_handler(bus: *mut GstBus, func: GstBusSyncHandler,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_bus_create_watch(bus: *mut GstBus) -> *mut GSource;
pub fn gst_bus_add_watch_full(bus: *mut GstBus, priority: gint,
func: GstBusFunc, user_data: gpointer,
notify: GDestroyNotify) -> guint;
pub fn gst_bus_add_watch(bus: *mut GstBus, func: GstBusFunc,
user_data: gpointer) -> guint;
pub fn gst_bus_poll(bus: *mut GstBus, events: GstMessageType,
timeout: GstClockTime) -> *mut GstMessage;
pub fn gst_bus_async_signal_func(bus: *mut GstBus,
message: *mut GstMessage, data: gpointer)
-> gboolean;
pub fn gst_bus_sync_signal_handler(bus: *mut GstBus,
message: *mut GstMessage,
data: gpointer) -> GstBusSyncReply;
pub fn gst_bus_add_signal_watch(bus: *mut GstBus);
pub fn gst_bus_add_signal_watch_full(bus: *mut GstBus, priority: gint);
pub fn gst_bus_remove_signal_watch(bus: *mut GstBus);
pub fn gst_bus_enable_sync_message_emission(bus: *mut GstBus);
pub fn gst_bus_disable_sync_message_emission(bus: *mut GstBus);
pub fn gst_plugin_error_quark() -> GQuark;
pub fn gst_plugin_get_type() -> GType;
pub fn gst_plugin_register_static(major_version: gint,
minor_version: gint, name: *const gchar,
description: *const gchar,
init_func: GstPluginInitFunc,
version: *const gchar,
license: *const gchar,
source: *const gchar,
package: *const gchar,
origin: *const gchar) -> gboolean;
pub fn gst_plugin_register_static_full(major_version: gint,
minor_version: gint,
name: *const gchar,
description: *const gchar,
init_full_func:
GstPluginInitFullFunc,
version: *const gchar,
license: *const gchar,
source: *const gchar,
package: *const gchar,
origin: *const gchar,
user_data: gpointer) -> gboolean;
pub fn gst_plugin_get_name(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_description(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_filename(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_version(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_license(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_source(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_package(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_origin(plugin: *mut GstPlugin) -> *const gchar;
pub fn gst_plugin_get_release_date_string(plugin: *mut GstPlugin)
-> *const gchar;
pub fn gst_plugin_get_cache_data(plugin: *mut GstPlugin)
-> *const GstStructure;
pub fn gst_plugin_set_cache_data(plugin: *mut GstPlugin,
cache_data: *mut GstStructure);
pub fn gst_plugin_is_loaded(plugin: *mut GstPlugin) -> gboolean;
pub fn gst_plugin_load_file(filename: *const gchar,
error: *mut *mut GError) -> *mut GstPlugin;
pub fn gst_plugin_load(plugin: *mut GstPlugin) -> *mut GstPlugin;
pub fn gst_plugin_load_by_name(name: *const gchar) -> *mut GstPlugin;
pub fn gst_plugin_add_dependency(plugin: *mut GstPlugin,
env_vars: *mut *const gchar,
paths: *mut *const gchar,
names: *mut *const gchar,
flags: GstPluginDependencyFlags);
pub fn gst_plugin_add_dependency_simple(plugin: *mut GstPlugin,
env_vars: *const gchar,
paths: *const gchar,
names: *const gchar,
flags: GstPluginDependencyFlags);
pub fn gst_plugin_list_free(list: *mut GList);
pub fn gst_plugin_feature_get_type() -> GType;
pub fn gst_plugin_feature_load(feature: *mut GstPluginFeature)
-> *mut GstPluginFeature;
pub fn gst_plugin_feature_set_rank(feature: *mut GstPluginFeature,
rank: guint);
pub fn gst_plugin_feature_get_rank(feature: *mut GstPluginFeature)
-> guint;
pub fn gst_plugin_feature_get_plugin(feature: *mut GstPluginFeature)
-> *mut GstPlugin;
pub fn gst_plugin_feature_get_plugin_name(feature: *mut GstPluginFeature)
-> *const gchar;
pub fn gst_plugin_feature_list_free(list: *mut GList);
pub fn gst_plugin_feature_list_copy(list: *mut GList) -> *mut GList;
pub fn gst_plugin_feature_list_debug(list: *mut GList);
pub fn gst_plugin_feature_check_version(feature: *mut GstPluginFeature,
min_major: guint,
min_minor: guint,
min_micro: guint) -> gboolean;
pub fn gst_plugin_feature_rank_compare_func(p1: gconstpointer,
p2: gconstpointer) -> gint;
pub fn gst_uri_error_quark() -> GQuark;
pub fn gst_uri_protocol_is_valid(protocol: *const gchar) -> gboolean;
pub fn gst_uri_protocol_is_supported(_type: GstURIType,
protocol: *const gchar) -> gboolean;
pub fn gst_uri_is_valid(uri: *const gchar) -> gboolean;
pub fn gst_uri_get_protocol(uri: *const gchar) -> *mut gchar;
pub fn gst_uri_has_protocol(uri: *const gchar, protocol: *const gchar)
-> gboolean;
pub fn gst_uri_get_location(uri: *const gchar) -> *mut gchar;
pub fn gst_uri_construct(protocol: *const gchar, location: *const gchar)
-> *mut gchar;
pub fn gst_filename_to_uri(filename: *const gchar,
error: *mut *mut GError) -> *mut gchar;
pub fn gst_element_make_from_uri(_type: GstURIType, uri: *const gchar,
elementname: *const gchar,
error: *mut *mut GError)
-> *mut GstElement;
pub fn gst_uri_handler_get_type() -> GType;
pub fn gst_uri_handler_get_uri_type(handler: *mut GstURIHandler)
-> GstURIType;
pub fn gst_uri_handler_get_protocols(handler: *mut GstURIHandler)
-> *const *const gchar;
pub fn gst_uri_handler_get_uri(handler: *mut GstURIHandler) -> *mut gchar;
pub fn gst_uri_handler_set_uri(handler: *mut GstURIHandler,
uri: *const gchar, error: *mut *mut GError)
-> gboolean;
pub fn gst_element_factory_get_type() -> GType;
pub fn gst_element_factory_find(name: *const gchar)
-> *mut GstElementFactory;
pub fn gst_element_factory_get_element_type(factory:
*mut GstElementFactory)
-> GType;
pub fn gst_element_factory_get_metadata(factory: *mut GstElementFactory,
key: *const gchar)
-> *const gchar;
pub fn gst_element_factory_get_metadata_keys(factory:
*mut GstElementFactory)
-> *mut *mut gchar;
pub fn gst_element_factory_get_num_pad_templates(factory:
*mut GstElementFactory)
-> guint;
pub fn gst_element_factory_get_static_pad_templates(factory:
*mut GstElementFactory)
-> *const GList;
pub fn gst_element_factory_get_uri_type(factory: *mut GstElementFactory)
-> GstURIType;
pub fn gst_element_factory_get_uri_protocols(factory:
*mut GstElementFactory)
-> *const *const gchar;
pub fn gst_element_factory_has_interface(factory: *mut GstElementFactory,
interfacename: *const gchar)
-> gboolean;
pub fn gst_element_factory_create(factory: *mut GstElementFactory,
name: *const gchar) -> *mut GstElement;
pub fn gst_element_factory_make(factoryname: *const gchar,
name: *const gchar) -> *mut GstElement;
pub fn gst_element_register(plugin: *mut GstPlugin, name: *const gchar,
rank: guint, _type: GType) -> gboolean;
pub fn gst_element_factory_list_is_type(factory: *mut GstElementFactory,
_type: GstElementFactoryListType)
-> gboolean;
pub fn gst_element_factory_list_get_elements(_type:
GstElementFactoryListType,
minrank: GstRank)
-> *mut GList;
pub fn gst_element_factory_list_filter(list: *mut GList,
caps: *const GstCaps,
direction: GstPadDirection,
subsetonly: gboolean)
-> *mut GList;
pub fn gst_element_class_add_pad_template(klass: *mut GstElementClass,
templ: *mut GstPadTemplate);
pub fn gst_element_class_get_pad_template(element_class:
*mut GstElementClass,
name: *const gchar)
-> *mut GstPadTemplate;
pub fn gst_element_class_get_pad_template_list(element_class:
*mut GstElementClass)
-> *mut GList;
pub fn gst_element_class_set_metadata(klass: *mut GstElementClass,
longname: *const gchar,
classification: *const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_element_class_set_static_metadata(klass: *mut GstElementClass,
longname: *const gchar,
classification: *const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_element_class_add_metadata(klass: *mut GstElementClass,
key: *const gchar,
value: *const gchar);
pub fn gst_element_class_add_static_metadata(klass: *mut GstElementClass,
key: *const gchar,
value: *const gchar);
pub fn gst_element_class_get_metadata(klass: *mut GstElementClass,
key: *const gchar) -> *const gchar;
pub fn gst_element_get_type() -> GType;
pub fn gst_element_provide_clock(element: *mut GstElement)
-> *mut GstClock;
pub fn gst_element_get_clock(element: *mut GstElement) -> *mut GstClock;
pub fn gst_element_set_clock(element: *mut GstElement,
clock: *mut GstClock) -> gboolean;
pub fn gst_element_set_base_time(element: *mut GstElement,
time: GstClockTime);
pub fn gst_element_get_base_time(element: *mut GstElement)
-> GstClockTime;
pub fn gst_element_set_start_time(element: *mut GstElement,
time: GstClockTime);
pub fn gst_element_get_start_time(element: *mut GstElement)
-> GstClockTime;
pub fn gst_element_set_bus(element: *mut GstElement, bus: *mut GstBus);
pub fn gst_element_get_bus(element: *mut GstElement) -> *mut GstBus;
pub fn gst_element_set_context(element: *mut GstElement,
context: *mut GstContext);
pub fn gst_element_add_pad(element: *mut GstElement, pad: *mut GstPad)
-> gboolean;
pub fn gst_element_remove_pad(element: *mut GstElement, pad: *mut GstPad)
-> gboolean;
pub fn gst_element_no_more_pads(element: *mut GstElement);
pub fn gst_element_get_static_pad(element: *mut GstElement,
name: *const gchar) -> *mut GstPad;
pub fn gst_element_get_request_pad(element: *mut GstElement,
name: *const gchar) -> *mut GstPad;
pub fn gst_element_request_pad(element: *mut GstElement,
templ: *mut GstPadTemplate,
name: *const gchar, caps: *const GstCaps)
-> *mut GstPad;
pub fn gst_element_release_request_pad(element: *mut GstElement,
pad: *mut GstPad);
pub fn gst_element_iterate_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_iterate_src_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_iterate_sink_pads(element: *mut GstElement)
-> *mut GstIterator;
pub fn gst_element_send_event(element: *mut GstElement,
event: *mut GstEvent) -> gboolean;
pub fn gst_element_seek(element: *mut GstElement, rate: gdouble,
format: GstFormat, flags: GstSeekFlags,
start_type: GstSeekType, start: gint64,
stop_type: GstSeekType, stop: gint64) -> gboolean;
pub fn gst_element_query(element: *mut GstElement, query: *mut GstQuery)
-> gboolean;
pub fn gst_element_post_message(element: *mut GstElement,
message: *mut GstMessage) -> gboolean;
pub fn _gst_element_error_printf(format: *const gchar, ...) -> *mut gchar;
pub fn gst_element_message_full(element: *mut GstElement,
_type: GstMessageType, domain: GQuark,
code: gint, text: *mut gchar,
debug: *mut gchar, file: *const gchar,
function: *const gchar, line: gint);
pub fn gst_element_is_locked_state(element: *mut GstElement) -> gboolean;
pub fn gst_element_set_locked_state(element: *mut GstElement,
locked_state: gboolean) -> gboolean;
pub fn gst_element_sync_state_with_parent(element: *mut GstElement)
-> gboolean;
pub fn gst_element_get_state(element: *mut GstElement,
state: *mut GstState, pending: *mut GstState,
timeout: GstClockTime)
-> GstStateChangeReturn;
pub fn gst_element_set_state(element: *mut GstElement, state: GstState)
-> GstStateChangeReturn;
pub fn gst_element_abort_state(element: *mut GstElement);
pub fn gst_element_change_state(element: *mut GstElement,
transition: GstStateChange)
-> GstStateChangeReturn;
pub fn gst_element_continue_state(element: *mut GstElement,
ret: GstStateChangeReturn)
-> GstStateChangeReturn;
pub fn gst_element_lost_state(element: *mut GstElement);
pub fn gst_element_get_factory(element: *mut GstElement)
-> *mut GstElementFactory;
pub fn gst_bin_get_type() -> GType;
pub fn gst_bin_new(name: *const gchar) -> *mut GstElement;
pub fn gst_bin_add(bin: *mut GstBin, element: *mut GstElement)
-> gboolean;
pub fn gst_bin_remove(bin: *mut GstBin, element: *mut GstElement)
-> gboolean;
pub fn gst_bin_get_by_name(bin: *mut GstBin, name: *const gchar)
-> *mut GstElement;
pub fn gst_bin_get_by_name_recurse_up(bin: *mut GstBin,
name: *const gchar)
-> *mut GstElement;
pub fn gst_bin_get_by_interface(bin: *mut GstBin, iface: GType)
-> *mut GstElement;
pub fn gst_bin_iterate_elements(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sorted(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_recurse(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sinks(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_sources(bin: *mut GstBin) -> *mut GstIterator;
pub fn gst_bin_iterate_all_by_interface(bin: *mut GstBin, iface: GType)
-> *mut GstIterator;
pub fn gst_bin_recalculate_latency(bin: *mut GstBin) -> gboolean;
pub fn gst_buffer_pool_get_type() -> GType;
pub fn gst_buffer_pool_new() -> *mut GstBufferPool;
pub fn gst_buffer_pool_set_active(pool: *mut GstBufferPool,
active: gboolean) -> gboolean;
pub fn gst_buffer_pool_is_active(pool: *mut GstBufferPool) -> gboolean;
pub fn gst_buffer_pool_set_config(pool: *mut GstBufferPool,
config: *mut GstStructure) -> gboolean;
pub fn gst_buffer_pool_get_config(pool: *mut GstBufferPool)
-> *mut GstStructure;
pub fn gst_buffer_pool_get_options(pool: *mut GstBufferPool)
-> *mut *const gchar;
pub fn gst_buffer_pool_has_option(pool: *mut GstBufferPool,
option: *const gchar) -> gboolean;
pub fn gst_buffer_pool_set_flushing(pool: *mut GstBufferPool,
flushing: gboolean);
pub fn gst_buffer_pool_config_set_params(config: *mut GstStructure,
caps: *mut GstCaps, size: guint,
min_buffers: guint,
max_buffers: guint);
pub fn gst_buffer_pool_config_get_params(config: *mut GstStructure,
caps: *mut *mut GstCaps,
size: *mut guint,
min_buffers: *mut guint,
max_buffers: *mut guint)
-> gboolean;
pub fn gst_buffer_pool_config_set_allocator(config: *mut GstStructure,
allocator: *mut GstAllocator,
params:
*const GstAllocationParams);
pub fn gst_buffer_pool_config_get_allocator(config: *mut GstStructure,
allocator:
*mut *mut GstAllocator,
params:
*mut GstAllocationParams)
-> gboolean;
pub fn gst_buffer_pool_config_n_options(config: *mut GstStructure)
-> guint;
pub fn gst_buffer_pool_config_add_option(config: *mut GstStructure,
option: *const gchar);
pub fn gst_buffer_pool_config_get_option(config: *mut GstStructure,
index: guint) -> *const gchar;
pub fn gst_buffer_pool_config_has_option(config: *mut GstStructure,
option: *const gchar)
-> gboolean;
pub fn gst_buffer_pool_config_validate_params(config: *mut GstStructure,
caps: *mut GstCaps,
size: guint,
min_buffers: guint,
max_buffers: guint)
-> gboolean;
pub fn gst_buffer_pool_acquire_buffer(pool: *mut GstBufferPool,
buffer: *mut *mut GstBuffer,
params:
*mut GstBufferPoolAcquireParams)
-> GstFlowReturn;
pub fn gst_buffer_pool_release_buffer(pool: *mut GstBufferPool,
buffer: *mut GstBuffer);
pub fn gst_child_proxy_get_type() -> GType;
pub fn gst_child_proxy_get_child_by_name(parent: *mut GstChildProxy,
name: *const gchar)
-> *mut GObject;
pub fn gst_child_proxy_get_children_count(parent: *mut GstChildProxy)
-> guint;
pub fn gst_child_proxy_get_child_by_index(parent: *mut GstChildProxy,
index: guint) -> *mut GObject;
pub fn gst_child_proxy_lookup(object: *mut GstChildProxy,
name: *const gchar,
target: *mut *mut GObject,
pspec: *mut *mut GParamSpec) -> gboolean;
pub fn gst_child_proxy_get_property(object: *mut GstChildProxy,
name: *const gchar,
value: *mut GValue);
pub fn gst_child_proxy_get_valist(object: *mut GstChildProxy,
first_property_name: *const gchar,
var_args: va_list);
pub fn gst_child_proxy_get(object: *mut GstChildProxy,
first_property_name: *const gchar, ...);
pub fn gst_child_proxy_set_property(object: *mut GstChildProxy,
name: *const gchar,
value: *const GValue);
pub fn gst_child_proxy_set_valist(object: *mut GstChildProxy,
first_property_name: *const gchar,
var_args: va_list);
pub fn gst_child_proxy_set(object: *mut GstChildProxy,
first_property_name: *const gchar, ...);
pub fn gst_child_proxy_child_added(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar);
pub fn gst_child_proxy_child_removed(parent: *mut GstChildProxy,
child: *mut GObject,
name: *const gchar);
pub fn gst_debug_bin_to_dot_file(bin: *mut GstBin,
details: GstDebugGraphDetails,
file_name: *const gchar);
pub fn gst_debug_bin_to_dot_file_with_ts(bin: *mut GstBin,
details: GstDebugGraphDetails,
file_name: *const gchar);
pub fn gst_device_provider_get_type() -> GType;
pub fn gst_device_provider_get_devices(provider: *mut GstDeviceProvider)
-> *mut GList;
pub fn gst_device_provider_start(provider: *mut GstDeviceProvider)
-> gboolean;
pub fn gst_device_provider_stop(provider: *mut GstDeviceProvider);
pub fn gst_device_provider_can_monitor(provider: *mut GstDeviceProvider)
-> gboolean;
pub fn gst_device_provider_get_bus(provider: *mut GstDeviceProvider)
-> *mut GstBus;
pub fn gst_device_provider_device_add(provider: *mut GstDeviceProvider,
device: *mut GstDevice);
pub fn gst_device_provider_device_remove(provider: *mut GstDeviceProvider,
device: *mut GstDevice);
pub fn gst_device_provider_class_set_metadata(klass:
*mut GstDeviceProviderClass,
longname: *const gchar,
classification:
*const gchar,
description: *const gchar,
author: *const gchar);
pub fn gst_device_provider_class_set_static_metadata(klass:
*mut GstDeviceProviderClass,
longname:
*const gchar,
classification:
*const gchar,
description:
*const gchar,
author:
*const gchar);
pub fn gst_device_provider_class_add_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar,
value: *const gchar);
pub fn gst_device_provider_class_add_static_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar,
value: *const gchar);
pub fn gst_device_provider_class_get_metadata(klass:
*mut GstDeviceProviderClass,
key: *const gchar)
-> *const gchar;
pub fn gst_device_provider_get_factory(provider: *mut GstDeviceProvider)
-> *mut GstDeviceProviderFactory;
pub fn gst_device_provider_factory_get_type() -> GType;
pub fn gst_device_provider_factory_find(name: *const gchar)
-> *mut GstDeviceProviderFactory;
pub fn gst_device_provider_factory_get_device_provider_type(factory:
*mut GstDeviceProviderFactory)
-> GType;
pub fn gst_device_provider_factory_get_metadata(factory:
*mut GstDeviceProviderFactory,
key: *const gchar)
-> *const gchar;
pub fn gst_device_provider_factory_get_metadata_keys(factory:
*mut GstDeviceProviderFactory)
-> *mut *mut gchar;
pub fn gst_device_provider_factory_get(factory:
*mut GstDeviceProviderFactory)
-> *mut GstDeviceProvider;
pub fn gst_device_provider_factory_get_by_name(factoryname: *const gchar)
-> *mut GstDeviceProvider;
pub fn gst_device_provider_register(plugin: *mut GstPlugin,
name: *const gchar, rank: guint,
_type: GType) -> gboolean;
pub fn gst_device_provider_factory_has_classesv(factory:
*mut GstDeviceProviderFactory,
classes: *mut *mut gchar)
-> gboolean;
pub fn gst_device_provider_factory_has_classes(factory:
*mut GstDeviceProviderFactory,
classes: *const gchar)
-> gboolean;
pub fn gst_device_provider_factory_list_get_device_providers(minrank:
GstRank)
-> *mut GList;
pub fn __errno_location() -> *mut ::libc::c_int;
pub fn gst_error_get_message(domain: GQuark, code: gint) -> *mut gchar;
pub fn gst_stream_error_quark() -> GQuark;
pub fn gst_core_error_quark() -> GQuark;
pub fn gst_resource_error_quark() -> GQuark;
pub fn gst_library_error_quark() -> GQuark;
pub fn gst_proxy_pad_get_type() -> GType;
pub fn gst_proxy_pad_get_internal(pad: *mut GstProxyPad)
-> *mut GstProxyPad;
pub fn gst_proxy_pad_iterate_internal_links_default(pad: *mut GstPad,
parent:
*mut GstObject)
-> *mut GstIterator;
pub fn gst_proxy_pad_chain_default(pad: *mut GstPad,
parent: *mut GstObject,
buffer: *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_proxy_pad_chain_list_default(pad: *mut GstPad,
parent: *mut GstObject,
list: *mut GstBufferList)
-> GstFlowReturn;
pub fn gst_proxy_pad_getrange_default(pad: *mut GstPad,
parent: *mut GstObject,
offset: guint64, size: guint,
buffer: *mut *mut GstBuffer)
-> GstFlowReturn;
pub fn gst_ghost_pad_get_type() -> GType;
pub fn gst_ghost_pad_new(name: *const gchar, target: *mut GstPad)
-> *mut GstPad;
pub fn gst_ghost_pad_new_no_target(name: *const gchar,
dir: GstPadDirection) -> *mut GstPad;
pub fn gst_ghost_pad_new_from_template(name: *const gchar,
target: *mut GstPad,
templ: *mut GstPadTemplate)
-> *mut GstPad;
pub fn gst_ghost_pad_new_no_target_from_template(name: *const gchar,
templ:
*mut GstPadTemplate)
-> *mut GstPad;
pub fn gst_ghost_pad_get_target(gpad: *mut GstGhostPad) -> *mut GstPad;
pub fn gst_ghost_pad_set_target(gpad: *mut GstGhostPad,
newtarget: *mut GstPad) -> gboolean;
pub fn gst_ghost_pad_construct(gpad: *mut GstGhostPad) -> gboolean;
pub fn gst_ghost_pad_activate_mode_default(pad: *mut GstPad,
parent: *mut GstObject,
mode: GstPadMode,
active: gboolean) -> gboolean;
pub fn gst_ghost_pad_internal_activate_mode_default(pad: *mut GstPad,
parent:
*mut GstObject,
mode: GstPadMode,
active: gboolean)
-> gboolean;
pub fn gst_device_monitor_get_type() -> GType;
pub fn gst_device_monitor_new() -> *mut GstDeviceMonitor;
pub fn gst_device_monitor_get_bus(monitor: *mut GstDeviceMonitor)
-> *mut GstBus;
pub fn gst_device_monitor_get_devices(monitor: *mut GstDeviceMonitor)
-> *mut GList;
pub fn gst_device_monitor_start(monitor: *mut GstDeviceMonitor)
-> gboolean;
pub fn gst_device_monitor_stop(monitor: *mut GstDeviceMonitor);
pub fn gst_device_monitor_add_filter(monitor: *mut GstDeviceMonitor,
classes: *const gchar,
caps: *mut GstCaps) -> guint;
pub fn gst_device_monitor_remove_filter(monitor: *mut GstDeviceMonitor,
filter_id: guint) -> gboolean;
pub fn gst_debug_log(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject, format: *const gchar, ...);
pub fn gst_debug_log_valist(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject, format: *const gchar,
args: va_list);
pub fn _gst_debug_category_new(name: *const gchar, color: guint,
description: *const gchar)
-> *mut GstDebugCategory;
pub fn _gst_debug_get_category(name: *const gchar)
-> *mut GstDebugCategory;
pub fn _gst_debug_dump_mem(cat: *mut GstDebugCategory, file: *const gchar,
func: *const gchar, line: gint,
obj: *mut GObject, msg: *const gchar,
data: *const guint8, length: guint);
pub fn _gst_debug_register_funcptr(func: GstDebugFuncPtr,
ptrname: *const gchar);
pub fn _gst_debug_nameof_funcptr(func: GstDebugFuncPtr) -> *const gchar;
pub fn gst_debug_message_get(message: *mut GstDebugMessage)
-> *const gchar;
pub fn gst_debug_log_default(category: *mut GstDebugCategory,
level: GstDebugLevel, file: *const gchar,
function: *const gchar, line: gint,
object: *mut GObject,
message: *mut GstDebugMessage,
unused: gpointer);
pub fn gst_debug_level_get_name(level: GstDebugLevel) -> *const gchar;
pub fn gst_debug_add_log_function(func: GstLogFunction,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_debug_remove_log_function(func: GstLogFunction) -> guint;
pub fn gst_debug_remove_log_function_by_data(data: gpointer) -> guint;
pub fn gst_debug_set_active(active: gboolean);
pub fn gst_debug_is_active() -> gboolean;
pub fn gst_debug_set_colored(colored: gboolean);
pub fn gst_debug_set_color_mode(mode: GstDebugColorMode);
pub fn gst_debug_set_color_mode_from_string(mode: *const gchar);
pub fn gst_debug_is_colored() -> gboolean;
pub fn gst_debug_get_color_mode() -> GstDebugColorMode;
pub fn gst_debug_set_default_threshold(level: GstDebugLevel);
pub fn gst_debug_get_default_threshold() -> GstDebugLevel;
pub fn gst_debug_set_threshold_for_name(name: *const gchar,
level: GstDebugLevel);
pub fn gst_debug_set_threshold_from_string(list: *const gchar,
reset: gboolean);
pub fn gst_debug_unset_threshold_for_name(name: *const gchar);
pub fn gst_debug_category_free(category: *mut GstDebugCategory);
pub fn gst_debug_category_set_threshold(category: *mut GstDebugCategory,
level: GstDebugLevel);
pub fn gst_debug_category_reset_threshold(category:
*mut GstDebugCategory);
pub fn gst_debug_category_get_threshold(category: *mut GstDebugCategory)
-> GstDebugLevel;
pub fn gst_debug_category_get_name(category: *mut GstDebugCategory)
-> *const gchar;
pub fn gst_debug_category_get_color(category: *mut GstDebugCategory)
-> guint;
pub fn gst_debug_category_get_description(category: *mut GstDebugCategory)
-> *const gchar;
pub fn gst_debug_get_all_categories() -> *mut GSList;
pub fn gst_debug_construct_term_color(colorinfo: guint) -> *mut gchar;
pub fn gst_debug_construct_win_color(colorinfo: guint) -> gint;
pub fn gst_debug_print_stack_trace();
pub fn gst_int_range_get_type() -> GType;
pub fn gst_int64_range_get_type() -> GType;
pub fn gst_double_range_get_type() -> GType;
pub fn gst_fraction_range_get_type() -> GType;
pub fn gst_fraction_get_type() -> GType;
pub fn gst_value_list_get_type() -> GType;
pub fn gst_value_array_get_type() -> GType;
pub fn gst_bitmask_get_type() -> GType;
pub fn gst_g_thread_get_type() -> GType;
pub fn gst_value_register(table: *const GstValueTable);
pub fn gst_value_init_and_copy(dest: *mut GValue, src: *const GValue);
pub fn gst_value_serialize(value: *const GValue) -> *mut gchar;
pub fn gst_value_deserialize(dest: *mut GValue, src: *const gchar)
-> gboolean;
pub fn gst_value_list_append_value(value: *mut GValue,
append_value: *const GValue);
pub fn gst_value_list_append_and_take_value(value: *mut GValue,
append_value: *mut GValue);
pub fn gst_value_list_prepend_value(value: *mut GValue,
prepend_value: *const GValue);
pub fn gst_value_list_concat(dest: *mut GValue, value1: *const GValue,
value2: *const GValue);
pub fn gst_value_list_merge(dest: *mut GValue, value1: *const GValue,
value2: *const GValue);
pub fn gst_value_list_get_size(value: *const GValue) -> guint;
pub fn gst_value_list_get_value(value: *const GValue, index: guint)
-> *const GValue;
pub fn gst_value_array_append_value(value: *mut GValue,
append_value: *const GValue);
pub fn gst_value_array_append_and_take_value(value: *mut GValue,
append_value: *mut GValue);
pub fn gst_value_array_prepend_value(value: *mut GValue,
prepend_value: *const GValue);
pub fn gst_value_array_get_size(value: *const GValue) -> guint;
pub fn gst_value_array_get_value(value: *const GValue, index: guint)
-> *const GValue;
pub fn gst_value_set_int_range(value: *mut GValue, start: gint,
end: gint);
pub fn gst_value_set_int_range_step(value: *mut GValue, start: gint,
end: gint, step: gint);
pub fn gst_value_get_int_range_min(value: *const GValue) -> gint;
pub fn gst_value_get_int_range_max(value: *const GValue) -> gint;
pub fn gst_value_get_int_range_step(value: *const GValue) -> gint;
pub fn gst_value_set_int64_range(value: *mut GValue, start: gint64,
end: gint64);
pub fn gst_value_set_int64_range_step(value: *mut GValue, start: gint64,
end: gint64, step: gint64);
pub fn gst_value_get_int64_range_min(value: *const GValue) -> gint64;
pub fn gst_value_get_int64_range_max(value: *const GValue) -> gint64;
pub fn gst_value_get_int64_range_step(value: *const GValue) -> gint64;
pub fn gst_value_set_double_range(value: *mut GValue, start: gdouble,
end: gdouble);
pub fn gst_value_get_double_range_min(value: *const GValue) -> gdouble;
pub fn gst_value_get_double_range_max(value: *const GValue) -> gdouble;
pub fn gst_value_get_caps(value: *const GValue) -> *const GstCaps;
pub fn gst_value_set_caps(value: *mut GValue, caps: *const GstCaps);
pub fn gst_value_get_structure(value: *const GValue)
-> *const GstStructure;
pub fn gst_value_set_structure(value: *mut GValue,
structure: *const GstStructure);
pub fn gst_value_get_caps_features(value: *const GValue)
-> *const GstCapsFeatures;
pub fn gst_value_set_caps_features(value: *mut GValue,
features: *const GstCapsFeatures);
pub fn gst_value_set_fraction(value: *mut GValue, numerator: gint,
denominator: gint);
pub fn gst_value_get_fraction_numerator(value: *const GValue) -> gint;
pub fn gst_value_get_fraction_denominator(value: *const GValue) -> gint;
pub fn gst_value_fraction_multiply(product: *mut GValue,
factor1: *const GValue,
factor2: *const GValue) -> gboolean;
pub fn gst_value_fraction_subtract(dest: *mut GValue,
minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_set_fraction_range(value: *mut GValue,
start: *const GValue,
end: *const GValue);
pub fn gst_value_set_fraction_range_full(value: *mut GValue,
numerator_start: gint,
denominator_start: gint,
numerator_end: gint,
denominator_end: gint);
pub fn gst_value_get_fraction_range_min(value: *const GValue)
-> *const GValue;
pub fn gst_value_get_fraction_range_max(value: *const GValue)
-> *const GValue;
pub fn gst_value_get_bitmask(value: *const GValue) -> guint64;
pub fn gst_value_set_bitmask(value: *mut GValue, bitmask: guint64);
pub fn gst_value_compare(value1: *const GValue, value2: *const GValue)
-> gint;
pub fn gst_value_can_compare(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_is_subset(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_union(dest: *mut GValue, value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_can_union(value1: *const GValue, value2: *const GValue)
-> gboolean;
pub fn gst_value_intersect(dest: *mut GValue, value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_can_intersect(value1: *const GValue,
value2: *const GValue) -> gboolean;
pub fn gst_value_subtract(dest: *mut GValue, minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_can_subtract(minuend: *const GValue,
subtrahend: *const GValue) -> gboolean;
pub fn gst_value_is_fixed(value: *const GValue) -> gboolean;
pub fn gst_value_fixate(dest: *mut GValue, src: *const GValue)
-> gboolean;
pub fn gst_param_spec_fraction_get_type() -> GType;
pub fn gst_param_spec_fraction(name: *const gchar, nick: *const gchar,
blurb: *const gchar, min_num: gint,
min_denom: gint, max_num: gint,
max_denom: gint, default_num: gint,
default_denom: gint, flags: GParamFlags)
-> *mut GParamSpec;
pub fn gst_pipeline_get_type() -> GType;
pub fn gst_pipeline_new(name: *const gchar) -> *mut GstElement;
pub fn gst_pipeline_get_bus(pipeline: *mut GstPipeline) -> *mut GstBus;
pub fn gst_pipeline_use_clock(pipeline: *mut GstPipeline,
clock: *mut GstClock);
pub fn gst_pipeline_set_clock(pipeline: *mut GstPipeline,
clock: *mut GstClock) -> gboolean;
pub fn gst_pipeline_get_clock(pipeline: *mut GstPipeline)
-> *mut GstClock;
pub fn gst_pipeline_auto_clock(pipeline: *mut GstPipeline);
pub fn gst_pipeline_set_delay(pipeline: *mut GstPipeline,
delay: GstClockTime);
pub fn gst_pipeline_get_delay(pipeline: *mut GstPipeline) -> GstClockTime;
pub fn gst_pipeline_set_auto_flush_bus(pipeline: *mut GstPipeline,
auto_flush: gboolean);
pub fn gst_pipeline_get_auto_flush_bus(pipeline: *mut GstPipeline)
-> gboolean;
pub fn gst_poll_new(controllable: gboolean) -> *mut GstPoll;
pub fn gst_poll_new_timer() -> *mut GstPoll;
pub fn gst_poll_free(set: *mut GstPoll);
pub fn gst_poll_get_read_gpollfd(set: *mut GstPoll, fd: *mut GPollFD);
pub fn gst_poll_fd_init(fd: *mut GstPollFD);
pub fn gst_poll_add_fd(set: *mut GstPoll, fd: *mut GstPollFD) -> gboolean;
pub fn gst_poll_remove_fd(set: *mut GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_ctl_write(set: *mut GstPoll, fd: *mut GstPollFD,
active: gboolean) -> gboolean;
pub fn gst_poll_fd_ctl_read(set: *mut GstPoll, fd: *mut GstPollFD,
active: gboolean) -> gboolean;
pub fn gst_poll_fd_ignored(set: *mut GstPoll, fd: *mut GstPollFD);
pub fn gst_poll_fd_has_closed(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_has_error(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_can_read(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_fd_can_write(set: *const GstPoll, fd: *mut GstPollFD)
-> gboolean;
pub fn gst_poll_wait(set: *mut GstPoll, timeout: GstClockTime) -> gint;
pub fn gst_poll_set_controllable(set: *mut GstPoll,
controllable: gboolean) -> gboolean;
pub fn gst_poll_restart(set: *mut GstPoll);
pub fn gst_poll_set_flushing(set: *mut GstPoll, flushing: gboolean);
pub fn gst_poll_write_control(set: *mut GstPoll) -> gboolean;
pub fn gst_poll_read_control(set: *mut GstPoll) -> gboolean;
pub fn gst_preset_get_type() -> GType;
pub fn gst_preset_get_preset_names(preset: *mut GstPreset)
-> *mut *mut gchar;
pub fn gst_preset_get_property_names(preset: *mut GstPreset)
-> *mut *mut gchar;
pub fn gst_preset_load_preset(preset: *mut GstPreset, name: *const gchar)
-> gboolean;
pub fn gst_preset_save_preset(preset: *mut GstPreset, name: *const gchar)
-> gboolean;
pub fn gst_preset_rename_preset(preset: *mut GstPreset,
old_name: *const gchar,
new_name: *const gchar) -> gboolean;
pub fn gst_preset_delete_preset(preset: *mut GstPreset,
name: *const gchar) -> gboolean;
pub fn gst_preset_set_meta(preset: *mut GstPreset, name: *const gchar,
tag: *const gchar, value: *const gchar)
-> gboolean;
pub fn gst_preset_get_meta(preset: *mut GstPreset, name: *const gchar,
tag: *const gchar, value: *mut *mut gchar)
-> gboolean;
pub fn gst_preset_set_app_dir(app_dir: *const gchar) -> gboolean;
pub fn gst_preset_get_app_dir() -> *const gchar;
pub fn gst_registry_get_type() -> GType;
pub fn gst_registry_get() -> *mut GstRegistry;
pub fn gst_registry_scan_path(registry: *mut GstRegistry,
path: *const gchar) -> gboolean;
pub fn gst_registry_add_plugin(registry: *mut GstRegistry,
plugin: *mut GstPlugin) -> gboolean;
pub fn gst_registry_remove_plugin(registry: *mut GstRegistry,
plugin: *mut GstPlugin);
pub fn gst_registry_add_feature(registry: *mut GstRegistry,
feature: *mut GstPluginFeature)
-> gboolean;
pub fn gst_registry_remove_feature(registry: *mut GstRegistry,
feature: *mut GstPluginFeature);
pub fn gst_registry_get_plugin_list(registry: *mut GstRegistry)
-> *mut GList;
pub fn gst_registry_plugin_filter(registry: *mut GstRegistry,
filter: GstPluginFilter,
first: gboolean, user_data: gpointer)
-> *mut GList;
pub fn gst_registry_feature_filter(registry: *mut GstRegistry,
filter: GstPluginFeatureFilter,
first: gboolean, user_data: gpointer)
-> *mut GList;
pub fn gst_registry_get_feature_list(registry: *mut GstRegistry,
_type: GType) -> *mut GList;
pub fn gst_registry_get_feature_list_by_plugin(registry: *mut GstRegistry,
name: *const gchar)
-> *mut GList;
pub fn gst_registry_get_feature_list_cookie(registry: *mut GstRegistry)
-> guint32;
pub fn gst_registry_find_plugin(registry: *mut GstRegistry,
name: *const gchar) -> *mut GstPlugin;
pub fn gst_registry_find_feature(registry: *mut GstRegistry,
name: *const gchar, _type: GType)
-> *mut GstPluginFeature;
pub fn gst_registry_lookup(registry: *mut GstRegistry,
filename: *const ::libc::c_char)
-> *mut GstPlugin;
pub fn gst_registry_lookup_feature(registry: *mut GstRegistry,
name: *const ::libc::c_char)
-> *mut GstPluginFeature;
pub fn gst_registry_check_feature_version(registry: *mut GstRegistry,
feature_name: *const gchar,
min_major: guint,
min_minor: guint,
min_micro: guint) -> gboolean;
pub fn gst_system_clock_get_type() -> GType;
pub fn gst_system_clock_obtain() -> *mut GstClock;
pub fn gst_system_clock_set_default(new_clock: *mut GstClock);
pub fn gst_tag_setter_get_type() -> GType;
pub fn gst_tag_setter_reset_tags(setter: *mut GstTagSetter);
pub fn gst_tag_setter_merge_tags(setter: *mut GstTagSetter,
list: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_tag_setter_add_tags(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_setter_add_tag_values(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar, ...);
pub fn gst_tag_setter_add_tag_valist(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_setter_add_tag_valist_values(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
var_args: va_list);
pub fn gst_tag_setter_add_tag_value(setter: *mut GstTagSetter,
mode: GstTagMergeMode,
tag: *const gchar,
value: *const GValue);
pub fn gst_tag_setter_get_tag_list(setter: *mut GstTagSetter)
-> *const GstTagList;
pub fn gst_tag_setter_set_tag_merge_mode(setter: *mut GstTagSetter,
mode: GstTagMergeMode);
pub fn gst_tag_setter_get_tag_merge_mode(setter: *mut GstTagSetter)
-> GstTagMergeMode;
pub fn gst_toc_setter_get_type() -> GType;
pub fn gst_toc_setter_reset(setter: *mut GstTocSetter);
pub fn gst_toc_setter_get_toc(setter: *mut GstTocSetter) -> *mut GstToc;
pub fn gst_toc_setter_set_toc(setter: *mut GstTocSetter,
toc: *mut GstToc);
pub fn gst_type_find_get_type() -> GType;
pub fn gst_type_find_peek(find: *mut GstTypeFind, offset: gint64,
size: guint) -> *const guint8;
pub fn gst_type_find_suggest(find: *mut GstTypeFind, probability: guint,
caps: *mut GstCaps);
pub fn gst_type_find_suggest_simple(find: *mut GstTypeFind,
probability: guint,
media_type: *const ::libc::c_char,
fieldname:
*const ::libc::c_char, ...);
pub fn gst_type_find_get_length(find: *mut GstTypeFind) -> guint64;
pub fn gst_type_find_register(plugin: *mut GstPlugin, name: *const gchar,
rank: guint, func: GstTypeFindFunction,
extensions: *const gchar,
possible_caps: *mut GstCaps, data: gpointer,
data_notify: GDestroyNotify) -> gboolean;
pub fn gst_type_find_factory_get_type() -> GType;
pub fn gst_type_find_factory_get_list() -> *mut GList;
pub fn gst_type_find_factory_get_extensions(factory:
*mut GstTypeFindFactory)
-> *const *const gchar;
pub fn gst_type_find_factory_get_caps(factory: *mut GstTypeFindFactory)
-> *mut GstCaps;
pub fn gst_type_find_factory_has_function(factory:
*mut GstTypeFindFactory)
-> gboolean;
pub fn gst_type_find_factory_call_function(factory:
*mut GstTypeFindFactory,
find: *mut GstTypeFind);
pub fn gst_parse_error_quark() -> GQuark;
pub fn gst_parse_context_get_type() -> GType;
pub fn gst_parse_context_new() -> *mut GstParseContext;
pub fn gst_parse_context_get_missing_elements(context:
*mut GstParseContext)
-> *mut *mut gchar;
pub fn gst_parse_context_free(context: *mut GstParseContext);
pub fn gst_parse_launch(pipeline_description: *const gchar,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_parse_launchv(argv: *mut *const gchar, error: *mut *mut GError)
-> *mut GstElement;
pub fn gst_parse_launch_full(pipeline_description: *const gchar,
context: *mut GstParseContext,
flags: GstParseFlags,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_parse_launchv_full(argv: *mut *const gchar,
context: *mut GstParseContext,
flags: GstParseFlags,
error: *mut *mut GError) -> *mut GstElement;
pub fn gst_util_set_value_from_string(value: *mut GValue,
value_str: *const gchar);
pub fn gst_util_set_object_arg(object: *mut GObject, name: *const gchar,
value: *const gchar);
pub fn gst_util_dump_mem(mem: *const guchar, size: guint);
pub fn gst_util_gdouble_to_guint64(value: gdouble) -> guint64;
pub fn gst_util_guint64_to_gdouble(value: guint64) -> gdouble;
pub fn gst_util_uint64_scale(val: guint64, num: guint64, denom: guint64)
-> guint64;
pub fn gst_util_uint64_scale_round(val: guint64, num: guint64,
denom: guint64) -> guint64;
pub fn gst_util_uint64_scale_ceil(val: guint64, num: guint64,
denom: guint64) -> guint64;
pub fn gst_util_uint64_scale_int(val: guint64, num: gint, denom: gint)
-> guint64;
pub fn gst_util_uint64_scale_int_round(val: guint64, num: gint,
denom: gint) -> guint64;
pub fn gst_util_uint64_scale_int_ceil(val: guint64, num: gint,
denom: gint) -> guint64;
pub fn gst_util_seqnum_next() -> guint32;
pub fn gst_util_seqnum_compare(s1: guint32, s2: guint32) -> gint32;
pub fn gst_util_group_id_next() -> guint;
pub fn gst_object_default_error(source: *mut GstObject,
error: *const GError,
debug: *const gchar);
pub fn gst_element_create_all_pads(element: *mut GstElement);
pub fn gst_element_get_compatible_pad(element: *mut GstElement,
pad: *mut GstPad,
caps: *mut GstCaps) -> *mut GstPad;
pub fn gst_element_get_compatible_pad_template(element: *mut GstElement,
compattempl:
*mut GstPadTemplate)
-> *mut GstPadTemplate;
pub fn gst_element_state_get_name(state: GstState) -> *const gchar;
pub fn gst_element_state_change_return_get_name(state_ret:
GstStateChangeReturn)
-> *const gchar;
pub fn gst_element_link(src: *mut GstElement, dest: *mut GstElement)
-> gboolean;
pub fn gst_element_link_many(element_1: *mut GstElement,
element_2: *mut GstElement, ...) -> gboolean;
pub fn gst_element_link_filtered(src: *mut GstElement,
dest: *mut GstElement,
filter: *mut GstCaps) -> gboolean;
pub fn gst_element_unlink(src: *mut GstElement, dest: *mut GstElement);
pub fn gst_element_unlink_many(element_1: *mut GstElement,
element_2: *mut GstElement, ...);
pub fn gst_element_link_pads(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar) -> gboolean;
pub fn gst_element_link_pads_full(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar,
flags: GstPadLinkCheck) -> gboolean;
pub fn gst_element_unlink_pads(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar);
pub fn gst_element_link_pads_filtered(src: *mut GstElement,
srcpadname: *const gchar,
dest: *mut GstElement,
destpadname: *const gchar,
filter: *mut GstCaps) -> gboolean;
pub fn gst_element_seek_simple(element: *mut GstElement,
format: GstFormat,
seek_flags: GstSeekFlags, seek_pos: gint64)
-> gboolean;
pub fn gst_element_factory_can_sink_all_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_src_all_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_sink_any_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_factory_can_src_any_caps(factory:
*mut GstElementFactory,
caps: *const GstCaps)
-> gboolean;
pub fn gst_element_query_position(element: *mut GstElement,
format: GstFormat, cur: *mut gint64)
-> gboolean;
pub fn gst_element_query_duration(element: *mut GstElement,
format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_element_query_convert(element: *mut GstElement,
src_format: GstFormat, src_val: gint64,
dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_use_fixed_caps(pad: *mut GstPad);
pub fn gst_pad_get_parent_element(pad: *mut GstPad) -> *mut GstElement;
pub fn gst_pad_proxy_query_accept_caps(pad: *mut GstPad,
query: *mut GstQuery) -> gboolean;
pub fn gst_pad_proxy_query_caps(pad: *mut GstPad, query: *mut GstQuery)
-> gboolean;
pub fn gst_pad_query_position(pad: *mut GstPad, format: GstFormat,
cur: *mut gint64) -> gboolean;
pub fn gst_pad_query_duration(pad: *mut GstPad, format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_pad_query_convert(pad: *mut GstPad, src_format: GstFormat,
src_val: gint64, dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_query_caps(pad: *mut GstPad, filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_pad_query_accept_caps(pad: *mut GstPad, caps: *mut GstCaps)
-> gboolean;
pub fn gst_pad_peer_query_position(pad: *mut GstPad, format: GstFormat,
cur: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_duration(pad: *mut GstPad, format: GstFormat,
duration: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_convert(pad: *mut GstPad, src_format: GstFormat,
src_val: gint64, dest_format: GstFormat,
dest_val: *mut gint64) -> gboolean;
pub fn gst_pad_peer_query_caps(pad: *mut GstPad, filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_pad_peer_query_accept_caps(pad: *mut GstPad,
caps: *mut GstCaps) -> gboolean;
pub fn gst_pad_create_stream_id(pad: *mut GstPad, parent: *mut GstElement,
stream_id: *const gchar) -> *mut gchar;
pub fn gst_pad_create_stream_id_printf(pad: *mut GstPad,
parent: *mut GstElement,
stream_id: *const gchar, ...)
-> *mut gchar;
pub fn gst_pad_create_stream_id_printf_valist(pad: *mut GstPad,
parent: *mut GstElement,
stream_id: *const gchar,
var_args: va_list)
-> *mut gchar;
pub fn gst_pad_get_stream_id(pad: *mut GstPad) -> *mut gchar;
pub fn gst_bin_add_many(bin: *mut GstBin,
element_1: *mut GstElement, ...);
pub fn gst_bin_remove_many(bin: *mut GstBin,
element_1: *mut GstElement, ...);
pub fn gst_bin_find_unlinked_pad(bin: *mut GstBin,
direction: GstPadDirection)
-> *mut GstPad;
pub fn gst_parse_bin_from_description(bin_description: *const gchar,
ghost_unlinked_pads: gboolean,
err: *mut *mut GError)
-> *mut GstElement;
pub fn gst_parse_bin_from_description_full(bin_description: *const gchar,
ghost_unlinked_pads: gboolean,
context: *mut GstParseContext,
flags: GstParseFlags,
err: *mut *mut GError)
-> *mut GstElement;
pub fn gst_util_get_timestamp() -> GstClockTime;
pub fn gst_util_array_binary_search(array: gpointer, num_elements: guint,
element_size: gsize,
search_func: GCompareDataFunc,
mode: GstSearchMode,
search_data: gconstpointer,
user_data: gpointer) -> gpointer;
pub fn gst_util_greatest_common_divisor(a: gint, b: gint) -> gint;
pub fn gst_util_greatest_common_divisor_int64(a: gint64, b: gint64)
-> gint64;
pub fn gst_util_fraction_to_double(src_n: gint, src_d: gint,
dest: *mut gdouble);
pub fn gst_util_double_to_fraction(src: gdouble, dest_n: *mut gint,
dest_d: *mut gint);
pub fn gst_util_fraction_multiply(a_n: gint, a_d: gint, b_n: gint,
b_d: gint, res_n: *mut gint,
res_d: *mut gint) -> gboolean;
pub fn gst_util_fraction_add(a_n: gint, a_d: gint, b_n: gint, b_d: gint,
res_n: *mut gint, res_d: *mut gint)
-> gboolean;
pub fn gst_util_fraction_compare(a_n: gint, a_d: gint, b_n: gint,
b_d: gint) -> gint;
pub fn gst_init(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char);
pub fn gst_init_check(argc: *mut ::libc::c_int,
argv: *mut *mut *mut ::libc::c_char,
err: *mut *mut GError) -> gboolean;
pub fn gst_is_initialized() -> gboolean;
pub fn gst_init_get_option_group() -> *mut GOptionGroup;
pub fn gst_deinit();
pub fn gst_version(major: *mut guint, minor: *mut guint,
micro: *mut guint, nano: *mut guint);
pub fn gst_version_string() -> *mut gchar;
pub fn gst_segtrap_is_enabled() -> gboolean;
pub fn gst_segtrap_set_enabled(enabled: gboolean);
pub fn gst_registry_fork_is_enabled() -> gboolean;
pub fn gst_registry_fork_set_enabled(enabled: gboolean);
pub fn gst_update_registry() -> gboolean;
pub fn gst_base_sink_get_type() -> GType;
pub fn gst_base_sink_do_preroll(sink: *mut GstBaseSink,
obj: *mut GstMiniObject) -> GstFlowReturn;
pub fn gst_base_sink_wait_preroll(sink: *mut GstBaseSink)
-> GstFlowReturn;
pub fn gst_base_sink_set_sync(sink: *mut GstBaseSink, sync: gboolean);
pub fn gst_base_sink_get_sync(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_max_lateness(sink: *mut GstBaseSink,
max_lateness: gint64);
pub fn gst_base_sink_get_max_lateness(sink: *mut GstBaseSink) -> gint64;
pub fn gst_base_sink_set_qos_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_qos_enabled(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_async_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_async_enabled(sink: *mut GstBaseSink) -> gboolean;
pub fn gst_base_sink_set_ts_offset(sink: *mut GstBaseSink,
offset: GstClockTimeDiff);
pub fn gst_base_sink_get_ts_offset(sink: *mut GstBaseSink)
-> GstClockTimeDiff;
pub fn gst_base_sink_get_last_sample(sink: *mut GstBaseSink)
-> *mut GstSample;
pub fn gst_base_sink_set_last_sample_enabled(sink: *mut GstBaseSink,
enabled: gboolean);
pub fn gst_base_sink_is_last_sample_enabled(sink: *mut GstBaseSink)
-> gboolean;
pub fn gst_base_sink_query_latency(sink: *mut GstBaseSink,
live: *mut gboolean,
upstream_live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime)
-> gboolean;
pub fn gst_base_sink_get_latency(sink: *mut GstBaseSink) -> GstClockTime;
pub fn gst_base_sink_set_render_delay(sink: *mut GstBaseSink,
delay: GstClockTime);
pub fn gst_base_sink_get_render_delay(sink: *mut GstBaseSink)
-> GstClockTime;
pub fn gst_base_sink_set_blocksize(sink: *mut GstBaseSink,
blocksize: guint);
pub fn gst_base_sink_get_blocksize(sink: *mut GstBaseSink) -> guint;
pub fn gst_base_sink_set_throttle_time(sink: *mut GstBaseSink,
throttle: guint64);
pub fn gst_base_sink_get_throttle_time(sink: *mut GstBaseSink) -> guint64;
pub fn gst_base_sink_set_max_bitrate(sink: *mut GstBaseSink,
max_bitrate: guint64);
pub fn gst_base_sink_get_max_bitrate(sink: *mut GstBaseSink) -> guint64;
pub fn gst_base_sink_wait_clock(sink: *mut GstBaseSink,
time: GstClockTime,
jitter: *mut GstClockTimeDiff)
-> GstClockReturn;
pub fn gst_base_sink_wait(sink: *mut GstBaseSink, time: GstClockTime,
jitter: *mut GstClockTimeDiff) -> GstFlowReturn;
pub fn gst_app_sink_get_type() -> GType;
pub fn gst_app_sink_set_caps(appsink: *mut GstAppSink,
caps: *const GstCaps);
pub fn gst_app_sink_get_caps(appsink: *mut GstAppSink) -> *mut GstCaps;
pub fn gst_app_sink_is_eos(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_set_emit_signals(appsink: *mut GstAppSink,
emit: gboolean);
pub fn gst_app_sink_get_emit_signals(appsink: *mut GstAppSink)
-> gboolean;
pub fn gst_app_sink_set_max_buffers(appsink: *mut GstAppSink, max: guint);
pub fn gst_app_sink_get_max_buffers(appsink: *mut GstAppSink) -> guint;
pub fn gst_app_sink_set_drop(appsink: *mut GstAppSink, drop: gboolean);
pub fn gst_app_sink_get_drop(appsink: *mut GstAppSink) -> gboolean;
pub fn gst_app_sink_pull_preroll(appsink: *mut GstAppSink)
-> *mut GstSample;
pub fn gst_app_sink_pull_sample(appsink: *mut GstAppSink)
-> *mut GstSample;
pub fn gst_app_sink_set_callbacks(appsink: *mut GstAppSink,
callbacks: *mut GstAppSinkCallbacks,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_base_src_get_type() -> GType;
pub fn gst_base_src_wait_playing(src: *mut GstBaseSrc) -> GstFlowReturn;
pub fn gst_base_src_set_live(src: *mut GstBaseSrc, live: gboolean);
pub fn gst_base_src_is_live(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_set_format(src: *mut GstBaseSrc, format: GstFormat);
pub fn gst_base_src_set_dynamic_size(src: *mut GstBaseSrc,
dynamic: gboolean);
pub fn gst_base_src_set_automatic_eos(src: *mut GstBaseSrc,
automatic_eos: gboolean);
pub fn gst_base_src_set_async(src: *mut GstBaseSrc, async: gboolean);
pub fn gst_base_src_is_async(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_start_complete(basesrc: *mut GstBaseSrc,
ret: GstFlowReturn);
pub fn gst_base_src_start_wait(basesrc: *mut GstBaseSrc) -> GstFlowReturn;
pub fn gst_base_src_query_latency(src: *mut GstBaseSrc,
live: *mut gboolean,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime)
-> gboolean;
pub fn gst_base_src_set_blocksize(src: *mut GstBaseSrc, blocksize: guint);
pub fn gst_base_src_get_blocksize(src: *mut GstBaseSrc) -> guint;
pub fn gst_base_src_set_do_timestamp(src: *mut GstBaseSrc,
timestamp: gboolean);
pub fn gst_base_src_get_do_timestamp(src: *mut GstBaseSrc) -> gboolean;
pub fn gst_base_src_new_seamless_segment(src: *mut GstBaseSrc,
start: gint64, stop: gint64,
time: gint64) -> gboolean;
pub fn gst_base_src_set_caps(src: *mut GstBaseSrc, caps: *mut GstCaps)
-> gboolean;
pub fn gst_base_src_get_buffer_pool(src: *mut GstBaseSrc)
-> *mut GstBufferPool;
pub fn gst_base_src_get_allocator(src: *mut GstBaseSrc,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_push_src_get_type() -> GType;
pub fn gst_app_src_get_type() -> GType;
pub fn gst_app_stream_type_get_type() -> GType;
pub fn gst_app_src_set_caps(appsrc: *mut GstAppSrc, caps: *const GstCaps);
pub fn gst_app_src_get_caps(appsrc: *mut GstAppSrc) -> *mut GstCaps;
pub fn gst_app_src_set_size(appsrc: *mut GstAppSrc, size: gint64);
pub fn gst_app_src_get_size(appsrc: *mut GstAppSrc) -> gint64;
pub fn gst_app_src_set_stream_type(appsrc: *mut GstAppSrc,
_type: GstAppStreamType);
pub fn gst_app_src_get_stream_type(appsrc: *mut GstAppSrc)
-> GstAppStreamType;
pub fn gst_app_src_set_max_bytes(appsrc: *mut GstAppSrc, max: guint64);
pub fn gst_app_src_get_max_bytes(appsrc: *mut GstAppSrc) -> guint64;
pub fn gst_app_src_get_current_level_bytes(appsrc: *mut GstAppSrc)
-> guint64;
pub fn gst_app_src_set_latency(appsrc: *mut GstAppSrc, min: guint64,
max: guint64);
pub fn gst_app_src_get_latency(appsrc: *mut GstAppSrc, min: *mut guint64,
max: *mut guint64);
pub fn gst_app_src_set_emit_signals(appsrc: *mut GstAppSrc,
emit: gboolean);
pub fn gst_app_src_get_emit_signals(appsrc: *mut GstAppSrc) -> gboolean;
pub fn gst_app_src_push_buffer(appsrc: *mut GstAppSrc,
buffer: *mut GstBuffer) -> GstFlowReturn;
pub fn gst_app_src_end_of_stream(appsrc: *mut GstAppSrc) -> GstFlowReturn;
pub fn gst_app_src_set_callbacks(appsrc: *mut GstAppSrc,
callbacks: *mut GstAppSrcCallbacks,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_video_format_get_type() -> GType;
pub fn gst_video_format_flags_get_type() -> GType;
pub fn gst_video_pack_flags_get_type() -> GType;
pub fn gst_video_color_range_get_type() -> GType;
pub fn gst_video_color_matrix_get_type() -> GType;
pub fn gst_video_transfer_function_get_type() -> GType;
pub fn gst_video_color_primaries_get_type() -> GType;
pub fn gst_video_interlace_mode_get_type() -> GType;
pub fn gst_video_flags_get_type() -> GType;
pub fn gst_color_balance_type_get_type() -> GType;
pub fn gst_navigation_command_get_type() -> GType;
pub fn gst_navigation_query_type_get_type() -> GType;
pub fn gst_navigation_message_type_get_type() -> GType;
pub fn gst_navigation_event_type_get_type() -> GType;
pub fn gst_video_chroma_site_get_type() -> GType;
pub fn gst_video_chroma_method_get_type() -> GType;
pub fn gst_video_chroma_flags_get_type() -> GType;
pub fn gst_video_tile_type_get_type() -> GType;
pub fn gst_video_tile_mode_get_type() -> GType;
pub fn gst_video_tile_get_index(mode: GstVideoTileMode, x: gint, y: gint,
x_tiles: gint, y_tiles: gint) -> guint;
pub fn gst_video_chroma_from_string(s: *const gchar)
-> GstVideoChromaSite;
pub fn gst_video_chroma_to_string(site: GstVideoChromaSite)
-> *const gchar;
pub fn gst_video_chroma_resample_new(method: GstVideoChromaMethod,
site: GstVideoChromaSite,
flags: GstVideoChromaFlags,
format: GstVideoFormat,
h_factor: gint, v_factor: gint)
-> *mut GstVideoChromaResample;
pub fn gst_video_chroma_resample_free(resample:
*mut GstVideoChromaResample);
pub fn gst_video_chroma_resample_get_info(resample:
*mut GstVideoChromaResample,
n_lines: *mut guint,
offset: *mut gint);
pub fn gst_video_chroma_resample(resample: *mut GstVideoChromaResample,
lines: *mut gpointer, width: gint);
pub fn gst_video_format_from_masks(depth: gint, bpp: gint,
endianness: gint, red_mask: guint,
green_mask: guint, blue_mask: guint,
alpha_mask: guint) -> GstVideoFormat;
pub fn gst_video_format_from_fourcc(fourcc: guint32) -> GstVideoFormat;
pub fn gst_video_format_from_string(format: *const gchar)
-> GstVideoFormat;
pub fn gst_video_format_to_fourcc(format: GstVideoFormat) -> guint32;
pub fn gst_video_format_to_string(format: GstVideoFormat) -> *const gchar;
pub fn gst_video_format_get_info(format: GstVideoFormat)
-> *const GstVideoFormatInfo;
pub fn gst_video_format_get_palette(format: GstVideoFormat,
size: *mut gsize) -> gconstpointer;
pub fn gst_video_colorimetry_matches(cinfo: *mut GstVideoColorimetry,
color: *const gchar) -> gboolean;
pub fn gst_video_colorimetry_from_string(cinfo: *mut GstVideoColorimetry,
color: *const gchar) -> gboolean;
pub fn gst_video_colorimetry_to_string(cinfo: *mut GstVideoColorimetry)
-> *mut gchar;
pub fn gst_video_color_range_offsets(range: GstVideoColorRange,
info: *const GstVideoFormatInfo,
offset: *mut gint, scale: *mut gint);
pub fn gst_video_info_init(info: *mut GstVideoInfo);
pub fn gst_video_info_set_format(info: *mut GstVideoInfo,
format: GstVideoFormat, width: guint,
height: guint);
pub fn gst_video_info_from_caps(info: *mut GstVideoInfo,
caps: *const GstCaps) -> gboolean;
pub fn gst_video_info_to_caps(info: *mut GstVideoInfo) -> *mut GstCaps;
pub fn gst_video_info_convert(info: *mut GstVideoInfo,
src_format: GstFormat, src_value: gint64,
dest_format: GstFormat,
dest_value: *mut gint64) -> gboolean;
pub fn gst_video_info_is_equal(info: *const GstVideoInfo,
other: *const GstVideoInfo) -> gboolean;
pub fn gst_video_info_align(info: *mut GstVideoInfo,
align: *mut GstVideoAlignment);
pub fn gst_video_frame_map(frame: *mut GstVideoFrame,
info: *mut GstVideoInfo,
buffer: *mut GstBuffer, flags: GstMapFlags)
-> gboolean;
pub fn gst_video_frame_map_id(frame: *mut GstVideoFrame,
info: *mut GstVideoInfo,
buffer: *mut GstBuffer, id: gint,
flags: GstMapFlags) -> gboolean;
pub fn gst_video_frame_unmap(frame: *mut GstVideoFrame);
pub fn gst_video_frame_copy(dest: *mut GstVideoFrame,
src: *const GstVideoFrame) -> gboolean;
pub fn gst_video_frame_copy_plane(dest: *mut GstVideoFrame,
src: *const GstVideoFrame, plane: guint)
-> gboolean;
pub fn gst_video_alignment_reset(align: *mut GstVideoAlignment);
pub fn gst_video_calculate_display_ratio(dar_n: *mut guint,
dar_d: *mut guint,
video_width: guint,
video_height: guint,
video_par_n: guint,
video_par_d: guint,
display_par_n: guint,
display_par_d: guint)
-> gboolean;
pub fn gst_video_convert_sample_async(sample: *mut GstSample,
to_caps: *const GstCaps,
timeout: GstClockTime,
callback:
GstVideoConvertSampleCallback,
user_data: gpointer,
destroy_notify: GDestroyNotify);
pub fn gst_video_convert_sample(sample: *mut GstSample,
to_caps: *const GstCaps,
timeout: GstClockTime,
error: *mut *mut GError)
-> *mut GstSample;
pub fn gst_color_balance_channel_get_type() -> GType;
pub fn gst_color_balance_get_type() -> GType;
pub fn gst_color_balance_list_channels(balance: *mut GstColorBalance)
-> *const GList;
pub fn gst_color_balance_set_value(balance: *mut GstColorBalance,
channel: *mut GstColorBalanceChannel,
value: gint);
pub fn gst_color_balance_get_value(balance: *mut GstColorBalance,
channel: *mut GstColorBalanceChannel)
-> gint;
pub fn gst_color_balance_get_balance_type(balance: *mut GstColorBalance)
-> GstColorBalanceType;
pub fn gst_color_balance_value_changed(balance: *mut GstColorBalance,
channel:
*mut GstColorBalanceChannel,
value: gint);
pub fn gst_adapter_get_type() -> GType;
pub fn gst_adapter_new() -> *mut GstAdapter;
pub fn gst_adapter_clear(adapter: *mut GstAdapter);
pub fn gst_adapter_push(adapter: *mut GstAdapter, buf: *mut GstBuffer);
pub fn gst_adapter_map(adapter: *mut GstAdapter, size: gsize)
-> gconstpointer;
pub fn gst_adapter_unmap(adapter: *mut GstAdapter);
pub fn gst_adapter_copy(adapter: *mut GstAdapter, dest: gpointer,
offset: gsize, size: gsize);
pub fn gst_adapter_copy_bytes(adapter: *mut GstAdapter, offset: gsize,
size: gsize) -> *mut GBytes;
pub fn gst_adapter_flush(adapter: *mut GstAdapter, flush: gsize);
pub fn gst_adapter_take(adapter: *mut GstAdapter, nbytes: gsize)
-> gpointer;
pub fn gst_adapter_take_buffer(adapter: *mut GstAdapter, nbytes: gsize)
-> *mut GstBuffer;
pub fn gst_adapter_take_list(adapter: *mut GstAdapter, nbytes: gsize)
-> *mut GList;
pub fn gst_adapter_take_buffer_fast(adapter: *mut GstAdapter,
nbytes: gsize) -> *mut GstBuffer;
pub fn gst_adapter_available(adapter: *mut GstAdapter) -> gsize;
pub fn gst_adapter_available_fast(adapter: *mut GstAdapter) -> gsize;
pub fn gst_adapter_prev_pts(adapter: *mut GstAdapter,
distance: *mut guint64) -> GstClockTime;
pub fn gst_adapter_prev_dts(adapter: *mut GstAdapter,
distance: *mut guint64) -> GstClockTime;
pub fn gst_adapter_prev_pts_at_offset(adapter: *mut GstAdapter,
offset: gsize,
distance: *mut guint64)
-> GstClockTime;
pub fn gst_adapter_prev_dts_at_offset(adapter: *mut GstAdapter,
offset: gsize,
distance: *mut guint64)
-> GstClockTime;
pub fn gst_adapter_masked_scan_uint32(adapter: *mut GstAdapter,
mask: guint32, pattern: guint32,
offset: gsize, size: gsize)
-> gssize;
pub fn gst_adapter_masked_scan_uint32_peek(adapter: *mut GstAdapter,
mask: guint32,
pattern: guint32,
offset: gsize, size: gsize,
value: *mut guint32) -> gssize;
pub fn gst_video_codec_state_get_type() -> GType;
pub fn gst_video_codec_state_ref(state: *mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_codec_state_unref(state: *mut GstVideoCodecState);
pub fn gst_video_codec_frame_get_type() -> GType;
pub fn gst_video_codec_frame_ref(frame: *mut GstVideoCodecFrame)
-> *mut GstVideoCodecFrame;
pub fn gst_video_codec_frame_unref(frame: *mut GstVideoCodecFrame);
pub fn gst_video_codec_frame_set_user_data(frame: *mut GstVideoCodecFrame,
user_data: gpointer,
notify: GDestroyNotify);
pub fn gst_video_codec_frame_get_user_data(frame: *mut GstVideoCodecFrame)
-> gpointer;
pub fn _gst_video_decoder_error(dec: *mut GstVideoDecoder, weight: gint,
domain: GQuark, code: gint,
txt: *mut gchar, debug: *mut gchar,
file: *const gchar,
function: *const gchar, line: gint)
-> GstFlowReturn;
pub fn gst_video_decoder_get_type() -> GType;
pub fn gst_video_decoder_set_packetized(decoder: *mut GstVideoDecoder,
packetized: gboolean);
pub fn gst_video_decoder_get_packetized(decoder: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_set_estimate_rate(dec: *mut GstVideoDecoder,
enabled: gboolean);
pub fn gst_video_decoder_get_estimate_rate(dec: *mut GstVideoDecoder)
-> gint;
pub fn gst_video_decoder_set_max_errors(dec: *mut GstVideoDecoder,
num: gint);
pub fn gst_video_decoder_get_max_errors(dec: *mut GstVideoDecoder)
-> gint;
pub fn gst_video_decoder_set_needs_format(dec: *mut GstVideoDecoder,
enabled: gboolean);
pub fn gst_video_decoder_get_needs_format(dec: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_set_latency(decoder: *mut GstVideoDecoder,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_video_decoder_get_latency(decoder: *mut GstVideoDecoder,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_video_decoder_get_allocator(decoder: *mut GstVideoDecoder,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_video_decoder_get_buffer_pool(decoder: *mut GstVideoDecoder)
-> *mut GstBufferPool;
pub fn gst_video_decoder_get_frame(decoder: *mut GstVideoDecoder,
frame_number: ::libc::c_int)
-> *mut GstVideoCodecFrame;
pub fn gst_video_decoder_get_oldest_frame(decoder: *mut GstVideoDecoder)
-> *mut GstVideoCodecFrame;
pub fn gst_video_decoder_get_frames(decoder: *mut GstVideoDecoder)
-> *mut GList;
pub fn gst_video_decoder_add_to_frame(decoder: *mut GstVideoDecoder,
n_bytes: ::libc::c_int);
pub fn gst_video_decoder_have_frame(decoder: *mut GstVideoDecoder)
-> GstFlowReturn;
pub fn gst_video_decoder_get_pending_frame_size(decoder:
*mut GstVideoDecoder)
-> gsize;
pub fn gst_video_decoder_allocate_output_buffer(decoder:
*mut GstVideoDecoder)
-> *mut GstBuffer;
pub fn gst_video_decoder_allocate_output_frame(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_set_output_state(decoder: *mut GstVideoDecoder,
fmt: GstVideoFormat,
width: guint, height: guint,
reference:
*mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_decoder_get_output_state(decoder: *mut GstVideoDecoder)
-> *mut GstVideoCodecState;
pub fn gst_video_decoder_negotiate(decoder: *mut GstVideoDecoder)
-> gboolean;
pub fn gst_video_decoder_get_max_decode_time(decoder:
*mut GstVideoDecoder,
frame:
*mut GstVideoCodecFrame)
-> GstClockTimeDiff;
pub fn gst_video_decoder_get_qos_proportion(decoder: *mut GstVideoDecoder)
-> gdouble;
pub fn gst_video_decoder_finish_frame(decoder: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_drop_frame(dec: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_decoder_release_frame(dec: *mut GstVideoDecoder,
frame: *mut GstVideoCodecFrame);
pub fn gst_video_decoder_merge_tags(decoder: *mut GstVideoDecoder,
tags: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_video_encoder_get_type() -> GType;
pub fn gst_video_encoder_get_output_state(encoder: *mut GstVideoEncoder)
-> *mut GstVideoCodecState;
pub fn gst_video_encoder_set_output_state(encoder: *mut GstVideoEncoder,
caps: *mut GstCaps,
reference:
*mut GstVideoCodecState)
-> *mut GstVideoCodecState;
pub fn gst_video_encoder_negotiate(encoder: *mut GstVideoEncoder)
-> gboolean;
pub fn gst_video_encoder_get_frame(encoder: *mut GstVideoEncoder,
frame_number: ::libc::c_int)
-> *mut GstVideoCodecFrame;
pub fn gst_video_encoder_get_oldest_frame(encoder: *mut GstVideoEncoder)
-> *mut GstVideoCodecFrame;
pub fn gst_video_encoder_get_frames(encoder: *mut GstVideoEncoder)
-> *mut GList;
pub fn gst_video_encoder_allocate_output_buffer(encoder:
*mut GstVideoEncoder,
size: gsize)
-> *mut GstBuffer;
pub fn gst_video_encoder_allocate_output_frame(encoder:
*mut GstVideoEncoder,
frame:
*mut GstVideoCodecFrame,
size: gsize)
-> GstFlowReturn;
pub fn gst_video_encoder_finish_frame(encoder: *mut GstVideoEncoder,
frame: *mut GstVideoCodecFrame)
-> GstFlowReturn;
pub fn gst_video_encoder_proxy_getcaps(enc: *mut GstVideoEncoder,
caps: *mut GstCaps,
filter: *mut GstCaps)
-> *mut GstCaps;
pub fn gst_video_encoder_set_latency(encoder: *mut GstVideoEncoder,
min_latency: GstClockTime,
max_latency: GstClockTime);
pub fn gst_video_encoder_get_latency(encoder: *mut GstVideoEncoder,
min_latency: *mut GstClockTime,
max_latency: *mut GstClockTime);
pub fn gst_video_encoder_set_headers(encoder: *mut GstVideoEncoder,
headers: *mut GList);
pub fn gst_video_encoder_merge_tags(encoder: *mut GstVideoEncoder,
tags: *const GstTagList,
mode: GstTagMergeMode);
pub fn gst_video_encoder_get_allocator(encoder: *mut GstVideoEncoder,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_base_transform_get_type() -> GType;
pub fn gst_base_transform_set_passthrough(trans: *mut GstBaseTransform,
passthrough: gboolean);
pub fn gst_base_transform_is_passthrough(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_set_in_place(trans: *mut GstBaseTransform,
in_place: gboolean);
pub fn gst_base_transform_is_in_place(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_update_qos(trans: *mut GstBaseTransform,
proportion: gdouble,
diff: GstClockTimeDiff,
timestamp: GstClockTime);
pub fn gst_base_transform_set_qos_enabled(trans: *mut GstBaseTransform,
enabled: gboolean);
pub fn gst_base_transform_is_qos_enabled(trans: *mut GstBaseTransform)
-> gboolean;
pub fn gst_base_transform_set_gap_aware(trans: *mut GstBaseTransform,
gap_aware: gboolean);
pub fn gst_base_transform_set_prefer_passthrough(trans:
*mut GstBaseTransform,
prefer_passthrough:
gboolean);
pub fn gst_base_transform_get_buffer_pool(trans: *mut GstBaseTransform)
-> *mut GstBufferPool;
pub fn gst_base_transform_get_allocator(trans: *mut GstBaseTransform,
allocator: *mut *mut GstAllocator,
params: *mut GstAllocationParams);
pub fn gst_base_transform_reconfigure_sink(trans: *mut GstBaseTransform);
pub fn gst_base_transform_reconfigure_src(trans: *mut GstBaseTransform);
pub fn gst_video_filter_get_type() -> GType;
pub fn gst_video_meta_api_get_type() -> GType;
pub fn gst_video_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_get_video_meta_id(buffer: *mut GstBuffer, id: gint)
-> *mut GstVideoMeta;
pub fn gst_buffer_add_video_meta(buffer: *mut GstBuffer,
flags: GstVideoFrameFlags,
format: GstVideoFormat, width: guint,
height: guint) -> *mut GstVideoMeta;
pub fn gst_buffer_add_video_meta_full(buffer: *mut GstBuffer,
flags: GstVideoFrameFlags,
format: GstVideoFormat,
width: guint, height: guint,
n_planes: guint, offset: *mut gsize,
stride: *mut gint)
-> *mut GstVideoMeta;
pub fn gst_video_meta_map(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo, data: *mut gpointer,
stride: *mut gint, flags: GstMapFlags)
-> gboolean;
pub fn gst_video_meta_unmap(meta: *mut GstVideoMeta, plane: guint,
info: *mut GstMapInfo) -> gboolean;
pub fn gst_video_crop_meta_api_get_type() -> GType;
pub fn gst_video_crop_meta_get_info() -> *const GstMetaInfo;
pub fn gst_video_meta_transform_scale_get_quark() -> GQuark;
pub fn gst_video_gl_texture_upload_meta_api_get_type() -> GType;
pub fn gst_video_gl_texture_upload_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_add_video_gl_texture_upload_meta(buffer: *mut GstBuffer,
texture_orientation:
GstVideoGLTextureOrientation,
n_textures: guint,
texture_type:
*mut GstVideoGLTextureType,
upload:
GstVideoGLTextureUpload,
user_data: gpointer,
user_data_copy:
GBoxedCopyFunc,
user_data_free:
GBoxedFreeFunc)
-> *mut GstVideoGLTextureUploadMeta;
pub fn gst_video_gl_texture_upload_meta_upload(meta:
*mut GstVideoGLTextureUploadMeta,
texture_id: *mut guint)
-> gboolean;
pub fn gst_video_region_of_interest_meta_api_get_type() -> GType;
pub fn gst_video_region_of_interest_meta_get_info() -> *const GstMetaInfo;
pub fn gst_buffer_get_video_region_of_interest_meta_id(buffer:
*mut GstBuffer,
id: gint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_add_video_region_of_interest_meta(buffer:
*mut GstBuffer,
roi_type:
*const gchar,
x: guint, y: guint,
w: guint, h: guint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_add_video_region_of_interest_meta_id(buffer:
*mut GstBuffer,
roi_type: GQuark,
x: guint, y: guint,
w: guint, h: guint)
-> *mut GstVideoRegionOfInterestMeta;
pub fn gst_buffer_pool_config_set_video_alignment(config:
*mut GstStructure,
align:
*mut GstVideoAlignment);
pub fn gst_buffer_pool_config_get_video_alignment(config:
*mut GstStructure,
align:
*mut GstVideoAlignment)
-> gboolean;
pub fn gst_video_buffer_pool_get_type() -> GType;
pub fn gst_video_buffer_pool_new() -> *mut GstBufferPool;
pub fn gst_video_sink_get_type() -> GType;
pub fn gst_video_sink_center_rect(src: GstVideoRectangle,
dst: GstVideoRectangle,
result: *mut GstVideoRectangle,
scaling: gboolean);
pub fn gst_navigation_get_type() -> GType;
pub fn gst_navigation_query_get_type(query: *mut GstQuery)
-> GstNavigationQueryType;
pub fn gst_navigation_query_new_commands() -> *mut GstQuery;
pub fn gst_navigation_query_set_commands(query: *mut GstQuery,
n_cmds: gint, ...);
pub fn gst_navigation_query_set_commandsv(query: *mut GstQuery,
n_cmds: gint,
cmds:
*mut GstNavigationCommand);
pub fn gst_navigation_query_parse_commands_length(query: *mut GstQuery,
n_cmds: *mut guint)
-> gboolean;
pub fn gst_navigation_query_parse_commands_nth(query: *mut GstQuery,
nth: guint,
cmd:
*mut GstNavigationCommand)
-> gboolean;
pub fn gst_navigation_query_new_angles() -> *mut GstQuery;
pub fn gst_navigation_query_set_angles(query: *mut GstQuery,
cur_angle: guint, n_angles: guint);
pub fn gst_navigation_query_parse_angles(query: *mut GstQuery,
cur_angle: *mut guint,
n_angles: *mut guint)
-> gboolean;
pub fn gst_navigation_message_get_type(message: *mut GstMessage)
-> GstNavigationMessageType;
pub fn gst_navigation_message_new_mouse_over(src: *mut GstObject,
active: gboolean)
-> *mut GstMessage;
pub fn gst_navigation_message_parse_mouse_over(message: *mut GstMessage,
active: *mut gboolean)
-> gboolean;
pub fn gst_navigation_message_new_commands_changed(src: *mut GstObject)
-> *mut GstMessage;
pub fn gst_navigation_message_new_angles_changed(src: *mut GstObject,
cur_angle: guint,
n_angles: guint)
-> *mut GstMessage;
pub fn gst_navigation_message_parse_angles_changed(message:
*mut GstMessage,
cur_angle: *mut guint,
n_angles: *mut guint)
-> gboolean;
pub fn gst_navigation_event_get_type(event: *mut GstEvent)
-> GstNavigationEventType;
pub fn gst_navigation_event_parse_key_event(event: *mut GstEvent,
key: *mut *const gchar)
-> gboolean;
pub fn gst_navigation_event_parse_mouse_button_event(event: *mut GstEvent,
button: *mut gint,
x: *mut gdouble,
y: *mut gdouble)
-> gboolean;
pub fn gst_navigation_event_parse_mouse_move_event(event: *mut GstEvent,
x: *mut gdouble,
y: *mut gdouble)
-> gboolean;
pub fn gst_navigation_event_parse_command(event: *mut GstEvent,
command:
*mut GstNavigationCommand)
-> gboolean;
pub fn gst_navigation_send_event(navigation: *mut GstNavigation,
structure: *mut GstStructure);
pub fn gst_navigation_send_key_event(navigation: *mut GstNavigation,
event: *const ::libc::c_char,
key: *const ::libc::c_char);
pub fn gst_navigation_send_mouse_event(navigation: *mut GstNavigation,
event: *const ::libc::c_char,
button: ::libc::c_int,
x: ::libc::c_double,
y: ::libc::c_double);
pub fn gst_navigation_send_command(navigation: *mut GstNavigation,
command: GstNavigationCommand);
pub fn gst_video_blend_scale_linear_RGBA(src: *mut GstVideoInfo,
src_buffer: *mut GstBuffer,
dest_height: gint,
dest_width: gint,
dest: *mut GstVideoInfo,
dest_buffer:
*mut *mut GstBuffer);
pub fn gst_video_blend(dest: *mut GstVideoFrame, src: *mut GstVideoFrame,
x: gint, y: gint, global_alpha: gfloat)
-> gboolean;
pub fn gst_video_event_new_still_frame(in_still: gboolean)
-> *mut GstEvent;
pub fn gst_video_event_parse_still_frame(event: *mut GstEvent,
in_still: *mut gboolean)
-> gboolean;
pub fn gst_video_event_new_downstream_force_key_unit(timestamp:
GstClockTime,
stream_time:
GstClockTime,
running_time:
GstClockTime,
all_headers:
gboolean,
count: guint)
-> *mut GstEvent;
pub fn gst_video_event_parse_downstream_force_key_unit(event:
*mut GstEvent,
timestamp:
*mut GstClockTime,
stream_time:
*mut GstClockTime,
running_time:
*mut GstClockTime,
all_headers:
*mut gboolean,
count: *mut guint)
-> gboolean;
pub fn gst_video_event_new_upstream_force_key_unit(running_time:
GstClockTime,
all_headers: gboolean,
count: guint)
-> *mut GstEvent;
pub fn gst_video_event_parse_upstream_force_key_unit(event: *mut GstEvent,
running_time:
*mut GstClockTime,
all_headers:
*mut gboolean,
count: *mut guint)
-> gboolean;
pub fn gst_video_event_is_force_key_unit(event: *mut GstEvent)
-> gboolean;
pub fn gst_video_orientation_get_type() -> GType;
pub fn gst_video_orientation_get_hflip(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean) -> gboolean;
pub fn gst_video_orientation_get_vflip(video_orientation:
*mut GstVideoOrientation,
flip: *mut gboolean) -> gboolean;
pub fn gst_video_orientation_get_hcenter(video_orientation:
*mut GstVideoOrientation,
center: *mut gint) -> gboolean;
pub fn gst_video_orientation_get_vcenter(video_orientation:
*mut GstVideoOrientation,
center: *mut gint) -> gboolean;
pub fn gst_video_orientation_set_hflip(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean;
pub fn gst_video_orientation_set_vflip(video_orientation:
*mut GstVideoOrientation,
flip: gboolean) -> gboolean;
pub fn gst_video_orientation_set_hcenter(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean;
pub fn gst_video_orientation_set_vcenter(video_orientation:
*mut GstVideoOrientation,
center: gint) -> gboolean;
pub fn gst_video_overlay_rectangle_get_type() -> GType;
pub fn gst_video_overlay_rectangle_new_raw(pixels: *mut GstBuffer,
render_x: gint, render_y: gint,
render_width: guint,
render_height: guint,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_rectangle_copy(rectangle:
*mut GstVideoOverlayRectangle)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_rectangle_get_seqnum(rectangle:
*mut GstVideoOverlayRectangle)
-> guint;
pub fn gst_video_overlay_rectangle_set_render_rectangle(rectangle:
*mut GstVideoOverlayRectangle,
render_x: gint,
render_y: gint,
render_width:
guint,
render_height:
guint);
pub fn gst_video_overlay_rectangle_get_render_rectangle(rectangle:
*mut GstVideoOverlayRectangle,
render_x:
*mut gint,
render_y:
*mut gint,
render_width:
*mut guint,
render_height:
*mut guint)
-> gboolean;
pub fn gst_video_overlay_rectangle_get_pixels_raw(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_argb(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_ayuv(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_raw(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_argb(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_pixels_unscaled_ayuv(rectangle:
*mut GstVideoOverlayRectangle,
flags:
GstVideoOverlayFormatFlags)
-> *mut GstBuffer;
pub fn gst_video_overlay_rectangle_get_flags(rectangle:
*mut GstVideoOverlayRectangle)
-> GstVideoOverlayFormatFlags;
pub fn gst_video_overlay_rectangle_get_global_alpha(rectangle:
*mut GstVideoOverlayRectangle)
-> gfloat;
pub fn gst_video_overlay_rectangle_set_global_alpha(rectangle:
*mut GstVideoOverlayRectangle,
global_alpha: gfloat);
pub fn gst_video_overlay_composition_get_type() -> GType;
pub fn gst_video_overlay_composition_copy(comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_make_writable(comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_new(rectangle:
*mut GstVideoOverlayRectangle)
-> *mut GstVideoOverlayComposition;
pub fn gst_video_overlay_composition_add_rectangle(comp:
*mut GstVideoOverlayComposition,
rectangle:
*mut GstVideoOverlayRectangle);
pub fn gst_video_overlay_composition_n_rectangles(comp:
*mut GstVideoOverlayComposition)
-> guint;
pub fn gst_video_overlay_composition_get_rectangle(comp:
*mut GstVideoOverlayComposition,
n: guint)
-> *mut GstVideoOverlayRectangle;
pub fn gst_video_overlay_composition_get_seqnum(comp:
*mut GstVideoOverlayComposition)
-> guint;
pub fn gst_video_overlay_composition_blend(comp:
*mut GstVideoOverlayComposition,
video_buf: *mut GstVideoFrame)
-> gboolean;
pub fn gst_video_overlay_composition_meta_api_get_type() -> GType;
pub fn gst_video_overlay_composition_meta_get_info()
-> *const GstMetaInfo;
pub fn gst_buffer_add_video_overlay_composition_meta(buf: *mut GstBuffer,
comp:
*mut GstVideoOverlayComposition)
-> *mut GstVideoOverlayCompositionMeta;
pub fn gst_video_overlay_get_type() -> GType;
pub fn gst_video_overlay_set_render_rectangle(overlay:
*mut GstVideoOverlay,
x: gint, y: gint,
width: gint, height: gint)
-> gboolean;
pub fn gst_video_overlay_expose(overlay: *mut GstVideoOverlay);
pub fn gst_video_overlay_handle_events(overlay: *mut GstVideoOverlay,
handle_events: gboolean);
pub fn gst_video_overlay_set_window_handle(overlay: *mut GstVideoOverlay,
handle: guintptr);
pub fn gst_video_overlay_got_window_handle(overlay: *mut GstVideoOverlay,
handle: guintptr);
pub fn gst_video_overlay_prepare_window_handle(overlay:
*mut GstVideoOverlay);
pub fn gst_is_video_overlay_prepare_window_handle_message(msg:
*mut GstMessage)
-> gboolean;
}
|
use bytecode::{Chunk, Inst};
use std::collections::HashMap;
use syntax::{Expr, ExprF, Literal};
pub struct Codegen<'str> {
next_str_id: usize,
strs: HashMap<usize, &'str str>,
pub chunks: Vec<Chunk>,
}
impl<'str> Codegen<'str> {
pub fn new() -> Self {
Codegen{
next_str_id: 0,
strs: HashMap::new(),
chunks: vec![],
}
}
pub fn strs(&self) -> &HashMap<usize, &'str str> {
&self.strs
}
fn codegen_func_bytecode(
&mut self,
locals: usize,
captures: usize,
insts: Vec<Inst>,
) -> usize {
self.chunks.push(Chunk{
insts: insts,
locals: locals,
captures: captures,
});
self.chunks.len() - 1
}
pub fn codegen_func<'expr, T>(
&mut self,
env: &HashMap<&str, usize>,
captures: usize,
body: &Expr<'str, 'expr, T>,
) -> usize {
let mut insts = vec![];
self.codegen_expr(env, body, &mut insts);
insts.push(Inst::Return);
self.chunks.push(Chunk{
insts: insts,
locals: 1 + captures,
captures: captures,
});
self.chunks.len() - 1
}
pub fn codegen_expr<'expr, T>(
&mut self,
env: &HashMap<&str, usize>,
expr: &Expr<'str, 'expr, T>,
insts: &mut Vec<Inst>,
) {
match expr.1 {
ExprF::Lit(ref lit) =>
self.codegen_literal(lit, insts),
ExprF::Var("stdout#") => // TODO: Move to feldspar::builtin
insts.push(Inst::NewI32(1)),
ExprF::Var("to_utf8#") => { // TODO: Move to feldspar::builtin
let chunk_id = self.codegen_func_bytecode(1, 0, vec![
Inst::GetLocal(0),
Inst::Return,
]);
insts.push(Inst::NewFunc(chunk_id));
},
ExprF::Var("write#") => { // TODO: Move to feldspar::builtin
let action_chunk_id = self.codegen_func_bytecode(3, 2, vec![
Inst::GetLocal(1), // handle
Inst::GetLocal(2), // bytes
Inst::Write,
Inst::Return,
]);
let curry2_chunk_id = self.codegen_func_bytecode(2, 1, vec![
Inst::GetLocal(0), // bytes
Inst::GetLocal(1), // handle
Inst::NewFunc(action_chunk_id),
Inst::Return,
]);
let curry1_chunk_id = self.codegen_func_bytecode(1, 0, vec![
Inst::GetLocal(0), // handle
Inst::NewFunc(curry2_chunk_id),
Inst::Return,
]);
insts.push(Inst::NewFunc(curry1_chunk_id));
},
ExprF::Var(name) => {
let offset = env[name];
insts.push(Inst::GetLocal(offset));
},
ExprF::Abs(param, body) => {
let mut body_env = HashMap::new();
body_env.insert(param, 0);
for (i, (k, &v)) in env.iter().enumerate() {
body_env.insert(k, i + 1);
insts.push(Inst::GetLocal(v));
}
let chunk_id = self.codegen_func(&body_env, env.len(), body);
insts.push(Inst::NewFunc(chunk_id));
},
ExprF::App(callee, argument) => {
self.codegen_expr(env, callee, insts);
self.codegen_expr(env, argument, insts);
insts.push(Inst::Call);
},
ExprF::Tup(_) => panic!("NYI"),
}
}
pub fn codegen_literal(
&mut self,
lit: &Literal<'str>,
insts: &mut Vec<Inst>,
) {
match *lit {
Literal::Bool(value) =>
insts.push(Inst::NewI32(value as i32)),
Literal::Str(value) => {
let id = self.next_str_id;
self.next_str_id += 1;
self.strs.insert(id, value);
insts.push(Inst::NewStr(id));
},
_ => panic!("codegen_literal: NYI"),
}
}
}
Codegen tuple expressions
use bytecode::{Chunk, Inst};
use std::collections::HashMap;
use syntax::{Expr, ExprF, Literal};
pub struct Codegen<'str> {
next_str_id: usize,
strs: HashMap<usize, &'str str>,
pub chunks: Vec<Chunk>,
}
impl<'str> Codegen<'str> {
pub fn new() -> Self {
Codegen{
next_str_id: 0,
strs: HashMap::new(),
chunks: vec![],
}
}
pub fn strs(&self) -> &HashMap<usize, &'str str> {
&self.strs
}
fn codegen_func_bytecode(
&mut self,
locals: usize,
captures: usize,
insts: Vec<Inst>,
) -> usize {
self.chunks.push(Chunk{
insts: insts,
locals: locals,
captures: captures,
});
self.chunks.len() - 1
}
pub fn codegen_func<'expr, T>(
&mut self,
env: &HashMap<&str, usize>,
captures: usize,
body: &Expr<'str, 'expr, T>,
) -> usize {
let mut insts = vec![];
self.codegen_expr(env, body, &mut insts);
insts.push(Inst::Return);
self.chunks.push(Chunk{
insts: insts,
locals: 1 + captures,
captures: captures,
});
self.chunks.len() - 1
}
pub fn codegen_expr<'expr, T>(
&mut self,
env: &HashMap<&str, usize>,
expr: &Expr<'str, 'expr, T>,
insts: &mut Vec<Inst>,
) {
match expr.1 {
ExprF::Lit(ref lit) =>
self.codegen_literal(lit, insts),
ExprF::Var("stdout#") => // TODO: Move to feldspar::builtin
insts.push(Inst::NewI32(1)),
ExprF::Var("to_utf8#") => { // TODO: Move to feldspar::builtin
let chunk_id = self.codegen_func_bytecode(1, 0, vec![
Inst::GetLocal(0),
Inst::Return,
]);
insts.push(Inst::NewFunc(chunk_id));
},
ExprF::Var("write#") => { // TODO: Move to feldspar::builtin
let action_chunk_id = self.codegen_func_bytecode(3, 2, vec![
Inst::GetLocal(1), // handle
Inst::GetLocal(2), // bytes
Inst::Write,
Inst::Return,
]);
let curry2_chunk_id = self.codegen_func_bytecode(2, 1, vec![
Inst::GetLocal(0), // bytes
Inst::GetLocal(1), // handle
Inst::NewFunc(action_chunk_id),
Inst::Return,
]);
let curry1_chunk_id = self.codegen_func_bytecode(1, 0, vec![
Inst::GetLocal(0), // handle
Inst::NewFunc(curry2_chunk_id),
Inst::Return,
]);
insts.push(Inst::NewFunc(curry1_chunk_id));
},
ExprF::Var(name) => {
let offset = env[name];
insts.push(Inst::GetLocal(offset));
},
ExprF::Abs(param, body) => {
let mut body_env = HashMap::new();
body_env.insert(param, 0);
for (i, (k, &v)) in env.iter().enumerate() {
body_env.insert(k, i + 1);
insts.push(Inst::GetLocal(v));
}
let chunk_id = self.codegen_func(&body_env, env.len(), body);
insts.push(Inst::NewFunc(chunk_id));
},
ExprF::App(callee, argument) => {
self.codegen_expr(env, callee, insts);
self.codegen_expr(env, argument, insts);
insts.push(Inst::Call);
},
ExprF::Tup(ref elems) => {
for elem in elems {
self.codegen_expr(env, elem, insts);
}
insts.push(Inst::New(elems.len(), 0));
},
}
}
pub fn codegen_literal(
&mut self,
lit: &Literal<'str>,
insts: &mut Vec<Inst>,
) {
match *lit {
Literal::Bool(value) =>
insts.push(Inst::NewI32(value as i32)),
Literal::Str(value) => {
let id = self.next_str_id;
self.next_str_id += 1;
self.strs.insert(id, value);
insts.push(Inst::NewStr(id));
},
_ => panic!("codegen_literal: NYI"),
}
}
}
|
use std::fs;
use std::path::Path;
pub fn initialize() {
println!("Initialize ...");
let dir_name = ".keepha";
if !dir_exists(dir_name) {
match fs::create_dir(dir_name) {
Ok(_) => println!(" OK: Created \"{}\" directory.", dir_name),
Err(why) => panic!("{:?}", why),
}
} else {
println!(" OK: \"{}\" directory has already exist.", dir_name);
}
}
fn dir_exists<P: AsRef<Path>>(path: P) -> bool {
match fs::metadata(path) {
Ok(m) => m.is_dir(),
Err(why) => {
match why.raw_os_error() {
Some(2) => false,
_ => panic!("{:?}", why),
}
}
}
}
pub fn set_params() {
println!("set parameters");
}
pub fn sweep() {
println!("sweep");
}
pub fn register_with_cron() {
println!("register");
}
pub fn unregister_cron() {
println!("unregister");
}
pub fn destroy() {
println!("destroy");
}
Swap "if" statements
use std::fs;
use std::path::Path;
pub fn initialize() {
println!("Initialize ...");
let dir_name = ".keepha";
if dir_exists(dir_name) {
println!(" OK: \"{}\" directory has already exist.", dir_name);
} else {
match fs::create_dir(dir_name) {
Ok(_) => println!(" OK: Created \"{}\" directory.", dir_name),
Err(why) => panic!("{:?}", why),
}
}
}
fn dir_exists<P: AsRef<Path>>(path: P) -> bool {
match fs::metadata(path) {
Ok(m) => m.is_dir(),
Err(why) => {
match why.raw_os_error() {
Some(2) => false,
_ => panic!("{:?}", why),
}
}
}
}
pub fn set_params() {
println!("set parameters");
}
pub fn sweep() {
println!("sweep");
}
pub fn register_with_cron() {
println!("register");
}
pub fn unregister_cron() {
println!("unregister");
}
pub fn destroy() {
println!("destroy");
}
|
//! Comparators.
//!
//! A comparator is any type that implements the [`Compare`](trait.Compare.html) trait,
//! which imposes a [total order](https://en.wikipedia.org/wiki/Total_order). Its
//! [`compare`](trait.Compare.html#tymethod.compare) method accepts two values, which may
//! be of the same type or different types, and returns an ordering on them.
//!
//! Comparators are useful for parameterizing the behavior of sort methods and certain
//! data structures.
//!
//! The most basic comparator is [`Natural`](struct.Natural.html), which simply delegates
//! to the type's implementation of [`Ord`]
//! (http://doc.rust-lang.org/std/cmp/trait.Ord.html):
//!
//! ```rust
//! use collect::compare::{Compare, Natural};
//! use std::cmp::Ordering::{Less, Equal, Greater};
//!
//! let a = &1;
//! let b = &2;
//!
//! let cmp = Natural;
//! assert_eq!(cmp.compare(a, b), Less);
//! assert_eq!(cmp.compare(b, a), Greater);
//! assert_eq!(cmp.compare(a, a), Equal);
//! ```
//!
//! There are convenience methods for checking each of the six relations:
//!
//! ```rust
//! use collect::compare::{Compare, Natural};
//!
//! let a = &1;
//! let b = &2;
//!
//! let cmp = Natural;
//! assert!(cmp.compares_lt(a, b));
//! assert!(cmp.compares_le(a, b));
//! assert!(cmp.compares_ge(b, a));
//! assert!(cmp.compares_gt(b, a));
//! assert!(cmp.compares_eq(a, a));
//! assert!(cmp.compares_ne(a, b));
//! ```
//!
//! The [`CompareExt`](trait.CompareExt.html) trait provides extension methods that
//! consume a comparator to produce a new one with different behavior, similar to
//! [iterator adaptors](http://doc.rust-lang.org/std/iter/trait.IteratorExt.html). For
//! example, all comparators can be [reversed](trait.CompareExt.html#method.rev):
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt, Natural};
//! use std::cmp::Ordering::Greater;
//!
//! let cmp = Natural.rev();
//! assert_eq!(cmp.compare(&1, &2), Greater);
//! ```
//!
//! It is possible to implement a comparator that is not based on the natural ordering of
//! a type by using a closure of type `Fn(&Lhs, &Rhs) -> Ordering`. For example, vectors
//! can be compared by their length instead of their contents:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt};
//! use std::cmp::Ordering::{Less, Greater};
//!
//! let a = vec![1, 2, 3];
//! let b = vec![4, 5];
//!
//! let cmp = |&: lhs: &Vec<u8>, rhs: &Vec<u8>| lhs.len().cmp(&rhs.len());
//! assert_eq!(cmp.compare(&a, &b), Greater);
//!
//! let cmp = cmp.rev();
//! assert_eq!(cmp.compare(&a, &b), Less);
//! ```
//!
//! Comparators can be combined [lexicographically]
//! (https://en.wikipedia.org/wiki/Lexicographical_order) in order to compare values
//! first by one key, [then](trait.CompareExt.html#method.then), if the first keys were
//! equal, by another:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt};
//! use std::cmp::Ordering::{Less, Equal, Greater};
//!
//! struct Pet { name: &'static str, age: u8 }
//!
//! let fido4 = &Pet { name: "Fido", age: 4 };
//! let ruff2 = &Pet { name: "Ruff", age: 2 };
//! let fido3 = &Pet { name: "Fido", age: 3 };
//!
//! let name_cmp = |&: lhs: &Pet, rhs: &Pet| lhs.name.cmp(rhs.name);
//! assert_eq!(name_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_cmp.compare(fido4, fido3), Equal);
//! assert_eq!(name_cmp.compare(ruff2, fido3), Greater);
//!
//! let age_cmp = |&: lhs: &Pet, rhs: &Pet| lhs.age.cmp(&rhs.age);
//! assert_eq!(age_cmp.compare(fido4, ruff2), Greater);
//! assert_eq!(age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(age_cmp.compare(ruff2, fido3), Less);
//!
//! let name_age_cmp = name_cmp.then(age_cmp);
//! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater);
//! ```
//!
//! It is often repetitive to compare two values of the same type by the same key, so the
//! [key-extraction logic](struct.Extract.html) can be factored out, simplifying the
//! previous example:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt, Extract, Natural};
//! use std::cmp::Ordering::{Less, Greater};
//!
//! struct Pet { name: &'static str, age: u8 }
//!
//! let fido4 = &Pet { name: "Fido", age: 4 };
//! let ruff2 = &Pet { name: "Ruff", age: 2 };
//! let fido3 = &Pet { name: "Fido", age: 3 };
//!
//! let name_age_cmp = Extract::new(|p: &Pet| p.name, Natural)
//! .then(Extract::new(|p: &Pet| p.age, Natural));
//!
//! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater);
//! ```
use std::borrow::BorrowFrom;
use std::cmp::Ordering::{self, Less, Equal, Greater};
use std::default::Default;
/// Returns the maximum of two values according to the given comparator, or `lhs` if they
/// are equal.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Extract, Natural, max};
///
/// struct Foo { key: char, id: u8 }
///
/// let f1 = &Foo { key: 'a', id: 1};
/// let f2 = &Foo { key: 'a', id: 2};
/// let f3 = &Foo { key: 'b', id: 3};
///
/// let cmp = Extract::new(|f: &Foo| f.key, Natural);
/// assert_eq!(max(&cmp, f1, f2).id, f1.id);
/// assert_eq!(max(&cmp, f1, f3).id, f3.id);
/// ```
// FIXME: convert to default method on `Compare` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
pub fn max<'a, C: ?Sized, T: ?Sized>(cmp: &C, lhs: &'a T, rhs: &'a T) -> &'a T
where C: Compare<T> {
if cmp.compares_ge(lhs, rhs) { lhs } else { rhs }
}
/// Returns the minimum of two values according to the given comparator, or `lhs` if they
/// are equal.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Extract, Natural, min};
///
/// struct Foo { key: char, id: u8 }
///
/// let f1 = &Foo { key: 'b', id: 1};
/// let f2 = &Foo { key: 'b', id: 2};
/// let f3 = &Foo { key: 'a', id: 3};
///
/// let cmp = Extract::new(|f: &Foo| f.key, Natural);
/// assert_eq!(min(&cmp, f1, f2).id, f1.id);
/// assert_eq!(min(&cmp, f1, f3).id, f3.id);
/// ```
// FIXME: convert to default method on `Compare` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
pub fn min<'a, C: ?Sized, T: ?Sized>(cmp: &C, lhs: &'a T, rhs: &'a T) -> &'a T
where C: Compare<T> {
if cmp.compares_le(lhs, rhs) { lhs } else { rhs }
}
/// A comparator imposing a [total order](https://en.wikipedia.org/wiki/Total_order).
///
/// See the [`compare` module's documentation](index.html) for detailed usage.
///
/// The `compares_*` methods may be overridden to provide more efficient implementations.
pub trait Compare<Lhs: ?Sized, Rhs: ?Sized = Lhs> {
/// Compares two values, returning `Less`, `Equal`, or `Greater` if `lhs` is less
/// than, equal to, or greater than `rhs`, respectively.
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering;
/// Checks if `lhs` is less than `rhs`.
fn compares_lt(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Less
}
/// Checks if `lhs` is less than or equal to `rhs`.
fn compares_le(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Greater
}
/// Checks if `lhs` is greater than or equal to `rhs`.
fn compares_ge(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Less
}
/// Checks if `lhs` is greater than `rhs`.
fn compares_gt(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Greater
}
/// Checks if `lhs` is equal to `rhs`.
fn compares_eq(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Equal
}
/// Checks if `lhs` is not equal to `rhs`.
fn compares_ne(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Equal
}
}
impl<F: ?Sized, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for F
where F: Fn(&Lhs, &Rhs) -> Ordering {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering { (*self)(lhs, rhs) }
}
/// An extension trait with methods applicable to all comparators.
pub trait CompareExt<Lhs: ?Sized, Rhs: ?Sized = Lhs> : Compare<Lhs, Rhs> + Sized {
/// Borrows the comparator's parameters before comparing them.
///
/// # Examples
///
/// ```rust
/// #![allow(unstable)]
/// use collect::compare::{Compare, CompareExt, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a_str = "a";
/// let a_string = a_str.to_string();
///
/// let b_str = "b";
/// let b_string = b_str.to_string();
///
/// let cmp = Natural::<str>.borrow();
/// assert_eq!(cmp.compare(a_str, &a_string), Equal);
/// assert_eq!(cmp.compare(a_str, b_str), Less);
/// assert_eq!(cmp.compare(&b_string, a_str), Greater);
/// ```
fn borrow(self) -> Borrow<Self> { Borrow(self) }
/// Reverses the ordering of the comparator.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a = &1;
/// let b = &2;
///
/// let cmp = Natural.rev();
/// assert_eq!(cmp.compare(a, b), Greater);
/// assert_eq!(cmp.compare(b, a), Less);
/// assert_eq!(cmp.compare(a, a), Equal);
/// ```
fn rev(self) -> Rev<Self> { Rev(self) }
/// Swaps the comparator's parameters, maintaining the underlying ordering.
///
/// This is useful for providing a comparator `C: Compare<T, U>` in a context that
/// expects `C: Compare<U, T>`.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let cmp = |&: lhs: &u8, rhs: &u16| (*lhs as u16).cmp(rhs);
/// assert_eq!(cmp.compare(&1u8, &2u16), Less);
/// assert_eq!(cmp.compare(&2u8, &1u16), Greater);
/// assert_eq!(cmp.compare(&1u8, &1u16), Equal);
///
/// let cmp = cmp.swap();
/// assert_eq!(cmp.compare(&2u16, &1u8), Less);
/// assert_eq!(cmp.compare(&1u16, &2u8), Greater);
/// assert_eq!(cmp.compare(&1u16, &1u8), Equal);
/// ```
fn swap(self) -> Swap<Self> { Swap(self) }
/// [Lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) combines
/// the comparator with another.
///
/// The retuned comparator compares values first using `self`, then, if they are
/// equal, using `then`.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt};
/// use std::cmp::Ordering::{Less, Equal};
///
/// struct Foo { key1: char, key2: u8 }
///
/// let f1 = &Foo { key1: 'a', key2: 2};
/// let f2 = &Foo { key1: 'a', key2: 3};
///
/// let cmp = |&: lhs: &Foo, rhs: &Foo| lhs.key1.cmp(&rhs.key1);
/// assert_eq!(cmp.compare(f1, f2), Equal);
///
/// let cmp = cmp.then(|&: lhs: &Foo, rhs: &Foo| lhs.key2.cmp(&rhs.key2));
/// assert_eq!(cmp.compare(f1, f2), Less);
/// ```
fn then<D>(self, then: D) -> Lexicographic<Self, D> where D: Compare<Lhs, Rhs> {
Lexicographic(self, then)
}
}
impl<C, Lhs: ?Sized, Rhs: ?Sized> CompareExt<Lhs, Rhs> for C where C: Compare<Lhs, Rhs> {}
/// A comparator that borrows its parameters before comparing them.
///
/// See [`CompareExt::borrow`](trait.CompareExt.html#method.borrow) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Borrow<C>(C);
#[old_impl_check]
impl<C, Lhs: ?Sized, Rhs: ?Sized, Lb: ?Sized, Rb: ?Sized> Compare<Lhs, Rhs> for Borrow<C>
where C: Compare<Lb, Rb>, Lb: BorrowFrom<Lhs>, Rb: BorrowFrom<Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
self.0.compare(BorrowFrom::borrow_from(lhs), BorrowFrom::borrow_from(rhs))
}
}
/// A comparator that extracts a sort key from a value.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, Extract, Natural};
/// use std::cmp::Ordering::Greater;
///
/// let a = vec![1, 2, 3];
/// let b = vec![4, 5];
///
/// let cmp = Extract::new(|vec: &Vec<u8>| vec.len(), Natural);
/// assert_eq!(cmp.compare(&a, &b), Greater);
/// ```
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Extract<E, C> {
ext: E,
cmp: C,
}
// FIXME: convert to default method on `CompareExt` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
#[old_impl_check]
impl<E, C, T: ?Sized, K> Extract<E, C> where E: Fn(&T) -> K, C: Compare<K> {
/// Returns a comparator that extracts a sort key using `ext` and compares it using
/// `cmp`.
pub fn new(ext: E, cmp: C) -> Extract<E, C> { Extract { ext: ext, cmp: cmp } }
}
#[old_impl_check]
impl<E, C, T: ?Sized, K> Compare<T> for Extract<E, C>
where E: Fn(&T) -> K, C: Compare<K> {
fn compare(&self, lhs: &T, rhs: &T) -> Ordering {
self.cmp.compare(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_lt(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_lt(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_le(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_le(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_ge(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_ge(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_gt(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_gt(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_eq(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_eq(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_ne(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_ne(&(self.ext)(lhs), &(self.ext)(rhs))
}
}
/// A comparator that [lexicographically]
/// (https://en.wikipedia.org/wiki/Lexicographical_order) combines two others.
///
/// See [`CompareExt::then`](trait.CompareExt.html#method.then) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Lexicographic<C, D>(C, D);
impl<C, D, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for Lexicographic<C, D>
where C: Compare<Lhs, Rhs>, D: Compare<Lhs, Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
match self.0.compare(lhs, rhs) {
Equal => self.1.compare(lhs, rhs),
order => order,
}
}
}
/// A comparator that delegates to [`Ord`]
/// (http://doc.rust-lang.org/std/cmp/trait.Ord.html).
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a = &1;
/// let b = &2;
///
/// let cmp = Natural;
/// assert_eq!(cmp.compare(a, b), Less);
/// assert_eq!(cmp.compare(b, a), Greater);
/// assert_eq!(cmp.compare(a, a), Equal);
/// ```
pub struct Natural<T: Ord + ?Sized>;
impl<T: Ord + ?Sized> Compare<T> for Natural<T> {
fn compare(&self, lhs: &T, rhs: &T) -> Ordering { Ord::cmp(lhs, rhs) }
fn compares_lt(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::lt(lhs, rhs) }
fn compares_le(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::le(lhs, rhs) }
fn compares_ge(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::ge(lhs, rhs) }
fn compares_gt(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::gt(lhs, rhs) }
fn compares_eq(&self, lhs: &T, rhs: &T) -> bool { PartialEq::eq(lhs, rhs) }
fn compares_ne(&self, lhs: &T, rhs: &T) -> bool { PartialEq::ne(lhs, rhs) }
}
// FIXME: replace with `derive(Clone)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Clone for Natural<T> {
fn clone(&self) -> Natural<T> { *self }
}
// FIXME: replace with `derive(Copy)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Copy for Natural<T> {}
// FIXME: replace with `derive(Default)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Default for Natural<T> {
fn default() -> Natural<T> { Natural }
}
// FIXME: replace with `derive(PartialEq)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> PartialEq for Natural<T> {
fn eq(&self, _other: &Natural<T>) -> bool { true }
}
// FIXME: replace with `derive(Eq)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Eq for Natural<T> {}
/// A comparator that reverses the ordering of another.
///
/// See [`CompareExt::rev`](trait.CompareExt.html#method.rev) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Rev<C>(C);
impl<C, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for Rev<C> where C: Compare<Lhs, Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
self.0.compare(lhs, rhs).reverse()
}
fn compares_lt(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_gt(lhs, rhs) }
fn compares_le(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_ge(lhs, rhs) }
fn compares_ge(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_le(lhs, rhs) }
fn compares_gt(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_lt(lhs, rhs) }
fn compares_eq(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_eq(lhs, rhs) }
fn compares_ne(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_ne(lhs, rhs) }
}
/// A comparator that swaps another's parameters, maintaining the underlying ordering.
///
/// This is useful for providing a comparator `C: Compare<T, U>` in a context that
/// expects `C: Compare<U, T>`.
///
/// See [`CompareExt::swap`](trait.CompareExt.html#method.swap) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Swap<C>(C);
impl<C, Lhs: ?Sized, Rhs: ?Sized> Compare<Rhs, Lhs> for Swap<C>
where C: Compare<Lhs, Rhs> {
fn compare(&self, rhs: &Rhs, lhs: &Lhs) -> Ordering { self.0.compare(lhs, rhs) }
fn compares_lt(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_lt(lhs, rhs) }
fn compares_le(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_le(lhs, rhs) }
fn compares_ge(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_ge(lhs, rhs) }
fn compares_gt(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_gt(lhs, rhs) }
fn compares_eq(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_eq(lhs, rhs) }
fn compares_ne(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_ne(lhs, rhs) }
}
implement `Compare` for references
//! Comparators.
//!
//! A comparator is any type that implements the [`Compare`](trait.Compare.html) trait,
//! which imposes a [total order](https://en.wikipedia.org/wiki/Total_order). Its
//! [`compare`](trait.Compare.html#tymethod.compare) method accepts two values, which may
//! be of the same type or different types, and returns an ordering on them.
//!
//! Comparators are useful for parameterizing the behavior of sort methods and certain
//! data structures.
//!
//! The most basic comparator is [`Natural`](struct.Natural.html), which simply delegates
//! to the type's implementation of [`Ord`]
//! (http://doc.rust-lang.org/std/cmp/trait.Ord.html):
//!
//! ```rust
//! use collect::compare::{Compare, Natural};
//! use std::cmp::Ordering::{Less, Equal, Greater};
//!
//! let a = &1;
//! let b = &2;
//!
//! let cmp = Natural;
//! assert_eq!(cmp.compare(a, b), Less);
//! assert_eq!(cmp.compare(b, a), Greater);
//! assert_eq!(cmp.compare(a, a), Equal);
//! ```
//!
//! There are convenience methods for checking each of the six relations:
//!
//! ```rust
//! use collect::compare::{Compare, Natural};
//!
//! let a = &1;
//! let b = &2;
//!
//! let cmp = Natural;
//! assert!(cmp.compares_lt(a, b));
//! assert!(cmp.compares_le(a, b));
//! assert!(cmp.compares_ge(b, a));
//! assert!(cmp.compares_gt(b, a));
//! assert!(cmp.compares_eq(a, a));
//! assert!(cmp.compares_ne(a, b));
//! ```
//!
//! The [`CompareExt`](trait.CompareExt.html) trait provides extension methods that
//! consume a comparator to produce a new one with different behavior, similar to
//! [iterator adaptors](http://doc.rust-lang.org/std/iter/trait.IteratorExt.html). For
//! example, all comparators can be [reversed](trait.CompareExt.html#method.rev):
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt, Natural};
//! use std::cmp::Ordering::Greater;
//!
//! let cmp = Natural.rev();
//! assert_eq!(cmp.compare(&1, &2), Greater);
//! ```
//!
//! It is possible to implement a comparator that is not based on the natural ordering of
//! a type by using a closure of type `Fn(&Lhs, &Rhs) -> Ordering`. For example, vectors
//! can be compared by their length instead of their contents:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt};
//! use std::cmp::Ordering::{Less, Greater};
//!
//! let a = vec![1, 2, 3];
//! let b = vec![4, 5];
//!
//! let cmp = |&: lhs: &Vec<u8>, rhs: &Vec<u8>| lhs.len().cmp(&rhs.len());
//! assert_eq!(cmp.compare(&a, &b), Greater);
//!
//! let cmp = cmp.rev();
//! assert_eq!(cmp.compare(&a, &b), Less);
//! ```
//!
//! Comparators can be combined [lexicographically]
//! (https://en.wikipedia.org/wiki/Lexicographical_order) in order to compare values
//! first by one key, [then](trait.CompareExt.html#method.then), if the first keys were
//! equal, by another:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt};
//! use std::cmp::Ordering::{Less, Equal, Greater};
//!
//! struct Pet { name: &'static str, age: u8 }
//!
//! let fido4 = &Pet { name: "Fido", age: 4 };
//! let ruff2 = &Pet { name: "Ruff", age: 2 };
//! let fido3 = &Pet { name: "Fido", age: 3 };
//!
//! let name_cmp = |&: lhs: &Pet, rhs: &Pet| lhs.name.cmp(rhs.name);
//! assert_eq!(name_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_cmp.compare(fido4, fido3), Equal);
//! assert_eq!(name_cmp.compare(ruff2, fido3), Greater);
//!
//! let age_cmp = |&: lhs: &Pet, rhs: &Pet| lhs.age.cmp(&rhs.age);
//! assert_eq!(age_cmp.compare(fido4, ruff2), Greater);
//! assert_eq!(age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(age_cmp.compare(ruff2, fido3), Less);
//!
//! let name_age_cmp = name_cmp.then(age_cmp);
//! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater);
//! ```
//!
//! It is often repetitive to compare two values of the same type by the same key, so the
//! [key-extraction logic](struct.Extract.html) can be factored out, simplifying the
//! previous example:
//!
//! ```rust
//! use collect::compare::{Compare, CompareExt, Extract, Natural};
//! use std::cmp::Ordering::{Less, Greater};
//!
//! struct Pet { name: &'static str, age: u8 }
//!
//! let fido4 = &Pet { name: "Fido", age: 4 };
//! let ruff2 = &Pet { name: "Ruff", age: 2 };
//! let fido3 = &Pet { name: "Fido", age: 3 };
//!
//! let name_age_cmp = Extract::new(|p: &Pet| p.name, Natural)
//! .then(Extract::new(|p: &Pet| p.age, Natural));
//!
//! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less);
//! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater);
//! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater);
//! ```
use std::borrow::BorrowFrom;
use std::cmp::Ordering::{self, Less, Equal, Greater};
use std::default::Default;
/// Returns the maximum of two values according to the given comparator, or `lhs` if they
/// are equal.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Extract, Natural, max};
///
/// struct Foo { key: char, id: u8 }
///
/// let f1 = &Foo { key: 'a', id: 1};
/// let f2 = &Foo { key: 'a', id: 2};
/// let f3 = &Foo { key: 'b', id: 3};
///
/// let cmp = Extract::new(|f: &Foo| f.key, Natural);
/// assert_eq!(max(&cmp, f1, f2).id, f1.id);
/// assert_eq!(max(&cmp, f1, f3).id, f3.id);
/// ```
// FIXME: convert to default method on `Compare` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
pub fn max<'a, C: ?Sized, T: ?Sized>(cmp: &C, lhs: &'a T, rhs: &'a T) -> &'a T
where C: Compare<T> {
if cmp.compares_ge(lhs, rhs) { lhs } else { rhs }
}
/// Returns the minimum of two values according to the given comparator, or `lhs` if they
/// are equal.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Extract, Natural, min};
///
/// struct Foo { key: char, id: u8 }
///
/// let f1 = &Foo { key: 'b', id: 1};
/// let f2 = &Foo { key: 'b', id: 2};
/// let f3 = &Foo { key: 'a', id: 3};
///
/// let cmp = Extract::new(|f: &Foo| f.key, Natural);
/// assert_eq!(min(&cmp, f1, f2).id, f1.id);
/// assert_eq!(min(&cmp, f1, f3).id, f3.id);
/// ```
// FIXME: convert to default method on `Compare` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
pub fn min<'a, C: ?Sized, T: ?Sized>(cmp: &C, lhs: &'a T, rhs: &'a T) -> &'a T
where C: Compare<T> {
if cmp.compares_le(lhs, rhs) { lhs } else { rhs }
}
/// A comparator imposing a [total order](https://en.wikipedia.org/wiki/Total_order).
///
/// See the [`compare` module's documentation](index.html) for detailed usage.
///
/// The `compares_*` methods may be overridden to provide more efficient implementations.
pub trait Compare<Lhs: ?Sized, Rhs: ?Sized = Lhs> {
/// Compares two values, returning `Less`, `Equal`, or `Greater` if `lhs` is less
/// than, equal to, or greater than `rhs`, respectively.
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering;
/// Checks if `lhs` is less than `rhs`.
fn compares_lt(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Less
}
/// Checks if `lhs` is less than or equal to `rhs`.
fn compares_le(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Greater
}
/// Checks if `lhs` is greater than or equal to `rhs`.
fn compares_ge(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Less
}
/// Checks if `lhs` is greater than `rhs`.
fn compares_gt(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Greater
}
/// Checks if `lhs` is equal to `rhs`.
fn compares_eq(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) == Equal
}
/// Checks if `lhs` is not equal to `rhs`.
fn compares_ne(&self, lhs: &Lhs, rhs: &Rhs) -> bool {
self.compare(lhs, rhs) != Equal
}
}
impl<F: ?Sized, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for F
where F: Fn(&Lhs, &Rhs) -> Ordering {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering { (*self)(lhs, rhs) }
}
impl<'a, Lhs: ?Sized, Rhs: ?Sized, C: ?Sized> Compare<Lhs, Rhs> for &'a C
where C: Compare<Lhs, Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
Compare::compare(*self, lhs, rhs)
}
}
/// An extension trait with methods applicable to all comparators.
pub trait CompareExt<Lhs: ?Sized, Rhs: ?Sized = Lhs> : Compare<Lhs, Rhs> + Sized {
/// Borrows the comparator's parameters before comparing them.
///
/// # Examples
///
/// ```rust
/// #![allow(unstable)]
/// use collect::compare::{Compare, CompareExt, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a_str = "a";
/// let a_string = a_str.to_string();
///
/// let b_str = "b";
/// let b_string = b_str.to_string();
///
/// let cmp = Natural::<str>.borrow();
/// assert_eq!(cmp.compare(a_str, &a_string), Equal);
/// assert_eq!(cmp.compare(a_str, b_str), Less);
/// assert_eq!(cmp.compare(&b_string, a_str), Greater);
/// ```
fn borrow(self) -> Borrow<Self> { Borrow(self) }
/// Reverses the ordering of the comparator.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a = &1;
/// let b = &2;
///
/// let cmp = Natural.rev();
/// assert_eq!(cmp.compare(a, b), Greater);
/// assert_eq!(cmp.compare(b, a), Less);
/// assert_eq!(cmp.compare(a, a), Equal);
/// ```
fn rev(self) -> Rev<Self> { Rev(self) }
/// Swaps the comparator's parameters, maintaining the underlying ordering.
///
/// This is useful for providing a comparator `C: Compare<T, U>` in a context that
/// expects `C: Compare<U, T>`.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let cmp = |&: lhs: &u8, rhs: &u16| (*lhs as u16).cmp(rhs);
/// assert_eq!(cmp.compare(&1u8, &2u16), Less);
/// assert_eq!(cmp.compare(&2u8, &1u16), Greater);
/// assert_eq!(cmp.compare(&1u8, &1u16), Equal);
///
/// let cmp = cmp.swap();
/// assert_eq!(cmp.compare(&2u16, &1u8), Less);
/// assert_eq!(cmp.compare(&1u16, &2u8), Greater);
/// assert_eq!(cmp.compare(&1u16, &1u8), Equal);
/// ```
fn swap(self) -> Swap<Self> { Swap(self) }
/// [Lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) combines
/// the comparator with another.
///
/// The retuned comparator compares values first using `self`, then, if they are
/// equal, using `then`.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, CompareExt};
/// use std::cmp::Ordering::{Less, Equal};
///
/// struct Foo { key1: char, key2: u8 }
///
/// let f1 = &Foo { key1: 'a', key2: 2};
/// let f2 = &Foo { key1: 'a', key2: 3};
///
/// let cmp = |&: lhs: &Foo, rhs: &Foo| lhs.key1.cmp(&rhs.key1);
/// assert_eq!(cmp.compare(f1, f2), Equal);
///
/// let cmp = cmp.then(|&: lhs: &Foo, rhs: &Foo| lhs.key2.cmp(&rhs.key2));
/// assert_eq!(cmp.compare(f1, f2), Less);
/// ```
fn then<D>(self, then: D) -> Lexicographic<Self, D> where D: Compare<Lhs, Rhs> {
Lexicographic(self, then)
}
}
impl<C, Lhs: ?Sized, Rhs: ?Sized> CompareExt<Lhs, Rhs> for C where C: Compare<Lhs, Rhs> {}
/// A comparator that borrows its parameters before comparing them.
///
/// See [`CompareExt::borrow`](trait.CompareExt.html#method.borrow) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Borrow<C>(C);
#[old_impl_check]
impl<C, Lhs: ?Sized, Rhs: ?Sized, Lb: ?Sized, Rb: ?Sized> Compare<Lhs, Rhs> for Borrow<C>
where C: Compare<Lb, Rb>, Lb: BorrowFrom<Lhs>, Rb: BorrowFrom<Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
self.0.compare(BorrowFrom::borrow_from(lhs), BorrowFrom::borrow_from(rhs))
}
}
/// A comparator that extracts a sort key from a value.
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, Extract, Natural};
/// use std::cmp::Ordering::Greater;
///
/// let a = vec![1, 2, 3];
/// let b = vec![4, 5];
///
/// let cmp = Extract::new(|vec: &Vec<u8>| vec.len(), Natural);
/// assert_eq!(cmp.compare(&a, &b), Greater);
/// ```
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Extract<E, C> {
ext: E,
cmp: C,
}
// FIXME: convert to default method on `CompareExt` once where clauses permit equality
// (https://github.com/rust-lang/rust/issues/20041)
#[old_impl_check]
impl<E, C, T: ?Sized, K> Extract<E, C> where E: Fn(&T) -> K, C: Compare<K> {
/// Returns a comparator that extracts a sort key using `ext` and compares it using
/// `cmp`.
pub fn new(ext: E, cmp: C) -> Extract<E, C> { Extract { ext: ext, cmp: cmp } }
}
#[old_impl_check]
impl<E, C, T: ?Sized, K> Compare<T> for Extract<E, C>
where E: Fn(&T) -> K, C: Compare<K> {
fn compare(&self, lhs: &T, rhs: &T) -> Ordering {
self.cmp.compare(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_lt(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_lt(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_le(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_le(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_ge(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_ge(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_gt(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_gt(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_eq(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_eq(&(self.ext)(lhs), &(self.ext)(rhs))
}
fn compares_ne(&self, lhs: &T, rhs: &T) -> bool {
self.cmp.compares_ne(&(self.ext)(lhs), &(self.ext)(rhs))
}
}
/// A comparator that [lexicographically]
/// (https://en.wikipedia.org/wiki/Lexicographical_order) combines two others.
///
/// See [`CompareExt::then`](trait.CompareExt.html#method.then) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Lexicographic<C, D>(C, D);
impl<C, D, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for Lexicographic<C, D>
where C: Compare<Lhs, Rhs>, D: Compare<Lhs, Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
match self.0.compare(lhs, rhs) {
Equal => self.1.compare(lhs, rhs),
order => order,
}
}
}
/// A comparator that delegates to [`Ord`]
/// (http://doc.rust-lang.org/std/cmp/trait.Ord.html).
///
/// # Examples
///
/// ```rust
/// use collect::compare::{Compare, Natural};
/// use std::cmp::Ordering::{Less, Equal, Greater};
///
/// let a = &1;
/// let b = &2;
///
/// let cmp = Natural;
/// assert_eq!(cmp.compare(a, b), Less);
/// assert_eq!(cmp.compare(b, a), Greater);
/// assert_eq!(cmp.compare(a, a), Equal);
/// ```
pub struct Natural<T: Ord + ?Sized>;
impl<T: Ord + ?Sized> Compare<T> for Natural<T> {
fn compare(&self, lhs: &T, rhs: &T) -> Ordering { Ord::cmp(lhs, rhs) }
fn compares_lt(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::lt(lhs, rhs) }
fn compares_le(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::le(lhs, rhs) }
fn compares_ge(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::ge(lhs, rhs) }
fn compares_gt(&self, lhs: &T, rhs: &T) -> bool { PartialOrd::gt(lhs, rhs) }
fn compares_eq(&self, lhs: &T, rhs: &T) -> bool { PartialEq::eq(lhs, rhs) }
fn compares_ne(&self, lhs: &T, rhs: &T) -> bool { PartialEq::ne(lhs, rhs) }
}
// FIXME: replace with `derive(Clone)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Clone for Natural<T> {
fn clone(&self) -> Natural<T> { *self }
}
// FIXME: replace with `derive(Copy)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Copy for Natural<T> {}
// FIXME: replace with `derive(Default)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Default for Natural<T> {
fn default() -> Natural<T> { Natural }
}
// FIXME: replace with `derive(PartialEq)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> PartialEq for Natural<T> {
fn eq(&self, _other: &Natural<T>) -> bool { true }
}
// FIXME: replace with `derive(Eq)` once
// https://github.com/rust-lang/rust/issues/19839 is fixed
impl<T: Ord + ?Sized> Eq for Natural<T> {}
/// A comparator that reverses the ordering of another.
///
/// See [`CompareExt::rev`](trait.CompareExt.html#method.rev) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Rev<C>(C);
impl<C, Lhs: ?Sized, Rhs: ?Sized> Compare<Lhs, Rhs> for Rev<C> where C: Compare<Lhs, Rhs> {
fn compare(&self, lhs: &Lhs, rhs: &Rhs) -> Ordering {
self.0.compare(lhs, rhs).reverse()
}
fn compares_lt(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_gt(lhs, rhs) }
fn compares_le(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_ge(lhs, rhs) }
fn compares_ge(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_le(lhs, rhs) }
fn compares_gt(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_lt(lhs, rhs) }
fn compares_eq(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_eq(lhs, rhs) }
fn compares_ne(&self, lhs: &Lhs, rhs: &Rhs) -> bool { self.0.compares_ne(lhs, rhs) }
}
/// A comparator that swaps another's parameters, maintaining the underlying ordering.
///
/// This is useful for providing a comparator `C: Compare<T, U>` in a context that
/// expects `C: Compare<U, T>`.
///
/// See [`CompareExt::swap`](trait.CompareExt.html#method.swap) for an example.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Swap<C>(C);
impl<C, Lhs: ?Sized, Rhs: ?Sized> Compare<Rhs, Lhs> for Swap<C>
where C: Compare<Lhs, Rhs> {
fn compare(&self, rhs: &Rhs, lhs: &Lhs) -> Ordering { self.0.compare(lhs, rhs) }
fn compares_lt(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_lt(lhs, rhs) }
fn compares_le(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_le(lhs, rhs) }
fn compares_ge(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_ge(lhs, rhs) }
fn compares_gt(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_gt(lhs, rhs) }
fn compares_eq(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_eq(lhs, rhs) }
fn compares_ne(&self, rhs: &Rhs, lhs: &Lhs) -> bool { self.0.compares_ne(lhs, rhs) }
}
|
//! Details of generating code for the `ruma_event` procedural macro.
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse::{self, Parse, ParseStream},
parse_quote,
punctuated::Punctuated,
spanned::Spanned,
Attribute, Field, Ident, Path, Token, Type,
};
use crate::parse::{Content, EventKind, RumaEventInput};
/// The result of processing the `ruma_event` macro, ready for output back to source code.
pub struct RumaEvent {
/// Outer attributes on the field, such as a docstring.
attrs: Vec<Attribute>,
/// Information for generating the type used for the event's `content` field.
content: Content,
/// The name of the type of the event's `content` field.
content_name: Ident,
/// The variant of `ruma_events::EventType` for this event, determined by the `event_type`
/// field.
event_type: Path,
/// Struct fields of the event.
fields: Vec<Field>,
/// Whether or not the event type is `EventType::Custom`.
is_custom: bool,
/// The kind of event.
kind: EventKind,
/// The name of the event.
name: Ident,
}
impl From<RumaEventInput> for RumaEvent {
fn from(input: RumaEventInput) -> Self {
let kind = input.kind;
let name = input.name;
let content_name = Ident::new(&format!("{}Content", &name), Span::call_site());
let event_type = input.event_type;
let is_custom = is_custom_event_type(&event_type);
let mut fields = match kind {
EventKind::Event => populate_event_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
EventKind::RoomEvent => populate_room_event_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
EventKind::StateEvent => populate_state_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
};
fields.sort_unstable_by_key(|field| field.ident.clone().unwrap());
Self {
attrs: input.attrs,
content: input.content,
content_name,
event_type,
fields,
is_custom,
kind,
name,
}
}
}
impl ToTokens for RumaEvent {
// TODO: Maybe break this off into functions so it's not so large. Then remove the clippy
// allowance.
#[allow(clippy::cognitive_complexity)]
fn to_tokens(&self, tokens: &mut TokenStream) {
let attrs = &self.attrs;
let content_name = &self.content_name;
let event_fields = &self.fields;
let event_type = if self.is_custom {
quote! {
crate::EventType::Custom(self.event_type.clone())
}
} else {
let event_type = &self.event_type;
quote! {
#event_type
}
};
let name = &self.name;
let name_str = format!("{}", name);
let content_docstring = format!("The payload for `{}`.", name);
let content = match &self.content {
Content::Struct(fields) => {
quote! {
#[doc = #content_docstring]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct #content_name {
#(#fields),*
}
}
}
Content::Typedef(typedef) => {
let content_attrs = &typedef.attrs;
let path = &typedef.path;
quote! {
#(#content_attrs)*
pub type #content_name = #path;
}
}
};
let raw_content = match &self.content {
Content::Struct(fields) => {
quote! {
#[doc = #content_docstring]
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
pub struct #content_name {
#(#fields),*
}
}
}
Content::Typedef(_) => TokenStream::new(),
};
// Custom events will already have an event_type field. All other events need to account
// for this field being manually inserted in `Serialize` impls.
let mut base_field_count: usize = if self.is_custom { 0 } else { 1 };
// Keep track of all the optional fields, because we'll need to check at runtime if they
// are `Some` in order to increase the number of fields we tell serde to serialize.
let mut optional_field_idents = Vec::with_capacity(event_fields.len());
let mut try_from_field_values: Vec<TokenStream> = Vec::with_capacity(event_fields.len());
let mut serialize_field_calls: Vec<TokenStream> = Vec::with_capacity(event_fields.len());
for field in event_fields {
let ident = field.ident.clone().unwrap();
let ident_str = if ident == "event_type" {
"type".to_string()
} else {
format!("{}", ident)
};
let span = field.span();
let try_from_field_value = if ident == "content" {
match &self.content {
Content::Struct(content_fields) => {
let mut content_field_values: Vec<TokenStream> =
Vec::with_capacity(content_fields.len());
for content_field in content_fields {
let content_field_ident = content_field.ident.clone().unwrap();
let span = content_field.span();
let token_stream = quote_spanned! {span=>
#content_field_ident: raw.content.#content_field_ident,
};
content_field_values.push(token_stream);
}
quote_spanned! {span=>
content: #content_name {
#(#content_field_values)*
},
}
}
Content::Typedef(_) => {
quote_spanned! {span=>
content: raw.content,
}
}
}
} else if ident == "prev_content" {
match &self.content {
Content::Struct(content_fields) => {
let mut content_field_values: Vec<TokenStream> =
Vec::with_capacity(content_fields.len());
for content_field in content_fields {
let content_field_ident = content_field.ident.clone().unwrap();
let span = content_field.span();
let token_stream = quote_spanned! {span=>
#content_field_ident: prev.#content_field_ident,
};
content_field_values.push(token_stream);
}
quote_spanned! {span=>
prev_content: raw.prev_content.map(|prev| {
#content_name {
#(#content_field_values)*
}
}),
}
}
Content::Typedef(_) => {
quote_spanned! {span=>
prev_content: raw.prev_content,
}
}
}
} else {
quote_spanned! {span=>
#ident: raw.#ident,
}
};
try_from_field_values.push(try_from_field_value);
// Does the same thing as #[serde(skip_serializing_if = "Option::is_none")]
let serialize_field_call = if is_option(&field.ty) {
optional_field_idents.push(ident.clone());
quote_spanned! {span=>
if self.#ident.is_some() {
state.serialize_field(#ident_str, &self.#ident)?;
}
}
} else {
base_field_count += 1;
quote_spanned! {span=>
state.serialize_field(#ident_str, &self.#ident)?;
}
};
serialize_field_calls.push(serialize_field_call);
}
let (manually_serialize_type_field, import_event_in_serialize_impl) = if self.is_custom {
(TokenStream::new(), TokenStream::new())
} else {
let manually_serialize_type_field = quote! {
state.serialize_field("type", &self.event_type())?;
};
let import_event_in_serialize_impl = quote! {
use crate::Event as _;
};
(
manually_serialize_type_field,
import_event_in_serialize_impl,
)
};
let increment_struct_len_statements: Vec<TokenStream> = optional_field_idents
.iter()
.map(|ident| {
let span = ident.span();
quote_spanned! {span=>
if self.#ident.is_some() {
len += 1;
}
}
})
.collect();
let set_up_struct_serializer = quote! {
let mut len = #base_field_count;
#(#increment_struct_len_statements)*
let mut state = serializer.serialize_struct(#name_str, len)?;
};
let impl_room_event = match self.kind {
EventKind::RoomEvent | EventKind::StateEvent => {
quote! {
impl crate::RoomEvent for #name {
/// The unique identifier for the event.
fn event_id(&self) -> &ruma_identifiers::EventId {
&self.event_id
}
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this event was
/// sent.
fn origin_server_ts(&self) -> js_int::UInt {
self.origin_server_ts
}
/// The unique identifier for the room associated with this event.
///
/// This can be `None` if the event came from a context where there is
/// no ambiguity which room it belongs to, like a `/sync` response for example.
fn room_id(&self) -> Option<&ruma_identifiers::RoomId> {
self.room_id.as_ref()
}
/// The unique identifier for the user who sent this event.
fn sender(&self) -> &ruma_identifiers::UserId {
&self.sender
}
/// Additional key-value pairs not signed by the homeserver.
fn unsigned(&self) -> Option<&serde_json::Value> {
self.unsigned.as_ref()
}
}
}
}
_ => TokenStream::new(),
};
let impl_state_event = if self.kind == EventKind::StateEvent {
quote! {
impl crate::StateEvent for #name {
/// The previous content for this state key, if any.
fn prev_content(&self) -> Option<&Self::Content> {
self.prev_content.as_ref()
}
/// A key that determines which piece of room state the event represents.
fn state_key(&self) -> &str {
&self.state_key
}
}
}
} else {
TokenStream::new()
};
let output = quote!(
#(#attrs)*
#[derive(Clone, PartialEq, Debug)]
pub struct #name {
#(#event_fields),*
}
#content
impl std::str::FromStr for #name {
type Err = crate::InvalidEvent;
/// Attempt to create `Self` from parsing a string of JSON data.
fn from_str(json: &str) -> Result<Self, Self::Err> {
let raw = serde_json::from_str::<raw::#name>(json)?;
Ok(Self {
#(#try_from_field_values)*
})
}
}
impl<'a> std::convert::TryFrom<&'a str> for #name {
type Error = crate::InvalidEvent;
/// Attempt to create `Self` from parsing a string of JSON data.
fn try_from(json: &'a str) -> Result<Self, Self::Error> {
std::str::FromStr::from_str(json)
}
}
use serde::ser::SerializeStruct as _;
impl serde::Serialize for #name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer
{
#import_event_in_serialize_impl
#set_up_struct_serializer
#(#serialize_field_calls)*
#manually_serialize_type_field
state.end()
}
}
impl crate::Event for #name {
/// The type of this event's `content` field.
type Content = #content_name;
/// The event's content.
fn content(&self) -> &Self::Content {
&self.content
}
/// The type of the event.
fn event_type(&self) -> crate::EventType {
#event_type
}
}
#impl_room_event
#impl_state_event
/// "Raw" versions of the event and its content which implement `serde::Deserialize`.
mod raw {
use super::*;
#(#attrs)*
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
pub struct #name {
#(#event_fields),*
}
#raw_content
}
);
output.to_tokens(tokens);
}
}
/// Fills in the event's struct definition with fields common to all basic events.
fn populate_event_fields(
is_custom: bool,
content_name: Ident,
mut fields: Vec<Field>,
) -> Vec<Field> {
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = if is_custom {
parse_quote! {
/// The event's content.
pub content: #content_name,
/// The custom type of the event.
pub event_type: String,
}
} else {
parse_quote! {
/// The event's content.
pub content: #content_name,
}
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Fills in the event's struct definition with fields common to all room events.
fn populate_room_event_fields(
is_custom: bool,
content_name: Ident,
fields: Vec<Field>,
) -> Vec<Field> {
let mut fields = populate_event_fields(is_custom, content_name, fields);
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = parse_quote! {
/// The unique identifier for the event.
pub event_id: ruma_identifiers::EventId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
/// event was sent.
pub origin_server_ts: js_int::UInt,
/// The unique identifier for the room associated with this event.
pub room_id: Option<ruma_identifiers::RoomId>,
/// Additional key-value pairs not signed by the homeserver.
pub unsigned: Option<serde_json::Value>,
/// The unique identifier for the user who sent this event.
pub sender: ruma_identifiers::UserId,
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Fills in the event's struct definition with fields common to all state events.
fn populate_state_fields(is_custom: bool, content_name: Ident, fields: Vec<Field>) -> Vec<Field> {
let mut fields = populate_room_event_fields(is_custom, content_name.clone(), fields);
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = parse_quote! {
/// The previous content for this state key, if any.
pub prev_content: Option<#content_name>,
/// A key that determines which piece of room state the event represents.
pub state_key: String,
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Checks if the given `Path` refers to `EventType::Custom`.
fn is_custom_event_type(event_type: &Path) -> bool {
event_type.segments.last().unwrap().value().ident == "Custom"
}
/// Checks if a type is an `Option`.
fn is_option(ty: &Type) -> bool {
if let Type::Path(ref type_path) = ty {
type_path.path.segments.first().unwrap().value().ident == "Option"
} else {
panic!("struct field had unexpected non-path type");
}
}
/// A wrapper around `syn::Field` that makes it possible to parse `Punctuated<Field, Token![,]>`
/// from a `TokenStream`.
///
/// See https://github.com/dtolnay/syn/issues/651 for more context.
struct ParsableNamedField {
/// The wrapped `Field`.
pub field: Field,
}
impl Parse for ParsableNamedField {
fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
let field = Field::parse_named(input)?;
Ok(Self { field })
}
}
Alphabetize struct fields.
//! Details of generating code for the `ruma_event` procedural macro.
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse::{self, Parse, ParseStream},
parse_quote,
punctuated::Punctuated,
spanned::Spanned,
Attribute, Field, Ident, Path, Token, Type,
};
use crate::parse::{Content, EventKind, RumaEventInput};
/// The result of processing the `ruma_event` macro, ready for output back to source code.
pub struct RumaEvent {
/// Outer attributes on the field, such as a docstring.
attrs: Vec<Attribute>,
/// Information for generating the type used for the event's `content` field.
content: Content,
/// The name of the type of the event's `content` field.
content_name: Ident,
/// The variant of `ruma_events::EventType` for this event, determined by the `event_type`
/// field.
event_type: Path,
/// Struct fields of the event.
fields: Vec<Field>,
/// Whether or not the event type is `EventType::Custom`.
is_custom: bool,
/// The kind of event.
kind: EventKind,
/// The name of the event.
name: Ident,
}
impl From<RumaEventInput> for RumaEvent {
fn from(input: RumaEventInput) -> Self {
let kind = input.kind;
let name = input.name;
let content_name = Ident::new(&format!("{}Content", &name), Span::call_site());
let event_type = input.event_type;
let is_custom = is_custom_event_type(&event_type);
let mut fields = match kind {
EventKind::Event => populate_event_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
EventKind::RoomEvent => populate_room_event_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
EventKind::StateEvent => populate_state_fields(
is_custom,
content_name.clone(),
input.fields.unwrap_or_else(Vec::new),
),
};
fields.sort_unstable_by_key(|field| field.ident.clone().unwrap());
Self {
attrs: input.attrs,
content: input.content,
content_name,
event_type,
fields,
is_custom,
kind,
name,
}
}
}
impl ToTokens for RumaEvent {
// TODO: Maybe break this off into functions so it's not so large. Then remove the clippy
// allowance.
#[allow(clippy::cognitive_complexity)]
fn to_tokens(&self, tokens: &mut TokenStream) {
let attrs = &self.attrs;
let content_name = &self.content_name;
let event_fields = &self.fields;
let event_type = if self.is_custom {
quote! {
crate::EventType::Custom(self.event_type.clone())
}
} else {
let event_type = &self.event_type;
quote! {
#event_type
}
};
let name = &self.name;
let name_str = format!("{}", name);
let content_docstring = format!("The payload for `{}`.", name);
let content = match &self.content {
Content::Struct(fields) => {
quote! {
#[doc = #content_docstring]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct #content_name {
#(#fields),*
}
}
}
Content::Typedef(typedef) => {
let content_attrs = &typedef.attrs;
let path = &typedef.path;
quote! {
#(#content_attrs)*
pub type #content_name = #path;
}
}
};
let raw_content = match &self.content {
Content::Struct(fields) => {
quote! {
#[doc = #content_docstring]
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
pub struct #content_name {
#(#fields),*
}
}
}
Content::Typedef(_) => TokenStream::new(),
};
// Custom events will already have an event_type field. All other events need to account
// for this field being manually inserted in `Serialize` impls.
let mut base_field_count: usize = if self.is_custom { 0 } else { 1 };
// Keep track of all the optional fields, because we'll need to check at runtime if they
// are `Some` in order to increase the number of fields we tell serde to serialize.
let mut optional_field_idents = Vec::with_capacity(event_fields.len());
let mut try_from_field_values: Vec<TokenStream> = Vec::with_capacity(event_fields.len());
let mut serialize_field_calls: Vec<TokenStream> = Vec::with_capacity(event_fields.len());
for field in event_fields {
let ident = field.ident.clone().unwrap();
let ident_str = if ident == "event_type" {
"type".to_string()
} else {
format!("{}", ident)
};
let span = field.span();
let try_from_field_value = if ident == "content" {
match &self.content {
Content::Struct(content_fields) => {
let mut content_field_values: Vec<TokenStream> =
Vec::with_capacity(content_fields.len());
for content_field in content_fields {
let content_field_ident = content_field.ident.clone().unwrap();
let span = content_field.span();
let token_stream = quote_spanned! {span=>
#content_field_ident: raw.content.#content_field_ident,
};
content_field_values.push(token_stream);
}
quote_spanned! {span=>
content: #content_name {
#(#content_field_values)*
},
}
}
Content::Typedef(_) => {
quote_spanned! {span=>
content: raw.content,
}
}
}
} else if ident == "prev_content" {
match &self.content {
Content::Struct(content_fields) => {
let mut content_field_values: Vec<TokenStream> =
Vec::with_capacity(content_fields.len());
for content_field in content_fields {
let content_field_ident = content_field.ident.clone().unwrap();
let span = content_field.span();
let token_stream = quote_spanned! {span=>
#content_field_ident: prev.#content_field_ident,
};
content_field_values.push(token_stream);
}
quote_spanned! {span=>
prev_content: raw.prev_content.map(|prev| {
#content_name {
#(#content_field_values)*
}
}),
}
}
Content::Typedef(_) => {
quote_spanned! {span=>
prev_content: raw.prev_content,
}
}
}
} else {
quote_spanned! {span=>
#ident: raw.#ident,
}
};
try_from_field_values.push(try_from_field_value);
// Does the same thing as #[serde(skip_serializing_if = "Option::is_none")]
let serialize_field_call = if is_option(&field.ty) {
optional_field_idents.push(ident.clone());
quote_spanned! {span=>
if self.#ident.is_some() {
state.serialize_field(#ident_str, &self.#ident)?;
}
}
} else {
base_field_count += 1;
quote_spanned! {span=>
state.serialize_field(#ident_str, &self.#ident)?;
}
};
serialize_field_calls.push(serialize_field_call);
}
let (manually_serialize_type_field, import_event_in_serialize_impl) = if self.is_custom {
(TokenStream::new(), TokenStream::new())
} else {
let manually_serialize_type_field = quote! {
state.serialize_field("type", &self.event_type())?;
};
let import_event_in_serialize_impl = quote! {
use crate::Event as _;
};
(
manually_serialize_type_field,
import_event_in_serialize_impl,
)
};
let increment_struct_len_statements: Vec<TokenStream> = optional_field_idents
.iter()
.map(|ident| {
let span = ident.span();
quote_spanned! {span=>
if self.#ident.is_some() {
len += 1;
}
}
})
.collect();
let set_up_struct_serializer = quote! {
let mut len = #base_field_count;
#(#increment_struct_len_statements)*
let mut state = serializer.serialize_struct(#name_str, len)?;
};
let impl_room_event = match self.kind {
EventKind::RoomEvent | EventKind::StateEvent => {
quote! {
impl crate::RoomEvent for #name {
/// The unique identifier for the event.
fn event_id(&self) -> &ruma_identifiers::EventId {
&self.event_id
}
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this event was
/// sent.
fn origin_server_ts(&self) -> js_int::UInt {
self.origin_server_ts
}
/// The unique identifier for the room associated with this event.
///
/// This can be `None` if the event came from a context where there is
/// no ambiguity which room it belongs to, like a `/sync` response for example.
fn room_id(&self) -> Option<&ruma_identifiers::RoomId> {
self.room_id.as_ref()
}
/// The unique identifier for the user who sent this event.
fn sender(&self) -> &ruma_identifiers::UserId {
&self.sender
}
/// Additional key-value pairs not signed by the homeserver.
fn unsigned(&self) -> Option<&serde_json::Value> {
self.unsigned.as_ref()
}
}
}
}
_ => TokenStream::new(),
};
let impl_state_event = if self.kind == EventKind::StateEvent {
quote! {
impl crate::StateEvent for #name {
/// The previous content for this state key, if any.
fn prev_content(&self) -> Option<&Self::Content> {
self.prev_content.as_ref()
}
/// A key that determines which piece of room state the event represents.
fn state_key(&self) -> &str {
&self.state_key
}
}
}
} else {
TokenStream::new()
};
let output = quote!(
#(#attrs)*
#[derive(Clone, PartialEq, Debug)]
pub struct #name {
#(#event_fields),*
}
#content
impl std::str::FromStr for #name {
type Err = crate::InvalidEvent;
/// Attempt to create `Self` from parsing a string of JSON data.
fn from_str(json: &str) -> Result<Self, Self::Err> {
let raw = serde_json::from_str::<raw::#name>(json)?;
Ok(Self {
#(#try_from_field_values)*
})
}
}
impl<'a> std::convert::TryFrom<&'a str> for #name {
type Error = crate::InvalidEvent;
/// Attempt to create `Self` from parsing a string of JSON data.
fn try_from(json: &'a str) -> Result<Self, Self::Error> {
std::str::FromStr::from_str(json)
}
}
use serde::ser::SerializeStruct as _;
impl serde::Serialize for #name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer
{
#import_event_in_serialize_impl
#set_up_struct_serializer
#(#serialize_field_calls)*
#manually_serialize_type_field
state.end()
}
}
impl crate::Event for #name {
/// The type of this event's `content` field.
type Content = #content_name;
/// The event's content.
fn content(&self) -> &Self::Content {
&self.content
}
/// The type of the event.
fn event_type(&self) -> crate::EventType {
#event_type
}
}
#impl_room_event
#impl_state_event
/// "Raw" versions of the event and its content which implement `serde::Deserialize`.
mod raw {
use super::*;
#(#attrs)*
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
pub struct #name {
#(#event_fields),*
}
#raw_content
}
);
output.to_tokens(tokens);
}
}
/// Fills in the event's struct definition with fields common to all basic events.
fn populate_event_fields(
is_custom: bool,
content_name: Ident,
mut fields: Vec<Field>,
) -> Vec<Field> {
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = if is_custom {
parse_quote! {
/// The event's content.
pub content: #content_name,
/// The custom type of the event.
pub event_type: String,
}
} else {
parse_quote! {
/// The event's content.
pub content: #content_name,
}
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Fills in the event's struct definition with fields common to all room events.
fn populate_room_event_fields(
is_custom: bool,
content_name: Ident,
fields: Vec<Field>,
) -> Vec<Field> {
let mut fields = populate_event_fields(is_custom, content_name, fields);
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = parse_quote! {
/// The unique identifier for the event.
pub event_id: ruma_identifiers::EventId,
/// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
/// event was sent.
pub origin_server_ts: js_int::UInt,
/// The unique identifier for the room associated with this event.
pub room_id: Option<ruma_identifiers::RoomId>,
/// The unique identifier for the user who sent this event.
pub sender: ruma_identifiers::UserId,
/// Additional key-value pairs not signed by the homeserver.
pub unsigned: Option<serde_json::Value>,
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Fills in the event's struct definition with fields common to all state events.
fn populate_state_fields(is_custom: bool, content_name: Ident, fields: Vec<Field>) -> Vec<Field> {
let mut fields = populate_room_event_fields(is_custom, content_name.clone(), fields);
let punctuated_fields: Punctuated<ParsableNamedField, Token![,]> = parse_quote! {
/// The previous content for this state key, if any.
pub prev_content: Option<#content_name>,
/// A key that determines which piece of room state the event represents.
pub state_key: String,
};
let mut additional_fields = Vec::with_capacity(punctuated_fields.len());
for punctuated_field in punctuated_fields {
additional_fields.push(punctuated_field.field);
}
fields.extend(additional_fields);
fields
}
/// Checks if the given `Path` refers to `EventType::Custom`.
fn is_custom_event_type(event_type: &Path) -> bool {
event_type.segments.last().unwrap().value().ident == "Custom"
}
/// Checks if a type is an `Option`.
fn is_option(ty: &Type) -> bool {
if let Type::Path(ref type_path) = ty {
type_path.path.segments.first().unwrap().value().ident == "Option"
} else {
panic!("struct field had unexpected non-path type");
}
}
/// A wrapper around `syn::Field` that makes it possible to parse `Punctuated<Field, Token![,]>`
/// from a `TokenStream`.
///
/// See https://github.com/dtolnay/syn/issues/651 for more context.
struct ParsableNamedField {
/// The wrapped `Field`.
pub field: Field,
}
impl Parse for ParsableNamedField {
fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
let field = Field::parse_named(input)?;
Ok(Self { field })
}
}
|
use std;
use std::cmp;
use std::cell::RefCell;
use std::vec::Vec;
use std::rc::Rc;
use std::collections::HashMap;
use syntax::abi::Abi;
use syntax::ast;
use syntax::codemap::{Span, Spanned, respan, ExpnInfo, NameAndSpan, MacroBang};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig;
use syntax::ext::quote::rt::ToTokens;
use syntax::feature_gate::Features;
use syntax::owned_slice::OwnedSlice;
use syntax::parse;
use syntax::parse::token::{InternedString, intern};
use syntax::attr::mk_attr_id;
use syntax::ptr::P;
use syntax::print::pprust::tts_to_string;
use super::BindgenOptions;
use super::LinkType;
use types::*;
struct GenCtx<'r> {
ext_cx: base::ExtCtxt<'r>,
options: BindgenOptions,
span: Span,
module_map: ModuleMap,
current_module_id: ModuleId,
}
impl<'r> GenCtx<'r> {
fn full_path_for_module(&self, id: ModuleId) -> Vec<String> {
if !self.options.enable_cxx_namespaces {
return vec![];
}
let mut ret = vec![];
let mut current_id = Some(id);
while let Some(current) = current_id {
let module = &self.module_map.get(¤t).unwrap();
ret.push(module.name.clone());
current_id = module.parent_id;
}
if self.current_module_id == ROOT_MODULE_ID {
ret.pop(); // The root module doens'n need a root:: in the pattern
}
ret.reverse();
ret
}
fn current_module_mut(&mut self) -> &mut Module {
let id = self.current_module_id;
self.module_map.get_mut(&id).expect("Module not found!")
}
}
fn first<A, B>((val, _): (A, B)) -> A {
val
}
fn ref_eq<T>(thing: &T, other: &T) -> bool {
(thing as *const T) == (other as *const T)
}
fn empty_generics() -> ast::Generics {
ast::Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new()
}
}
}
fn rust_id(ctx: &mut GenCtx, name: &str) -> (String, bool) {
let token = parse::token::Ident(ctx.ext_cx.ident_of(name), parse::token::Plain);
if token.is_any_keyword() || "bool" == name {
let mut s = name.to_owned();
s.push_str("_");
(s, true)
} else {
(name.to_owned(), false)
}
}
fn rust_type_id(ctx: &mut GenCtx, name: &str) -> String {
match name {
"bool" | "uint" | "u8" | "u16" |
"u32" | "f32" | "f64" | "i8" |
"i16" | "i32" | "i64" | "Self" |
"str" => {
let mut s = name.to_owned();
s.push_str("_");
s
}
"int8_t" => "i8".to_owned(),
"uint8_t" => "u8".to_owned(),
"int16_t" => "i16".to_owned(),
"uint16_t" => "u16".to_owned(),
"int32_t" => "i32".to_owned(),
"uint32_t" => "u32".to_owned(),
"int64_t" => "i64".to_owned(),
"uint64_t" => "u64".to_owned(),
"uintptr_t"
| "size_t" => "usize".to_owned(),
"intptr_t"
| "ptrdiff_t"
| "ssize_t" => "isize".to_owned(),
_ => first(rust_id(ctx, name))
}
}
fn comp_name(ctx: &GenCtx, kind: CompKind, name: &str) -> String {
match kind {
CompKind::Struct => struct_name(ctx, name),
CompKind::Union => union_name(ctx, name),
}
}
fn struct_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Struct_{}", name)
} else {
name.to_owned()
}
}
fn union_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Union_{}", name)
} else {
name.to_owned()
}
}
fn enum_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Enum_{}", name)
} else {
name.to_owned()
}
}
fn gen_unmangle_method(ctx: &mut GenCtx,
v: &VarInfo,
counts: &mut HashMap<String, isize>,
self_kind: ast::SelfKind)
-> ast::ImplItem {
let fndecl;
let mut args = vec!();
match self_kind {
ast::SelfKind::Static => (),
ast::SelfKind::Region(_, mutable, _) => {
let selfexpr = match mutable {
ast::Mutability::Immutable => quote_expr!(&ctx.ext_cx, &*self),
ast::Mutability::Mutable => quote_expr!(&ctx.ext_cx, &mut *self),
};
args.push(selfexpr);
},
_ => unreachable!()
}
match v.ty {
TFuncPtr(ref sig) => {
fndecl = cfuncty_to_rs(ctx,
&*sig.ret_ty, sig.args.as_slice(),
false);
let mut unnamed: usize = 0;
let iter = if args.len() > 0 {
sig.args[1..].iter()
} else {
sig.args.iter()
};
for arg in iter {
let (ref n, _) = *arg;
let argname = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
first(rust_id(ctx, &n))
};
let expr = ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, ast::Path {
span: ctx.span,
global: false,
segments: vec!(ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&argname),
parameters: ast::PathParameters::none()
})
}),
span: ctx.span,
attrs: None,
};
args.push(P(expr));
}
},
_ => unreachable!()
};
let sig = ast::MethodSig {
unsafety: ast::Unsafety::Unsafe,
abi: Abi::Rust,
decl: P(fndecl),
generics: empty_generics(),
explicit_self: respan(ctx.span, self_kind),
constness: ast::Constness::NotConst,
};
let block = ast::Block {
stmts: vec!(),
expr: Some(P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Call(
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, ast::Path {
span: ctx.span,
global: false,
segments: vec!(ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&v.mangled),
parameters: ast::PathParameters::none()
})
}),
span: ctx.span,
attrs: None,
}),
args
),
span: ctx.span,
attrs: None,
})),
id: ast::DUMMY_NODE_ID,
rules: ast::BlockCheckMode::Default,
span: ctx.span
};
let mut name = v.name.clone();
let mut count = 0;
match counts.get(&v.name) {
Some(x) => {
count = *x;
name.push_str(&x.to_string());
},
None => ()
}
count += 1;
counts.insert(v.name.clone(), count);
let mut attrs = mk_doc_attr(ctx, &v.comment);
attrs.push(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("inline")))),
is_sugared_doc: false
}));
let name = first(rust_id(ctx, &name));
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: ctx.ext_cx.ident_of(&name),
vis: ast::Visibility::Public,
attrs: attrs,
node: ast::ImplItemKind::Method(sig, P(block)),
span: ctx.span
}
}
pub fn gen_mods(links: &[(String, LinkType)],
map: ModuleMap,
options: BindgenOptions,
span: Span) -> Vec<P<ast::Item>> {
// Create a dummy ExtCtxt. We only need this for string interning and that uses TLS.
let mut features = Features::new();
features.allow_quote = true;
let cfg = ExpansionConfig {
crate_name: "xxx".to_owned(),
features: Some(&features),
recursion_limit: 64,
trace_mac: false,
};
let sess = &parse::ParseSess::new();
let mut feature_gated_cfgs = vec![];
let mut ctx = GenCtx {
ext_cx: base::ExtCtxt::new(sess, Vec::new(), cfg, &mut feature_gated_cfgs),
options: options,
span: span,
module_map: map,
current_module_id: ROOT_MODULE_ID,
};
ctx.ext_cx.bt_push(ExpnInfo {
call_site: ctx.span,
callee: NameAndSpan {
format: MacroBang(intern("")),
allow_internal_unstable: false,
span: None
}
});
if let Some(root_mod) = gen_mod(&mut ctx, ROOT_MODULE_ID, links, span) {
if !ctx.options.enable_cxx_namespaces {
match root_mod.node {
// XXX This clone might be really expensive, but doing:
// ast::ItemMod(ref mut root) => {
// return ::std::mem::replace(&mut root.items, vec![]);
// }
// fails with "error: cannot borrow immutable anonymous field as mutable".
// So...
ast::ItemKind::Mod(ref root) => {
return root.items.clone()
}
_ => unreachable!(),
}
}
let root_export = P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Use(P(
Spanned {
node: ast::ViewPathGlob(ast::Path {
span: span.clone(),
global: false,
segments: vec![ast::PathSegment {
identifier: root_mod.ident,
parameters: ast::PathParameters::none(),
}]
}),
span: span.clone(),
})),
vis: ast::Visibility::Public,
span: span.clone(),
});
vec![root_export, root_mod]
} else {
vec![]
}
}
fn gen_mod(mut ctx: &mut GenCtx,
module_id: ModuleId,
links: &[(String, LinkType)],
span: Span) -> Option<P<ast::Item>> {
// XXX avoid this clone
let module = ctx.module_map.get(&module_id).unwrap().clone();
// Import just the root to minimise name conflicts
let mut globals = if module_id != ROOT_MODULE_ID {
// XXX Pass this previously instead of looking it up always?
let root = ctx.ext_cx.ident_of(&ctx.module_map.get(&ROOT_MODULE_ID).unwrap().name);
vec![P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Use(P(
Spanned {
node: ast::ViewPathSimple(root.clone(),
ast::Path {
span: span.clone(),
global: false,
segments: vec![ast::PathSegment {
identifier: root,
parameters: ast::PathParameters::none(),
}]
}),
span: span.clone(),
})),
vis: ast::Visibility::Public,
span: span.clone(),
})]
} else {
// TODO: Could be worth it to avoid this if
// we know there won't be any union.
let union_fields_decl = quote_item!(&ctx.ext_cx,
#[derive(Copy, Clone, Debug)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
).unwrap();
let union_fields_impl = quote_item!(&ctx.ext_cx,
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
}
}
).unwrap();
let union_fields_default_impl = quote_item!(&ctx.ext_cx,
impl<T> ::std::default::Default for __BindgenUnionField<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
).unwrap();
vec![union_fields_decl, union_fields_impl, union_fields_default_impl]
};
ctx.current_module_id = module_id;
globals.extend(gen_globals(&mut ctx, links, &module.globals).into_iter());
globals.extend(module.children_ids.iter().filter_map(|id| {
gen_mod(ctx, *id, links, span.clone())
}));
if !globals.is_empty() {
Some(P(ast::Item {
ident: ctx.ext_cx.ident_of(&module.name),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Mod(ast::Mod {
inner: span,
items: globals,
}),
vis: ast::Visibility::Public,
span: span.clone(),
}))
} else {
None
}
}
fn type_opaque(ctx: &GenCtx, ty: &Type) -> bool {
let ty_name = ty.name();
match ty_name {
Some(ty_name)
=> ctx.options.opaque_types.iter().any(|name| *name == ty_name),
None => false,
}
}
fn global_opaque(ctx: &GenCtx, global: &Global) -> bool {
let global_name = global.name();
// Can't make an opaque type without layout
global.layout().is_some() &&
ctx.options.opaque_types.iter().any(|name| *name == global_name)
}
fn type_blacklisted(ctx: &GenCtx, global: &Global) -> bool {
let global_name = global.name();
ctx.options.blacklist_type.iter().any(|name| *name == global_name)
}
fn gen_global(mut ctx: &mut GenCtx,
g: Global,
defs: &mut Vec<P<ast::Item>>) {
// XXX unify with anotations both type_blacklisted
// and type_opaque (which actually doesn't mean the same).
if type_blacklisted(ctx, &g) {
return;
}
if global_opaque(ctx, &g) {
let name = first(rust_id(ctx, &g.name()));
let layout = g.layout().unwrap();
defs.push(mk_opaque_struct(ctx, &name, &layout));
// This should always be true but anyways..
defs.push(mk_test_fn(ctx, &name, &layout));
return;
}
match g {
GType(ti) => {
let t = ti.borrow().clone();
defs.push(ctypedef_to_rs(&mut ctx, t))
},
GCompDecl(ci) => {
let c = ci.borrow().clone();
let name = comp_name(&ctx, c.kind, &c.name);
defs.push(opaque_to_rs(&mut ctx, &name, c.layout));
},
GComp(ci) => {
let c = ci.borrow().clone();
let name = comp_name(&ctx, c.kind, &c.name);
defs.extend(comp_to_rs(&mut ctx, &name, c).into_iter())
},
GEnumDecl(ei) => {
let e = ei.borrow().clone();
let name = enum_name(&ctx, &e.name);
let dummy = EnumItem::new("_BindgenOpaqueEnum".to_owned(), "".to_owned(), 0);
defs.extend(cenum_to_rs(&mut ctx, &name, e.kind, e.comment, &[dummy], e.layout).into_iter())
},
GEnum(ei) => {
let e = ei.borrow().clone();
let name = enum_name(&ctx, &e.name);
defs.extend(cenum_to_rs(&mut ctx, &name, e.kind, e.comment, &e.items, e.layout).into_iter())
},
GVar(vi) => {
let v = vi.borrow();
let ty = cty_to_rs(&mut ctx, &v.ty, v.is_const, true);
defs.push(const_to_rs(&mut ctx, v.name.clone(), v.val.unwrap(), ty));
},
_ => { }
}
}
fn gen_globals(mut ctx: &mut GenCtx,
links: &[(String, LinkType)],
globs: &[Global]) -> Vec<P<ast::Item>> {
let uniq_globs = tag_dup_decl(globs);
let mut fs = vec!();
let mut vs = vec!();
let mut gs = vec!();
for g in uniq_globs.into_iter() {
match g {
GOther => {}
GFunc(_) => fs.push(g),
GVar(_) => {
let is_int_const = {
match g {
GVar(ref vi) => {
let v = vi.borrow();
v.is_const && v.val.is_some()
}
_ => unreachable!()
}
};
if is_int_const {
gs.push(g);
} else {
vs.push(g);
}
}
_ => gs.push(g)
}
}
let mut defs = vec!();
gs = remove_redundant_decl(gs);
for mut g in gs.into_iter() {
if let Some(substituted) = ctx.current_module_mut().translations.remove(&g.name()) {
match (substituted.layout(), g.layout()) {
(Some(l), Some(lg)) if l.size == lg.size => {},
(None, None) => {},
_ => {
// XXX real logger
println!("warning: substituted type for {} does not match its size", g.name());
}
}
g = substituted;
}
gen_global(ctx, g, &mut defs);
}
let mut pending_translations = std::mem::replace(&mut ctx.current_module_mut().translations, HashMap::new());
for (name, g) in pending_translations.drain() {
println!("warning: generating definition for not found type: {}", name);
gen_global(ctx, g, &mut defs);
}
let vars: Vec<_> = vs.into_iter().map(|v| {
match v {
GVar(vi) => {
let v = vi.borrow();
cvar_to_rs(&mut ctx, v.name.clone(), v.mangled.clone(), &v.ty, v.is_const)
},
_ => unreachable!()
}
}).collect();
let mut unmangle_count: HashMap<String, isize> = HashMap::new();
let funcs = {
let func_list = fs.into_iter().map(|f| {
match f {
GFunc(vi) => {
let v = vi.borrow();
match v.ty {
TFuncPtr(ref sig) => {
let mut name = v.name.clone();
let mut count = 0;
match unmangle_count.get(&v.name) {
Some(x) => {
count = *x;
name.push_str(&x.to_string());
},
None => ()
}
count += 1;
unmangle_count.insert(v.name.clone(), count);
let decl = cfunc_to_rs(&mut ctx, name, v.mangled.clone(), v.comment.clone(),
&*sig.ret_ty, &sig.args[..],
sig.is_variadic, ast::Visibility::Public);
(sig.abi, decl)
}
_ => unreachable!()
}
},
_ => unreachable!()
}
});
let mut map: HashMap<Abi, Vec<_>> = HashMap::new();
for (abi, func) in func_list {
map.entry(abi).or_insert(vec![]).push(func);
}
map
};
if !vars.is_empty() {
defs.push(mk_extern(&mut ctx, links, vars, Abi::C));
}
for (abi, funcs) in funcs.into_iter() {
defs.push(mk_extern(&mut ctx, &links, funcs, abi));
}
//let attrs = vec!(mk_attr_list(&mut ctx, "allow", ["dead_code", "non_camel_case_types", "uppercase_variables"]));
defs
}
fn mk_extern(ctx: &mut GenCtx, links: &[(String, LinkType)],
foreign_items: Vec<ast::ForeignItem>,
abi: Abi) -> P<ast::Item> {
let attrs: Vec<_> = links.iter().map(|&(ref l, ref k)| {
let k = match *k {
LinkType::Default => None,
LinkType::Static => Some("static"),
LinkType::Framework => Some("framework")
};
let link_name = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("name"),
respan(ctx.span, ast::LitKind::Str(intern(l).as_str(), ast::StrStyle::Cooked))
)));
let link_args = match k {
None => vec!(link_name),
Some(ref k) => vec!(link_name, P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("kind"),
respan(ctx.span, ast::LitKind::Str(intern(k).as_str(), ast::StrStyle::Cooked))
))))
};
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("link"),
link_args)
)),
is_sugared_doc: false
})
}).collect();
let mut items = Vec::new();
items.extend(foreign_items.into_iter());
let ext = ast::ItemKind::ForeignMod(ast::ForeignMod {
abi: abi,
items: items
});
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn mk_impl(ctx: &mut GenCtx, ty: P<ast::Ty>,
items: Vec<ast::ImplItem>)
-> P<ast::Item> {
let ext = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
ty,
items
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn remove_redundant_decl(gs: Vec<Global>) -> Vec<Global> {
fn check_decl(a: &Global, ty: &Type) -> bool {
match *a {
GComp(ref ci1) => match *ty {
TComp(ref ci2) => {
ref_eq(ci1, ci2) && ci1.borrow().name.is_empty()
},
_ => false
},
GEnum(ref ei1) => match *ty {
TEnum(ref ei2) => {
ref_eq(ei1, ei2) && ei1.borrow().name.is_empty()
},
_ => false
},
_ => false
}
}
let typedefs: Vec<Type> = gs.iter().filter_map(|g|
match *g {
GType(ref ti) => Some(ti.borrow().ty.clone()),
_ => None
}
).collect();
gs.into_iter().filter(|g|
!typedefs.iter().any(|t| check_decl(g, t))
).collect()
}
fn tag_dup_decl(gs: &[Global]) -> Vec<Global> {
fn check(name1: &str, name2: &str) -> bool {
!name1.is_empty() && name1 == name2
}
fn check_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(>ype(ref ti1), >ype(ref ti2)) => {
let a = ti1.borrow();
let b = ti2.borrow();
check(&a.name, &b.name)
},
(&GComp(ref ci1), &GComp(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GCompDecl(ref ci1), &GCompDecl(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GEnum(ref ei1), &GEnum(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
(&GEnumDecl(ref ei1), &GEnumDecl(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
(&GVar(ref vi1), &GVar(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name, &b.name) &&
check(&a.mangled, &b.mangled)
},
(&GFunc(ref vi1), &GFunc(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name, &b.name) &&
check(&a.mangled, &b.mangled)
},
_ => false
}
}
fn check_opaque_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(&GCompDecl(ref ci1), &GComp(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GEnumDecl(ref ei1), &GEnum(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
_ => false,
}
}
if gs.is_empty() {
return vec![];
}
let mut step: Vec<Global> = vec!();
step.push(gs[0].clone());
for (i, _gsi) in gs.iter().enumerate().skip(1) {
let mut dup = false;
for j in 0..i {
if i == j {
continue;
}
if check_dup(&gs[i], &gs[j]) {
dup = true;
break;
}
}
if !dup {
step.push(gs[i].clone());
}
}
let len = step.len();
let mut res: Vec<Global> = vec!();
for i in 0..len {
let mut dup = false;
match &step[i] {
&GCompDecl(_) | &GEnumDecl(_) => {
for j in 0..len {
if i == j {
continue;
}
if check_opaque_dup(&step[i], &step[j]) {
dup = true;
break;
}
}
},
_ => (),
}
if !dup {
res.push(step[i].clone());
}
}
res
}
fn ctypedef_to_rs(ctx: &mut GenCtx, ty: TypeInfo) -> P<ast::Item> {
fn mk_item(ctx: &mut GenCtx, name: &str, comment: &str, ty: &Type) -> P<ast::Item> {
let rust_name = rust_type_id(ctx, name);
let rust_ty = if cty_is_translatable(ty) {
cty_to_rs(ctx, ty, true, true)
} else {
cty_to_rs(ctx, &TVoid, true, true)
};
let base = ast::ItemKind::Ty(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: rust_ty.node,
span: ctx.span,
}),
empty_generics()
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: mk_doc_attr(ctx, comment),
id: ast::DUMMY_NODE_ID,
node: base,
vis: ast::Visibility::Public,
span: ctx.span
})
}
match ty.ty {
TComp(ref ci) => {
assert!(!ci.borrow().name.is_empty());
mk_item(ctx, &ty.name, &ty.comment, &ty.ty)
},
TEnum(ref ei) => {
assert!(!ei.borrow().name.is_empty());
mk_item(ctx, &ty.name, &ty.comment, &ty.ty)
},
_ => mk_item(ctx, &ty.name, &ty.comment, &ty.ty),
}
}
fn comp_to_rs(ctx: &mut GenCtx, name: &str, ci: CompInfo)
-> Vec<P<ast::Item>> {
match ci.kind {
CompKind::Struct => cstruct_to_rs(ctx, name, ci),
CompKind::Union => cunion_to_rs(ctx, name, ci.layout, ci.members),
}
}
fn cstruct_to_rs(ctx: &mut GenCtx, name: &str, ci: CompInfo) -> Vec<P<ast::Item>> {
let layout = ci.layout;
let members = &ci.members;
let template_args = &ci.args;
let methodlist = &ci.methods;
let mut fields = vec!();
let mut methods = vec!();
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current struct.
let mut extra = vec!();
let mut unnamed: u32 = 0;
let mut bitfields: u32 = 0;
if ci.hide ||
ci.has_non_type_template_params ||
template_args.iter().any(|f| f == &TVoid) {
return vec!();
}
let id = rust_type_id(ctx, name);
let id_ty = P(mk_ty(ctx, false, &[id.clone()]));
if ci.has_vtable {
let mut vffields = vec!();
let base_vftable = if !members.is_empty() {
if let CompMember::Field(ref fi) = members[0] {
match fi.ty {
TComp(ref ci2) => {
let ci2 = ci2.borrow();
if ci2.has_vtable {
Some(format!("_vftable_{}", ci2.name))
} else {
None
}
},
_ => None
}
} else {
None
}
} else {
None
};
if let Some(ref base) = base_vftable {
let field = ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of("_base"), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(mk_ty(ctx, false, &[base.clone()])),
attrs: vec!(),
};
vffields.push(respan(ctx.span, field));
}
for vm in ci.vmethods.iter() {
let ty = match vm.ty {
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, sig.args.as_slice(), sig.is_variadic);
mk_fn_proto_ty(ctx, &decl, sig.abi)
},
_ => unreachable!()
};
let field = ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of(&vm.name), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(ty),
attrs: vec!(),
};
vffields.push(respan(ctx.span, field));
}
// FIXME: rustc actually generates tons of warnings
// due to an empty repr(C) type, so we just generate
// a dummy field with pointer-alignment to supress it.
if vffields.is_empty() {
vffields.push(mk_blob_field(ctx, "_bindgen_empty_ctype_warning_fix",
Layout::new(::std::mem::size_of::<*mut ()>(), ::std::mem::align_of::<*mut ()>())));
}
let vf_name = format!("_vftable_{}", name);
let item = P(ast::Item {
ident: ctx.ext_cx.ident_of(&vf_name),
attrs: vec!(mk_repr_attr(ctx, layout)),
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Struct(
ast::VariantData::Struct(vffields, ast::DUMMY_NODE_ID),
empty_generics()
),
vis: ast::Visibility::Public,
span: ctx.span,
});
extra.push(item);
if base_vftable.is_none() {
let vf_type = mk_ty(ctx, false, &[vf_name]);
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of("_vftable"), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(mk_ptrty(ctx, &vf_type, true)),
attrs: Vec::new()
}));
}
}
let mut anon_enum_count = 0;
let mut setters = vec!();
let mut has_destructor = ci.has_destructor;
let mut template_args_used = vec![false; template_args.len()];
for m in members.iter() {
if let CompMember::Enum(ref ei) = *m {
let empty_name = ei.borrow().name.is_empty();
if empty_name {
ei.borrow_mut().name = format!("{}_enum{}", name, anon_enum_count);
anon_enum_count += 1;
}
let e = ei.borrow().clone();
extra.extend(cenum_to_rs(ctx, &e.name, e.kind, e.comment, &e.items, e.layout).into_iter());
continue;
}
fn comp_fields(m: &CompMember)
-> (Option<Rc<RefCell<CompInfo>>>, Option<FieldInfo>) {
match *m {
CompMember::Field(ref f) => { (None, Some(f.clone())) }
CompMember::Comp(ref rc_c) => { (Some(rc_c.clone()), None) }
CompMember::CompField(ref rc_c, ref f) => { (Some(rc_c.clone()), Some(f.clone())) }
_ => unreachable!()
}
}
let (opt_rc_c, opt_f) = comp_fields(m);
if let Some(f) = opt_f {
if cty_has_destructor(&f.ty) {
has_destructor = true;
}
let (f_name, f_ty) = match f.bitfields {
Some(ref v) => {
bitfields += 1;
// NOTE: We rely on the name of the type converted to rust types,
// and on the alignment.
let bits = v.iter().fold(0, |acc, &(_, w)| acc + w);
let layout_size = cmp::max(1, bits.next_power_of_two() / 8) as usize;
let name = match layout_size {
1 => "uint8_t",
2 => "uint16_t",
4 => "uint32_t",
8 => "uint64_t",
_ => panic!("bitfield width not supported: {}", layout_size),
};
let ty = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.to_owned(), ROOT_MODULE_ID, TVoid, Layout::new(layout_size, layout_size)))));
(format!("_bitfield_{}", bitfields), ty)
}
None => (rust_type_id(ctx, &f.name), f.ty.clone())
};
drop(f.ty); // to ensure it's not used unintentionally
let is_translatable = cty_is_translatable(&f_ty);
if !is_translatable || type_opaque(ctx, &f_ty) {
if !is_translatable {
println!("{}::{} not translatable, void: {}", ci.name, f.name, f_ty == TVoid);
}
if let Some(layout) = f_ty.layout() {
fields.push(mk_blob_field(ctx, &f_name, layout));
}
continue;
}
if ctx.options.gen_bitfield_methods {
let mut offset: u32 = 0;
if let Some(ref bitfields) = f.bitfields {
for &(ref bf_name, bf_size) in bitfields.iter() {
setters.push(gen_bitfield_method(ctx, &f_name, bf_name, &f_ty, offset as usize, bf_size));
offset += bf_size;
}
setters.push(gen_fullbitfield_method(ctx, &f_name, &f_ty, bitfields))
}
}
let mut bypass = false;
let f_ty = if let Some(ref rc_c) = opt_rc_c {
if rc_c.borrow().members.len() == 1 {
if let CompMember::Field(ref inner_f) = rc_c.borrow().members[0] {
bypass = true;
inner_f.ty.clone()
} else {
f_ty
}
} else {
f_ty
}
} else {
f_ty
};
// If the member is not a template argument, it needs the full path.
let mut needs_full_path = true;
for (index, arg) in template_args.iter().enumerate() {
let used = f_ty == *arg || match f_ty {
TPtr(ref t, _, _, _) => **t == *arg,
TArray(ref t, _, _) => **t == *arg,
_ => false,
};
if used {
template_args_used[index] = true;
needs_full_path = false;
break;
}
}
let f_ty = P(cty_to_rs(ctx, &f_ty, f.bitfields.is_none(), needs_full_path));
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(&f_name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: f_ty,
attrs: mk_doc_attr(ctx, &f.comment)
}));
if bypass {
continue;
}
}
if let Some(rc_c) = opt_rc_c {
let name_is_empty = rc_c.borrow().name.is_empty();
if name_is_empty {
let c = rc_c.borrow();
unnamed += 1;
let field_name = format!("_bindgen_data_{}_", unnamed);
fields.push(mk_blob_field(ctx, &field_name, c.layout));
methods.extend(gen_comp_methods(ctx, &field_name, 0, c.kind, &c.members, &mut extra).into_iter());
} else {
let name = comp_name(&ctx, rc_c.borrow().kind, &rc_c.borrow().name);
extra.extend(comp_to_rs(ctx, &name, rc_c.borrow().clone()).into_iter());
}
}
}
let mut phantom_count = 0;
for (i, arg) in template_args.iter().enumerate() {
if template_args_used[i] {
continue;
}
let f_name = format!("_phantom{}", phantom_count);
phantom_count += 1;
let inner_type = P(cty_to_rs(ctx, &arg, true, false));
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(&f_name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: quote_ty!(&ctx.ext_cx, ::std::marker::PhantomData<$inner_type>),
attrs: vec!(),
}));
}
if !setters.is_empty() {
extra.push(P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
id_ty.clone(),
setters
),
vis: ast::Visibility::Inherited,
span: ctx.span
}));
}
let field_count = fields.len();
let variant_data = if fields.is_empty() {
ast::VariantData::Unit(ast::DUMMY_NODE_ID)
} else {
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID)
};
let ty_params = template_args.iter().map(|gt| {
let name = match gt {
&TNamed(ref ti) => {
ctx.ext_cx.ident_of(&ti.borrow().name)
},
_ => ctx.ext_cx.ident_of("")
};
ast::TyParam {
ident: name,
id: ast::DUMMY_NODE_ID,
bounds: OwnedSlice::empty(),
default: None,
span: ctx.span
}
}).collect();
let def = ast::ItemKind::Struct(
variant_data,
ast::Generics {
lifetimes: vec!(),
ty_params: OwnedSlice::from_vec(ty_params),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: vec!()
}
}
);
let mut attrs = mk_doc_attr(ctx, &ci.comment);
attrs.push(mk_repr_attr(ctx, layout));
if !has_destructor {
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
if template_args.is_empty() {
extra.push(mk_clone_impl(ctx, name));
attrs.push(if can_derive_debug && ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Debug", "Copy"])
} else {
mk_deriving_attr(ctx, &["Copy"])
});
} else {
attrs.push(if can_derive_debug && ctx.options.derive_debug {
// TODO: make mk_clone_impl work for template arguments,
// meanwhile just fallback to deriving.
mk_deriving_attr(ctx, &["Copy", "Clone", "Debug"])
} else {
mk_deriving_attr(ctx, &["Copy", "Clone"])
});
}
}
let struct_def = ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
};
let mut items = vec!(P(struct_def));
if !methods.is_empty() {
let impl_ = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
id_ty.clone(),
methods
);
items.push(
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: impl_,
vis: ast::Visibility::Inherited,
span: ctx.span}));
}
// Template args have incomplete type in general
//
// XXX if x is a class without members, C++ still will report
// sizeof(x) == 1, since it requires to be adressable.
//
// We maybe should add a dummy byte if it's the case, but...
// That could play wrong with inheritance.
//
// So for now don't generate a test if the struct/class is empty
// or has only empty bases.
if ci.args.is_empty() && field_count > 0 &&
(ci.has_nonempty_base || ci.base_members < field_count) {
extra.push(mk_test_fn(ctx, name, &layout));
}
items.extend(extra.into_iter());
let mut mangledlist = vec!();
let mut unmangledlist = vec!();
let mut unmangle_count: HashMap<String, isize> = HashMap::new();
for v in methodlist {
let v = v.clone();
match v.ty {
TFuncPtr(ref sig) => {
let name = v.mangled.clone();
let explicit_self = if v.is_static {
ast::SelfKind::Static
} else if v.is_const {
ast::SelfKind::Region(None, ast::Mutability::Immutable, ctx.ext_cx.ident_of("self"))
} else {
ast::SelfKind::Region(None, ast::Mutability::Mutable, ctx.ext_cx.ident_of("self"))
};
unmangledlist.push(gen_unmangle_method(ctx, &v, &mut unmangle_count, explicit_self));
mangledlist.push(cfunc_to_rs(ctx, name, String::new(), String::new(),
&*sig.ret_ty, sig.args.as_slice(),
sig.is_variadic, ast::Visibility::Inherited));
}
_ => unreachable!()
}
}
if mangledlist.len() > 0 {
items.push(mk_extern(ctx, &vec!(), mangledlist, Abi::C));
items.push(mk_impl(ctx, id_ty, unmangledlist));
}
items
}
fn opaque_to_rs(ctx: &mut GenCtx, name: &str, _layout: Layout) -> P<ast::Item> {
let def = ast::ItemKind::Enum(
ast::EnumDef {
variants: vec!()
},
empty_generics()
);
// XXX can't repr(C) an empty enum
let id = rust_type_id(ctx, name);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn cunion_to_rs(ctx: &mut GenCtx, name: &str, layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
const UNION_DATA_FIELD_NAME: &'static str = "_bindgen_data_";
fn mk_item(ctx: &mut GenCtx, name: &str, item: ast::ItemKind, vis:
ast::Visibility, attrs: Vec<ast::Attribute>) -> P<ast::Item> {
P(ast::Item {
ident: ctx.ext_cx.ident_of(name),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: item,
vis: vis,
span: ctx.span
})
}
// XXX what module id is correct?
let ci = Rc::new(RefCell::new(CompInfo::new(name.to_owned(), ROOT_MODULE_ID, name.to_owned(), "".to_owned(), CompKind::Union, members.clone(), layout)));
let union = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.to_owned(), ROOT_MODULE_ID, TComp(ci), layout))));
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current union.
let mut extra = vec!();
fn mk_union_field(ctx: &GenCtx, name: &str, ty: ast::Ty) -> Spanned<ast::StructField_> {
let field_ty = if !ctx.options.enable_cxx_namespaces ||
ctx.current_module_id == ROOT_MODULE_ID {
quote_ty!(&ctx.ext_cx, __BindgenUnionField<$ty>)
} else {
quote_ty!(&ctx.ext_cx, root::__BindgenUnionField<$ty>)
};
respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: field_ty,
attrs: vec![],
})
}
let mut fields = members.iter()
.flat_map(|member| match *member {
CompMember::Field(ref f) => {
let cty = cty_to_rs(ctx, &f.ty, false, true);
Some(mk_union_field(ctx, &f.name, cty))
}
_ => None,
}).collect::<Vec<_>>();
fields.push(mk_blob_field(ctx, UNION_DATA_FIELD_NAME, layout));
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID),
empty_generics()
);
let union_id = rust_type_id(ctx, name);
let mut union_attrs = vec![mk_repr_attr(ctx, layout)];
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
extra.push(mk_clone_impl(ctx, name));
extra.push(mk_test_fn(ctx, &name, &layout));
union_attrs.push(if can_derive_debug {
mk_deriving_copy_and_maybe_debug_attr(ctx)
} else {
mk_deriving_copy_attr(ctx)
});
let union_def = mk_item(ctx, &union_id, def, ast::Visibility::Public, union_attrs);
let union_impl = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
P(cty_to_rs(ctx, &union, true, true)),
gen_comp_methods(ctx, UNION_DATA_FIELD_NAME, 0, CompKind::Union, &members, &mut extra),
);
let mut items = vec!(
union_def,
mk_item(ctx, "", union_impl, ast::Visibility::Inherited, vec![])
);
items.extend(extra.into_iter());
items
}
fn const_to_rs(ctx: &mut GenCtx, name: String, val: i64, val_ty: ast::Ty) -> P<ast::Item> {
let int_lit = ast::LitKind::Int(
val.abs() as u64,
ast::LitIntType::Unsuffixed
);
let mut value = ctx.ext_cx.expr_lit(ctx.span, int_lit);
if val < 0 {
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, value);
value = ctx.ext_cx.expr(ctx.span, negated);
}
let cst = ast::ItemKind::Const(
P(val_ty),
value
);
let id = first(rust_id(ctx, &name));
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id[..]),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: cst,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn enum_size_to_unsigned_max_value(size: usize) -> u64 {
match size {
1 => std::u8::MAX as u64,
2 => std::u16::MAX as u64,
4 => std::u32::MAX as u64,
8 => std::u64::MAX,
_ => unreachable!("invalid enum size: {}", size)
}
}
fn enum_size_to_rust_type_name(signed: bool, size: usize) -> &'static str {
match (signed, size) {
(true, 1) => "i8",
(false, 1) => "u8",
(true, 2) => "i16",
(false, 2) => "u16",
(true, 4) => "i32",
(false, 4) => "u32",
(true, 8) => "i64",
(false, 8) => "u64",
_ => {
println!("invalid enum decl: signed: {}, size: {}", signed, size);
"i32"
}
}
}
fn cenum_value_to_int_lit(ctx: &mut GenCtx,
enum_is_signed: bool,
size: usize,
value: i64) -> P<ast::Expr> {
if enum_is_signed {
if value == std::i64::MIN {
let lit = ast::LitKind::Int(std::u64::MAX, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, lit)
} else {
let lit = ast::LitKind::Int(value.abs() as u64, ast::LitIntType::Unsuffixed);
let expr = ctx.ext_cx.expr_lit(ctx.span, lit);
if value < 0 {
ctx.ext_cx.expr(ctx.span, ast::ExprKind::Unary(ast::UnOp::Neg, expr))
} else {
expr
}
}
} else {
let u64_value = value as u64 & enum_size_to_unsigned_max_value(size);
let int_lit = ast::LitKind::Int(u64_value, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, int_lit)
}
}
fn cenum_to_rs(ctx: &mut GenCtx,
name: &str,
kind: IKind,
comment: String,
enum_items: &[EnumItem],
layout: Layout) -> Vec<P<ast::Item>> {
let enum_name = ctx.ext_cx.ident_of(name);
let enum_ty = ctx.ext_cx.ty_ident(ctx.span, enum_name);
let enum_is_signed = kind.is_signed();
let enum_repr = enum_size_to_rust_type_name(enum_is_signed, layout.size);
// Rust is not happy with univariant enums
// if items.len() < 2 {
// return vec!();
// }
//
let mut items = vec![];
if !ctx.options.rust_enums {
items.push(ctx.ext_cx.item_ty(ctx.span,
enum_name,
ctx.ext_cx.ty_ident(ctx.span,
ctx.ext_cx.ident_of(enum_repr))));
for item in enum_items {
let value = cenum_value_to_int_lit(ctx, enum_is_signed, layout.size, item.val);
items.push(ctx.ext_cx.item_const(ctx.span, ctx.ext_cx.ident_of(&item.name), enum_ty.clone(), value));
}
return items;
}
let mut variants = vec![];
let mut found_values = HashMap::new();
for item in enum_items {
let name = ctx.ext_cx.ident_of(&item.name);
if let Some(orig) = found_values.get(&item.val) {
let value = ctx.ext_cx.expr_path(
ctx.ext_cx.path(ctx.span, vec![enum_name, *orig]));
items.push(P(ast::Item {
ident: name,
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Const(enum_ty.clone(), value),
vis: ast::Visibility::Public,
span: ctx.span,
}));
continue;
}
found_values.insert(item.val, name);
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
variants.push(respan(ctx.span, ast::Variant_ {
name: name,
attrs: vec![],
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
disr_expr: Some(value),
}));
}
let enum_repr = InternedString::new(enum_repr);
let repr_arg = ctx.ext_cx.meta_word(ctx.span, enum_repr);
let repr_list = ctx.ext_cx.meta_list(ctx.span, InternedString::new("repr"), vec![repr_arg]);
let mut attrs = mk_doc_attr(ctx, &comment);
attrs.push(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: repr_list,
is_sugared_doc: false,
}));
attrs.push(if ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Debug", "Copy", "Clone"])
} else {
mk_deriving_attr(ctx, &["Copy", "Clone"])
});
items.push(P(ast::Item {
ident: enum_name,
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Enum(ast::EnumDef { variants: variants }, empty_generics()),
vis: ast::Visibility::Public,
span: ctx.span,
}));
items
}
/// Generates accessors for fields in nested structs and unions which must be
/// represented in Rust as an untyped array. This process may generate
/// declarations and implementations that must be placed at the root level.
/// These are emitted into `extra`.
fn gen_comp_methods(ctx: &mut GenCtx, data_field: &str, data_offset: usize,
kind: CompKind, members: &[CompMember],
extra: &mut Vec<P<ast::Item>>) -> Vec<ast::ImplItem> {
let mk_field_method = |ctx: &mut GenCtx, f: &FieldInfo, offset: usize| {
// TODO: Implement bitfield accessors
if f.bitfields.is_some() { return None; }
let f_name = first(rust_id(ctx, &f.name));
let ret_ty = P(cty_to_rs(ctx, &TPtr(Box::new(f.ty.clone()), false, false, Layout::zero()), true, true));
// When the offset is zero, generate slightly prettier code.
let method = {
let impl_str = format!(r"
impl X {{
pub unsafe fn {}(&mut self) -> {} {{
let raw: *mut u8 = ::std::mem::transmute(&self.{});
::std::mem::transmute(raw.offset({}))
}}
}}
", f_name, tts_to_string(&ret_ty.to_tokens(&ctx.ext_cx)[..]), data_field, offset);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_string(), impl_str).parse_item().unwrap().unwrap()
};
method.and_then(|i| {
match i.node {
ast::ItemKind::Impl(_, _, _, _, _, mut items) => {
items.pop()
}
_ => unreachable!("impl parsed to something other than impl")
}
})
};
let mut offset = data_offset;
let mut methods = vec!();
for m in members.into_iter() {
let advance_by = match *m {
CompMember::Field(ref f) => {
if ctx.options.gen_bitfield_methods {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
}
f.ty.size()
}
CompMember::Comp(ref rc_c) => {
let c = rc_c.borrow();
let name = comp_name(&ctx, c.kind, &c.name);
extra.extend(comp_to_rs(ctx, &name, c.clone()).into_iter());
c.layout.size
}
CompMember::CompField(ref rc_c, ref f) => {
if ctx.options.gen_bitfield_methods {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
}
let c = rc_c.borrow();
let name = comp_name(&ctx, c.kind, &c.name);
extra.extend(comp_to_rs(ctx, &name, c.clone()).into_iter());
f.ty.size()
}
CompMember::Enum(_) => 0
};
match kind {
CompKind::Struct => { offset += advance_by; }
CompKind::Union => { }
}
}
methods
}
fn type_for_bitfield_width(ctx: &mut GenCtx, width: u32, is_arg: bool) -> ast::Ty {
let input_type = if width > 16 {
"u32"
} else if width > 8 {
"u16"
} else if width > 1 {
"u8"
} else {
if is_arg {
"bool"
} else {
"u8"
}
};
mk_ty(ctx, false, &[input_type.to_owned()])
}
fn gen_bitfield_method(ctx: &mut GenCtx, bindgen_name: &str,
field_name: &str, field_type: &Type,
offset: usize, width: u32) -> ast::ImplItem {
let input_type = type_for_bitfield_width(ctx, width, true);
let field_type = cty_to_rs(ctx, &field_type, false, true);
let setter_name = ctx.ext_cx.ident_of(&format!("set_{}", field_name));
let bindgen_ident = ctx.ext_cx.ident_of(bindgen_name);
let item = quote_item!(&ctx.ext_cx,
impl X {
pub fn $setter_name(&mut self, val: $input_type) {
self.$bindgen_ident &= !(((1 << $width as $field_type) - 1) << $offset);
self.$bindgen_ident |= (val as $field_type) << $offset;
}
}
).unwrap();
match &item.node {
&ast::ItemKind::Impl(_, _, _, _, _, ref items) => items[0].clone(),
_ => unreachable!()
}
}
fn gen_fullbitfield_method(ctx: &mut GenCtx, bindgen_name: &String,
bitfield_type: &Type, bitfields: &[(String, u32)]) -> ast::ImplItem {
let field_type = cty_to_rs(ctx, bitfield_type, false, true);
let mut args = vec!();
let mut unnamed: usize = 0;
for &(ref name, width) in bitfields.iter() {
let ident = if name.is_empty() {
unnamed += 1;
let dummy = format!("unnamed_bitfield{}", unnamed);
ctx.ext_cx.ident_of(&dummy)
} else {
ctx.ext_cx.ident_of(name)
};
args.push(ast::Arg {
ty: P(type_for_bitfield_width(ctx, width, true)),
pat: P(ast::Pat {
id: ast::DUMMY_NODE_ID,
node: ast::PatKind::Ident(
ast::BindingMode::ByValue(ast::Mutability::Immutable),
respan(ctx.span, ident),
None
),
span: ctx.span
}),
id: ast::DUMMY_NODE_ID,
});
}
let fndecl = ast::FnDecl {
inputs: args,
output: ast::FunctionRetTy::Ty(P(field_type.clone())),
variadic: false
};
let stmts = Vec::with_capacity(bitfields.len() + 1);
let mut offset = 0;
let mut exprs = quote_expr!(&ctx.ext_cx, 0);
let mut unnamed: usize = 0;
for &(ref name, width) in bitfields.iter() {
let name_ident = if name.is_empty() {
unnamed += 1;
let dummy = format!("unnamed_bitfield{}", unnamed);
ctx.ext_cx.ident_of(&dummy)
} else {
ctx.ext_cx.ident_of(name)
};
exprs = quote_expr!(&ctx.ext_cx,
$exprs | (($name_ident as $field_type) << $offset)
);
offset += width;
}
let block = ast::Block {
stmts: stmts,
expr: Some(exprs),
id: ast::DUMMY_NODE_ID,
rules: ast::BlockCheckMode::Default,
span: ctx.span
};
let node = ast::ImplItemKind::Method(
ast::MethodSig {
unsafety: ast::Unsafety::Normal,
abi: Abi::Rust,
decl: P(fndecl),
generics: empty_generics(),
explicit_self: respan(ctx.span, ast::SelfKind::Static),
constness: ast::Constness::Const,
}, P(block)
);
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: ctx.ext_cx.ident_of(&format!("new{}", bindgen_name)),
vis: ast::Visibility::Public,
attrs: vec!(),
node: node,
span: ctx.span,
}
}
fn mk_blob_field(ctx: &GenCtx, name: &str, layout: Layout) -> Spanned<ast::StructField_> {
let ty_name = match layout.align {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
let data_len = if ty_name == "u8" { layout.size } else { layout.size / layout.align };
let base_ty = mk_ty(ctx, false, &[ty_name.to_owned()]);
let data_ty = if data_len == 1 {
P(base_ty)
} else {
P(mk_arrty(ctx, &base_ty, data_len))
};
respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: data_ty,
attrs: Vec::new()
})
}
fn mk_link_name_attr(ctx: &mut GenCtx, name: String) -> ast::Attribute {
let lit = respan(ctx.span, ast::LitKind::Str(intern(&name).as_str(), ast::StrStyle::Cooked));
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("link_name"), lit
)));
let attr = ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
};
respan(ctx.span, attr)
}
fn mk_repr_attr(ctx: &GenCtx, layout: Layout) -> ast::Attribute {
let mut values = vec!(P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("C")))));
if layout.packed {
values.push(P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("packed")))));
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("repr"),
values
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_copy_attr(ctx: &mut GenCtx) -> ast::Attribute {
mk_deriving_attr(ctx, &["Copy"])
}
// NB: This requires that the type you implement it for also
// implements Copy.
//
// Implements std::clone::Clone using dereferencing.
//
// This is to bypass big arrays not implementing clone,
// but implementing copy due to hacks inside rustc's internals.
fn mk_clone_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::clone::Clone for {} {{
fn clone(&self) -> Self {{ *self }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
fn mk_deriving_copy_and_maybe_debug_attr(ctx: &mut GenCtx) -> ast::Attribute {
if ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Copy", "Debug"])
} else {
mk_deriving_copy_attr(ctx)
}
}
fn mk_deriving_attr(ctx: &mut GenCtx, attrs: &[&'static str]) -> ast::Attribute {
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("derive"),
attrs.iter().map(|attr| {
P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new(attr))))
}).collect()
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_doc_attr(ctx: &mut GenCtx, doc: &str) -> Vec<ast::Attribute> {
if doc.is_empty() {
return vec!();
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("doc"),
respan(ctx.span, ast::LitKind::Str(intern(doc).as_str(), ast::StrStyle::Cooked))
)));
vec!(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: true
}))
}
fn cvar_to_rs(ctx: &mut GenCtx, name: String,
mangled: String, ty: &Type,
is_const: bool) -> ast::ForeignItem {
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if !mangled.is_empty() {
attrs.push(mk_link_name_attr(ctx, mangled));
} else if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
let val_ty = P(cty_to_rs(ctx, ty, true, true));
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: attrs,
node: ast::ForeignItemKind::Static(val_ty, !is_const),
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cfuncty_to_rs(ctx: &mut GenCtx,
rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::FnDecl {
let ret = match *rty {
TVoid => ast::FunctionRetTy::Default(ctx.span),
// Disable references in returns for now
TPtr(ref t, is_const, _, ref layout) =>
ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, &TPtr(t.clone(), is_const, false, layout.clone()), true, true))),
_ => ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, rty, true, true)))
};
let mut unnamed: usize = 0;
let args: Vec<ast::Arg> = aty.iter().map(|arg| {
let (ref n, ref t) = *arg;
let arg_name = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
first(rust_id(ctx, &n))
};
// From the C90 standard (http://c0x.coding-guidelines.com/6.7.5.3.html)
// 1598 - A declaration of a parameter as “array of type” shall be
// adjusted to “qualified pointer to type”, where the type qualifiers
// (if any) are those specified within the [ and ] of the array type
// derivation.
let arg_ty = P(match *t {
TArray(ref typ, _, l) => cty_to_rs(ctx, &TPtr(typ.clone(), false, false, l), true, true),
_ => cty_to_rs(ctx, t, true, true),
});
ast::Arg {
ty: arg_ty,
pat: P(ast::Pat {
id: ast::DUMMY_NODE_ID,
node: ast::PatKind::Ident(
ast::BindingMode::ByValue(ast::Mutability::Immutable),
respan(ctx.span, ctx.ext_cx.ident_of(&arg_name)),
None
),
span: ctx.span
}),
id: ast::DUMMY_NODE_ID,
}
}).collect();
let var = !args.is_empty() && var;
ast::FnDecl {
inputs: args,
output: ret,
variadic: var
}
}
fn cfunc_to_rs(ctx: &mut GenCtx,
name: String,
mangled: String,
comment: String,
rty: &Type,
aty: &[(String, Type)],
var: bool,
vis: ast::Visibility) -> ast::ForeignItem {
let var = !aty.is_empty() && var;
let decl = ast::ForeignItemKind::Fn(
P(cfuncty_to_rs(ctx, rty, aty, var)),
empty_generics()
);
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = mk_doc_attr(ctx, &comment);
if !mangled.is_empty() {
attrs.push(mk_link_name_attr(ctx, mangled));
} else if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: attrs,
node: decl,
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: vis,
}
}
fn cty_to_rs(ctx: &mut GenCtx, ty: &Type, allow_bool: bool, use_full_path: bool) -> ast::Ty {
let prefix = vec!["std".to_owned(), "os".to_owned(), "raw".to_owned()];
let raw = |fragment: &str| {
let mut path = prefix.clone();
path.push(fragment.to_owned());
path
};
match *ty {
TVoid => mk_ty(ctx, true, &raw("c_void")),
TInt(i, ref layout) => match i {
IBool => {
let ty_name = match layout.size {
1 if allow_bool => "bool",
2 => "u16",
4 => "u32",
8 => "u64",
_ => "u8",
};
mk_ty(ctx, false, &[ty_name.to_owned()])
},
ISChar => mk_ty(ctx, true, &raw("c_char")),
IUChar => mk_ty(ctx, true, &raw("c_uchar")),
IInt => mk_ty(ctx, true, &raw("c_int")),
IUInt => mk_ty(ctx, true, &raw("c_uint")),
IShort => mk_ty(ctx, true, &raw("c_short")),
IUShort => mk_ty(ctx, true, &raw("c_ushort")),
ILong => mk_ty(ctx, true, &raw("c_long")),
IULong => mk_ty(ctx, true, &raw("c_ulong")),
ILongLong => mk_ty(ctx, true, &raw("c_longlong")),
IULongLong => mk_ty(ctx, true, &raw("c_ulonglong"))
},
TFloat(f, _) => match f {
FFloat => mk_ty(ctx, false, &["f32".to_owned()]),
FDouble => mk_ty(ctx, false, &["f64".to_owned()])
},
TPtr(ref t, is_const, _is_ref, _) => {
let id = cty_to_rs(ctx, &**t, allow_bool, use_full_path);
mk_ptrty(ctx, &id, is_const)
},
TArray(ref t, s, _) => {
let ty = cty_to_rs(ctx, &**t, allow_bool, use_full_path);
mk_arrty(ctx, &ty, s)
},
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
mk_fnty(ctx, &decl, sig.abi)
},
TFuncProto(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
mk_fn_proto_ty(ctx, &decl, sig.abi)
},
TNamed(ref ti) => {
let id = rust_type_id(ctx, &ti.borrow().name);
if use_full_path {
let mut path = ctx.full_path_for_module(ti.borrow().module_id);
path.push(id);
mk_ty(ctx, false, &path)
} else {
mk_ty(ctx, false, &[id])
}
},
TComp(ref ci) => {
let c = ci.borrow();
let id = comp_name(&ctx, c.kind, &c.name);
let args = c.args.iter().map(|gt| {
P(cty_to_rs(ctx, gt, allow_bool, false))
}).collect();
if use_full_path {
let mut path = ctx.full_path_for_module(c.module_id);
path.push(id);
mk_ty_args(ctx, false, &path, args)
} else {
mk_ty_args(ctx, false, &[id], args)
}
},
TEnum(ref ei) => {
let e = ei.borrow();
let id = enum_name(&ctx, &e.name);
if use_full_path {
let mut path = ctx.full_path_for_module(e.module_id);
path.push(id);
mk_ty(ctx, false, &path)
} else {
mk_ty(ctx, false, &[id])
}
}
}
}
fn cty_is_translatable(ty: &Type) -> bool {
match *ty {
TVoid => false,
TArray(ref t, _, _) => {
cty_is_translatable(&**t)
},
TComp(ref ci) => {
let c = ci.borrow();
!c.args.iter().any(|gt| gt == &TVoid) && !c.has_non_type_template_params
},
_ => true,
}
}
fn cty_has_destructor(ty: &Type) -> bool {
match ty {
&TArray(ref t, _, _) => {
cty_has_destructor(&**t)
}
&TComp(ref ci) => {
let c = ci.borrow();
if c.has_destructor || c.members.iter().any(|f| match f {
&CompMember::Field(ref f) |
&CompMember::CompField(_, ref f) =>
cty_has_destructor(&f.ty),
_ => false,
}) {
return true;
}
c.ref_template.is_some()
},
&TNamed(ref ti) => {
cty_has_destructor(&ti.borrow().ty)
},
_ => false,
}
}
fn mk_ty(ctx: &GenCtx, global: bool, segments: &[String]) -> ast::Ty {
mk_ty_args(ctx, global, segments, vec!())
}
fn mk_ty_args(ctx: &GenCtx, global: bool, segments: &[String], args: Vec<P<ast::Ty>>) -> ast::Ty {
let segment_count = segments.len();
let ty = ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: global,
segments: segments.iter().enumerate().map(|(i, s)| {
ast::PathSegment {
identifier: ctx.ext_cx.ident_of(s),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: vec!(),
types: OwnedSlice::from_vec(if i == segment_count - 1 { args.clone() } else { vec![] }),
bindings: OwnedSlice::empty(),
}),
}
}).collect()
},
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_ptrty(ctx: &mut GenCtx, base: &ast::Ty, is_const: bool) -> ast::Ty {
let ty = ast::TyKind::Ptr(ast::MutTy {
ty: P(base.clone()),
mutbl: if is_const { ast::Mutability::Immutable } else { ast::Mutability::Mutable }
});
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
#[allow(dead_code)]
fn mk_refty(ctx: &mut GenCtx, base: &ast::Ty, is_const: bool) -> ast::Ty {
let ty = ast::TyKind::Rptr(
None,
ast::MutTy {
ty: P(base.clone()),
mutbl: if is_const { ast::Mutability::Immutable } else { ast::Mutability::Mutable }
}
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_arrty(ctx: &GenCtx, base: &ast::Ty, n: usize) -> ast::Ty {
let int_lit = ast::LitKind::Int(n as u64, ast::LitIntType::Unsigned(ast::UintTy::Us));
let sz = ast::ExprKind::Lit(P(respan(ctx.span, int_lit)));
let ty = ast::TyKind::FixedLengthVec(
P(base.clone()),
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: sz,
span: ctx.span,
attrs: None,
})
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_fn_proto_ty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
abi: Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: ast::Unsafety::Unsafe,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span,
}
}
fn mk_fnty(ctx: &mut GenCtx, decl: &ast::FnDecl, abi: Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: ast::Unsafety::Unsafe,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
let segs = vec![
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("std"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("Option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::from_vec(vec!(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span
})
)),
bindings: OwnedSlice::empty(),
}),
}
];
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: true,
segments: segs
},
),
span: ctx.span
}
}
fn mk_test_fn(ctx: &GenCtx, name: &str, layout: &Layout) -> P<ast::Item> {
let size = layout.size;
let align = layout.align;
let struct_name = ctx.ext_cx.ident_of(name);
let fn_name = ctx.ext_cx.ident_of(&format!("bindgen_test_layout_{}", name));
let size_of_expr = quote_expr!(&ctx.ext_cx, ::std::mem::size_of::<$struct_name>());
let align_of_expr = quote_expr!(&ctx.ext_cx, ::std::mem::align_of::<$struct_name>());
let item = quote_item!(&ctx.ext_cx,
#[test]
fn $fn_name() {
assert_eq!($size_of_expr, $size);
assert_eq!($align_of_expr, $align);
}).unwrap();
item
}
fn mk_opaque_struct(ctx: &GenCtx, name: &str, layout: &Layout) -> P<ast::Item> {
// XXX prevent this spurious clone
let blob_field = mk_blob_field(ctx, "_bindgen_opaque_blob", layout.clone());
let variant_data = if layout.size == 0 {
ast::VariantData::Unit(ast::DUMMY_NODE_ID)
} else {
ast::VariantData::Struct(vec![blob_field], ast::DUMMY_NODE_ID)
};
let def = ast::ItemKind::Struct(
variant_data,
ast::Generics {
lifetimes: vec!(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: vec!()
}
}
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec![mk_repr_attr(ctx, layout.clone())],
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
gen: Simplify root export with namespaces.
use std;
use std::cmp;
use std::cell::RefCell;
use std::vec::Vec;
use std::rc::Rc;
use std::collections::HashMap;
use syntax::abi::Abi;
use syntax::ast;
use syntax::codemap::{Span, Spanned, respan, ExpnInfo, NameAndSpan, MacroBang};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig;
use syntax::ext::quote::rt::ToTokens;
use syntax::feature_gate::Features;
use syntax::owned_slice::OwnedSlice;
use syntax::parse;
use syntax::parse::token::{InternedString, intern};
use syntax::attr::mk_attr_id;
use syntax::ptr::P;
use syntax::print::pprust::tts_to_string;
use super::BindgenOptions;
use super::LinkType;
use types::*;
struct GenCtx<'r> {
ext_cx: base::ExtCtxt<'r>,
options: BindgenOptions,
span: Span,
module_map: ModuleMap,
current_module_id: ModuleId,
}
impl<'r> GenCtx<'r> {
fn full_path_for_module(&self, id: ModuleId) -> Vec<String> {
if !self.options.enable_cxx_namespaces {
return vec![];
}
let mut ret = vec![];
let mut current_id = Some(id);
while let Some(current) = current_id {
let module = &self.module_map.get(¤t).unwrap();
ret.push(module.name.clone());
current_id = module.parent_id;
}
if self.current_module_id == ROOT_MODULE_ID {
ret.pop(); // The root module doens'n need a root:: in the pattern
}
ret.reverse();
ret
}
fn current_module_mut(&mut self) -> &mut Module {
let id = self.current_module_id;
self.module_map.get_mut(&id).expect("Module not found!")
}
}
fn first<A, B>((val, _): (A, B)) -> A {
val
}
fn ref_eq<T>(thing: &T, other: &T) -> bool {
(thing as *const T) == (other as *const T)
}
fn empty_generics() -> ast::Generics {
ast::Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new()
}
}
}
fn rust_id(ctx: &mut GenCtx, name: &str) -> (String, bool) {
let token = parse::token::Ident(ctx.ext_cx.ident_of(name), parse::token::Plain);
if token.is_any_keyword() || "bool" == name {
let mut s = name.to_owned();
s.push_str("_");
(s, true)
} else {
(name.to_owned(), false)
}
}
fn rust_type_id(ctx: &mut GenCtx, name: &str) -> String {
match name {
"bool" | "uint" | "u8" | "u16" |
"u32" | "f32" | "f64" | "i8" |
"i16" | "i32" | "i64" | "Self" |
"str" => {
let mut s = name.to_owned();
s.push_str("_");
s
}
"int8_t" => "i8".to_owned(),
"uint8_t" => "u8".to_owned(),
"int16_t" => "i16".to_owned(),
"uint16_t" => "u16".to_owned(),
"int32_t" => "i32".to_owned(),
"uint32_t" => "u32".to_owned(),
"int64_t" => "i64".to_owned(),
"uint64_t" => "u64".to_owned(),
"uintptr_t"
| "size_t" => "usize".to_owned(),
"intptr_t"
| "ptrdiff_t"
| "ssize_t" => "isize".to_owned(),
_ => first(rust_id(ctx, name))
}
}
fn comp_name(ctx: &GenCtx, kind: CompKind, name: &str) -> String {
match kind {
CompKind::Struct => struct_name(ctx, name),
CompKind::Union => union_name(ctx, name),
}
}
fn struct_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Struct_{}", name)
} else {
name.to_owned()
}
}
fn union_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Union_{}", name)
} else {
name.to_owned()
}
}
fn enum_name(ctx: &GenCtx, name: &str) -> String {
if ctx.options.rename_types {
format!("Enum_{}", name)
} else {
name.to_owned()
}
}
fn gen_unmangle_method(ctx: &mut GenCtx,
v: &VarInfo,
counts: &mut HashMap<String, isize>,
self_kind: ast::SelfKind)
-> ast::ImplItem {
let fndecl;
let mut args = vec!();
match self_kind {
ast::SelfKind::Static => (),
ast::SelfKind::Region(_, mutable, _) => {
let selfexpr = match mutable {
ast::Mutability::Immutable => quote_expr!(&ctx.ext_cx, &*self),
ast::Mutability::Mutable => quote_expr!(&ctx.ext_cx, &mut *self),
};
args.push(selfexpr);
},
_ => unreachable!()
}
match v.ty {
TFuncPtr(ref sig) => {
fndecl = cfuncty_to_rs(ctx,
&*sig.ret_ty, sig.args.as_slice(),
false);
let mut unnamed: usize = 0;
let iter = if args.len() > 0 {
sig.args[1..].iter()
} else {
sig.args.iter()
};
for arg in iter {
let (ref n, _) = *arg;
let argname = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
first(rust_id(ctx, &n))
};
let expr = ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, ast::Path {
span: ctx.span,
global: false,
segments: vec!(ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&argname),
parameters: ast::PathParameters::none()
})
}),
span: ctx.span,
attrs: None,
};
args.push(P(expr));
}
},
_ => unreachable!()
};
let sig = ast::MethodSig {
unsafety: ast::Unsafety::Unsafe,
abi: Abi::Rust,
decl: P(fndecl),
generics: empty_generics(),
explicit_self: respan(ctx.span, self_kind),
constness: ast::Constness::NotConst,
};
let block = ast::Block {
stmts: vec!(),
expr: Some(P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Call(
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, ast::Path {
span: ctx.span,
global: false,
segments: vec!(ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&v.mangled),
parameters: ast::PathParameters::none()
})
}),
span: ctx.span,
attrs: None,
}),
args
),
span: ctx.span,
attrs: None,
})),
id: ast::DUMMY_NODE_ID,
rules: ast::BlockCheckMode::Default,
span: ctx.span
};
let mut name = v.name.clone();
let mut count = 0;
match counts.get(&v.name) {
Some(x) => {
count = *x;
name.push_str(&x.to_string());
},
None => ()
}
count += 1;
counts.insert(v.name.clone(), count);
let mut attrs = mk_doc_attr(ctx, &v.comment);
attrs.push(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("inline")))),
is_sugared_doc: false
}));
let name = first(rust_id(ctx, &name));
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: ctx.ext_cx.ident_of(&name),
vis: ast::Visibility::Public,
attrs: attrs,
node: ast::ImplItemKind::Method(sig, P(block)),
span: ctx.span
}
}
pub fn gen_mods(links: &[(String, LinkType)],
map: ModuleMap,
options: BindgenOptions,
span: Span) -> Vec<P<ast::Item>> {
// Create a dummy ExtCtxt. We only need this for string interning and that uses TLS.
let mut features = Features::new();
features.allow_quote = true;
let cfg = ExpansionConfig {
crate_name: "xxx".to_owned(),
features: Some(&features),
recursion_limit: 64,
trace_mac: false,
};
let sess = &parse::ParseSess::new();
let mut feature_gated_cfgs = vec![];
let mut ctx = GenCtx {
ext_cx: base::ExtCtxt::new(sess, Vec::new(), cfg, &mut feature_gated_cfgs),
options: options,
span: span,
module_map: map,
current_module_id: ROOT_MODULE_ID,
};
ctx.ext_cx.bt_push(ExpnInfo {
call_site: ctx.span,
callee: NameAndSpan {
format: MacroBang(intern("")),
allow_internal_unstable: false,
span: None
}
});
if let Some(root_mod) = gen_mod(&mut ctx, ROOT_MODULE_ID, links, span) {
if !ctx.options.enable_cxx_namespaces {
match root_mod.node {
// XXX This clone might be really expensive, but doing:
// ast::ItemMod(ref mut root) => {
// return ::std::mem::replace(&mut root.items, vec![]);
// }
// fails with "error: cannot borrow immutable anonymous field as mutable".
// So...
ast::ItemKind::Mod(ref root) => {
return root.items.clone()
}
_ => unreachable!(),
}
}
let ident = root_mod.ident;
let root_export = quote_item!(&ctx.ext_cx, pub use $ident::*;).unwrap();
vec![root_export, root_mod]
} else {
vec![]
}
}
fn gen_mod(mut ctx: &mut GenCtx,
module_id: ModuleId,
links: &[(String, LinkType)],
span: Span) -> Option<P<ast::Item>> {
// XXX avoid this clone
let module = ctx.module_map.get(&module_id).unwrap().clone();
// Import just the root to minimise name conflicts
let mut globals = if module_id != ROOT_MODULE_ID {
// XXX Pass this previously instead of looking it up always?
let root = ctx.ext_cx.ident_of(&ctx.module_map.get(&ROOT_MODULE_ID).unwrap().name);
vec![P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Use(P(
Spanned {
node: ast::ViewPathSimple(root.clone(),
ast::Path {
span: span.clone(),
global: false,
segments: vec![ast::PathSegment {
identifier: root,
parameters: ast::PathParameters::none(),
}]
}),
span: span.clone(),
})),
vis: ast::Visibility::Public,
span: span.clone(),
})]
} else {
// TODO: Could be worth it to avoid this if
// we know there won't be any union.
let union_fields_decl = quote_item!(&ctx.ext_cx,
#[derive(Copy, Clone, Debug)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
).unwrap();
let union_fields_impl = quote_item!(&ctx.ext_cx,
impl<T> __BindgenUnionField<T> {
#[inline]
pub fn new() -> Self {
__BindgenUnionField(::std::marker::PhantomData)
}
#[inline]
pub unsafe fn as_ref(&self) -> &T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
::std::mem::transmute(self)
}
}
).unwrap();
let union_fields_default_impl = quote_item!(&ctx.ext_cx,
impl<T> ::std::default::Default for __BindgenUnionField<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
).unwrap();
vec![union_fields_decl, union_fields_impl, union_fields_default_impl]
};
ctx.current_module_id = module_id;
globals.extend(gen_globals(&mut ctx, links, &module.globals).into_iter());
globals.extend(module.children_ids.iter().filter_map(|id| {
gen_mod(ctx, *id, links, span.clone())
}));
if !globals.is_empty() {
Some(P(ast::Item {
ident: ctx.ext_cx.ident_of(&module.name),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Mod(ast::Mod {
inner: span,
items: globals,
}),
vis: ast::Visibility::Public,
span: span.clone(),
}))
} else {
None
}
}
fn type_opaque(ctx: &GenCtx, ty: &Type) -> bool {
let ty_name = ty.name();
match ty_name {
Some(ty_name)
=> ctx.options.opaque_types.iter().any(|name| *name == ty_name),
None => false,
}
}
fn global_opaque(ctx: &GenCtx, global: &Global) -> bool {
let global_name = global.name();
// Can't make an opaque type without layout
global.layout().is_some() &&
ctx.options.opaque_types.iter().any(|name| *name == global_name)
}
fn type_blacklisted(ctx: &GenCtx, global: &Global) -> bool {
let global_name = global.name();
ctx.options.blacklist_type.iter().any(|name| *name == global_name)
}
fn gen_global(mut ctx: &mut GenCtx,
g: Global,
defs: &mut Vec<P<ast::Item>>) {
// XXX unify with anotations both type_blacklisted
// and type_opaque (which actually doesn't mean the same).
if type_blacklisted(ctx, &g) {
return;
}
if global_opaque(ctx, &g) {
let name = first(rust_id(ctx, &g.name()));
let layout = g.layout().unwrap();
defs.push(mk_opaque_struct(ctx, &name, &layout));
// This should always be true but anyways..
defs.push(mk_test_fn(ctx, &name, &layout));
return;
}
match g {
GType(ti) => {
let t = ti.borrow().clone();
defs.push(ctypedef_to_rs(&mut ctx, t))
},
GCompDecl(ci) => {
let c = ci.borrow().clone();
let name = comp_name(&ctx, c.kind, &c.name);
defs.push(opaque_to_rs(&mut ctx, &name, c.layout));
},
GComp(ci) => {
let c = ci.borrow().clone();
let name = comp_name(&ctx, c.kind, &c.name);
defs.extend(comp_to_rs(&mut ctx, &name, c).into_iter())
},
GEnumDecl(ei) => {
let e = ei.borrow().clone();
let name = enum_name(&ctx, &e.name);
let dummy = EnumItem::new("_BindgenOpaqueEnum".to_owned(), "".to_owned(), 0);
defs.extend(cenum_to_rs(&mut ctx, &name, e.kind, e.comment, &[dummy], e.layout).into_iter())
},
GEnum(ei) => {
let e = ei.borrow().clone();
let name = enum_name(&ctx, &e.name);
defs.extend(cenum_to_rs(&mut ctx, &name, e.kind, e.comment, &e.items, e.layout).into_iter())
},
GVar(vi) => {
let v = vi.borrow();
let ty = cty_to_rs(&mut ctx, &v.ty, v.is_const, true);
defs.push(const_to_rs(&mut ctx, v.name.clone(), v.val.unwrap(), ty));
},
_ => { }
}
}
fn gen_globals(mut ctx: &mut GenCtx,
links: &[(String, LinkType)],
globs: &[Global]) -> Vec<P<ast::Item>> {
let uniq_globs = tag_dup_decl(globs);
let mut fs = vec!();
let mut vs = vec!();
let mut gs = vec!();
for g in uniq_globs.into_iter() {
match g {
GOther => {}
GFunc(_) => fs.push(g),
GVar(_) => {
let is_int_const = {
match g {
GVar(ref vi) => {
let v = vi.borrow();
v.is_const && v.val.is_some()
}
_ => unreachable!()
}
};
if is_int_const {
gs.push(g);
} else {
vs.push(g);
}
}
_ => gs.push(g)
}
}
let mut defs = vec!();
gs = remove_redundant_decl(gs);
for mut g in gs.into_iter() {
if let Some(substituted) = ctx.current_module_mut().translations.remove(&g.name()) {
match (substituted.layout(), g.layout()) {
(Some(l), Some(lg)) if l.size == lg.size => {},
(None, None) => {},
_ => {
// XXX real logger
println!("warning: substituted type for {} does not match its size", g.name());
}
}
g = substituted;
}
gen_global(ctx, g, &mut defs);
}
let mut pending_translations = std::mem::replace(&mut ctx.current_module_mut().translations, HashMap::new());
for (name, g) in pending_translations.drain() {
println!("warning: generating definition for not found type: {}", name);
gen_global(ctx, g, &mut defs);
}
let vars: Vec<_> = vs.into_iter().map(|v| {
match v {
GVar(vi) => {
let v = vi.borrow();
cvar_to_rs(&mut ctx, v.name.clone(), v.mangled.clone(), &v.ty, v.is_const)
},
_ => unreachable!()
}
}).collect();
let mut unmangle_count: HashMap<String, isize> = HashMap::new();
let funcs = {
let func_list = fs.into_iter().map(|f| {
match f {
GFunc(vi) => {
let v = vi.borrow();
match v.ty {
TFuncPtr(ref sig) => {
let mut name = v.name.clone();
let mut count = 0;
match unmangle_count.get(&v.name) {
Some(x) => {
count = *x;
name.push_str(&x.to_string());
},
None => ()
}
count += 1;
unmangle_count.insert(v.name.clone(), count);
let decl = cfunc_to_rs(&mut ctx, name, v.mangled.clone(), v.comment.clone(),
&*sig.ret_ty, &sig.args[..],
sig.is_variadic, ast::Visibility::Public);
(sig.abi, decl)
}
_ => unreachable!()
}
},
_ => unreachable!()
}
});
let mut map: HashMap<Abi, Vec<_>> = HashMap::new();
for (abi, func) in func_list {
map.entry(abi).or_insert(vec![]).push(func);
}
map
};
if !vars.is_empty() {
defs.push(mk_extern(&mut ctx, links, vars, Abi::C));
}
for (abi, funcs) in funcs.into_iter() {
defs.push(mk_extern(&mut ctx, &links, funcs, abi));
}
//let attrs = vec!(mk_attr_list(&mut ctx, "allow", ["dead_code", "non_camel_case_types", "uppercase_variables"]));
defs
}
fn mk_extern(ctx: &mut GenCtx, links: &[(String, LinkType)],
foreign_items: Vec<ast::ForeignItem>,
abi: Abi) -> P<ast::Item> {
let attrs: Vec<_> = links.iter().map(|&(ref l, ref k)| {
let k = match *k {
LinkType::Default => None,
LinkType::Static => Some("static"),
LinkType::Framework => Some("framework")
};
let link_name = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("name"),
respan(ctx.span, ast::LitKind::Str(intern(l).as_str(), ast::StrStyle::Cooked))
)));
let link_args = match k {
None => vec!(link_name),
Some(ref k) => vec!(link_name, P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("kind"),
respan(ctx.span, ast::LitKind::Str(intern(k).as_str(), ast::StrStyle::Cooked))
))))
};
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("link"),
link_args)
)),
is_sugared_doc: false
})
}).collect();
let mut items = Vec::new();
items.extend(foreign_items.into_iter());
let ext = ast::ItemKind::ForeignMod(ast::ForeignMod {
abi: abi,
items: items
});
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn mk_impl(ctx: &mut GenCtx, ty: P<ast::Ty>,
items: Vec<ast::ImplItem>)
-> P<ast::Item> {
let ext = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
ty,
items
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn remove_redundant_decl(gs: Vec<Global>) -> Vec<Global> {
fn check_decl(a: &Global, ty: &Type) -> bool {
match *a {
GComp(ref ci1) => match *ty {
TComp(ref ci2) => {
ref_eq(ci1, ci2) && ci1.borrow().name.is_empty()
},
_ => false
},
GEnum(ref ei1) => match *ty {
TEnum(ref ei2) => {
ref_eq(ei1, ei2) && ei1.borrow().name.is_empty()
},
_ => false
},
_ => false
}
}
let typedefs: Vec<Type> = gs.iter().filter_map(|g|
match *g {
GType(ref ti) => Some(ti.borrow().ty.clone()),
_ => None
}
).collect();
gs.into_iter().filter(|g|
!typedefs.iter().any(|t| check_decl(g, t))
).collect()
}
fn tag_dup_decl(gs: &[Global]) -> Vec<Global> {
fn check(name1: &str, name2: &str) -> bool {
!name1.is_empty() && name1 == name2
}
fn check_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(>ype(ref ti1), >ype(ref ti2)) => {
let a = ti1.borrow();
let b = ti2.borrow();
check(&a.name, &b.name)
},
(&GComp(ref ci1), &GComp(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GCompDecl(ref ci1), &GCompDecl(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GEnum(ref ei1), &GEnum(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
(&GEnumDecl(ref ei1), &GEnumDecl(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
(&GVar(ref vi1), &GVar(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name, &b.name) &&
check(&a.mangled, &b.mangled)
},
(&GFunc(ref vi1), &GFunc(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name, &b.name) &&
check(&a.mangled, &b.mangled)
},
_ => false
}
}
fn check_opaque_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(&GCompDecl(ref ci1), &GComp(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name, &b.name)
},
(&GEnumDecl(ref ei1), &GEnum(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name, &b.name)
},
_ => false,
}
}
if gs.is_empty() {
return vec![];
}
let mut step: Vec<Global> = vec!();
step.push(gs[0].clone());
for (i, _gsi) in gs.iter().enumerate().skip(1) {
let mut dup = false;
for j in 0..i {
if i == j {
continue;
}
if check_dup(&gs[i], &gs[j]) {
dup = true;
break;
}
}
if !dup {
step.push(gs[i].clone());
}
}
let len = step.len();
let mut res: Vec<Global> = vec!();
for i in 0..len {
let mut dup = false;
match &step[i] {
&GCompDecl(_) | &GEnumDecl(_) => {
for j in 0..len {
if i == j {
continue;
}
if check_opaque_dup(&step[i], &step[j]) {
dup = true;
break;
}
}
},
_ => (),
}
if !dup {
res.push(step[i].clone());
}
}
res
}
fn ctypedef_to_rs(ctx: &mut GenCtx, ty: TypeInfo) -> P<ast::Item> {
fn mk_item(ctx: &mut GenCtx, name: &str, comment: &str, ty: &Type) -> P<ast::Item> {
let rust_name = rust_type_id(ctx, name);
let rust_ty = if cty_is_translatable(ty) {
cty_to_rs(ctx, ty, true, true)
} else {
cty_to_rs(ctx, &TVoid, true, true)
};
let base = ast::ItemKind::Ty(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: rust_ty.node,
span: ctx.span,
}),
empty_generics()
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: mk_doc_attr(ctx, comment),
id: ast::DUMMY_NODE_ID,
node: base,
vis: ast::Visibility::Public,
span: ctx.span
})
}
match ty.ty {
TComp(ref ci) => {
assert!(!ci.borrow().name.is_empty());
mk_item(ctx, &ty.name, &ty.comment, &ty.ty)
},
TEnum(ref ei) => {
assert!(!ei.borrow().name.is_empty());
mk_item(ctx, &ty.name, &ty.comment, &ty.ty)
},
_ => mk_item(ctx, &ty.name, &ty.comment, &ty.ty),
}
}
fn comp_to_rs(ctx: &mut GenCtx, name: &str, ci: CompInfo)
-> Vec<P<ast::Item>> {
match ci.kind {
CompKind::Struct => cstruct_to_rs(ctx, name, ci),
CompKind::Union => cunion_to_rs(ctx, name, ci.layout, ci.members),
}
}
fn cstruct_to_rs(ctx: &mut GenCtx, name: &str, ci: CompInfo) -> Vec<P<ast::Item>> {
let layout = ci.layout;
let members = &ci.members;
let template_args = &ci.args;
let methodlist = &ci.methods;
let mut fields = vec!();
let mut methods = vec!();
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current struct.
let mut extra = vec!();
let mut unnamed: u32 = 0;
let mut bitfields: u32 = 0;
if ci.hide ||
ci.has_non_type_template_params ||
template_args.iter().any(|f| f == &TVoid) {
return vec!();
}
let id = rust_type_id(ctx, name);
let id_ty = P(mk_ty(ctx, false, &[id.clone()]));
if ci.has_vtable {
let mut vffields = vec!();
let base_vftable = if !members.is_empty() {
if let CompMember::Field(ref fi) = members[0] {
match fi.ty {
TComp(ref ci2) => {
let ci2 = ci2.borrow();
if ci2.has_vtable {
Some(format!("_vftable_{}", ci2.name))
} else {
None
}
},
_ => None
}
} else {
None
}
} else {
None
};
if let Some(ref base) = base_vftable {
let field = ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of("_base"), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(mk_ty(ctx, false, &[base.clone()])),
attrs: vec!(),
};
vffields.push(respan(ctx.span, field));
}
for vm in ci.vmethods.iter() {
let ty = match vm.ty {
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, sig.args.as_slice(), sig.is_variadic);
mk_fn_proto_ty(ctx, &decl, sig.abi)
},
_ => unreachable!()
};
let field = ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of(&vm.name), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(ty),
attrs: vec!(),
};
vffields.push(respan(ctx.span, field));
}
// FIXME: rustc actually generates tons of warnings
// due to an empty repr(C) type, so we just generate
// a dummy field with pointer-alignment to supress it.
if vffields.is_empty() {
vffields.push(mk_blob_field(ctx, "_bindgen_empty_ctype_warning_fix",
Layout::new(::std::mem::size_of::<*mut ()>(), ::std::mem::align_of::<*mut ()>())));
}
let vf_name = format!("_vftable_{}", name);
let item = P(ast::Item {
ident: ctx.ext_cx.ident_of(&vf_name),
attrs: vec!(mk_repr_attr(ctx, layout)),
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Struct(
ast::VariantData::Struct(vffields, ast::DUMMY_NODE_ID),
empty_generics()
),
vis: ast::Visibility::Public,
span: ctx.span,
});
extra.push(item);
if base_vftable.is_none() {
let vf_type = mk_ty(ctx, false, &[vf_name]);
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(ctx.ext_cx.ident_of("_vftable"), ast::Visibility::Public),
id: ast::DUMMY_NODE_ID,
ty: P(mk_ptrty(ctx, &vf_type, true)),
attrs: Vec::new()
}));
}
}
let mut anon_enum_count = 0;
let mut setters = vec!();
let mut has_destructor = ci.has_destructor;
let mut template_args_used = vec![false; template_args.len()];
for m in members.iter() {
if let CompMember::Enum(ref ei) = *m {
let empty_name = ei.borrow().name.is_empty();
if empty_name {
ei.borrow_mut().name = format!("{}_enum{}", name, anon_enum_count);
anon_enum_count += 1;
}
let e = ei.borrow().clone();
extra.extend(cenum_to_rs(ctx, &e.name, e.kind, e.comment, &e.items, e.layout).into_iter());
continue;
}
fn comp_fields(m: &CompMember)
-> (Option<Rc<RefCell<CompInfo>>>, Option<FieldInfo>) {
match *m {
CompMember::Field(ref f) => { (None, Some(f.clone())) }
CompMember::Comp(ref rc_c) => { (Some(rc_c.clone()), None) }
CompMember::CompField(ref rc_c, ref f) => { (Some(rc_c.clone()), Some(f.clone())) }
_ => unreachable!()
}
}
let (opt_rc_c, opt_f) = comp_fields(m);
if let Some(f) = opt_f {
if cty_has_destructor(&f.ty) {
has_destructor = true;
}
let (f_name, f_ty) = match f.bitfields {
Some(ref v) => {
bitfields += 1;
// NOTE: We rely on the name of the type converted to rust types,
// and on the alignment.
let bits = v.iter().fold(0, |acc, &(_, w)| acc + w);
let layout_size = cmp::max(1, bits.next_power_of_two() / 8) as usize;
let name = match layout_size {
1 => "uint8_t",
2 => "uint16_t",
4 => "uint32_t",
8 => "uint64_t",
_ => panic!("bitfield width not supported: {}", layout_size),
};
let ty = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.to_owned(), ROOT_MODULE_ID, TVoid, Layout::new(layout_size, layout_size)))));
(format!("_bitfield_{}", bitfields), ty)
}
None => (rust_type_id(ctx, &f.name), f.ty.clone())
};
drop(f.ty); // to ensure it's not used unintentionally
let is_translatable = cty_is_translatable(&f_ty);
if !is_translatable || type_opaque(ctx, &f_ty) {
if !is_translatable {
println!("{}::{} not translatable, void: {}", ci.name, f.name, f_ty == TVoid);
}
if let Some(layout) = f_ty.layout() {
fields.push(mk_blob_field(ctx, &f_name, layout));
}
continue;
}
if ctx.options.gen_bitfield_methods {
let mut offset: u32 = 0;
if let Some(ref bitfields) = f.bitfields {
for &(ref bf_name, bf_size) in bitfields.iter() {
setters.push(gen_bitfield_method(ctx, &f_name, bf_name, &f_ty, offset as usize, bf_size));
offset += bf_size;
}
setters.push(gen_fullbitfield_method(ctx, &f_name, &f_ty, bitfields))
}
}
let mut bypass = false;
let f_ty = if let Some(ref rc_c) = opt_rc_c {
if rc_c.borrow().members.len() == 1 {
if let CompMember::Field(ref inner_f) = rc_c.borrow().members[0] {
bypass = true;
inner_f.ty.clone()
} else {
f_ty
}
} else {
f_ty
}
} else {
f_ty
};
// If the member is not a template argument, it needs the full path.
let mut needs_full_path = true;
for (index, arg) in template_args.iter().enumerate() {
let used = f_ty == *arg || match f_ty {
TPtr(ref t, _, _, _) => **t == *arg,
TArray(ref t, _, _) => **t == *arg,
_ => false,
};
if used {
template_args_used[index] = true;
needs_full_path = false;
break;
}
}
let f_ty = P(cty_to_rs(ctx, &f_ty, f.bitfields.is_none(), needs_full_path));
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(&f_name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: f_ty,
attrs: mk_doc_attr(ctx, &f.comment)
}));
if bypass {
continue;
}
}
if let Some(rc_c) = opt_rc_c {
let name_is_empty = rc_c.borrow().name.is_empty();
if name_is_empty {
let c = rc_c.borrow();
unnamed += 1;
let field_name = format!("_bindgen_data_{}_", unnamed);
fields.push(mk_blob_field(ctx, &field_name, c.layout));
methods.extend(gen_comp_methods(ctx, &field_name, 0, c.kind, &c.members, &mut extra).into_iter());
} else {
let name = comp_name(&ctx, rc_c.borrow().kind, &rc_c.borrow().name);
extra.extend(comp_to_rs(ctx, &name, rc_c.borrow().clone()).into_iter());
}
}
}
let mut phantom_count = 0;
for (i, arg) in template_args.iter().enumerate() {
if template_args_used[i] {
continue;
}
let f_name = format!("_phantom{}", phantom_count);
phantom_count += 1;
let inner_type = P(cty_to_rs(ctx, &arg, true, false));
fields.push(respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(&f_name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: quote_ty!(&ctx.ext_cx, ::std::marker::PhantomData<$inner_type>),
attrs: vec!(),
}));
}
if !setters.is_empty() {
extra.push(P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
id_ty.clone(),
setters
),
vis: ast::Visibility::Inherited,
span: ctx.span
}));
}
let field_count = fields.len();
let variant_data = if fields.is_empty() {
ast::VariantData::Unit(ast::DUMMY_NODE_ID)
} else {
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID)
};
let ty_params = template_args.iter().map(|gt| {
let name = match gt {
&TNamed(ref ti) => {
ctx.ext_cx.ident_of(&ti.borrow().name)
},
_ => ctx.ext_cx.ident_of("")
};
ast::TyParam {
ident: name,
id: ast::DUMMY_NODE_ID,
bounds: OwnedSlice::empty(),
default: None,
span: ctx.span
}
}).collect();
let def = ast::ItemKind::Struct(
variant_data,
ast::Generics {
lifetimes: vec!(),
ty_params: OwnedSlice::from_vec(ty_params),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: vec!()
}
}
);
let mut attrs = mk_doc_attr(ctx, &ci.comment);
attrs.push(mk_repr_attr(ctx, layout));
if !has_destructor {
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
if template_args.is_empty() {
extra.push(mk_clone_impl(ctx, name));
attrs.push(if can_derive_debug && ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Debug", "Copy"])
} else {
mk_deriving_attr(ctx, &["Copy"])
});
} else {
attrs.push(if can_derive_debug && ctx.options.derive_debug {
// TODO: make mk_clone_impl work for template arguments,
// meanwhile just fallback to deriving.
mk_deriving_attr(ctx, &["Copy", "Clone", "Debug"])
} else {
mk_deriving_attr(ctx, &["Copy", "Clone"])
});
}
}
let struct_def = ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
};
let mut items = vec!(P(struct_def));
if !methods.is_empty() {
let impl_ = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
id_ty.clone(),
methods
);
items.push(
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: impl_,
vis: ast::Visibility::Inherited,
span: ctx.span}));
}
// Template args have incomplete type in general
//
// XXX if x is a class without members, C++ still will report
// sizeof(x) == 1, since it requires to be adressable.
//
// We maybe should add a dummy byte if it's the case, but...
// That could play wrong with inheritance.
//
// So for now don't generate a test if the struct/class is empty
// or has only empty bases.
if ci.args.is_empty() && field_count > 0 &&
(ci.has_nonempty_base || ci.base_members < field_count) {
extra.push(mk_test_fn(ctx, name, &layout));
}
items.extend(extra.into_iter());
let mut mangledlist = vec!();
let mut unmangledlist = vec!();
let mut unmangle_count: HashMap<String, isize> = HashMap::new();
for v in methodlist {
let v = v.clone();
match v.ty {
TFuncPtr(ref sig) => {
let name = v.mangled.clone();
let explicit_self = if v.is_static {
ast::SelfKind::Static
} else if v.is_const {
ast::SelfKind::Region(None, ast::Mutability::Immutable, ctx.ext_cx.ident_of("self"))
} else {
ast::SelfKind::Region(None, ast::Mutability::Mutable, ctx.ext_cx.ident_of("self"))
};
unmangledlist.push(gen_unmangle_method(ctx, &v, &mut unmangle_count, explicit_self));
mangledlist.push(cfunc_to_rs(ctx, name, String::new(), String::new(),
&*sig.ret_ty, sig.args.as_slice(),
sig.is_variadic, ast::Visibility::Inherited));
}
_ => unreachable!()
}
}
if mangledlist.len() > 0 {
items.push(mk_extern(ctx, &vec!(), mangledlist, Abi::C));
items.push(mk_impl(ctx, id_ty, unmangledlist));
}
items
}
fn opaque_to_rs(ctx: &mut GenCtx, name: &str, _layout: Layout) -> P<ast::Item> {
let def = ast::ItemKind::Enum(
ast::EnumDef {
variants: vec!()
},
empty_generics()
);
// XXX can't repr(C) an empty enum
let id = rust_type_id(ctx, name);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn cunion_to_rs(ctx: &mut GenCtx, name: &str, layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
const UNION_DATA_FIELD_NAME: &'static str = "_bindgen_data_";
fn mk_item(ctx: &mut GenCtx, name: &str, item: ast::ItemKind, vis:
ast::Visibility, attrs: Vec<ast::Attribute>) -> P<ast::Item> {
P(ast::Item {
ident: ctx.ext_cx.ident_of(name),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: item,
vis: vis,
span: ctx.span
})
}
// XXX what module id is correct?
let ci = Rc::new(RefCell::new(CompInfo::new(name.to_owned(), ROOT_MODULE_ID, name.to_owned(), "".to_owned(), CompKind::Union, members.clone(), layout)));
let union = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.to_owned(), ROOT_MODULE_ID, TComp(ci), layout))));
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current union.
let mut extra = vec!();
fn mk_union_field(ctx: &GenCtx, name: &str, ty: ast::Ty) -> Spanned<ast::StructField_> {
let field_ty = if !ctx.options.enable_cxx_namespaces ||
ctx.current_module_id == ROOT_MODULE_ID {
quote_ty!(&ctx.ext_cx, __BindgenUnionField<$ty>)
} else {
quote_ty!(&ctx.ext_cx, root::__BindgenUnionField<$ty>)
};
respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: field_ty,
attrs: vec![],
})
}
let mut fields = members.iter()
.flat_map(|member| match *member {
CompMember::Field(ref f) => {
let cty = cty_to_rs(ctx, &f.ty, false, true);
Some(mk_union_field(ctx, &f.name, cty))
}
_ => None,
}).collect::<Vec<_>>();
fields.push(mk_blob_field(ctx, UNION_DATA_FIELD_NAME, layout));
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID),
empty_generics()
);
let union_id = rust_type_id(ctx, name);
let mut union_attrs = vec![mk_repr_attr(ctx, layout)];
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
extra.push(mk_clone_impl(ctx, name));
extra.push(mk_test_fn(ctx, &name, &layout));
union_attrs.push(if can_derive_debug {
mk_deriving_copy_and_maybe_debug_attr(ctx)
} else {
mk_deriving_copy_attr(ctx)
});
let union_def = mk_item(ctx, &union_id, def, ast::Visibility::Public, union_attrs);
let union_impl = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
empty_generics(),
None,
P(cty_to_rs(ctx, &union, true, true)),
gen_comp_methods(ctx, UNION_DATA_FIELD_NAME, 0, CompKind::Union, &members, &mut extra),
);
let mut items = vec!(
union_def,
mk_item(ctx, "", union_impl, ast::Visibility::Inherited, vec![])
);
items.extend(extra.into_iter());
items
}
fn const_to_rs(ctx: &mut GenCtx, name: String, val: i64, val_ty: ast::Ty) -> P<ast::Item> {
let int_lit = ast::LitKind::Int(
val.abs() as u64,
ast::LitIntType::Unsuffixed
);
let mut value = ctx.ext_cx.expr_lit(ctx.span, int_lit);
if val < 0 {
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, value);
value = ctx.ext_cx.expr(ctx.span, negated);
}
let cst = ast::ItemKind::Const(
P(val_ty),
value
);
let id = first(rust_id(ctx, &name));
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id[..]),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: cst,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn enum_size_to_unsigned_max_value(size: usize) -> u64 {
match size {
1 => std::u8::MAX as u64,
2 => std::u16::MAX as u64,
4 => std::u32::MAX as u64,
8 => std::u64::MAX,
_ => unreachable!("invalid enum size: {}", size)
}
}
fn enum_size_to_rust_type_name(signed: bool, size: usize) -> &'static str {
match (signed, size) {
(true, 1) => "i8",
(false, 1) => "u8",
(true, 2) => "i16",
(false, 2) => "u16",
(true, 4) => "i32",
(false, 4) => "u32",
(true, 8) => "i64",
(false, 8) => "u64",
_ => {
println!("invalid enum decl: signed: {}, size: {}", signed, size);
"i32"
}
}
}
fn cenum_value_to_int_lit(ctx: &mut GenCtx,
enum_is_signed: bool,
size: usize,
value: i64) -> P<ast::Expr> {
if enum_is_signed {
if value == std::i64::MIN {
let lit = ast::LitKind::Int(std::u64::MAX, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, lit)
} else {
let lit = ast::LitKind::Int(value.abs() as u64, ast::LitIntType::Unsuffixed);
let expr = ctx.ext_cx.expr_lit(ctx.span, lit);
if value < 0 {
ctx.ext_cx.expr(ctx.span, ast::ExprKind::Unary(ast::UnOp::Neg, expr))
} else {
expr
}
}
} else {
let u64_value = value as u64 & enum_size_to_unsigned_max_value(size);
let int_lit = ast::LitKind::Int(u64_value, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, int_lit)
}
}
fn cenum_to_rs(ctx: &mut GenCtx,
name: &str,
kind: IKind,
comment: String,
enum_items: &[EnumItem],
layout: Layout) -> Vec<P<ast::Item>> {
let enum_name = ctx.ext_cx.ident_of(name);
let enum_ty = ctx.ext_cx.ty_ident(ctx.span, enum_name);
let enum_is_signed = kind.is_signed();
let enum_repr = enum_size_to_rust_type_name(enum_is_signed, layout.size);
// Rust is not happy with univariant enums
// if items.len() < 2 {
// return vec!();
// }
//
let mut items = vec![];
if !ctx.options.rust_enums {
items.push(ctx.ext_cx.item_ty(ctx.span,
enum_name,
ctx.ext_cx.ty_ident(ctx.span,
ctx.ext_cx.ident_of(enum_repr))));
for item in enum_items {
let value = cenum_value_to_int_lit(ctx, enum_is_signed, layout.size, item.val);
items.push(ctx.ext_cx.item_const(ctx.span, ctx.ext_cx.ident_of(&item.name), enum_ty.clone(), value));
}
return items;
}
let mut variants = vec![];
let mut found_values = HashMap::new();
for item in enum_items {
let name = ctx.ext_cx.ident_of(&item.name);
if let Some(orig) = found_values.get(&item.val) {
let value = ctx.ext_cx.expr_path(
ctx.ext_cx.path(ctx.span, vec![enum_name, *orig]));
items.push(P(ast::Item {
ident: name,
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Const(enum_ty.clone(), value),
vis: ast::Visibility::Public,
span: ctx.span,
}));
continue;
}
found_values.insert(item.val, name);
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
variants.push(respan(ctx.span, ast::Variant_ {
name: name,
attrs: vec![],
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
disr_expr: Some(value),
}));
}
let enum_repr = InternedString::new(enum_repr);
let repr_arg = ctx.ext_cx.meta_word(ctx.span, enum_repr);
let repr_list = ctx.ext_cx.meta_list(ctx.span, InternedString::new("repr"), vec![repr_arg]);
let mut attrs = mk_doc_attr(ctx, &comment);
attrs.push(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: repr_list,
is_sugared_doc: false,
}));
attrs.push(if ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Debug", "Copy", "Clone"])
} else {
mk_deriving_attr(ctx, &["Copy", "Clone"])
});
items.push(P(ast::Item {
ident: enum_name,
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Enum(ast::EnumDef { variants: variants }, empty_generics()),
vis: ast::Visibility::Public,
span: ctx.span,
}));
items
}
/// Generates accessors for fields in nested structs and unions which must be
/// represented in Rust as an untyped array. This process may generate
/// declarations and implementations that must be placed at the root level.
/// These are emitted into `extra`.
fn gen_comp_methods(ctx: &mut GenCtx, data_field: &str, data_offset: usize,
kind: CompKind, members: &[CompMember],
extra: &mut Vec<P<ast::Item>>) -> Vec<ast::ImplItem> {
let mk_field_method = |ctx: &mut GenCtx, f: &FieldInfo, offset: usize| {
// TODO: Implement bitfield accessors
if f.bitfields.is_some() { return None; }
let f_name = first(rust_id(ctx, &f.name));
let ret_ty = P(cty_to_rs(ctx, &TPtr(Box::new(f.ty.clone()), false, false, Layout::zero()), true, true));
// When the offset is zero, generate slightly prettier code.
let method = {
let impl_str = format!(r"
impl X {{
pub unsafe fn {}(&mut self) -> {} {{
let raw: *mut u8 = ::std::mem::transmute(&self.{});
::std::mem::transmute(raw.offset({}))
}}
}}
", f_name, tts_to_string(&ret_ty.to_tokens(&ctx.ext_cx)[..]), data_field, offset);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_string(), impl_str).parse_item().unwrap().unwrap()
};
method.and_then(|i| {
match i.node {
ast::ItemKind::Impl(_, _, _, _, _, mut items) => {
items.pop()
}
_ => unreachable!("impl parsed to something other than impl")
}
})
};
let mut offset = data_offset;
let mut methods = vec!();
for m in members.into_iter() {
let advance_by = match *m {
CompMember::Field(ref f) => {
if ctx.options.gen_bitfield_methods {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
}
f.ty.size()
}
CompMember::Comp(ref rc_c) => {
let c = rc_c.borrow();
let name = comp_name(&ctx, c.kind, &c.name);
extra.extend(comp_to_rs(ctx, &name, c.clone()).into_iter());
c.layout.size
}
CompMember::CompField(ref rc_c, ref f) => {
if ctx.options.gen_bitfield_methods {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
}
let c = rc_c.borrow();
let name = comp_name(&ctx, c.kind, &c.name);
extra.extend(comp_to_rs(ctx, &name, c.clone()).into_iter());
f.ty.size()
}
CompMember::Enum(_) => 0
};
match kind {
CompKind::Struct => { offset += advance_by; }
CompKind::Union => { }
}
}
methods
}
fn type_for_bitfield_width(ctx: &mut GenCtx, width: u32, is_arg: bool) -> ast::Ty {
let input_type = if width > 16 {
"u32"
} else if width > 8 {
"u16"
} else if width > 1 {
"u8"
} else {
if is_arg {
"bool"
} else {
"u8"
}
};
mk_ty(ctx, false, &[input_type.to_owned()])
}
fn gen_bitfield_method(ctx: &mut GenCtx, bindgen_name: &str,
field_name: &str, field_type: &Type,
offset: usize, width: u32) -> ast::ImplItem {
let input_type = type_for_bitfield_width(ctx, width, true);
let field_type = cty_to_rs(ctx, &field_type, false, true);
let setter_name = ctx.ext_cx.ident_of(&format!("set_{}", field_name));
let bindgen_ident = ctx.ext_cx.ident_of(bindgen_name);
let item = quote_item!(&ctx.ext_cx,
impl X {
pub fn $setter_name(&mut self, val: $input_type) {
self.$bindgen_ident &= !(((1 << $width as $field_type) - 1) << $offset);
self.$bindgen_ident |= (val as $field_type) << $offset;
}
}
).unwrap();
match &item.node {
&ast::ItemKind::Impl(_, _, _, _, _, ref items) => items[0].clone(),
_ => unreachable!()
}
}
fn gen_fullbitfield_method(ctx: &mut GenCtx, bindgen_name: &String,
bitfield_type: &Type, bitfields: &[(String, u32)]) -> ast::ImplItem {
let field_type = cty_to_rs(ctx, bitfield_type, false, true);
let mut args = vec!();
let mut unnamed: usize = 0;
for &(ref name, width) in bitfields.iter() {
let ident = if name.is_empty() {
unnamed += 1;
let dummy = format!("unnamed_bitfield{}", unnamed);
ctx.ext_cx.ident_of(&dummy)
} else {
ctx.ext_cx.ident_of(name)
};
args.push(ast::Arg {
ty: P(type_for_bitfield_width(ctx, width, true)),
pat: P(ast::Pat {
id: ast::DUMMY_NODE_ID,
node: ast::PatKind::Ident(
ast::BindingMode::ByValue(ast::Mutability::Immutable),
respan(ctx.span, ident),
None
),
span: ctx.span
}),
id: ast::DUMMY_NODE_ID,
});
}
let fndecl = ast::FnDecl {
inputs: args,
output: ast::FunctionRetTy::Ty(P(field_type.clone())),
variadic: false
};
let stmts = Vec::with_capacity(bitfields.len() + 1);
let mut offset = 0;
let mut exprs = quote_expr!(&ctx.ext_cx, 0);
let mut unnamed: usize = 0;
for &(ref name, width) in bitfields.iter() {
let name_ident = if name.is_empty() {
unnamed += 1;
let dummy = format!("unnamed_bitfield{}", unnamed);
ctx.ext_cx.ident_of(&dummy)
} else {
ctx.ext_cx.ident_of(name)
};
exprs = quote_expr!(&ctx.ext_cx,
$exprs | (($name_ident as $field_type) << $offset)
);
offset += width;
}
let block = ast::Block {
stmts: stmts,
expr: Some(exprs),
id: ast::DUMMY_NODE_ID,
rules: ast::BlockCheckMode::Default,
span: ctx.span
};
let node = ast::ImplItemKind::Method(
ast::MethodSig {
unsafety: ast::Unsafety::Normal,
abi: Abi::Rust,
decl: P(fndecl),
generics: empty_generics(),
explicit_self: respan(ctx.span, ast::SelfKind::Static),
constness: ast::Constness::Const,
}, P(block)
);
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: ctx.ext_cx.ident_of(&format!("new{}", bindgen_name)),
vis: ast::Visibility::Public,
attrs: vec!(),
node: node,
span: ctx.span,
}
}
fn mk_blob_field(ctx: &GenCtx, name: &str, layout: Layout) -> Spanned<ast::StructField_> {
let ty_name = match layout.align {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
let data_len = if ty_name == "u8" { layout.size } else { layout.size / layout.align };
let base_ty = mk_ty(ctx, false, &[ty_name.to_owned()]);
let data_ty = if data_len == 1 {
P(base_ty)
} else {
P(mk_arrty(ctx, &base_ty, data_len))
};
respan(ctx.span, ast::StructField_ {
kind: ast::NamedField(
ctx.ext_cx.ident_of(name),
ast::Visibility::Public,
),
id: ast::DUMMY_NODE_ID,
ty: data_ty,
attrs: Vec::new()
})
}
fn mk_link_name_attr(ctx: &mut GenCtx, name: String) -> ast::Attribute {
let lit = respan(ctx.span, ast::LitKind::Str(intern(&name).as_str(), ast::StrStyle::Cooked));
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("link_name"), lit
)));
let attr = ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
};
respan(ctx.span, attr)
}
fn mk_repr_attr(ctx: &GenCtx, layout: Layout) -> ast::Attribute {
let mut values = vec!(P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("C")))));
if layout.packed {
values.push(P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new("packed")))));
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("repr"),
values
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_copy_attr(ctx: &mut GenCtx) -> ast::Attribute {
mk_deriving_attr(ctx, &["Copy"])
}
// NB: This requires that the type you implement it for also
// implements Copy.
//
// Implements std::clone::Clone using dereferencing.
//
// This is to bypass big arrays not implementing clone,
// but implementing copy due to hacks inside rustc's internals.
fn mk_clone_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::clone::Clone for {} {{
fn clone(&self) -> Self {{ *self }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
fn mk_deriving_copy_and_maybe_debug_attr(ctx: &mut GenCtx) -> ast::Attribute {
if ctx.options.derive_debug {
mk_deriving_attr(ctx, &["Copy", "Debug"])
} else {
mk_deriving_copy_attr(ctx)
}
}
fn mk_deriving_attr(ctx: &mut GenCtx, attrs: &[&'static str]) -> ast::Attribute {
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
InternedString::new("derive"),
attrs.iter().map(|attr| {
P(respan(ctx.span, ast::MetaItemKind::Word(InternedString::new(attr))))
}).collect()
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_doc_attr(ctx: &mut GenCtx, doc: &str) -> Vec<ast::Attribute> {
if doc.is_empty() {
return vec!();
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
InternedString::new("doc"),
respan(ctx.span, ast::LitKind::Str(intern(doc).as_str(), ast::StrStyle::Cooked))
)));
vec!(respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: true
}))
}
fn cvar_to_rs(ctx: &mut GenCtx, name: String,
mangled: String, ty: &Type,
is_const: bool) -> ast::ForeignItem {
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if !mangled.is_empty() {
attrs.push(mk_link_name_attr(ctx, mangled));
} else if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
let val_ty = P(cty_to_rs(ctx, ty, true, true));
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: attrs,
node: ast::ForeignItemKind::Static(val_ty, !is_const),
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cfuncty_to_rs(ctx: &mut GenCtx,
rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::FnDecl {
let ret = match *rty {
TVoid => ast::FunctionRetTy::Default(ctx.span),
// Disable references in returns for now
TPtr(ref t, is_const, _, ref layout) =>
ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, &TPtr(t.clone(), is_const, false, layout.clone()), true, true))),
_ => ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, rty, true, true)))
};
let mut unnamed: usize = 0;
let args: Vec<ast::Arg> = aty.iter().map(|arg| {
let (ref n, ref t) = *arg;
let arg_name = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
first(rust_id(ctx, &n))
};
// From the C90 standard (http://c0x.coding-guidelines.com/6.7.5.3.html)
// 1598 - A declaration of a parameter as “array of type” shall be
// adjusted to “qualified pointer to type”, where the type qualifiers
// (if any) are those specified within the [ and ] of the array type
// derivation.
let arg_ty = P(match *t {
TArray(ref typ, _, l) => cty_to_rs(ctx, &TPtr(typ.clone(), false, false, l), true, true),
_ => cty_to_rs(ctx, t, true, true),
});
ast::Arg {
ty: arg_ty,
pat: P(ast::Pat {
id: ast::DUMMY_NODE_ID,
node: ast::PatKind::Ident(
ast::BindingMode::ByValue(ast::Mutability::Immutable),
respan(ctx.span, ctx.ext_cx.ident_of(&arg_name)),
None
),
span: ctx.span
}),
id: ast::DUMMY_NODE_ID,
}
}).collect();
let var = !args.is_empty() && var;
ast::FnDecl {
inputs: args,
output: ret,
variadic: var
}
}
fn cfunc_to_rs(ctx: &mut GenCtx,
name: String,
mangled: String,
comment: String,
rty: &Type,
aty: &[(String, Type)],
var: bool,
vis: ast::Visibility) -> ast::ForeignItem {
let var = !aty.is_empty() && var;
let decl = ast::ForeignItemKind::Fn(
P(cfuncty_to_rs(ctx, rty, aty, var)),
empty_generics()
);
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = mk_doc_attr(ctx, &comment);
if !mangled.is_empty() {
attrs.push(mk_link_name_attr(ctx, mangled));
} else if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: attrs,
node: decl,
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: vis,
}
}
fn cty_to_rs(ctx: &mut GenCtx, ty: &Type, allow_bool: bool, use_full_path: bool) -> ast::Ty {
let prefix = vec!["std".to_owned(), "os".to_owned(), "raw".to_owned()];
let raw = |fragment: &str| {
let mut path = prefix.clone();
path.push(fragment.to_owned());
path
};
match *ty {
TVoid => mk_ty(ctx, true, &raw("c_void")),
TInt(i, ref layout) => match i {
IBool => {
let ty_name = match layout.size {
1 if allow_bool => "bool",
2 => "u16",
4 => "u32",
8 => "u64",
_ => "u8",
};
mk_ty(ctx, false, &[ty_name.to_owned()])
},
ISChar => mk_ty(ctx, true, &raw("c_char")),
IUChar => mk_ty(ctx, true, &raw("c_uchar")),
IInt => mk_ty(ctx, true, &raw("c_int")),
IUInt => mk_ty(ctx, true, &raw("c_uint")),
IShort => mk_ty(ctx, true, &raw("c_short")),
IUShort => mk_ty(ctx, true, &raw("c_ushort")),
ILong => mk_ty(ctx, true, &raw("c_long")),
IULong => mk_ty(ctx, true, &raw("c_ulong")),
ILongLong => mk_ty(ctx, true, &raw("c_longlong")),
IULongLong => mk_ty(ctx, true, &raw("c_ulonglong"))
},
TFloat(f, _) => match f {
FFloat => mk_ty(ctx, false, &["f32".to_owned()]),
FDouble => mk_ty(ctx, false, &["f64".to_owned()])
},
TPtr(ref t, is_const, _is_ref, _) => {
let id = cty_to_rs(ctx, &**t, allow_bool, use_full_path);
mk_ptrty(ctx, &id, is_const)
},
TArray(ref t, s, _) => {
let ty = cty_to_rs(ctx, &**t, allow_bool, use_full_path);
mk_arrty(ctx, &ty, s)
},
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
mk_fnty(ctx, &decl, sig.abi)
},
TFuncProto(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
mk_fn_proto_ty(ctx, &decl, sig.abi)
},
TNamed(ref ti) => {
let id = rust_type_id(ctx, &ti.borrow().name);
if use_full_path {
let mut path = ctx.full_path_for_module(ti.borrow().module_id);
path.push(id);
mk_ty(ctx, false, &path)
} else {
mk_ty(ctx, false, &[id])
}
},
TComp(ref ci) => {
let c = ci.borrow();
let id = comp_name(&ctx, c.kind, &c.name);
let args = c.args.iter().map(|gt| {
P(cty_to_rs(ctx, gt, allow_bool, false))
}).collect();
if use_full_path {
let mut path = ctx.full_path_for_module(c.module_id);
path.push(id);
mk_ty_args(ctx, false, &path, args)
} else {
mk_ty_args(ctx, false, &[id], args)
}
},
TEnum(ref ei) => {
let e = ei.borrow();
let id = enum_name(&ctx, &e.name);
if use_full_path {
let mut path = ctx.full_path_for_module(e.module_id);
path.push(id);
mk_ty(ctx, false, &path)
} else {
mk_ty(ctx, false, &[id])
}
}
}
}
fn cty_is_translatable(ty: &Type) -> bool {
match *ty {
TVoid => false,
TArray(ref t, _, _) => {
cty_is_translatable(&**t)
},
TComp(ref ci) => {
let c = ci.borrow();
!c.args.iter().any(|gt| gt == &TVoid) && !c.has_non_type_template_params
},
_ => true,
}
}
fn cty_has_destructor(ty: &Type) -> bool {
match ty {
&TArray(ref t, _, _) => {
cty_has_destructor(&**t)
}
&TComp(ref ci) => {
let c = ci.borrow();
if c.has_destructor || c.members.iter().any(|f| match f {
&CompMember::Field(ref f) |
&CompMember::CompField(_, ref f) =>
cty_has_destructor(&f.ty),
_ => false,
}) {
return true;
}
c.ref_template.is_some()
},
&TNamed(ref ti) => {
cty_has_destructor(&ti.borrow().ty)
},
_ => false,
}
}
fn mk_ty(ctx: &GenCtx, global: bool, segments: &[String]) -> ast::Ty {
mk_ty_args(ctx, global, segments, vec!())
}
fn mk_ty_args(ctx: &GenCtx, global: bool, segments: &[String], args: Vec<P<ast::Ty>>) -> ast::Ty {
let segment_count = segments.len();
let ty = ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: global,
segments: segments.iter().enumerate().map(|(i, s)| {
ast::PathSegment {
identifier: ctx.ext_cx.ident_of(s),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: vec!(),
types: OwnedSlice::from_vec(if i == segment_count - 1 { args.clone() } else { vec![] }),
bindings: OwnedSlice::empty(),
}),
}
}).collect()
},
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_ptrty(ctx: &mut GenCtx, base: &ast::Ty, is_const: bool) -> ast::Ty {
let ty = ast::TyKind::Ptr(ast::MutTy {
ty: P(base.clone()),
mutbl: if is_const { ast::Mutability::Immutable } else { ast::Mutability::Mutable }
});
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
#[allow(dead_code)]
fn mk_refty(ctx: &mut GenCtx, base: &ast::Ty, is_const: bool) -> ast::Ty {
let ty = ast::TyKind::Rptr(
None,
ast::MutTy {
ty: P(base.clone()),
mutbl: if is_const { ast::Mutability::Immutable } else { ast::Mutability::Mutable }
}
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_arrty(ctx: &GenCtx, base: &ast::Ty, n: usize) -> ast::Ty {
let int_lit = ast::LitKind::Int(n as u64, ast::LitIntType::Unsigned(ast::UintTy::Us));
let sz = ast::ExprKind::Lit(P(respan(ctx.span, int_lit)));
let ty = ast::TyKind::FixedLengthVec(
P(base.clone()),
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: sz,
span: ctx.span,
attrs: None,
})
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_fn_proto_ty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
abi: Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: ast::Unsafety::Unsafe,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span,
}
}
fn mk_fnty(ctx: &mut GenCtx, decl: &ast::FnDecl, abi: Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: ast::Unsafety::Unsafe,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
let segs = vec![
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("std"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::empty(),
bindings: OwnedSlice::empty(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("Option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: OwnedSlice::from_vec(vec!(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span
})
)),
bindings: OwnedSlice::empty(),
}),
}
];
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: true,
segments: segs
},
),
span: ctx.span
}
}
fn mk_test_fn(ctx: &GenCtx, name: &str, layout: &Layout) -> P<ast::Item> {
let size = layout.size;
let align = layout.align;
let struct_name = ctx.ext_cx.ident_of(name);
let fn_name = ctx.ext_cx.ident_of(&format!("bindgen_test_layout_{}", name));
let size_of_expr = quote_expr!(&ctx.ext_cx, ::std::mem::size_of::<$struct_name>());
let align_of_expr = quote_expr!(&ctx.ext_cx, ::std::mem::align_of::<$struct_name>());
let item = quote_item!(&ctx.ext_cx,
#[test]
fn $fn_name() {
assert_eq!($size_of_expr, $size);
assert_eq!($align_of_expr, $align);
}).unwrap();
item
}
fn mk_opaque_struct(ctx: &GenCtx, name: &str, layout: &Layout) -> P<ast::Item> {
// XXX prevent this spurious clone
let blob_field = mk_blob_field(ctx, "_bindgen_opaque_blob", layout.clone());
let variant_data = if layout.size == 0 {
ast::VariantData::Unit(ast::DUMMY_NODE_ID)
} else {
ast::VariantData::Struct(vec![blob_field], ast::DUMMY_NODE_ID)
};
let def = ast::ItemKind::Struct(
variant_data,
ast::Generics {
lifetimes: vec!(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: vec!()
}
}
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec![mk_repr_attr(ctx, layout.clone())],
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
|
use std;
use std::cell::RefCell;
use std::vec::Vec;
use std::rc::Rc;
use std::collections::HashMap;
use syntax::abi;
use syntax::ast;
use syntax::codemap::{Span, respan, ExpnInfo, NameAndSpan, MacroBang};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig;
use syntax::ext::quote::rt::ToTokens;
use syntax::feature_gate::Features;
use syntax::parse;
use syntax::parse::token::InternedString;
use syntax::attr::mk_attr_id;
use syntax::ptr::P;
use syntax::print::pprust::tts_to_string;
use super::{BindgenOptions, LinkType};
use types::*;
struct GenCtx<'r> {
ext_cx: base::ExtCtxt<'r>,
unnamed_ty: usize,
span: Span
}
fn ref_eq<T>(thing: &T, other: &T) -> bool {
(thing as *const T) == (other as *const T)
}
fn to_intern_str(ctx: &mut GenCtx, s: &str) -> parse::token::InternedString {
let id = ctx.ext_cx.ident_of(s);
id.name.as_str()
}
fn rust_id(ctx: &mut GenCtx, name: &str) -> (String, bool) {
let token = parse::token::Ident(ctx.ext_cx.ident_of(name));
if token.is_any_keyword() || "bool" == name {
let s = format!("_{}", name);
(s, true)
} else {
(name.into(), false)
}
}
fn rust_type_id(ctx: &mut GenCtx, name: &str) -> String {
match name {
"bool" | "uint" | "u8" | "u16" | "u32" | "f32" | "f64" | "i8" | "i16" |
"i32" | "i64" | "Self" | "str" => {
format!("_{}", name)
},
_ => {
let (n, _) = rust_id(ctx, name);
n
}
}
}
fn unnamed_name(ctx: &mut GenCtx, name: &str) -> String {
if name.is_empty() {
ctx.unnamed_ty += 1;
format!("Unnamed{}", ctx.unnamed_ty)
} else {
name.into()
}
}
fn comp_name(kind: CompKind, name: &str) -> String {
match kind {
CompKind::Struct => struct_name(name),
CompKind::Union => union_name(name),
}
}
fn struct_name(name: &str) -> String {
format!("Struct_{}", name)
}
fn union_name(name: &str) -> String {
format!("Union_{}", name)
}
fn enum_name(name: &str) -> String {
format!("Enum_{}", name)
}
fn extract_definitions(ctx: &mut GenCtx,
options: &BindgenOptions,
globals: &[Global])
-> Vec<P<ast::Item>> {
let mut defs = vec!();
for g in globals {
match *g {
GType(ref ti) => {
let t = ti.borrow();
defs.extend(ctypedef_to_rs(
ctx,
options.rust_enums,
options.derive_debug,
&t.name, &t.ty))
},
GCompDecl(ref ci) => {
{
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
}
let c = ci.borrow().clone();
defs.push(opaque_to_rs(ctx, &comp_name(c.kind, &c.name)));
},
GComp(ref ci) => {
{
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
}
let c = ci.borrow().clone();
defs.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
options.derive_debug,
c.layout, c.members).into_iter())
},
GEnumDecl(ref ei) => {
{
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
}
let e = ei.borrow().clone();
defs.push(opaque_to_rs(ctx, &enum_name(&e.name)));
},
GEnum(ref ei) => {
{
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
}
let e = ei.borrow();
defs.extend(cenum_to_rs(
ctx,
options.rust_enums,
options.derive_debug,
&enum_name(&e.name), e.kind, e.layout, &e.items));
},
GVar(ref vi) => {
let v = vi.borrow();
let ty = cty_to_rs(ctx, &v.ty);
defs.push(const_to_rs(ctx, &v.name, v.val.unwrap(), ty));
},
_ => { }
}
}
defs
}
fn extract_functions(ctx: &mut GenCtx,
fs: &[Global])
-> HashMap<abi::Abi, Vec<ast::ForeignItem>> {
let func_list = fs.iter().map(|f| {
match *f {
GFunc(ref vi) => {
let v = vi.borrow();
match v.ty {
TFuncPtr(ref sig) => {
let decl = cfunc_to_rs(ctx, v.name.clone(),
&*sig.ret_ty, &sig.args[..],
sig.is_variadic);
(sig.abi, decl)
}
_ => unreachable!()
}
},
_ => unreachable!()
}
});
let mut map = HashMap::new();
for (abi, func) in func_list {
map.entry(abi).or_insert(vec!()).push(func);
}
map
}
pub fn gen_mod(
options: &BindgenOptions,
globs: Vec<Global>,
span: Span)
-> Vec<P<ast::Item>> {
// Create a dummy ExtCtxt. We only need this for string interning and that uses TLS.
let mut features = Features::new();
features.quote = true;
let cfg = ExpansionConfig {
crate_name: "xxx".to_owned(),
features: Some(&features),
recursion_limit: 64,
trace_mac: false,
};
let sess = &parse::ParseSess::new();
let mut feature_gated_cfgs = Vec::new();
let mut ctx = GenCtx {
ext_cx: base::ExtCtxt::new(
sess,
Vec::new(),
cfg,
&mut feature_gated_cfgs,
),
unnamed_ty: 0,
span: span
};
ctx.ext_cx.bt_push(ExpnInfo {
call_site: ctx.span,
callee: NameAndSpan {
format: MacroBang(parse::token::intern("")),
allow_internal_unstable: false,
span: None
}
});
let uniq_globs = tag_dup_decl(&globs);
let mut fs = vec!();
let mut vs = vec!();
let mut gs = vec!();
for g in uniq_globs.into_iter() {
match g {
GOther => {}
GFunc(_) => fs.push(g),
GVar(_) => {
let is_int_const = {
match g {
GVar(ref vi) => {
let v = vi.borrow();
v.is_const && v.val.is_some()
}
_ => unreachable!()
}
};
if is_int_const {
gs.push(g);
} else {
vs.push(g);
}
}
_ => gs.push(g)
}
}
gs = remove_redundant_decl(gs);
let mut defs = extract_definitions(&mut ctx, &options, &gs);
let vars = vs.into_iter().map(|v| {
match v {
GVar(vi) => {
let v = vi.borrow();
cvar_to_rs(&mut ctx, v.name.clone(), &v.ty, v.is_const)
},
_ => unreachable!()
}
}).collect();
let funcs = extract_functions(&mut ctx, &fs);
if !Vec::is_empty(&vars) {
defs.push(mk_extern(&mut ctx, &options.links, vars, abi::Abi::C));
}
for (abi, funcs) in funcs.into_iter() {
defs.push(mk_extern(&mut ctx, &options.links, funcs, abi));
}
//let attrs = vec!(mk_attr_list(&mut ctx, "allow", ["dead_code", "non_camel_case_types", "uppercase_variables"]));
defs
}
fn mk_extern(ctx: &mut GenCtx, links: &[(String, LinkType)],
foreign_items: Vec<ast::ForeignItem>,
abi: abi::Abi) -> P<ast::Item> {
let attrs = if links.is_empty() {
Vec::new()
} else {
links.iter().map(|&(ref l, ref k)| {
let k = match *k {
LinkType::Default => None,
LinkType::Static => Some("static"),
LinkType::Framework => Some("framework")
};
let link_name = P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "name"),
respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, l),
ast::StrStyle::Cooked
))
)));
let link_args = match k {
None => vec!(link_name),
Some(ref k) => vec!(link_name, P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "kind"),
respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, *k),
ast::StrStyle::Cooked
))
))))
};
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::List(
to_intern_str(ctx, "link"),
link_args)
)),
is_sugared_doc: false
})
}).collect()
};
let mut items = Vec::new();
items.extend(foreign_items.into_iter());
let ext = ast::ItemKind::ForeignMod(ast::ForeignMod {
abi: abi,
items: items
});
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn remove_redundant_decl(gs: Vec<Global>) -> Vec<Global> {
fn check_decl(a: &Global, ty: &Type) -> bool {
match *a {
GComp(ref ci1) => match *ty {
TComp(ref ci2) => {
ref_eq(ci1, ci2) && ci1.borrow().name.is_empty()
},
_ => false
},
GEnum(ref ei1) => match *ty {
TEnum(ref ei2) => {
ref_eq(ei1, ei2) && ei1.borrow().name.is_empty()
},
_ => false
},
_ => false
}
}
let typedefs: Vec<Type> = gs.iter().filter_map(|g|
match *g {
GType(ref ti) => Some(ti.borrow().ty.clone()),
_ => None
}
).collect();
gs.into_iter().filter(|g|
!typedefs.iter().any(|t| check_decl(g, t))
).collect()
}
fn tag_dup_decl(gs: &[Global]) -> Vec<Global> {
fn check(name1: &str, name2: &str) -> bool {
!name1.is_empty() && name1 == name2
}
fn is_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(>ype(ref ti1), >ype(ref ti2)) => {
let a = ti1.borrow();
let b = ti2.borrow();
check(&a.name[..], &b.name[..])
},
(&GComp(ref ci1), &GComp(ref ci2)) |
(&GCompDecl(ref ci1), &GCompDecl(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name[..], &b.name[..])
},
(&GEnum(ref ei1), &GEnum(ref ei2)) |
(&GEnumDecl(ref ei1), &GEnumDecl(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name[..], &b.name[..])
},
(&GVar(ref vi1), &GVar(ref vi2)) |
(&GFunc(ref vi1), &GFunc(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name[..], &b.name[..])
},
_ => false
}
}
if gs.is_empty() {
return vec!();
}
let mut res: Vec<Global> = vec!();
res.push(gs[0].clone());
for (i, gsi) in gs.iter().enumerate().skip(1) {
let dup = gs.iter().take(i).any(|item| is_dup(&item, &gsi));
if !dup {
res.push(gsi.clone());
}
}
res
}
/// Converts a C typedef to Rust AST Items.
fn ctypedef_to_rs(
ctx: &mut GenCtx,
rust_enums: bool,
derive_debug: bool,
name: &str,
ty: &Type)
-> Vec<P<ast::Item>> {
fn mk_item(ctx: &mut GenCtx, name: &str, ty: &Type) -> P<ast::Item> {
let rust_name = rust_type_id(ctx, &name);
let rust_ty = cty_to_rs(ctx, ty);
let base = ast::ItemKind::Ty(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: rust_ty.node,
span: ctx.span,
}),
ast::Generics::default()
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: base,
vis: ast::Visibility::Public,
span: ctx.span
})
}
match *ty {
TComp(ref ci) => {
let is_empty = ci.borrow().name.is_empty();
if is_empty {
ci.borrow_mut().name = name.into();
let c = ci.borrow().clone();
comp_to_rs(ctx, c.kind, name.into(), derive_debug, c.layout, c.members)
} else {
vec!(mk_item(ctx, name, ty))
}
},
TEnum(ref ei) => {
let is_empty = ei.borrow().name.is_empty();
if is_empty {
ei.borrow_mut().name = name.into();
let e = ei.borrow();
cenum_to_rs(ctx, rust_enums, derive_debug, name, e.kind, e.layout, &e.items)
} else {
vec!(mk_item(ctx, name, ty))
}
},
_ => vec!(mk_item(ctx, name, ty))
}
}
/// Converts a C composed type (struct or union) to Rust AST Items.
fn comp_to_rs(ctx: &mut GenCtx, kind: CompKind, name: String,
derive_debug: bool,
layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
match kind {
CompKind::Struct => cstruct_to_rs(ctx, &name, derive_debug, layout, members),
CompKind::Union => cunion_to_rs(ctx, name, derive_debug, layout, members),
}
}
/// Converts a C struct to Rust AST Items.
fn cstruct_to_rs(ctx: &mut GenCtx,
name: &str,
derive_debug: bool,
layout: Layout,
members: Vec<CompMember>) -> Vec<P<ast::Item>> {
let mut fields: Vec<ast::StructField> = vec!();
let mut methods = vec!();
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current struct.
let mut extra = vec!();
let mut unnamed: u32 = 0;
let mut bitfields: u32 = 0;
// Debug is only defined on little arrays
let mut can_derive_debug = derive_debug;
for m in &members {
let (opt_rc_c, opt_f) = match *m {
CompMember::Field(ref f) => { (None, Some(f)) }
CompMember::Comp(ref rc_c) => { (Some(rc_c), None) }
CompMember::CompField(ref rc_c, ref f) => { (Some(rc_c), Some(f)) }
};
if let Some(f) = opt_f {
let f_name = match f.bitfields {
Some(_) => {
bitfields += 1;
format!("_bindgen_bitfield_{}_", bitfields)
}
None => rust_type_id(ctx, &f.name)
};
if !f.ty.can_derive_debug() {
can_derive_debug = false;
}
let f_ty = P(cty_to_rs(ctx, &f.ty));
fields.push(ast::StructField {
span: ctx.span,
vis: ast::Visibility::Public,
ident: Some(ctx.ext_cx.ident_of(&f_name[..])),
id: ast::DUMMY_NODE_ID,
ty: f_ty,
attrs: Vec::new()
});
}
if let Some(rc_c) = opt_rc_c {
let c = rc_c.borrow();
if c.name.is_empty() {
unnamed += 1;
let field_name = format!("_bindgen_data_{}_", unnamed);
fields.push(mk_blob_field(ctx, &field_name, c.layout, ctx.span));
methods.extend(gen_comp_methods(ctx, &field_name, 0, c.kind, &c.members, &mut extra, derive_debug).into_iter());
} else {
extra.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
derive_debug,
c.layout, c.members.clone()).into_iter());
}
}
}
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID),
ast::Generics::default()
);
let id = rust_type_id(ctx, &name);
let mut attrs = vec!(mk_repr_attr(ctx, layout), mk_deriving_copy_attr(ctx, false));
if can_derive_debug {
attrs.push(mk_deriving_debug_attr(ctx));
}
let struct_def = P(ast::Item { ident: ctx.ext_cx.ident_of(&id),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
});
let mut items = vec!(struct_def);
if !methods.is_empty() {
let impl_ = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
ast::Generics::default(),
None,
P(mk_ty(ctx, false, vec!(id))),
methods
);
items.push(
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: impl_,
vis: ast::Visibility::Inherited,
span: ctx.span}));
}
items.push(mk_clone_impl(ctx, &name));
items.push(mk_default_impl(ctx, &name));
items.extend(extra.into_iter());
items
}
/// Convert a opaque type name to an ast Item.
fn opaque_to_rs(ctx: &mut GenCtx, name: &str) -> P<ast::Item> {
let def = ast::ItemKind::Enum(
ast::EnumDef {
variants: vec!()
},
ast::Generics::default()
);
let id = rust_type_id(ctx, &name);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn cunion_to_rs(ctx: &mut GenCtx, name: String, derive_debug: bool, layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
fn mk_item(ctx: &mut GenCtx, name: String, item: ast::ItemKind, vis:
ast::Visibility, attrs: Vec<ast::Attribute>) -> P<ast::Item> {
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name[..]),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: item,
vis: vis,
span: ctx.span
})
}
let ci = Rc::new(RefCell::new(CompInfo::new(name.clone(), CompKind::Union, members.clone(), layout)));
let union = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.clone(), TComp(ci)))));
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current union.
let mut extra = vec!();
let data_field_name = "_bindgen_data_";
let data_field = mk_blob_field(ctx, data_field_name, layout, ctx.span);
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(
vec!(data_field),
ast::DUMMY_NODE_ID),
ast::Generics::default()
);
let union_id = rust_type_id(ctx, &name);
let union_attrs = {
let mut attrs = vec!(mk_repr_attr(ctx, layout), mk_deriving_copy_attr(ctx, false));
if derive_debug {
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
if can_derive_debug {
attrs.push(mk_deriving_debug_attr(ctx))
}
}
attrs
};
let union_def = mk_item(ctx, union_id, def, ast::Visibility::Public, union_attrs);
let union_impl = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
ast::Generics::default(),
None,
P(cty_to_rs(ctx, &union)),
gen_comp_methods(ctx, data_field_name, 0, CompKind::Union, &members, &mut extra, derive_debug),
);
let mut items = vec!(
union_def,
mk_item(ctx, "".to_owned(), union_impl, ast::Visibility::Inherited, Vec::new())
);
items.push(mk_clone_impl(ctx, &name[..]));
items.push(mk_default_impl(ctx, &name[..]));
items.extend(extra.into_iter());
items
}
/// Converts a signed number to AST Expression.
fn i64_to_int_lit(ctx: &mut GenCtx, value: i64) -> P<ast::Expr> {
let int_lit = ast::LitKind::Int(value.abs() as u64,
ast::LitIntType::Unsuffixed);
let expr = ctx.ext_cx.expr_lit(ctx.span, int_lit);
if value < 0 {
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, expr);
ctx.ext_cx.expr(ctx.span, negated)
} else {
expr
}
}
/// Converts a C const to Rust AST.
fn const_to_rs(ctx: &mut GenCtx,
name: &str,
val: i64,
val_ty: ast::Ty) -> P<ast::Item> {
let int_lit = i64_to_int_lit(ctx, val);
let cst = ast::ItemKind::Const(P(val_ty), int_lit);
let id = rust_id(ctx, name).0;
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: cst,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn enum_size_to_rust_type_name(signed: bool, size: usize) -> &'static str {
match (signed, size) {
(true, 1) => "i8",
(false, 1) => "u8",
(true, 2) => "i16",
(false, 2) => "u16",
(true, 4) => "i32",
(false, 4) => "u32",
(true, 8) => "i64",
(false, 8) => "u64",
_ => unreachable!("invalid enum decl: signed: {}, size: {}", signed, size),
}
}
fn enum_size_to_unsigned_max_value(size: usize) -> u64 {
match size {
1 => std::u8::MAX as u64,
2 => std::u16::MAX as u64,
4 => std::u32::MAX as u64,
8 => std::u64::MAX,
_ => unreachable!("invalid enum size: {}", size)
}
}
/// Converts a C enum variant to an AST expression.
fn cenum_value_to_int_lit(
ctx: &mut GenCtx,
enum_is_signed: bool,
size: usize,
value: i64)
-> P<ast::Expr> {
if enum_is_signed {
i64_to_int_lit(ctx, value)
} else {
let u64_value =
value as u64 & enum_size_to_unsigned_max_value(size);
let int_lit =
ast::LitKind::Int(u64_value, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, int_lit)
}
}
fn cenum_to_rs(
ctx: &mut GenCtx,
rust_enums: bool,
derive_debug: bool,
name: &str,
kind: IKind,
layout: Layout,
enum_items: &[EnumItem])
-> Vec<P<ast::Item>> {
let enum_name = ctx.ext_cx.ident_of(name);
let enum_ty = ctx.ext_cx.ty_ident(ctx.span, enum_name);
let enum_is_signed = kind.is_signed();
let enum_repr = enum_size_to_rust_type_name(enum_is_signed, layout.size);
let mut items = vec![];
if !rust_enums {
items.push(ctx.ext_cx.item_ty(
ctx.span,
enum_name,
ctx.ext_cx.ty_ident(
ctx.span,
ctx.ext_cx.ident_of(enum_repr))));
for item in enum_items {
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
items.push(ctx.ext_cx.item_const(
ctx.span,
ctx.ext_cx.ident_of(&item.name),
enum_ty.clone(),
value));
}
return items;
}
let mut variants = vec![];
let mut found_values = HashMap::new();
for item in enum_items {
let name = ctx.ext_cx.ident_of(&item.name);
if let Some(orig) = found_values.get(&item.val) {
let value = ctx.ext_cx.expr_path(
ctx.ext_cx.path(ctx.span, vec![enum_name, *orig]));
items.push(P(ast::Item {
ident: name,
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Const(enum_ty.clone(), value),
vis: ast::Visibility::Public,
span: ctx.span,
}));
continue;
}
found_values.insert(item.val, name);
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
variants.push(respan(ctx.span, ast::Variant_ {
name: name,
attrs: vec![],
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
disr_expr: Some(value),
}));
}
let enum_repr = InternedString::new(enum_repr);
let repr_arg = ctx.ext_cx.meta_word(ctx.span, enum_repr);
let repr_list = ctx.ext_cx.meta_list(ctx.span, InternedString::new("repr"), vec![repr_arg]);
let repr_attr = respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: repr_list,
is_sugared_doc: false,
});
let attrs = {
let mut v = vec![mk_deriving_copy_attr(ctx, true), repr_attr];
if derive_debug {
v.push(mk_deriving_debug_attr(ctx));
}
v
};
items.push(P(ast::Item {
ident: enum_name,
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Enum(ast::EnumDef { variants: variants },
ast::Generics::default()),
vis: ast::Visibility::Public,
span: ctx.span,
}));
items
}
/// Generates accessors for fields in nested structs and unions which must be
/// represented in Rust as an untyped array. This process may generate
/// declarations and implementations that must be placed at the root level.
/// These are emitted into `extra`.
fn gen_comp_methods(ctx: &mut GenCtx, data_field: &str, data_offset: usize,
kind: CompKind, members: &[CompMember],
extra: &mut Vec<P<ast::Item>>,
derive_debug: bool) -> Vec<ast::ImplItem> {
let mk_field_method = |ctx: &mut GenCtx, f: &FieldInfo, offset: usize| {
// TODO: Implement bitfield accessors
if f.bitfields.is_some() { return None; }
let (f_name, _) = rust_id(ctx, &f.name);
let ret_ty = P(cty_to_rs(ctx, &TPtr(Box::new(f.ty.clone()), false, Layout::default())));
// When the offset is zero, generate slightly prettier code.
let method = {
let impl_str = format!(r"
impl X {{
pub unsafe fn {}(&mut self) -> {} {{
let raw: *mut u8 = ::std::mem::transmute(&self.{});
::std::mem::transmute(raw.offset({}))
}}
}}
", f_name, tts_to_string(&ret_ty.to_tokens(&ctx.ext_cx)[..]), data_field, offset);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
};
method.and_then(|i| {
match i.node {
ast::ItemKind::Impl(_, _, _, _, _, mut items) => {
items.pop()
}
_ => unreachable!("impl parsed to something other than impl")
}
})
};
let mut offset = data_offset;
let mut methods = vec!();
for m in members.into_iter() {
let advance_by = match *m {
CompMember::Field(ref f) => {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
f.ty.size()
}
CompMember::Comp(ref rc_c) => {
let c = &rc_c.borrow();
methods.extend(gen_comp_methods(ctx, data_field, offset, c.kind,
&c.members, extra, derive_debug).into_iter());
c.layout.size
}
CompMember::CompField(ref rc_c, ref f) => {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
let c = rc_c.borrow();
extra.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
derive_debug,
c.layout, c.members.clone()).into_iter());
f.ty.size()
}
};
match kind {
CompKind::Struct => { offset += advance_by; }
CompKind::Union => { }
}
}
methods
}
// Implements std::default::Default using std::mem::zeroed.
fn mk_default_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::default::Default for {} {{
fn default() -> Self {{ unsafe {{ ::std::mem::zeroed() }} }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
// Implements std::clone::Clone using dereferencing
fn mk_clone_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::clone::Clone for {} {{
fn clone(&self) -> Self {{ *self }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
fn mk_blob_field(ctx: &GenCtx, name: &str, layout: Layout, span: Span) -> ast::StructField {
let ty_name = match layout.align {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
let data_len = if ty_name == "u8" { layout.size } else { layout.size / layout.align };
let base_ty = mk_ty(ctx, false, vec!(ty_name.to_owned()));
let data_ty = P(mk_arrty(ctx, &base_ty, data_len));
ast::StructField{
span: span,
vis: ast::Visibility::Public,
ident: Some(ctx.ext_cx.ident_of(name)),
id: ast::DUMMY_NODE_ID,
ty: data_ty,
attrs: Vec::new()
}
}
fn mk_link_name_attr(ctx: &mut GenCtx, name: String) -> ast::Attribute {
let lit = respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, &name),
ast::StrStyle::Cooked
));
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "link_name"), lit
)));
let attr = ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
};
respan(ctx.span, attr)
}
fn mk_repr_attr(ctx: &mut GenCtx, layout: Layout) -> ast::Attribute {
let mut values = vec!(P(respan(ctx.span, ast::MetaItemKind::Word(to_intern_str(ctx, "C")))));
if layout.packed {
values.push(P(respan(ctx.span, ast::MetaItemKind::Word(to_intern_str(ctx, "packed")))));
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
to_intern_str(ctx, "repr"),
values
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_copy_attr(ctx: &mut GenCtx, clone: bool) -> ast::Attribute {
let mut words = vec!();
if clone {
words.push(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Clone")));
}
words.push(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Copy")));
let attr_val = ctx.ext_cx.meta_list(ctx.span, InternedString::new("derive"), words);
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_debug_attr(ctx: &mut GenCtx) -> ast::Attribute {
let words = vec!(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Debug")));
let attr_val = ctx.ext_cx.meta_list(ctx.span, InternedString::new("derive"), words);
ctx.ext_cx.attribute(ctx.span, attr_val)
}
fn cvar_to_rs(ctx: &mut GenCtx, name: String,
ty: &Type,
is_const: bool) -> ast::ForeignItem {
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
let val_ty = P(cty_to_rs(ctx, ty));
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name[..]),
attrs: attrs,
node: ast::ForeignItemKind::Static(val_ty, !is_const),
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cfuncty_to_rs(ctx: &mut GenCtx,
rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::FnDecl {
let ret = match *rty {
TVoid => ast::FunctionRetTy::Default(ctx.span),
_ => ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, rty)))
};
let mut unnamed: usize = 0;
let args: Vec<ast::Arg> = aty.iter().map(|arg| {
let (ref n, ref t) = *arg;
let arg_name = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
rust_id(ctx, &n).0
};
// From the C90 standard (http://c0x.coding-guidelines.com/6.7.5.3.html)
// 1598 - A declaration of a parameter as “array of type” shall be
// adjusted to “qualified pointer to type”, where the type qualifiers
// (if any) are those specified within the [ and ] of the array type
// derivation.
let arg_ty = P(match *t {
TArray(ref typ, _, l) => cty_to_rs(ctx, &TPtr(typ.clone(), false, l)),
_ => cty_to_rs(ctx, t),
});
let ident = ctx.ext_cx.ident_of(&arg_name);
ctx.ext_cx.arg(ctx.span, ident, arg_ty)
}).collect();
let var = !args.is_empty() && var;
ast::FnDecl {
inputs: args,
output: ret,
variadic: var
}
}
fn cfunc_to_rs(ctx: &mut GenCtx, name: String, rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::ForeignItem {
let var = !aty.is_empty() && var;
let decl = ast::ForeignItemKind::Fn(
P(cfuncty_to_rs(ctx, rty, aty, var)),
ast::Generics::default()
);
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name[..]),
attrs: attrs,
node: decl,
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cty_to_rs(ctx: &mut GenCtx, ty: &Type) -> ast::Ty {
let prefix = vec!["std".to_owned(), "os".to_owned(), "raw".to_owned()];
let raw = |fragment: &str| {
let mut path = prefix.clone();
path.push(fragment.to_owned());
path
};
match *ty {
TVoid => mk_ty(ctx, true, raw("c_void")),
TInt(i, ref layout) => match i {
IBool => {
let ty_name = match layout.size {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
mk_ty(ctx, false, vec!(ty_name.to_owned()))
},
ISChar => mk_ty(ctx, true, raw("c_char")),
IUChar => mk_ty(ctx, true, raw("c_uchar")),
IInt => mk_ty(ctx, true, raw("c_int")),
IUInt => mk_ty(ctx, true, raw("c_uint")),
IShort => mk_ty(ctx, true, raw("c_short")),
IUShort => mk_ty(ctx, true, raw("c_ushort")),
ILong => mk_ty(ctx, true, raw("c_long")),
IULong => mk_ty(ctx, true, raw("c_ulong")),
ILongLong => mk_ty(ctx, true, raw("c_longlong")),
IULongLong => mk_ty(ctx, true, raw("c_ulonglong"))
},
TFloat(f, _) => match f {
FFloat => mk_ty(ctx, true, raw("c_float")),
FDouble => mk_ty(ctx, true, raw("c_double"))
},
TPtr(ref t, is_const, _) => {
let id = cty_to_rs(ctx, &**t);
mk_ptrty(ctx, &id, is_const)
},
TArray(ref t, s, _) => {
let ty = cty_to_rs(ctx, &**t);
mk_arrty(ctx, &ty, s)
},
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
let unsafety = if sig.is_safe { ast::Unsafety::Normal } else { ast::Unsafety::Unsafe };
mk_fnty(ctx, &decl, unsafety, sig.abi)
},
TFuncProto(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
let unsafety = if sig.is_safe { ast::Unsafety::Normal } else { ast::Unsafety::Unsafe };
mk_fn_proto_ty(ctx, &decl, unsafety, sig.abi)
},
TNamed(ref ti) => {
let id = rust_type_id(ctx, &ti.borrow().name);
mk_ty(ctx, false, vec!(id))
},
TComp(ref ci) => {
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
mk_ty(ctx, false, vec!(comp_name(c.kind, &c.name)))
},
TEnum(ref ei) => {
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
mk_ty(ctx, false, vec!(enum_name(&e.name)))
}
}
}
fn mk_ty(ctx: &GenCtx, global: bool, segments: Vec<String>) -> ast::Ty {
let ty = ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: global,
segments: segments.iter().map(|s| {
ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&s[..]),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
}
}).collect()
},
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_ptrty(ctx: &mut GenCtx, base: &ast::Ty, is_const: bool) -> ast::Ty {
let ty = ast::TyKind::Ptr(ast::MutTy {
ty: P(base.clone()),
mutbl: if is_const { ast::Mutability::Immutable } else { ast::Mutability::Mutable }
});
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_arrty(ctx: &GenCtx, base: &ast::Ty, n: usize) -> ast::Ty {
let int_lit = ast::LitKind::Int(n as u64, ast::LitIntType::Unsigned(ast::UintTy::Us));
let sz = ast::ExprKind::Lit(P(respan(ctx.span, int_lit)));
let ty = ast::TyKind::FixedLengthVec(
P(base.clone()),
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: sz,
span: ctx.span,
attrs: None,
})
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_fn_proto_ty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: unsafety,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span,
}
}
fn mk_fnty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: unsafety,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
let segs = vec![
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("std"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("Option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::from_vec(vec!(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span
})
)),
bindings: P::new(),
}),
}
];
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: true,
segments: segs
},
),
span: ctx.span
}
}
[gen.rs] Improve mk_ptrty.
use std;
use std::cell::RefCell;
use std::vec::Vec;
use std::rc::Rc;
use std::collections::HashMap;
use syntax::abi;
use syntax::ast;
use syntax::codemap::{Span, respan, ExpnInfo, NameAndSpan, MacroBang};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::ext::expand::ExpansionConfig;
use syntax::ext::quote::rt::ToTokens;
use syntax::feature_gate::Features;
use syntax::parse;
use syntax::parse::token::InternedString;
use syntax::attr::mk_attr_id;
use syntax::ptr::P;
use syntax::print::pprust::tts_to_string;
use super::{BindgenOptions, LinkType};
use types::*;
struct GenCtx<'r> {
ext_cx: base::ExtCtxt<'r>,
unnamed_ty: usize,
span: Span
}
fn ref_eq<T>(thing: &T, other: &T) -> bool {
(thing as *const T) == (other as *const T)
}
fn to_intern_str(ctx: &mut GenCtx, s: &str) -> parse::token::InternedString {
let id = ctx.ext_cx.ident_of(s);
id.name.as_str()
}
fn rust_id(ctx: &mut GenCtx, name: &str) -> (String, bool) {
let token = parse::token::Ident(ctx.ext_cx.ident_of(name));
if token.is_any_keyword() || "bool" == name {
let s = format!("_{}", name);
(s, true)
} else {
(name.into(), false)
}
}
fn rust_type_id(ctx: &mut GenCtx, name: &str) -> String {
match name {
"bool" | "uint" | "u8" | "u16" | "u32" | "f32" | "f64" | "i8" | "i16" |
"i32" | "i64" | "Self" | "str" => {
format!("_{}", name)
},
_ => {
let (n, _) = rust_id(ctx, name);
n
}
}
}
fn unnamed_name(ctx: &mut GenCtx, name: &str) -> String {
if name.is_empty() {
ctx.unnamed_ty += 1;
format!("Unnamed{}", ctx.unnamed_ty)
} else {
name.into()
}
}
fn comp_name(kind: CompKind, name: &str) -> String {
match kind {
CompKind::Struct => struct_name(name),
CompKind::Union => union_name(name),
}
}
fn struct_name(name: &str) -> String {
format!("Struct_{}", name)
}
fn union_name(name: &str) -> String {
format!("Union_{}", name)
}
fn enum_name(name: &str) -> String {
format!("Enum_{}", name)
}
fn extract_definitions(ctx: &mut GenCtx,
options: &BindgenOptions,
globals: &[Global])
-> Vec<P<ast::Item>> {
let mut defs = vec!();
for g in globals {
match *g {
GType(ref ti) => {
let t = ti.borrow();
defs.extend(ctypedef_to_rs(
ctx,
options.rust_enums,
options.derive_debug,
&t.name, &t.ty))
},
GCompDecl(ref ci) => {
{
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
}
let c = ci.borrow().clone();
defs.push(opaque_to_rs(ctx, &comp_name(c.kind, &c.name)));
},
GComp(ref ci) => {
{
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
}
let c = ci.borrow().clone();
defs.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
options.derive_debug,
c.layout, c.members).into_iter())
},
GEnumDecl(ref ei) => {
{
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
}
let e = ei.borrow().clone();
defs.push(opaque_to_rs(ctx, &enum_name(&e.name)));
},
GEnum(ref ei) => {
{
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
}
let e = ei.borrow();
defs.extend(cenum_to_rs(
ctx,
options.rust_enums,
options.derive_debug,
&enum_name(&e.name), e.kind, e.layout, &e.items));
},
GVar(ref vi) => {
let v = vi.borrow();
let ty = cty_to_rs(ctx, &v.ty);
defs.push(const_to_rs(ctx, &v.name, v.val.unwrap(), ty));
},
_ => { }
}
}
defs
}
fn extract_functions(ctx: &mut GenCtx,
fs: &[Global])
-> HashMap<abi::Abi, Vec<ast::ForeignItem>> {
let func_list = fs.iter().map(|f| {
match *f {
GFunc(ref vi) => {
let v = vi.borrow();
match v.ty {
TFuncPtr(ref sig) => {
let decl = cfunc_to_rs(ctx, v.name.clone(),
&*sig.ret_ty, &sig.args[..],
sig.is_variadic);
(sig.abi, decl)
}
_ => unreachable!()
}
},
_ => unreachable!()
}
});
let mut map = HashMap::new();
for (abi, func) in func_list {
map.entry(abi).or_insert(vec!()).push(func);
}
map
}
pub fn gen_mod(
options: &BindgenOptions,
globs: Vec<Global>,
span: Span)
-> Vec<P<ast::Item>> {
// Create a dummy ExtCtxt. We only need this for string interning and that uses TLS.
let mut features = Features::new();
features.quote = true;
let cfg = ExpansionConfig {
crate_name: "xxx".to_owned(),
features: Some(&features),
recursion_limit: 64,
trace_mac: false,
};
let sess = &parse::ParseSess::new();
let mut feature_gated_cfgs = Vec::new();
let mut ctx = GenCtx {
ext_cx: base::ExtCtxt::new(
sess,
Vec::new(),
cfg,
&mut feature_gated_cfgs,
),
unnamed_ty: 0,
span: span
};
ctx.ext_cx.bt_push(ExpnInfo {
call_site: ctx.span,
callee: NameAndSpan {
format: MacroBang(parse::token::intern("")),
allow_internal_unstable: false,
span: None
}
});
let uniq_globs = tag_dup_decl(&globs);
let mut fs = vec!();
let mut vs = vec!();
let mut gs = vec!();
for g in uniq_globs.into_iter() {
match g {
GOther => {}
GFunc(_) => fs.push(g),
GVar(_) => {
let is_int_const = {
match g {
GVar(ref vi) => {
let v = vi.borrow();
v.is_const && v.val.is_some()
}
_ => unreachable!()
}
};
if is_int_const {
gs.push(g);
} else {
vs.push(g);
}
}
_ => gs.push(g)
}
}
gs = remove_redundant_decl(gs);
let mut defs = extract_definitions(&mut ctx, &options, &gs);
let vars = vs.into_iter().map(|v| {
match v {
GVar(vi) => {
let v = vi.borrow();
cvar_to_rs(&mut ctx, v.name.clone(), &v.ty, v.is_const)
},
_ => unreachable!()
}
}).collect();
let funcs = extract_functions(&mut ctx, &fs);
if !Vec::is_empty(&vars) {
defs.push(mk_extern(&mut ctx, &options.links, vars, abi::Abi::C));
}
for (abi, funcs) in funcs.into_iter() {
defs.push(mk_extern(&mut ctx, &options.links, funcs, abi));
}
//let attrs = vec!(mk_attr_list(&mut ctx, "allow", ["dead_code", "non_camel_case_types", "uppercase_variables"]));
defs
}
fn mk_extern(ctx: &mut GenCtx, links: &[(String, LinkType)],
foreign_items: Vec<ast::ForeignItem>,
abi: abi::Abi) -> P<ast::Item> {
let attrs = if links.is_empty() {
Vec::new()
} else {
links.iter().map(|&(ref l, ref k)| {
let k = match *k {
LinkType::Default => None,
LinkType::Static => Some("static"),
LinkType::Framework => Some("framework")
};
let link_name = P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "name"),
respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, l),
ast::StrStyle::Cooked
))
)));
let link_args = match k {
None => vec!(link_name),
Some(ref k) => vec!(link_name, P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "kind"),
respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, *k),
ast::StrStyle::Cooked
))
))))
};
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: P(respan(ctx.span, ast::MetaItemKind::List(
to_intern_str(ctx, "link"),
link_args)
)),
is_sugared_doc: false
})
}).collect()
};
let mut items = Vec::new();
items.extend(foreign_items.into_iter());
let ext = ast::ItemKind::ForeignMod(ast::ForeignMod {
abi: abi,
items: items
});
P(ast::Item {
ident: ctx.ext_cx.ident_of(""),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ext,
vis: ast::Visibility::Inherited,
span: ctx.span
})
}
fn remove_redundant_decl(gs: Vec<Global>) -> Vec<Global> {
fn check_decl(a: &Global, ty: &Type) -> bool {
match *a {
GComp(ref ci1) => match *ty {
TComp(ref ci2) => {
ref_eq(ci1, ci2) && ci1.borrow().name.is_empty()
},
_ => false
},
GEnum(ref ei1) => match *ty {
TEnum(ref ei2) => {
ref_eq(ei1, ei2) && ei1.borrow().name.is_empty()
},
_ => false
},
_ => false
}
}
let typedefs: Vec<Type> = gs.iter().filter_map(|g|
match *g {
GType(ref ti) => Some(ti.borrow().ty.clone()),
_ => None
}
).collect();
gs.into_iter().filter(|g|
!typedefs.iter().any(|t| check_decl(g, t))
).collect()
}
fn tag_dup_decl(gs: &[Global]) -> Vec<Global> {
fn check(name1: &str, name2: &str) -> bool {
!name1.is_empty() && name1 == name2
}
fn is_dup(g1: &Global, g2: &Global) -> bool {
match (g1, g2) {
(>ype(ref ti1), >ype(ref ti2)) => {
let a = ti1.borrow();
let b = ti2.borrow();
check(&a.name[..], &b.name[..])
},
(&GComp(ref ci1), &GComp(ref ci2)) |
(&GCompDecl(ref ci1), &GCompDecl(ref ci2)) => {
let a = ci1.borrow();
let b = ci2.borrow();
check(&a.name[..], &b.name[..])
},
(&GEnum(ref ei1), &GEnum(ref ei2)) |
(&GEnumDecl(ref ei1), &GEnumDecl(ref ei2)) => {
let a = ei1.borrow();
let b = ei2.borrow();
check(&a.name[..], &b.name[..])
},
(&GVar(ref vi1), &GVar(ref vi2)) |
(&GFunc(ref vi1), &GFunc(ref vi2)) => {
let a = vi1.borrow();
let b = vi2.borrow();
check(&a.name[..], &b.name[..])
},
_ => false
}
}
if gs.is_empty() {
return vec!();
}
let mut res: Vec<Global> = vec!();
res.push(gs[0].clone());
for (i, gsi) in gs.iter().enumerate().skip(1) {
let dup = gs.iter().take(i).any(|item| is_dup(&item, &gsi));
if !dup {
res.push(gsi.clone());
}
}
res
}
/// Converts a C typedef to Rust AST Items.
fn ctypedef_to_rs(
ctx: &mut GenCtx,
rust_enums: bool,
derive_debug: bool,
name: &str,
ty: &Type)
-> Vec<P<ast::Item>> {
fn mk_item(ctx: &mut GenCtx, name: &str, ty: &Type) -> P<ast::Item> {
let rust_name = rust_type_id(ctx, &name);
let rust_ty = cty_to_rs(ctx, ty);
let base = ast::ItemKind::Ty(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: rust_ty.node,
span: ctx.span,
}),
ast::Generics::default()
);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&rust_name),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: base,
vis: ast::Visibility::Public,
span: ctx.span
})
}
match *ty {
TComp(ref ci) => {
let is_empty = ci.borrow().name.is_empty();
if is_empty {
ci.borrow_mut().name = name.into();
let c = ci.borrow().clone();
comp_to_rs(ctx, c.kind, name.into(), derive_debug, c.layout, c.members)
} else {
vec!(mk_item(ctx, name, ty))
}
},
TEnum(ref ei) => {
let is_empty = ei.borrow().name.is_empty();
if is_empty {
ei.borrow_mut().name = name.into();
let e = ei.borrow();
cenum_to_rs(ctx, rust_enums, derive_debug, name, e.kind, e.layout, &e.items)
} else {
vec!(mk_item(ctx, name, ty))
}
},
_ => vec!(mk_item(ctx, name, ty))
}
}
/// Converts a C composed type (struct or union) to Rust AST Items.
fn comp_to_rs(ctx: &mut GenCtx, kind: CompKind, name: String,
derive_debug: bool,
layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
match kind {
CompKind::Struct => cstruct_to_rs(ctx, &name, derive_debug, layout, members),
CompKind::Union => cunion_to_rs(ctx, name, derive_debug, layout, members),
}
}
/// Converts a C struct to Rust AST Items.
fn cstruct_to_rs(ctx: &mut GenCtx,
name: &str,
derive_debug: bool,
layout: Layout,
members: Vec<CompMember>) -> Vec<P<ast::Item>> {
let mut fields: Vec<ast::StructField> = vec!();
let mut methods = vec!();
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current struct.
let mut extra = vec!();
let mut unnamed: u32 = 0;
let mut bitfields: u32 = 0;
// Debug is only defined on little arrays
let mut can_derive_debug = derive_debug;
for m in &members {
let (opt_rc_c, opt_f) = match *m {
CompMember::Field(ref f) => { (None, Some(f)) }
CompMember::Comp(ref rc_c) => { (Some(rc_c), None) }
CompMember::CompField(ref rc_c, ref f) => { (Some(rc_c), Some(f)) }
};
if let Some(f) = opt_f {
let f_name = match f.bitfields {
Some(_) => {
bitfields += 1;
format!("_bindgen_bitfield_{}_", bitfields)
}
None => rust_type_id(ctx, &f.name)
};
if !f.ty.can_derive_debug() {
can_derive_debug = false;
}
let f_ty = P(cty_to_rs(ctx, &f.ty));
fields.push(ast::StructField {
span: ctx.span,
vis: ast::Visibility::Public,
ident: Some(ctx.ext_cx.ident_of(&f_name[..])),
id: ast::DUMMY_NODE_ID,
ty: f_ty,
attrs: Vec::new()
});
}
if let Some(rc_c) = opt_rc_c {
let c = rc_c.borrow();
if c.name.is_empty() {
unnamed += 1;
let field_name = format!("_bindgen_data_{}_", unnamed);
fields.push(mk_blob_field(ctx, &field_name, c.layout, ctx.span));
methods.extend(gen_comp_methods(ctx, &field_name, 0, c.kind, &c.members, &mut extra, derive_debug).into_iter());
} else {
extra.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
derive_debug,
c.layout, c.members.clone()).into_iter());
}
}
}
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID),
ast::Generics::default()
);
let id = rust_type_id(ctx, &name);
let mut attrs = vec!(mk_repr_attr(ctx, layout), mk_deriving_copy_attr(ctx, false));
if can_derive_debug {
attrs.push(mk_deriving_debug_attr(ctx));
}
let struct_def = P(ast::Item { ident: ctx.ext_cx.ident_of(&id),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
});
let mut items = vec!(struct_def);
if !methods.is_empty() {
let impl_ = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
ast::Generics::default(),
None,
P(mk_ty(ctx, false, vec!(id))),
methods
);
items.push(
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name),
attrs: vec!(),
id: ast::DUMMY_NODE_ID,
node: impl_,
vis: ast::Visibility::Inherited,
span: ctx.span}));
}
items.push(mk_clone_impl(ctx, &name));
items.push(mk_default_impl(ctx, &name));
items.extend(extra.into_iter());
items
}
/// Convert a opaque type name to an ast Item.
fn opaque_to_rs(ctx: &mut GenCtx, name: &str) -> P<ast::Item> {
let def = ast::ItemKind::Enum(
ast::EnumDef {
variants: vec!()
},
ast::Generics::default()
);
let id = rust_type_id(ctx, &name);
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: def,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn cunion_to_rs(ctx: &mut GenCtx, name: String, derive_debug: bool, layout: Layout, members: Vec<CompMember>) -> Vec<P<ast::Item>> {
fn mk_item(ctx: &mut GenCtx, name: String, item: ast::ItemKind, vis:
ast::Visibility, attrs: Vec<ast::Attribute>) -> P<ast::Item> {
P(ast::Item {
ident: ctx.ext_cx.ident_of(&name[..]),
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: item,
vis: vis,
span: ctx.span
})
}
let ci = Rc::new(RefCell::new(CompInfo::new(name.clone(), CompKind::Union, members.clone(), layout)));
let union = TNamed(Rc::new(RefCell::new(TypeInfo::new(name.clone(), TComp(ci)))));
// Nested composites may need to emit declarations and implementations as
// they are encountered. The declarations end up in 'extra' and are emitted
// after the current union.
let mut extra = vec!();
let data_field_name = "_bindgen_data_";
let data_field = mk_blob_field(ctx, data_field_name, layout, ctx.span);
let def = ast::ItemKind::Struct(
ast::VariantData::Struct(
vec!(data_field),
ast::DUMMY_NODE_ID),
ast::Generics::default()
);
let union_id = rust_type_id(ctx, &name);
let union_attrs = {
let mut attrs = vec!(mk_repr_attr(ctx, layout), mk_deriving_copy_attr(ctx, false));
if derive_debug {
let can_derive_debug = members.iter()
.all(|member| match *member {
CompMember::Field(ref f) |
CompMember::CompField(_, ref f) => f.ty.can_derive_debug(),
_ => true
});
if can_derive_debug {
attrs.push(mk_deriving_debug_attr(ctx))
}
}
attrs
};
let union_def = mk_item(ctx, union_id, def, ast::Visibility::Public, union_attrs);
let union_impl = ast::ItemKind::Impl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
ast::Generics::default(),
None,
P(cty_to_rs(ctx, &union)),
gen_comp_methods(ctx, data_field_name, 0, CompKind::Union, &members, &mut extra, derive_debug),
);
let mut items = vec!(
union_def,
mk_item(ctx, "".to_owned(), union_impl, ast::Visibility::Inherited, Vec::new())
);
items.push(mk_clone_impl(ctx, &name[..]));
items.push(mk_default_impl(ctx, &name[..]));
items.extend(extra.into_iter());
items
}
/// Converts a signed number to AST Expression.
fn i64_to_int_lit(ctx: &mut GenCtx, value: i64) -> P<ast::Expr> {
let int_lit = ast::LitKind::Int(value.abs() as u64,
ast::LitIntType::Unsuffixed);
let expr = ctx.ext_cx.expr_lit(ctx.span, int_lit);
if value < 0 {
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, expr);
ctx.ext_cx.expr(ctx.span, negated)
} else {
expr
}
}
/// Converts a C const to Rust AST.
fn const_to_rs(ctx: &mut GenCtx,
name: &str,
val: i64,
val_ty: ast::Ty) -> P<ast::Item> {
let int_lit = i64_to_int_lit(ctx, val);
let cst = ast::ItemKind::Const(P(val_ty), int_lit);
let id = rust_id(ctx, name).0;
P(ast::Item {
ident: ctx.ext_cx.ident_of(&id),
attrs: Vec::new(),
id: ast::DUMMY_NODE_ID,
node: cst,
vis: ast::Visibility::Public,
span: ctx.span
})
}
fn enum_size_to_rust_type_name(signed: bool, size: usize) -> &'static str {
match (signed, size) {
(true, 1) => "i8",
(false, 1) => "u8",
(true, 2) => "i16",
(false, 2) => "u16",
(true, 4) => "i32",
(false, 4) => "u32",
(true, 8) => "i64",
(false, 8) => "u64",
_ => unreachable!("invalid enum decl: signed: {}, size: {}", signed, size),
}
}
fn enum_size_to_unsigned_max_value(size: usize) -> u64 {
match size {
1 => std::u8::MAX as u64,
2 => std::u16::MAX as u64,
4 => std::u32::MAX as u64,
8 => std::u64::MAX,
_ => unreachable!("invalid enum size: {}", size)
}
}
/// Converts a C enum variant to an AST expression.
fn cenum_value_to_int_lit(
ctx: &mut GenCtx,
enum_is_signed: bool,
size: usize,
value: i64)
-> P<ast::Expr> {
if enum_is_signed {
i64_to_int_lit(ctx, value)
} else {
let u64_value =
value as u64 & enum_size_to_unsigned_max_value(size);
let int_lit =
ast::LitKind::Int(u64_value, ast::LitIntType::Unsuffixed);
ctx.ext_cx.expr_lit(ctx.span, int_lit)
}
}
fn cenum_to_rs(
ctx: &mut GenCtx,
rust_enums: bool,
derive_debug: bool,
name: &str,
kind: IKind,
layout: Layout,
enum_items: &[EnumItem])
-> Vec<P<ast::Item>> {
let enum_name = ctx.ext_cx.ident_of(name);
let enum_ty = ctx.ext_cx.ty_ident(ctx.span, enum_name);
let enum_is_signed = kind.is_signed();
let enum_repr = enum_size_to_rust_type_name(enum_is_signed, layout.size);
let mut items = vec![];
if !rust_enums {
items.push(ctx.ext_cx.item_ty(
ctx.span,
enum_name,
ctx.ext_cx.ty_ident(
ctx.span,
ctx.ext_cx.ident_of(enum_repr))));
for item in enum_items {
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
items.push(ctx.ext_cx.item_const(
ctx.span,
ctx.ext_cx.ident_of(&item.name),
enum_ty.clone(),
value));
}
return items;
}
let mut variants = vec![];
let mut found_values = HashMap::new();
for item in enum_items {
let name = ctx.ext_cx.ident_of(&item.name);
if let Some(orig) = found_values.get(&item.val) {
let value = ctx.ext_cx.expr_path(
ctx.ext_cx.path(ctx.span, vec![enum_name, *orig]));
items.push(P(ast::Item {
ident: name,
attrs: vec![],
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Const(enum_ty.clone(), value),
vis: ast::Visibility::Public,
span: ctx.span,
}));
continue;
}
found_values.insert(item.val, name);
let value = cenum_value_to_int_lit(
ctx, enum_is_signed, layout.size, item.val);
variants.push(respan(ctx.span, ast::Variant_ {
name: name,
attrs: vec![],
data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
disr_expr: Some(value),
}));
}
let enum_repr = InternedString::new(enum_repr);
let repr_arg = ctx.ext_cx.meta_word(ctx.span, enum_repr);
let repr_list = ctx.ext_cx.meta_list(ctx.span, InternedString::new("repr"), vec![repr_arg]);
let repr_attr = respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: repr_list,
is_sugared_doc: false,
});
let attrs = {
let mut v = vec![mk_deriving_copy_attr(ctx, true), repr_attr];
if derive_debug {
v.push(mk_deriving_debug_attr(ctx));
}
v
};
items.push(P(ast::Item {
ident: enum_name,
attrs: attrs,
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Enum(ast::EnumDef { variants: variants },
ast::Generics::default()),
vis: ast::Visibility::Public,
span: ctx.span,
}));
items
}
/// Generates accessors for fields in nested structs and unions which must be
/// represented in Rust as an untyped array. This process may generate
/// declarations and implementations that must be placed at the root level.
/// These are emitted into `extra`.
fn gen_comp_methods(ctx: &mut GenCtx, data_field: &str, data_offset: usize,
kind: CompKind, members: &[CompMember],
extra: &mut Vec<P<ast::Item>>,
derive_debug: bool) -> Vec<ast::ImplItem> {
let mk_field_method = |ctx: &mut GenCtx, f: &FieldInfo, offset: usize| {
// TODO: Implement bitfield accessors
if f.bitfields.is_some() { return None; }
let (f_name, _) = rust_id(ctx, &f.name);
let ret_ty = P(cty_to_rs(ctx, &TPtr(Box::new(f.ty.clone()), false, Layout::default())));
// When the offset is zero, generate slightly prettier code.
let method = {
let impl_str = format!(r"
impl X {{
pub unsafe fn {}(&mut self) -> {} {{
let raw: *mut u8 = ::std::mem::transmute(&self.{});
::std::mem::transmute(raw.offset({}))
}}
}}
", f_name, tts_to_string(&ret_ty.to_tokens(&ctx.ext_cx)[..]), data_field, offset);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
};
method.and_then(|i| {
match i.node {
ast::ItemKind::Impl(_, _, _, _, _, mut items) => {
items.pop()
}
_ => unreachable!("impl parsed to something other than impl")
}
})
};
let mut offset = data_offset;
let mut methods = vec!();
for m in members.into_iter() {
let advance_by = match *m {
CompMember::Field(ref f) => {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
f.ty.size()
}
CompMember::Comp(ref rc_c) => {
let c = &rc_c.borrow();
methods.extend(gen_comp_methods(ctx, data_field, offset, c.kind,
&c.members, extra, derive_debug).into_iter());
c.layout.size
}
CompMember::CompField(ref rc_c, ref f) => {
methods.extend(mk_field_method(ctx, f, offset).into_iter());
let c = rc_c.borrow();
extra.extend(comp_to_rs(ctx, c.kind, comp_name(c.kind, &c.name),
derive_debug,
c.layout, c.members.clone()).into_iter());
f.ty.size()
}
};
match kind {
CompKind::Struct => { offset += advance_by; }
CompKind::Union => { }
}
}
methods
}
// Implements std::default::Default using std::mem::zeroed.
fn mk_default_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::default::Default for {} {{
fn default() -> Self {{ unsafe {{ ::std::mem::zeroed() }} }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
// Implements std::clone::Clone using dereferencing
fn mk_clone_impl(ctx: &GenCtx, ty_name: &str) -> P<ast::Item> {
let impl_str = format!(r"
impl ::std::clone::Clone for {} {{
fn clone(&self) -> Self {{ *self }}
}}
", ty_name);
parse::new_parser_from_source_str(ctx.ext_cx.parse_sess(),
ctx.ext_cx.cfg(), "".to_owned(), impl_str).parse_item().unwrap().unwrap()
}
fn mk_blob_field(ctx: &GenCtx, name: &str, layout: Layout, span: Span) -> ast::StructField {
let ty_name = match layout.align {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
let data_len = if ty_name == "u8" { layout.size } else { layout.size / layout.align };
let base_ty = mk_ty(ctx, false, vec!(ty_name.to_owned()));
let data_ty = P(mk_arrty(ctx, &base_ty, data_len));
ast::StructField{
span: span,
vis: ast::Visibility::Public,
ident: Some(ctx.ext_cx.ident_of(name)),
id: ast::DUMMY_NODE_ID,
ty: data_ty,
attrs: Vec::new()
}
}
fn mk_link_name_attr(ctx: &mut GenCtx, name: String) -> ast::Attribute {
let lit = respan(ctx.span, ast::LitKind::Str(
to_intern_str(ctx, &name),
ast::StrStyle::Cooked
));
let attr_val = P(respan(ctx.span, ast::MetaItemKind::NameValue(
to_intern_str(ctx, "link_name"), lit
)));
let attr = ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
};
respan(ctx.span, attr)
}
fn mk_repr_attr(ctx: &mut GenCtx, layout: Layout) -> ast::Attribute {
let mut values = vec!(P(respan(ctx.span, ast::MetaItemKind::Word(to_intern_str(ctx, "C")))));
if layout.packed {
values.push(P(respan(ctx.span, ast::MetaItemKind::Word(to_intern_str(ctx, "packed")))));
}
let attr_val = P(respan(ctx.span, ast::MetaItemKind::List(
to_intern_str(ctx, "repr"),
values
)));
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_copy_attr(ctx: &mut GenCtx, clone: bool) -> ast::Attribute {
let mut words = vec!();
if clone {
words.push(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Clone")));
}
words.push(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Copy")));
let attr_val = ctx.ext_cx.meta_list(ctx.span, InternedString::new("derive"), words);
respan(ctx.span, ast::Attribute_ {
id: mk_attr_id(),
style: ast::AttrStyle::Outer,
value: attr_val,
is_sugared_doc: false
})
}
fn mk_deriving_debug_attr(ctx: &mut GenCtx) -> ast::Attribute {
let words = vec!(ctx.ext_cx.meta_word(ctx.span, InternedString::new("Debug")));
let attr_val = ctx.ext_cx.meta_list(ctx.span, InternedString::new("derive"), words);
ctx.ext_cx.attribute(ctx.span, attr_val)
}
fn cvar_to_rs(ctx: &mut GenCtx, name: String,
ty: &Type,
is_const: bool) -> ast::ForeignItem {
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
let val_ty = P(cty_to_rs(ctx, ty));
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name[..]),
attrs: attrs,
node: ast::ForeignItemKind::Static(val_ty, !is_const),
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cfuncty_to_rs(ctx: &mut GenCtx,
rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::FnDecl {
let ret = match *rty {
TVoid => ast::FunctionRetTy::Default(ctx.span),
_ => ast::FunctionRetTy::Ty(P(cty_to_rs(ctx, rty)))
};
let mut unnamed: usize = 0;
let args: Vec<ast::Arg> = aty.iter().map(|arg| {
let (ref n, ref t) = *arg;
let arg_name = if n.is_empty() {
unnamed += 1;
format!("arg{}", unnamed)
} else {
rust_id(ctx, &n).0
};
// From the C90 standard (http://c0x.coding-guidelines.com/6.7.5.3.html)
// 1598 - A declaration of a parameter as “array of type” shall be
// adjusted to “qualified pointer to type”, where the type qualifiers
// (if any) are those specified within the [ and ] of the array type
// derivation.
let arg_ty = P(match *t {
TArray(ref typ, _, l) => cty_to_rs(ctx, &TPtr(typ.clone(), false, l)),
_ => cty_to_rs(ctx, t),
});
let ident = ctx.ext_cx.ident_of(&arg_name);
ctx.ext_cx.arg(ctx.span, ident, arg_ty)
}).collect();
let var = !args.is_empty() && var;
ast::FnDecl {
inputs: args,
output: ret,
variadic: var
}
}
fn cfunc_to_rs(ctx: &mut GenCtx, name: String, rty: &Type,
aty: &[(String, Type)],
var: bool) -> ast::ForeignItem {
let var = !aty.is_empty() && var;
let decl = ast::ForeignItemKind::Fn(
P(cfuncty_to_rs(ctx, rty, aty, var)),
ast::Generics::default()
);
let (rust_name, was_mangled) = rust_id(ctx, &name);
let mut attrs = Vec::new();
if was_mangled {
attrs.push(mk_link_name_attr(ctx, name));
}
ast::ForeignItem {
ident: ctx.ext_cx.ident_of(&rust_name[..]),
attrs: attrs,
node: decl,
id: ast::DUMMY_NODE_ID,
span: ctx.span,
vis: ast::Visibility::Public,
}
}
fn cty_to_rs(ctx: &mut GenCtx, ty: &Type) -> ast::Ty {
let prefix = vec!["std".to_owned(), "os".to_owned(), "raw".to_owned()];
let raw = |fragment: &str| {
let mut path = prefix.clone();
path.push(fragment.to_owned());
path
};
match *ty {
TVoid => mk_ty(ctx, true, raw("c_void")),
TInt(i, ref layout) => match i {
IBool => {
let ty_name = match layout.size {
8 => "u64",
4 => "u32",
2 => "u16",
1 | _ => "u8",
};
mk_ty(ctx, false, vec!(ty_name.to_owned()))
},
ISChar => mk_ty(ctx, true, raw("c_char")),
IUChar => mk_ty(ctx, true, raw("c_uchar")),
IInt => mk_ty(ctx, true, raw("c_int")),
IUInt => mk_ty(ctx, true, raw("c_uint")),
IShort => mk_ty(ctx, true, raw("c_short")),
IUShort => mk_ty(ctx, true, raw("c_ushort")),
ILong => mk_ty(ctx, true, raw("c_long")),
IULong => mk_ty(ctx, true, raw("c_ulong")),
ILongLong => mk_ty(ctx, true, raw("c_longlong")),
IULongLong => mk_ty(ctx, true, raw("c_ulonglong"))
},
TFloat(f, _) => match f {
FFloat => mk_ty(ctx, true, raw("c_float")),
FDouble => mk_ty(ctx, true, raw("c_double"))
},
TPtr(ref t, is_const, _) => {
let id = cty_to_rs(ctx, &**t);
mk_ptrty(ctx, id, is_const)
},
TArray(ref t, s, _) => {
let ty = cty_to_rs(ctx, &**t);
mk_arrty(ctx, &ty, s)
},
TFuncPtr(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
let unsafety = if sig.is_safe { ast::Unsafety::Normal } else { ast::Unsafety::Unsafe };
mk_fnty(ctx, &decl, unsafety, sig.abi)
},
TFuncProto(ref sig) => {
let decl = cfuncty_to_rs(ctx, &*sig.ret_ty, &sig.args[..], sig.is_variadic);
let unsafety = if sig.is_safe { ast::Unsafety::Normal } else { ast::Unsafety::Unsafe };
mk_fn_proto_ty(ctx, &decl, unsafety, sig.abi)
},
TNamed(ref ti) => {
let id = rust_type_id(ctx, &ti.borrow().name);
mk_ty(ctx, false, vec!(id))
},
TComp(ref ci) => {
let mut c = ci.borrow_mut();
c.name = unnamed_name(ctx, &c.name);
mk_ty(ctx, false, vec!(comp_name(c.kind, &c.name)))
},
TEnum(ref ei) => {
let mut e = ei.borrow_mut();
e.name = unnamed_name(ctx, &e.name);
mk_ty(ctx, false, vec!(enum_name(&e.name)))
}
}
}
fn mk_ty(ctx: &GenCtx, global: bool, segments: Vec<String>) -> ast::Ty {
let ty = ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: global,
segments: segments.iter().map(|s| {
ast::PathSegment {
identifier: ctx.ext_cx.ident_of(&s[..]),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
}
}).collect()
},
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_ptrty(ctx: &mut GenCtx, base: ast::Ty, is_const: bool) -> ast::Ty {
let mutability = if is_const {
ast::Mutability::Immutable
} else {
ast::Mutability::Mutable
};
ctx.ext_cx.ty_ptr(ctx.span, P(base), mutability).unwrap()
}
fn mk_arrty(ctx: &GenCtx, base: &ast::Ty, n: usize) -> ast::Ty {
let int_lit = ast::LitKind::Int(n as u64, ast::LitIntType::Unsigned(ast::UintTy::Us));
let sz = ast::ExprKind::Lit(P(respan(ctx.span, int_lit)));
let ty = ast::TyKind::FixedLengthVec(
P(base.clone()),
P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: sz,
span: ctx.span,
attrs: None,
})
);
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ty,
span: ctx.span
}
}
fn mk_fn_proto_ty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: unsafety,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span,
}
}
fn mk_fnty(ctx: &mut GenCtx,
decl: &ast::FnDecl,
unsafety: ast::Unsafety,
abi: abi::Abi) -> ast::Ty {
let fnty = ast::TyKind::BareFn(P(ast::BareFnTy {
unsafety: unsafety,
abi: abi,
lifetimes: Vec::new(),
decl: P(decl.clone())
}));
let segs = vec![
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("std"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::new(),
bindings: P::new(),
}),
},
ast::PathSegment {
identifier: ctx.ext_cx.ident_of("Option"),
parameters: ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::from_vec(vec!(
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
node: fnty,
span: ctx.span
})
)),
bindings: P::new(),
}),
}
];
ast::Ty {
id: ast::DUMMY_NODE_ID,
node: ast::TyKind::Path(
None,
ast::Path {
span: ctx.span,
global: true,
segments: segs
},
),
span: ctx.span
}
}
|
use std::vec::Vec;
use std::path::Path;
use std::str;
use super::git2;
use super::RepositoryConfiguration;
pub struct Repository<'repo> {
pub repository: git2::Repository,
details: &'repo RepositoryConfiguration,
}
pub struct Remote<'repo> {
pub remote: git2::Remote<'repo>,
repository: &'repo Repository<'repo>,
}
#[derive(Clone, Debug)]
pub struct RemoteHead {
pub is_local: bool,
pub oid: git2::Oid,
pub loid: git2::Oid,
pub name: String,
pub symref_target: Option<String>,
}
impl RemoteHead {
pub fn flatten(&self) -> &str {
match self.symref_target {
Some(ref s) => s,
_ => &self.name,
}
}
pub fn flatten_clone(&self) -> String {
self.flatten().to_string()
}
}
impl<'repo> Repository<'repo> {
pub fn new(repository: git2::Repository, configuration: &'repo RepositoryConfiguration) -> Repository<'repo> {
Repository {
repository: repository,
details: configuration,
}
}
pub fn clone_or_open(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
Repository::open(repo_details).or_else(|err| if err.code() == git2::ErrorCode::NotFound {
info!("Repository not found at {} -- cloning",
repo_details.checkout_path);
Repository::clone(repo_details)
} else {
Err(err)
})
}
pub fn open(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
info!("Opening repository at {}", &repo_details.checkout_path);
git2::Repository::open(&repo_details.checkout_path).and_then(|repo| Ok(Repository::new(repo, repo_details)))
}
pub fn clone(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
let remote_callbacks = Repository::remote_callbacks(repo_details);
let mut fetch_optoons = git2::FetchOptions::new();
fetch_optoons.remote_callbacks(remote_callbacks);
let mut repo_builder = git2::build::RepoBuilder::new();
repo_builder.fetch_options(fetch_optoons);
info!("Cloning repository from {} into {}",
repo_details.uri,
repo_details.checkout_path);
repo_builder.clone(&repo_details.uri, &Path::new(&repo_details.checkout_path))
.and_then(|repo| Ok(Repository::new(repo, repo_details)))
}
fn remote_callbacks(repo_details: &'repo RepositoryConfiguration) -> git2::RemoteCallbacks<'repo> {
debug!("Making remote authentication callbacks");
let mut remote_callbacks = git2::RemoteCallbacks::new();
let repo_details = repo_details.clone();
remote_callbacks.credentials(move |uri, username, cred_type| {
Repository::resolve_credentials(&repo_details, uri, username, cred_type)
})
.transfer_progress(Repository::transfer_progress_log)
.sideband_progress(Repository::sideband_progress_log)
.update_tips(Repository::update_tips_log);
remote_callbacks
}
pub fn resolve_credentials(repo_details: &RepositoryConfiguration,
_uri: &str,
username: Option<&str>,
cred_type: git2::CredentialType)
-> Result<git2::Cred, git2::Error> {
let username = username.or_else(|| match repo_details.username {
Some(ref username) => Some(username),
None => None,
});
if cred_type.intersects(git2::USERNAME) && username.is_some() {
git2::Cred::username(username.as_ref().unwrap())
} else if cred_type.intersects(git2::USER_PASS_PLAINTEXT) && username.is_some() &&
repo_details.password.is_some() {
git2::Cred::userpass_plaintext(username.as_ref().unwrap(),
repo_details.password.as_ref().unwrap())
} else if cred_type.intersects(git2::SSH_KEY) && username.is_some() {
if repo_details.key.is_some() {
git2::Cred::ssh_key(username.unwrap(),
None,
Path::new(repo_details.key.as_ref().unwrap()),
repo_details.key_passphrase.as_ref().map(|x| &**x))
} else {
git2::Cred::ssh_key_from_agent(username.unwrap())
}
} else {
let config = git2::Config::open_default()?;
git2::Cred::credential_helper(&config, &repo_details.uri, username)
}
}
pub fn transfer_progress_log(progress: git2::Progress) -> bool {
// TODO: Maybe throttle this, or update UI
if progress.received_objects() == progress.total_objects() {
debug!("Resolving deltas {}/{}\r",
progress.indexed_deltas(),
progress.total_deltas());
} else if progress.total_objects() > 0 {
debug!("Received {}/{} objects ({}) in {} bytes\r",
progress.received_objects(),
progress.total_objects(),
progress.indexed_objects(),
progress.received_bytes());
}
true
}
pub fn sideband_progress_log(data: &[u8]) -> bool {
debug!("remote: {}", str::from_utf8(data).unwrap_or(""));
true
}
pub fn update_tips_log(refname: &str, a: git2::Oid, b: git2::Oid) -> bool {
if a.is_zero() {
debug!("[new] {:20} {}", b, refname);
} else {
debug!("[updated] {:10}..{:10} {}", a, b, refname);
}
true
}
pub fn remote(&self, remote: Option<&str>) -> Result<Remote, git2::Error> {
Ok(Remote {
remote: self.repository.find_remote(&Repository::remote_name_or_default(remote))?,
repository: self,
})
}
pub fn remote_name_or_default(remote: Option<&str>) -> String {
remote.unwrap_or("origin").to_string()
}
pub fn signature(&self) -> Result<git2::Signature, git2::Error> {
if self.details.signature_name.is_some() && self.details.signature_email.is_some() {
return git2::Signature::now(self.details.signature_name.as_ref().unwrap(),
self.details.signature_email.as_ref().unwrap());
}
match self.repository.signature() {
Ok(signature) => Ok(signature),
Err(_) => git2::Signature::now("fusionner", "fusionner@github.com"),
}
}
}
impl<'repo> Remote<'repo> {
fn connect<'connection>(&'connection mut self)
-> Result<git2::RemoteConnection<'repo, 'connection, 'connection>, git2::Error> {
let callbacks = Repository::remote_callbacks(self.repository.details);
info!("Connecting to remote");
self.remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)
}
pub fn disconnect(&mut self) {
self.remote.disconnect();
}
pub fn name(&self) -> Option<&str> {
self.remote.name()
}
pub fn refspecs(&self) -> git2::Refspecs {
self.remote.refspecs()
}
pub fn remote_ls(&mut self) -> Result<Vec<RemoteHead>, git2::Error> {
let connection = self.connect()?;
info!("Retrieving remote references `git ls-remote`");
let heads = connection.list()?;
Ok(heads.iter()
.map(|head| {
RemoteHead {
is_local: head.is_local(),
oid: head.oid(),
loid: head.loid(),
name: head.name().to_string(),
symref_target: head.symref_target().map(|s| s.to_string()),
}
})
.collect())
}
// Get the remote reference of renote HEAD (i.e. default branch)
pub fn head(&mut self) -> Result<Option<String>, git2::Error> {
let connection = self.connect()?;
info!("Retrieving remote references `git ls-remote`");
let heads = connection.list()?;
Ok(Remote::resolve_head(heads))
}
// Resolve the remote HEAD (i.e. default branch) from a list of heads
// and return the remote reference
pub fn resolve_head(heads: &[git2::RemoteHead]) -> Option<String> {
heads.iter()
.find(|head| head.name() == "HEAD" && head.symref_target().is_some())
.and_then(|head| Some(head.symref_target().unwrap().to_string()))
}
pub fn fetch(&mut self, refspecs: &[&str]) -> Result<(), git2::Error> {
let mut fetch_options = git2::FetchOptions::new();
let callbacks = Repository::remote_callbacks(self.repository.details);
fetch_options.remote_callbacks(callbacks)
.prune(git2::FetchPrune::On);
debug!("Fetching {:?}", refspecs);
self.remote.fetch(refspecs, Some(&mut fetch_options), None)?;
self.remote.disconnect();
Ok(())
}
pub fn push(&mut self, refspecs: &[&str]) -> Result<(), git2::Error> {
let mut push_options = git2::PushOptions::new();
let callbacks = Repository::remote_callbacks(self.repository.details);
push_options.remote_callbacks(callbacks);
self.remote.push(refspecs, Some(&mut push_options))
}
/// For a given local reference, generate a refspec for the remote with the same path on remote
/// i.e. refs/pulls/* --> refs/pulls/*:refs/remotes/origin/pulls/*
pub fn generate_refspec(&self, src: &str, force: bool) -> Result<String, String> {
let parts: Vec<&str> = src.split('/').collect();
if parts[0] != "refs" {
return Err("Invalid reference -- does not begin with refs/".to_string());
}
let prepend = vec!["refs", "remotes", self.name().ok_or("Un-named remote")?];
let dest: Vec<&&str> = prepend.iter().chain(parts.iter().skip(1)).collect();
let dest = dest.iter().map(|s| **s).collect::<Vec<&str>>().join("/");
let force_flag = if force { "+" } else { "" };
Ok(format!("{}{}:{}", force_flag, src, dest))
}
pub fn add_refspec(&self, refspec: &str, direction: git2::Direction) -> Result<(), git2::Error> {
let remote_name = self.name().ok_or(git2::Error::from_str("Un-named remote used"))?;
info!("Checking and adding refspec {}", refspec);
if let None = Remote::find_matching_refspec(self.refspecs(), direction, refspec) {
match direction {
git2::Direction::Fetch => {
info!("No existing fetch refpec found: adding {}", refspec);
self.repository.repository.remote_add_fetch(remote_name, &refspec)
}
git2::Direction::Push => {
info!("No existing push refpec found: adding {}", refspec);
self.repository.repository.remote_add_push(remote_name, &refspec)
}
}
} else {
Ok(())
}
}
pub fn add_refspecs(&self, refspecs: &[&str], direction: git2::Direction) -> Result<(), git2::Error> {
for refspec in refspecs {
self.add_refspec(refspec, direction)?
}
Ok(())
}
pub fn resolve_target_ref(&mut self, target_ref: Option<&str>) -> Result<String, git2::Error> {
match target_ref {
Some(reference) if reference != "HEAD" => {
info!("Target Reference Specified: {}", reference);
let remote_refs = self.remote_ls()?;
if let None = remote_refs.iter().find(|head| &head.name == reference) {
return Err(git_err!(&format!("Could not find {} on remote", reference)));
}
Ok(reference.to_string())
}
None | Some(_) => {
// matches Some("HEAD")
let head = self.head()?;
if let None = head {
return Err(git_err!("Could not find a default HEAD on remote"));
}
let head = head.unwrap();
info!("Target Reference set to remote HEAD: {}", head);
Ok(head)
}
}
}
pub fn find_matching_refspec<'a>(mut refspecs: git2::Refspecs<'a>,
direction: git2::Direction,
refspec: &str)
-> Option<git2::Refspec<'a>> {
refspecs.find(|r| {
let rs = r.str();
Remote::direction_eq(&r.direction(), &direction) && rs.is_some() && rs.unwrap() == refspec
})
}
pub fn direction_eq(left: &git2::Direction, right: &git2::Direction) -> bool {
use git2::Direction::*;
match (left, right) {
(&Fetch, &Fetch) => true,
(&Push, &Push) => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::vec::Vec;
use git2;
use git2_raw;
use tempdir::TempDir;
use git::{Repository, Remote};
fn to_option_str(opt: &Option<String>) -> Option<&str> {
opt.as_ref().map(|s| &**s)
}
#[test]
fn smoke_test_opem() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
not_err!(Repository::clone_or_open(&config));
}
#[test]
fn smoke_test_clone() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
not_err!(Repository::clone_or_open(&config));
}
#[test]
fn resolve_credentials_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let test_types: HashMap<git2::CredentialType, git2_raw::git_credtype_t> =
[(git2::USERNAME, git2_raw::GIT_CREDTYPE_USERNAME),
(git2::USER_PASS_PLAINTEXT, git2_raw::GIT_CREDTYPE_USERPASS_PLAINTEXT),
(git2::SSH_KEY, git2_raw::GIT_CREDTYPE_SSH_KEY)]
.iter()
.cloned()
.collect();
for (requested_cred_type, expected_cred_type) in test_types {
let actual_cred = not_err!(Repository::resolve_credentials(&config, "", None, requested_cred_type));
assert_eq!(expected_cred_type, actual_cred.credtype());
}
}
#[test]
fn resolve_credentials_will_get_key_from_ssh_agent_in_absence_of_key() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
config.key = None;
let requested_cred_type = git2::SSH_KEY;
let expected_cred_type = git2_raw::GIT_CREDTYPE_SSH_KEY;
let actual_cred = not_err!(Repository::resolve_credentials(&config, "", None, requested_cred_type));
assert_eq!(expected_cred_type, actual_cred.credtype());
}
#[test]
fn remote_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
assert_eq!("origin", not_none!(remote.name()));
not_err!(remote.remote_ls());
not_none!(not_err!(remote.head()));
not_err!(remote.fetch(&[]));
}
#[test]
fn refspecs_are_generated_correctly() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let repo = ::test::repo_init(&config);
let remote = not_err!(repo.remote(None));
for force in [true, false].iter() {
let force_flag = if *force { "+" } else { "" };
let expected_refspec = format!("{}{}",
force_flag,
"refs/pulls/*:refs/remotes/origin/pulls/*");
assert_eq!(expected_refspec,
not_err!(remote.generate_refspec("refs/pulls/*", *force)));
}
}
#[test]
fn refspecs_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let repo = ::test::repo_init(&config);
let remote = not_err!(repo.remote(None));
let refspec = not_err!(remote.generate_refspec("refs/pulls/*", true));
not_err!(remote.add_refspec(&refspec, git2::Direction::Push));
not_err!(remote.add_refspec(&refspec, git2::Direction::Fetch));
let remote = not_err!(repo.remote(None)); // new remote object with "refreshed" refspecs
for refspec in remote.refspecs() {
println!("{}", refspec.str().unwrap());
}
not_none!(Remote::find_matching_refspec(remote.refspecs(), git2::Direction::Push, &refspec));
not_none!(Remote::find_matching_refspec(remote.refspecs(), git2::Direction::Fetch, &refspec));
}
#[test]
fn directions_are_eq_correctly() {
let test_values: Vec<(git2::Direction, git2::Direction, bool)> =
vec![(git2::Direction::Fetch, git2::Direction::Fetch, true),
(git2::Direction::Push, git2::Direction::Push, true),
(git2::Direction::Push, git2::Direction::Fetch, false),
(git2::Direction::Fetch, git2::Direction::Push, false)];
for (left, right, expected_result) in test_values {
assert_eq!(expected_result, Remote::direction_eq(&left, &right));
}
}
#[test]
fn target_ref_is_resolved_to_head_by_default() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
let target_ref = not_err!(remote.resolve_target_ref(None));
assert_eq!("refs/heads/master", target_ref);
}
#[test]
fn target_ref_is_resolved_correctly() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let target_ref = Some("refs/heads/master".to_string());
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
let target_ref = not_err!(remote.resolve_target_ref(to_option_str(&target_ref)));
assert_eq!("refs/heads/master", target_ref);
}
#[test]
fn invalid_target_ref_should_error() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let target_ref = Some("refs/heads/unknown".to_string());
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
is_err!(remote.resolve_target_ref(to_option_str(&target_ref)));
}
}
Update tips after fetching
use std::vec::Vec;
use std::path::Path;
use std::str;
use super::git2;
use super::RepositoryConfiguration;
pub struct Repository<'repo> {
pub repository: git2::Repository,
details: &'repo RepositoryConfiguration,
}
pub struct Remote<'repo> {
pub remote: git2::Remote<'repo>,
repository: &'repo Repository<'repo>,
}
#[derive(Clone, Debug)]
pub struct RemoteHead {
pub is_local: bool,
pub oid: git2::Oid,
pub loid: git2::Oid,
pub name: String,
pub symref_target: Option<String>,
}
impl RemoteHead {
pub fn flatten(&self) -> &str {
match self.symref_target {
Some(ref s) => s,
_ => &self.name,
}
}
pub fn flatten_clone(&self) -> String {
self.flatten().to_string()
}
}
impl<'repo> Repository<'repo> {
pub fn new(repository: git2::Repository, configuration: &'repo RepositoryConfiguration) -> Repository<'repo> {
Repository {
repository: repository,
details: configuration,
}
}
pub fn clone_or_open(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
Repository::open(repo_details).or_else(|err| if err.code() == git2::ErrorCode::NotFound {
info!("Repository not found at {} -- cloning",
repo_details.checkout_path);
Repository::clone(repo_details)
} else {
Err(err)
})
}
pub fn open(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
info!("Opening repository at {}", &repo_details.checkout_path);
git2::Repository::open(&repo_details.checkout_path).and_then(|repo| Ok(Repository::new(repo, repo_details)))
}
pub fn clone(repo_details: &'repo RepositoryConfiguration) -> Result<Repository<'repo>, git2::Error> {
let remote_callbacks = Repository::remote_callbacks(repo_details);
let mut fetch_optoons = git2::FetchOptions::new();
fetch_optoons.remote_callbacks(remote_callbacks);
let mut repo_builder = git2::build::RepoBuilder::new();
repo_builder.fetch_options(fetch_optoons);
info!("Cloning repository from {} into {}",
repo_details.uri,
repo_details.checkout_path);
repo_builder.clone(&repo_details.uri, &Path::new(&repo_details.checkout_path))
.and_then(|repo| Ok(Repository::new(repo, repo_details)))
}
fn remote_callbacks(repo_details: &'repo RepositoryConfiguration) -> git2::RemoteCallbacks<'repo> {
debug!("Making remote authentication callbacks");
let mut remote_callbacks = git2::RemoteCallbacks::new();
let repo_details = repo_details.clone();
remote_callbacks.credentials(move |uri, username, cred_type| {
Repository::resolve_credentials(&repo_details, uri, username, cred_type)
})
.transfer_progress(Repository::transfer_progress_log)
.sideband_progress(Repository::sideband_progress_log)
.update_tips(Repository::update_tips_log);
remote_callbacks
}
pub fn resolve_credentials(repo_details: &RepositoryConfiguration,
_uri: &str,
username: Option<&str>,
cred_type: git2::CredentialType)
-> Result<git2::Cred, git2::Error> {
let username = username.or_else(|| match repo_details.username {
Some(ref username) => Some(username),
None => None,
});
if cred_type.intersects(git2::USERNAME) && username.is_some() {
git2::Cred::username(username.as_ref().unwrap())
} else if cred_type.intersects(git2::USER_PASS_PLAINTEXT) && username.is_some() &&
repo_details.password.is_some() {
git2::Cred::userpass_plaintext(username.as_ref().unwrap(),
repo_details.password.as_ref().unwrap())
} else if cred_type.intersects(git2::SSH_KEY) && username.is_some() {
if repo_details.key.is_some() {
git2::Cred::ssh_key(username.unwrap(),
None,
Path::new(repo_details.key.as_ref().unwrap()),
repo_details.key_passphrase.as_ref().map(|x| &**x))
} else {
git2::Cred::ssh_key_from_agent(username.unwrap())
}
} else {
let config = git2::Config::open_default()?;
git2::Cred::credential_helper(&config, &repo_details.uri, username)
}
}
pub fn transfer_progress_log(progress: git2::Progress) -> bool {
// TODO: Maybe throttle this, or update UI
if progress.received_objects() == progress.total_objects() {
debug!("Resolving deltas {}/{}\r",
progress.indexed_deltas(),
progress.total_deltas());
} else if progress.total_objects() > 0 {
debug!("Received {}/{} objects ({}) in {} bytes\r",
progress.received_objects(),
progress.total_objects(),
progress.indexed_objects(),
progress.received_bytes());
}
true
}
pub fn sideband_progress_log(data: &[u8]) -> bool {
debug!("remote: {}", str::from_utf8(data).unwrap_or(""));
true
}
pub fn update_tips_log(refname: &str, a: git2::Oid, b: git2::Oid) -> bool {
if a.is_zero() {
debug!("[new] {:20} {}", b, refname);
} else {
debug!("[updated] {:10}..{:10} {}", a, b, refname);
}
true
}
pub fn remote(&self, remote: Option<&str>) -> Result<Remote, git2::Error> {
Ok(Remote {
remote: self.repository.find_remote(&Repository::remote_name_or_default(remote))?,
repository: self,
})
}
pub fn remote_name_or_default(remote: Option<&str>) -> String {
remote.unwrap_or("origin").to_string()
}
pub fn signature(&self) -> Result<git2::Signature, git2::Error> {
if self.details.signature_name.is_some() && self.details.signature_email.is_some() {
return git2::Signature::now(self.details.signature_name.as_ref().unwrap(),
self.details.signature_email.as_ref().unwrap());
}
match self.repository.signature() {
Ok(signature) => Ok(signature),
Err(_) => git2::Signature::now("fusionner", "fusionner@github.com"),
}
}
}
impl<'repo> Remote<'repo> {
fn connect<'connection>(&'connection mut self)
-> Result<git2::RemoteConnection<'repo, 'connection, 'connection>, git2::Error> {
let callbacks = Repository::remote_callbacks(self.repository.details);
info!("Connecting to remote");
self.remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)
}
pub fn disconnect(&mut self) {
self.remote.disconnect();
}
pub fn name(&self) -> Option<&str> {
self.remote.name()
}
pub fn refspecs(&self) -> git2::Refspecs {
self.remote.refspecs()
}
pub fn remote_ls(&mut self) -> Result<Vec<RemoteHead>, git2::Error> {
let connection = self.connect()?;
info!("Retrieving remote references `git ls-remote`");
let heads = connection.list()?;
Ok(heads.iter()
.map(|head| {
RemoteHead {
is_local: head.is_local(),
oid: head.oid(),
loid: head.loid(),
name: head.name().to_string(),
symref_target: head.symref_target().map(|s| s.to_string()),
}
})
.collect())
}
// Get the remote reference of renote HEAD (i.e. default branch)
pub fn head(&mut self) -> Result<Option<String>, git2::Error> {
let connection = self.connect()?;
info!("Retrieving remote references `git ls-remote`");
let heads = connection.list()?;
Ok(Remote::resolve_head(heads))
}
// Resolve the remote HEAD (i.e. default branch) from a list of heads
// and return the remote reference
pub fn resolve_head(heads: &[git2::RemoteHead]) -> Option<String> {
heads.iter()
.find(|head| head.name() == "HEAD" && head.symref_target().is_some())
.and_then(|head| Some(head.symref_target().unwrap().to_string()))
}
pub fn fetch(&mut self, refspecs: &[&str]) -> Result<(), git2::Error> {
let mut fetch_options = git2::FetchOptions::new();
let callbacks = Repository::remote_callbacks(self.repository.details);
fetch_options.remote_callbacks(callbacks)
.prune(git2::FetchPrune::On);
debug!("Fetching {:?}", refspecs);
self.remote.fetch(refspecs, Some(&mut fetch_options), None)?;
let mut callbacks = Repository::remote_callbacks(self.repository.details);
self.remote.update_tips(Some(&mut callbacks), true, git2::AutotagOption::Unspecified, None)?;
self.remote.disconnect();
Ok(())
}
pub fn push(&mut self, refspecs: &[&str]) -> Result<(), git2::Error> {
let mut push_options = git2::PushOptions::new();
let callbacks = Repository::remote_callbacks(self.repository.details);
push_options.remote_callbacks(callbacks);
self.remote.push(refspecs, Some(&mut push_options))
}
/// For a given local reference, generate a refspec for the remote with the same path on remote
/// i.e. refs/pulls/* --> refs/pulls/*:refs/remotes/origin/pulls/*
pub fn generate_refspec(&self, src: &str, force: bool) -> Result<String, String> {
let parts: Vec<&str> = src.split('/').collect();
if parts[0] != "refs" {
return Err("Invalid reference -- does not begin with refs/".to_string());
}
let prepend = vec!["refs", "remotes", self.name().ok_or("Un-named remote")?];
let dest: Vec<&&str> = prepend.iter().chain(parts.iter().skip(1)).collect();
let dest = dest.iter().map(|s| **s).collect::<Vec<&str>>().join("/");
let force_flag = if force { "+" } else { "" };
Ok(format!("{}{}:{}", force_flag, src, dest))
}
pub fn add_refspec(&self, refspec: &str, direction: git2::Direction) -> Result<(), git2::Error> {
let remote_name = self.name().ok_or(git2::Error::from_str("Un-named remote used"))?;
info!("Checking and adding refspec {}", refspec);
if let None = Remote::find_matching_refspec(self.refspecs(), direction, refspec) {
match direction {
git2::Direction::Fetch => {
info!("No existing fetch refpec found: adding {}", refspec);
self.repository.repository.remote_add_fetch(remote_name, &refspec)
}
git2::Direction::Push => {
info!("No existing push refpec found: adding {}", refspec);
self.repository.repository.remote_add_push(remote_name, &refspec)
}
}
} else {
Ok(())
}
}
pub fn add_refspecs(&self, refspecs: &[&str], direction: git2::Direction) -> Result<(), git2::Error> {
for refspec in refspecs {
self.add_refspec(refspec, direction)?
}
Ok(())
}
pub fn resolve_target_ref(&mut self, target_ref: Option<&str>) -> Result<String, git2::Error> {
match target_ref {
Some(reference) if reference != "HEAD" => {
info!("Target Reference Specified: {}", reference);
let remote_refs = self.remote_ls()?;
if let None = remote_refs.iter().find(|head| &head.name == reference) {
return Err(git_err!(&format!("Could not find {} on remote", reference)));
}
Ok(reference.to_string())
}
None | Some(_) => {
// matches Some("HEAD")
let head = self.head()?;
if let None = head {
return Err(git_err!("Could not find a default HEAD on remote"));
}
let head = head.unwrap();
info!("Target Reference set to remote HEAD: {}", head);
Ok(head)
}
}
}
pub fn find_matching_refspec<'a>(mut refspecs: git2::Refspecs<'a>,
direction: git2::Direction,
refspec: &str)
-> Option<git2::Refspec<'a>> {
refspecs.find(|r| {
let rs = r.str();
Remote::direction_eq(&r.direction(), &direction) && rs.is_some() && rs.unwrap() == refspec
})
}
pub fn direction_eq(left: &git2::Direction, right: &git2::Direction) -> bool {
use git2::Direction::*;
match (left, right) {
(&Fetch, &Fetch) => true,
(&Push, &Push) => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::vec::Vec;
use git2;
use git2_raw;
use tempdir::TempDir;
use git::{Repository, Remote};
fn to_option_str(opt: &Option<String>) -> Option<&str> {
opt.as_ref().map(|s| &**s)
}
#[test]
fn smoke_test_opem() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
not_err!(Repository::clone_or_open(&config));
}
#[test]
fn smoke_test_clone() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
not_err!(Repository::clone_or_open(&config));
}
#[test]
fn resolve_credentials_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let test_types: HashMap<git2::CredentialType, git2_raw::git_credtype_t> =
[(git2::USERNAME, git2_raw::GIT_CREDTYPE_USERNAME),
(git2::USER_PASS_PLAINTEXT, git2_raw::GIT_CREDTYPE_USERPASS_PLAINTEXT),
(git2::SSH_KEY, git2_raw::GIT_CREDTYPE_SSH_KEY)]
.iter()
.cloned()
.collect();
for (requested_cred_type, expected_cred_type) in test_types {
let actual_cred = not_err!(Repository::resolve_credentials(&config, "", None, requested_cred_type));
assert_eq!(expected_cred_type, actual_cred.credtype());
}
}
#[test]
fn resolve_credentials_will_get_key_from_ssh_agent_in_absence_of_key() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
config.key = None;
let requested_cred_type = git2::SSH_KEY;
let expected_cred_type = git2_raw::GIT_CREDTYPE_SSH_KEY;
let actual_cred = not_err!(Repository::resolve_credentials(&config, "", None, requested_cred_type));
assert_eq!(expected_cred_type, actual_cred.credtype());
}
#[test]
fn remote_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
assert_eq!("origin", not_none!(remote.name()));
not_err!(remote.remote_ls());
not_none!(not_err!(remote.head()));
not_err!(remote.fetch(&[]));
}
#[test]
fn refspecs_are_generated_correctly() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let repo = ::test::repo_init(&config);
let remote = not_err!(repo.remote(None));
for force in [true, false].iter() {
let force_flag = if *force { "+" } else { "" };
let expected_refspec = format!("{}{}",
force_flag,
"refs/pulls/*:refs/remotes/origin/pulls/*");
assert_eq!(expected_refspec,
not_err!(remote.generate_refspec("refs/pulls/*", *force)));
}
}
#[test]
fn refspecs_smoke_test() {
let (td, _raw) = ::test::raw_repo_init();
let config = ::test::config_init(&td);
let repo = ::test::repo_init(&config);
let remote = not_err!(repo.remote(None));
let refspec = not_err!(remote.generate_refspec("refs/pulls/*", true));
not_err!(remote.add_refspec(&refspec, git2::Direction::Push));
not_err!(remote.add_refspec(&refspec, git2::Direction::Fetch));
let remote = not_err!(repo.remote(None)); // new remote object with "refreshed" refspecs
for refspec in remote.refspecs() {
println!("{}", refspec.str().unwrap());
}
not_none!(Remote::find_matching_refspec(remote.refspecs(), git2::Direction::Push, &refspec));
not_none!(Remote::find_matching_refspec(remote.refspecs(), git2::Direction::Fetch, &refspec));
}
#[test]
fn directions_are_eq_correctly() {
let test_values: Vec<(git2::Direction, git2::Direction, bool)> =
vec![(git2::Direction::Fetch, git2::Direction::Fetch, true),
(git2::Direction::Push, git2::Direction::Push, true),
(git2::Direction::Push, git2::Direction::Fetch, false),
(git2::Direction::Fetch, git2::Direction::Push, false)];
for (left, right, expected_result) in test_values {
assert_eq!(expected_result, Remote::direction_eq(&left, &right));
}
}
#[test]
fn target_ref_is_resolved_to_head_by_default() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
let target_ref = not_err!(remote.resolve_target_ref(None));
assert_eq!("refs/heads/master", target_ref);
}
#[test]
fn target_ref_is_resolved_correctly() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let target_ref = Some("refs/heads/master".to_string());
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
let target_ref = not_err!(remote.resolve_target_ref(to_option_str(&target_ref)));
assert_eq!("refs/heads/master", target_ref);
}
#[test]
fn invalid_target_ref_should_error() {
let (td, _raw) = ::test::raw_repo_init();
let mut config = ::test::config_init(&td);
let target_ref = Some("refs/heads/unknown".to_string());
let td_new = TempDir::new("test").unwrap();
config.checkout_path = not_none!(td_new.path().to_str()).to_string();
let repo = not_err!(Repository::clone_or_open(&config));
let mut remote = not_err!(repo.remote(None));
is_err!(remote.resolve_target_ref(to_option_str(&target_ref)));
}
}
|
use std::fs::File;
use std::io::{Read, Seek, Cursor};
use std::io::{SeekFrom, Error, ErrorKind};
use std::convert::AsMut;
extern crate uuid;
extern crate byteorder;
use self::byteorder::{LittleEndian, ReadBytesExt, BigEndian};
use self::uuid::Uuid;
#[derive(Debug)]
pub struct Header {
pub signature: String, // EFI PART
pub revision: u32, // 00 00 01 00
pub header_size_le: u32, // little endian
pub crc32: u32,
pub reserved: u32, // must be 0
pub current_lba: u64,
pub backup_lba: u64,
pub first_usable: u64,
pub last_usable: u64,
pub disk_guid: uuid::Uuid,
pub start_lba: u64,
pub num_parts: u32,
pub part_size: u32, // usually 128
pub crc32_parts: u32,
}
fn parse_uuid(rdr: &mut Cursor<&[u8]>) -> Result<Uuid, Error> {
//let mut rdr = Cursor::new(bytes);
let d1: u32 = rdr.read_u32::<LittleEndian>()?;
let d2: u16 = rdr.read_u16::<LittleEndian>()?;
let d3: u16 = rdr.read_u16::<LittleEndian>()?;
match Uuid::from_fields(d1, d2, d3, &rdr.get_ref()[8..]) {
Ok(uuid) => Ok(uuid),
Err(_) => Err(Error::new(ErrorKind::Other, "Invalid Disk UUID?")),
}
}
pub fn read_header2(path: &String) -> Result<Header, Error> {
let mut file = File::open(path)?;
let _ = file.seek(SeekFrom::Start(512));
let mut hdr: [u8; 92] = [0; 92];
let _ = file.read_exact(&mut hdr);
let mut reader = Cursor::new(&hdr[..]);
let sigstr = reader.read_u64::<LittleEndian>()?.to_string();
if sigstr != "EFI PART" {
return Err(Error::new(ErrorKind::Other, "Invalid GPT Signature."));
};
let h = Header {
signature: sigstr.to_string(),
revision: reader.read_u32::<LittleEndian>()?,
header_size_le: reader.read_u32::<LittleEndian>()?,
crc32: reader.read_u32::<LittleEndian>()?,
reserved: reader.read_u32::<LittleEndian>()?,
current_lba: reader.read_u64::<LittleEndian>()?,
backup_lba: reader.read_u64::<LittleEndian>()?,
first_usable: reader.read_u64::<LittleEndian>()?,
last_usable: reader.read_u64::<LittleEndian>()?,
disk_guid: parse_uuid(&mut reader)?,
start_lba: reader.read_u64::<LittleEndian>()?,
num_parts: reader.read_u32::<LittleEndian>()?,
part_size: reader.read_u32::<LittleEndian>()?,
crc32_parts: reader.read_u32::<LittleEndian>()?,
};
Ok(h)
}
/*
pub fn read_header(path:&String) -> Result<Header, Error>
{
let mut file = File::open(path)?;
let _ = file.seek(SeekFrom::Start(512))?;
let mut signature: [u8;8] = [0;8];
let _ = file.read_exact(&mut signature);
let sigstr = String::from_utf8_lossy(&signature);
if sigstr.as_ref() != "EFI PART" { return Err(Error::new(ErrorKind::Other,
"Invalid GPT Signature")) };
let mut revision: [u8; 4] = [0; 4];
let mut header_size_le: [u8;4] = [0; 4];
let mut crc32: [u8;4] = [0; 4];
let mut reserved: [u8;4] = [0; 4];
let mut current_lba: [u8;8] = [0; 8];
let mut backup_lba: [u8;8] = [0; 8];
let mut first_usable: [u8;8] = [0; 8];
let mut last_usable: [u8;8] = [0; 8];
let mut disk_guid: [u8;16] = [0; 16];
let mut start_lba: [u8; 8] = [0; 8];
let mut num_parts: [u8; 4] = [0; 4];
let mut part_size: [u8; 4]= [0; 4];
let mut crc32_parts: [u8; 4] = [0; 4];
let _ = file.read_exact(&mut revision);
let _ = file.read_exact(&mut header_size_le);
let _ = file.read_exact(&mut crc32);
let _ = file.read_exact(&mut reserved);
let _ = file.read_exact(&mut current_lba);
let _ = file.read_exact(&mut backup_lba);
let _ = file.read_exact(&mut first_usable);
let _ = file.read_exact(&mut last_usable);
let _ = file.read_exact(&mut disk_guid);
let _ = file.read_exact(&mut start_lba);
let _ = file.read_exact(&mut num_parts);
let _ = file.read_exact(&mut part_size);
let _ = file.read_exact(&mut crc32_parts);
return Ok(Header{
signature: signature,
revision: revision,
header_size_le: header_size_le,
crc32: crc32,
reserved: reserved,
current_lba: current_lba,
backup_lba: backup_lba,
first_usable: first_usable,
last_usable: last_usable,
disk_guid: parse_uuid(&disk_guid)?,
start_lba: start_lba,
num_parts: num_parts,
part_size: part_size,
crc32_parts: crc32_parts
});
}
*/
Remove unused import
use std::fs::File;
use std::io::{Read, Seek, Cursor};
use std::io::{SeekFrom, Error, ErrorKind};
extern crate uuid;
extern crate byteorder;
use self::byteorder::{LittleEndian, ReadBytesExt, BigEndian};
use self::uuid::Uuid;
#[derive(Debug)]
pub struct Header {
pub signature: String, // EFI PART
pub revision: u32, // 00 00 01 00
pub header_size_le: u32, // little endian
pub crc32: u32,
pub reserved: u32, // must be 0
pub current_lba: u64,
pub backup_lba: u64,
pub first_usable: u64,
pub last_usable: u64,
pub disk_guid: uuid::Uuid,
pub start_lba: u64,
pub num_parts: u32,
pub part_size: u32, // usually 128
pub crc32_parts: u32,
}
fn parse_uuid(rdr: &mut Cursor<&[u8]>) -> Result<Uuid, Error> {
//let mut rdr = Cursor::new(bytes);
let d1: u32 = rdr.read_u32::<LittleEndian>()?;
let d2: u16 = rdr.read_u16::<LittleEndian>()?;
let d3: u16 = rdr.read_u16::<LittleEndian>()?;
match Uuid::from_fields(d1, d2, d3, &rdr.get_ref()[8..]) {
Ok(uuid) => Ok(uuid),
Err(_) => Err(Error::new(ErrorKind::Other, "Invalid Disk UUID?")),
}
}
pub fn read_header2(path: &String) -> Result<Header, Error> {
let mut file = File::open(path)?;
let _ = file.seek(SeekFrom::Start(512));
let mut hdr: [u8; 92] = [0; 92];
let _ = file.read_exact(&mut hdr);
let mut reader = Cursor::new(&hdr[..]);
let sigstr = reader.read_u64::<LittleEndian>()?.to_string();
if sigstr != "EFI PART" {
return Err(Error::new(ErrorKind::Other, "Invalid GPT Signature."));
};
let h = Header {
signature: sigstr.to_string(),
revision: reader.read_u32::<LittleEndian>()?,
header_size_le: reader.read_u32::<LittleEndian>()?,
crc32: reader.read_u32::<LittleEndian>()?,
reserved: reader.read_u32::<LittleEndian>()?,
current_lba: reader.read_u64::<LittleEndian>()?,
backup_lba: reader.read_u64::<LittleEndian>()?,
first_usable: reader.read_u64::<LittleEndian>()?,
last_usable: reader.read_u64::<LittleEndian>()?,
disk_guid: parse_uuid(&mut reader)?,
start_lba: reader.read_u64::<LittleEndian>()?,
num_parts: reader.read_u32::<LittleEndian>()?,
part_size: reader.read_u32::<LittleEndian>()?,
crc32_parts: reader.read_u32::<LittleEndian>()?,
};
Ok(h)
}
/*
pub fn read_header(path:&String) -> Result<Header, Error>
{
let mut file = File::open(path)?;
let _ = file.seek(SeekFrom::Start(512))?;
let mut signature: [u8;8] = [0;8];
let _ = file.read_exact(&mut signature);
let sigstr = String::from_utf8_lossy(&signature);
if sigstr.as_ref() != "EFI PART" { return Err(Error::new(ErrorKind::Other,
"Invalid GPT Signature")) };
let mut revision: [u8; 4] = [0; 4];
let mut header_size_le: [u8;4] = [0; 4];
let mut crc32: [u8;4] = [0; 4];
let mut reserved: [u8;4] = [0; 4];
let mut current_lba: [u8;8] = [0; 8];
let mut backup_lba: [u8;8] = [0; 8];
let mut first_usable: [u8;8] = [0; 8];
let mut last_usable: [u8;8] = [0; 8];
let mut disk_guid: [u8;16] = [0; 16];
let mut start_lba: [u8; 8] = [0; 8];
let mut num_parts: [u8; 4] = [0; 4];
let mut part_size: [u8; 4]= [0; 4];
let mut crc32_parts: [u8; 4] = [0; 4];
let _ = file.read_exact(&mut revision);
let _ = file.read_exact(&mut header_size_le);
let _ = file.read_exact(&mut crc32);
let _ = file.read_exact(&mut reserved);
let _ = file.read_exact(&mut current_lba);
let _ = file.read_exact(&mut backup_lba);
let _ = file.read_exact(&mut first_usable);
let _ = file.read_exact(&mut last_usable);
let _ = file.read_exact(&mut disk_guid);
let _ = file.read_exact(&mut start_lba);
let _ = file.read_exact(&mut num_parts);
let _ = file.read_exact(&mut part_size);
let _ = file.read_exact(&mut crc32_parts);
return Ok(Header{
signature: signature,
revision: revision,
header_size_le: header_size_le,
crc32: crc32,
reserved: reserved,
current_lba: current_lba,
backup_lba: backup_lba,
first_usable: first_usable,
last_usable: last_usable,
disk_guid: parse_uuid(&disk_guid)?,
start_lba: start_lba,
num_parts: num_parts,
part_size: part_size,
crc32_parts: crc32_parts
});
}
*/
|
// Copyright 2015 The Ramp Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std;
use std::cmp::{
Ordering,
Ord, Eq,
PartialOrd, PartialEq
};
use std::error::Error;
use std::{fmt, hash};
use std::io;
use std::num::Zero;
use std::ops::{
Add, Sub, Mul, Div, Rem, Neg,
AddAssign, SubAssign, MulAssign, DivAssign, RemAssign,
Shl, Shr, BitAnd, BitOr,
ShlAssign, ShrAssign, BitAndAssign, BitOrAssign,
};
use std::ptr::Unique;
use std::str::FromStr;
use rand::Rng;
use alloc;
use ll;
use ll::limb::{BaseInt, Limb};
use alloc::raw_vec::RawVec;
/**
* An arbitrary-precision signed integer.
*
* This type grows to the size it needs to in order to store the result of any operation.
*
* ## Creation
*
* An `Int` can be constructed in a number of ways:
*
* - `Int::zero` and `Int::one` construct a zero- and one-valued `Int` respectively.
*
* - `Int::from` will convert from any primitive integer type to an `Int` of the same value
*
* ```
* # use ramp::Int;
* let four = Int::from(4);
* ```
*
* - `Int::from_str` (or `str::parse`) will attempt to convert from a string to an `Int`
*
* ```
* # use ramp::Int;
* # use std::str::FromStr;
* let i = Int::from_str("123456789").unwrap();
* ```
*
* ## Output
*
* `Int` supports all the formatting traits, allowing it to be used just like a regular integer
* when used in `format!` and similar macros. `Int` also supports conversion to primitive integer
* types, truncating if the `Int` cannot fit into the target type. Conversion to primtive integers
* is done with the `From` trait:
*
* ```
* # use ramp::Int;
* let big_i = Int::from(123456789);
* let i = i32::from(&big_i);
* assert_eq!(123456789, i);
* ```
*
* ## Usage
*
* `Int` has a number of operator overloads to make working with them as painless as possible.
*
* The most basic usage is simply `a + b` or similar. Assuming `a` and `b` are of type `Int`, this
* operation will consume both operands, reusing the storage from one of them. If you do not wish
* your operands to be moved, one or both of them can be references: `&a + &b` works as well, but
* requires an entire new `Int` to be allocated for the return value.
*
* There are also a overloads for a small number of primitive integer types, namely `i32` and
* `usize`. While automatic type widening isn't done in Rust in general, many operations are much
* more efficient when working with a single integer. This means you can do `a + 1` knowing that it
* will be performed as efficiently as possible. Comparison with these integer types is also
* possible, allowing checks for small constant values to be done easily:
*
* ```
* # use ramp::Int;
* let big_i = Int::from(123456789);
* assert!(big_i == 123456789);
* ```
*
* ### Semantics
*
* Addition, subtraction and multiplication follow the expected rules for integers. Division of two
* integers, `N / D` is defined as producing two values: a quotient, `Q`, and a remainder, `R`,
* such that the following equation holds: `N = Q*D + R`. The division operator itself returns `Q`
* while the remainder/modulo operator returns `R`.
*
* The "bit-shift" operations are defined as being multiplication and division by a power-of-two for
* shift-left and shift-right respectively. The sign of the number is unaffected.
*
* The remaining bitwise operands act as if the numbers are stored in two's complement format and as
* if the two inputs have the same number of bits.
*
*/
pub struct Int {
ptr: Unique<Limb>,
size: i32,
cap: u32
}
impl Int {
pub fn zero() -> Int {
<Int as Zero>::zero()
}
pub fn one() -> Int {
<Int as std::num::One>::one()
}
/// Creates a new Int from the given Limb.
pub fn from_single_limb(limb: Limb) -> Int {
let mut i = Int::with_capacity(1);
unsafe {
*i.ptr.get_mut() = limb;
}
i.size = 1;
i
}
/**
* Views the internal memory as a `RawVec`, which can be
* manipulated to change `self`'s allocation.
*/
fn with_raw_vec<F: FnOnce(&mut RawVec<Limb>)>(&mut self, f: F) {
unsafe {
let old_cap = self.cap as usize;
let mut vec = RawVec::from_raw_parts(self.ptr.get_mut(), old_cap);
// if `f` panics, let `vec` do the cleaning up, not self.
self.cap = 0;
f(&mut vec);
// update `self` for any changes that happened
self.ptr = Unique::new(vec.ptr());
let new_cap = vec.cap();
assert!(new_cap <= std::u32::MAX as usize);
self.cap = new_cap as u32;
// ownership has transferred back into `self`, so make
// sure that allocation isn't freed by `vec`.
std::mem::forget(vec);
if old_cap < new_cap {
// the allocation got larger, new Limbs should be
// zero.
let self_ptr = self.ptr.get_mut() as *mut _;
std::ptr::write_bytes(self_ptr.offset(old_cap as isize) as *mut u8,
0,
(new_cap - old_cap) * std::mem::size_of::<Limb>());
}
}
}
fn with_capacity(cap: u32) -> Int {
let mut ret = Int::zero();
if cap != 0 {
ret.with_raw_vec(|v| v.reserve_exact(0, cap as usize))
}
ret
}
/**
* Returns the sign of the Int as either -1, 0 or 1 for self being negative, zero
* or positive, respectively.
*/
#[inline(always)]
pub fn sign(&self) -> i32 {
if self.size == 0 {
0
} else if self.size < 0 {
-1
} else {
1
}
}
/**
* Consumes self and returns the absolute value
*/
#[inline]
pub fn abs(mut self) -> Int {
self.size = self.size.abs();
self
}
/**
* Returns the least-significant limb of self.
*/
#[inline]
pub fn to_single_limb(&self) -> Limb {
if self.sign() == 0 {
return Limb(0);
} else {
return unsafe { *self.ptr.get() };
}
}
#[inline(always)]
fn abs_size(&self) -> i32 {
self.size.abs()
}
/**
* Compare the absolute value of self to the absolute value of other,
* returning an Ordering with the result.
*/
pub fn abs_cmp(&self, other: &Int) -> Ordering {
if self.abs_size() > other.abs_size() {
Ordering::Greater
} else if self.abs_size() < other.abs_size() {
Ordering::Less
} else {
unsafe {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size())
}
}
}
/**
* Try to shrink the allocated data for this Int.
*/
pub fn shrink_to_fit(&mut self) {
let mut size = self.abs_size() as usize;
if (self.cap as usize) == size { return; } // already as small as possible
if size == 0 { size = 1; } // Keep space for at least one limb around
self.with_raw_vec(|v| {
v.shrink_to_fit(size);
})
}
/**
* Returns a string containing the value of self in base `base`. For bases greater than
* ten, if `upper` is true, upper-case letters are used, otherwise lower-case ones are used.
*
* Panics if `base` is less than two or greater than 36.
*/
pub fn to_str_radix(&self, base: u8, upper: bool) -> String {
if self.size == 0 {
return "0".to_string();
}
if base < 2 || base > 36 {
panic!("Invalid base: {}", base);
}
let size = self.abs_size();
let num_digits = unsafe {
ll::base::num_base_digits(self.ptr.get(), size - 1, base as u32)
};
let mut buf : Vec<u8> = Vec::with_capacity(num_digits);
self.write_radix(&mut buf, base, upper).unwrap();
unsafe { String::from_utf8_unchecked(buf) }
}
pub fn write_radix<W: io::Write>(&self, w: &mut W, base: u8, upper: bool) -> io::Result<()> {
debug_assert!(self.well_formed());
if self.sign() == -1 {
try!(w.write_all(b"-"));
}
let letter = if upper { b'A' } else { b'a' };
let size = self.abs_size();
unsafe {
ll::base::to_base(base as u32, self.ptr.get(), size, |b| {
if b < 10 {
w.write_all(&[b + b'0']).unwrap();
} else {
w.write_all(&[(b - 10) + letter]).unwrap();
}
});
}
Ok(())
}
/**
* Creates a new Int from the given string in base `base`.
*/
pub fn from_str_radix(mut src: &str, base: u8) -> Result<Int, ParseIntError> {
if base < 2 || base > 36 {
panic!("Invalid base: {}", base);
}
if src.len() == 0 {
return Err(ParseIntError { kind: ErrorKind::Empty });
}
let mut sign = 1;
if src.starts_with('-') {
sign = -1;
src = &src[1..];
}
if src.len() == 0 {
return Err(ParseIntError { kind: ErrorKind::Empty });
}
let mut buf = Vec::with_capacity(src.len());
for c in src.bytes() {
let b = match c {
b'0'...b'9' => c - b'0',
b'A'...b'Z' => (c - b'A') + 10,
b'a'...b'z' => (c - b'a') + 10,
_ => {
return Err(ParseIntError { kind: ErrorKind::InvalidDigit });
}
};
if b >= base { return Err(ParseIntError { kind: ErrorKind::InvalidDigit }); }
buf.push(b);
}
let num_digits = ll::base::base_digits_to_len(src.len(), base as u32);
let mut i = Int::with_capacity(num_digits as u32);
unsafe {
let size = ll::base::from_base(i.ptr.get_mut(), buf.as_ptr(), buf.len() as i32, base as u32);
i.size = (size as i32) * sign;
}
Ok(i)
}
/**
* Divide self by other, returning the quotient, Q, and remainder, R as (Q, R).
*
* With N = self, D = other, Q and R satisfy: `N = QD + R`.
*/
pub fn divmod(&self, other: &Int) -> (Int, Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
let out_size = if self.abs_size() < other.abs_size() {
1
} else {
(self.abs_size() - other.abs_size()) + 1
};
let out_sign = self.sign() * other.sign();
let mut q = Int::with_capacity(out_size as u32);
q.size = out_size * out_sign;
let mut r = Int::with_capacity(other.abs_size() as u32);
r.size = other.abs_size() * self.sign();
unsafe {
ll::divrem(q.ptr.get_mut(), r.ptr.get_mut(),
self.ptr.get(), self.abs_size(),
other.ptr.get(), other.abs_size());
}
q.normalize();
r.normalize();
(q, r)
}
/**
* Raises self to the power of exp
*/
pub fn pow(&self, exp: usize) -> Int {
debug_assert!(self.well_formed());
match exp {
0 => Int::one(),
1 => self.clone(),
2 => self.square(),
_ => {
let mut signum = self.sign();
if signum == 0 {
return Int::zero();
}
if exp & 1 == 0 {
signum = 1
}
let ret_sz = unsafe {
ll::pow::num_pow_limbs(self.ptr.get(), self.abs_size(), exp as u32)
};
let mut ret = Int::with_capacity(ret_sz as u32);
ret.size = ret_sz * signum;
unsafe {
ll::pow::pow(ret.ptr.get_mut(), self.ptr.get(), self.abs_size(), exp as u32);
}
ret.normalize();
ret
}
}
}
/**
* Returns the square of `self`.
*/
pub fn square(&self) -> Int {
debug_assert!(self.well_formed());
let s = self.sign();
if s == 0 {
Int::zero()
} else if self.abs_size() == 1 {
let a = self.clone() * self.to_single_limb();
if s == -1 {
a.abs()
} else if s == 1 {
a
} else {
unreachable!()
}
} else {
let sz = self.abs_size() * 2;
let mut ret = Int::with_capacity(sz as u32);
ret.size = sz;
unsafe {
ll::sqr(ret.ptr.get_mut(), self.ptr.get(), self.abs_size());
}
ret.normalize();
ret
}
}
// DESTRUCTIVE square. Is there a more idiomatic way of doing this?
pub fn dsquare(mut self) -> Int {
debug_assert!(self.well_formed());
let s = self.sign();
if s == 0 {
Int::zero()
} else if self.abs_size() == 1 {
let l = self.to_single_limb();
self = self * l;
if s == -1 {
self.abs()
} else if s == 1 {
self
} else {
unreachable!()
}
} else {
self.square()
}
}
/**
* Negates `self` in-place
*/
pub fn negate(&mut self) {
self.size *= -1;
}
/**
* Returns whether or not this number is even.
*
* Returns 0 if `self == 0`
*/
#[inline]
pub fn is_even(&self) -> bool {
debug_assert!(self.well_formed());
(self.to_single_limb().0 & 1) == 0
}
/**
* Returns the number of trailing zero bits in this number
*
* Returns 0 if `self == 0`
*/
#[inline]
pub fn trailing_zeros(&self) -> u32 {
debug_assert!(self.well_formed());
if self.sign() == 0 {
0
} else {
unsafe {
ll::scan_1(self.ptr.get(), self.abs_size())
}
}
}
fn ensure_capacity(&mut self, cap: u32) {
if cap > self.cap {
let old_cap = self.cap as usize;
self.with_raw_vec(|v| {
v.reserve_exact(old_cap, cap as usize - old_cap)
})
}
}
fn push(&mut self, limb: Limb) {
let new_size = (self.abs_size() + 1) as u32;
self.ensure_capacity(new_size);
unsafe {
let pos = self.abs_size() as isize;
*self.ptr.offset(pos) = limb;
// If it was previously empty, then just make it positive,
// otherwise maintain the signedness
if self.size == 0 {
self.size = 1;
} else {
self.size += self.sign();
}
}
}
/**
* Adjust the size field so the most significant limb is non-zero
*/
fn normalize(&mut self) {
if self.size == 0 { return }
let sign = self.sign();
unsafe {
while self.size != 0 &&
*self.ptr.offset((self.abs_size() - 1) as isize) == 0 {
self.size -= sign;
}
}
debug_assert!(self.well_formed());
}
/**
* Make sure the Int is "well-formed", i.e. that the size doesn't exceed the
* the capacity and that the most significant limb is non-zero
*/
fn well_formed(&self) -> bool {
if self.size == 0 { return true; }
if (self.abs_size() as u32) > self.cap {
return false;
}
let high_limb = unsafe {
*self.ptr.offset((self.abs_size() - 1) as isize)
};
return high_limb != 0;
}
}
impl Clone for Int {
fn clone(&self) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 {
return Int::zero();
}
let mut new = Int::with_capacity(self.abs_size() as u32);
unsafe {
ll::copy_incr(self.ptr.get(), new.ptr.get_mut(), self.abs_size());
}
new.size = self.size;
new
}
fn clone_from(&mut self, other: &Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
self.size = 0;
return;
}
self.ensure_capacity(other.abs_size() as u32);
unsafe {
ll::copy_incr(other.ptr.get(), self.ptr.get_mut(), other.abs_size());
self.size = other.size;
}
}
}
impl std::default::Default for Int {
#[inline]
fn default() -> Int {
Int::zero()
}
}
impl Drop for Int {
fn drop(&mut self) {
if self.cap > 0 {
unsafe {
drop(RawVec::from_raw_parts(self.ptr.get_mut(),
self.cap as usize));
}
self.cap = 0;
self.size = 0;
}
}
}
impl PartialEq<Int> for Int {
#[inline]
fn eq(&self, other: &Int) -> bool {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if self.size == other.size {
unsafe {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size()) == Ordering::Equal
}
} else {
false
}
}
}
impl PartialEq<Limb> for Int {
#[inline]
fn eq(&self, other: &Limb) -> bool {
if *other == 0 && self.size == 0 {
return true;
}
self.size == 1 && unsafe { *self.ptr.get() == *other }
}
}
impl PartialEq<Int> for Limb {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl Eq for Int { }
impl Ord for Int {
#[inline]
fn cmp(&self, other: &Int) -> Ordering {
if self.size < other.size {
Ordering::Less
} else if self.size > other.size {
Ordering::Greater
} else { // Same number of digits and same sign
// Check for zero
if self.size == 0 {
return Ordering::Equal;
}
unsafe {
// If both are positive, do `self cmp other`, if both are
// negative, do `other cmp self`
if self.sign() == 1 {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size())
} else {
ll::cmp(other.ptr.get(), self.ptr.get(), self.abs_size())
}
}
}
}
}
impl PartialOrd<Int> for Int {
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd<Limb> for Int {
#[inline]
fn partial_cmp(&self, other: &Limb) -> Option<Ordering> {
if self.eq(other) {
return Some(Ordering::Equal);
}
if self.size < 1 {
Some(Ordering::Less)
} else if self.size > 1 {
Some(Ordering::Greater)
} else {
unsafe {
self.ptr.get().partial_cmp(other)
}
}
}
}
impl PartialOrd<Int> for Limb {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
other.partial_cmp(self).map(|o| o.reverse())
}
}
impl hash::Hash for Int {
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
debug_assert!(self.well_formed());
self.sign().hash(state);
let mut size = self.abs_size();
unsafe {
let mut ptr = self.ptr.get() as *const Limb;
while size > 0 {
let l = *ptr;
l.hash(state);
ptr = ptr.offset(1);
size -= 1;
}
}
}
}
impl AddAssign<Limb> for Int {
fn add_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 { return; }
// No capacity means `self` is zero. Just push `other` into it
if self.cap == 0 {
self.push(other);
return;
}
// This is zero, but has allocated space, so just store `other`
if self.size == 0 {
unsafe {
*self.ptr.get_mut() = other;
self.size = 1;
}
}
// `self` is non-zero, reuse the storage for the result.
unsafe {
let sign = self.sign();
let size = self.abs_size();
let ptr = self.ptr.get_mut() as *mut Limb;
// Self is positive, just add `other`
if sign == 1 {
let carry = ll::add_1(ptr, ptr, size, other);
if carry != 0 {
self.push(carry);
}
} else {
// Self is negative, "subtract" other from self, basically doing:
// -(-self - other) == self + other
let borrow = ll::sub_1(ptr, ptr, size, other);
if borrow != 0 {
// There was a borrow, ignore it but flip the sign on self
self.size = self.abs_size();
}
}
}
}
}
impl Add<Limb> for Int {
type Output = Int;
#[inline]
fn add(mut self, other: Limb) -> Int {
self += other;
self
}
}
impl<'a> AddAssign<&'a Int> for Int {
fn add_assign(&mut self, other: &'a Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if self.sign() == 0 {
// Try to reuse the allocation from `self`
self.clone_from(other);
return;
}
if other.sign() == 0 {
return;
}
if self.sign() == other.sign() {
// Signs are the same, add the two numbers together and re-apply
// the sign after.
let sign = self.sign();
unsafe {
// There's a restriction that x-size >= y-size, we can swap the operands
// no problem, but we'd like to re-use `self`s memory if possible, so
// if `self` is the smaller of the two we make sure it has enough space
// for the result
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::add(ptr,
xp, xs,
yp, ys);
self.size = xs * sign;
self.normalize();
if carry != 0 {
self.push(carry);
}
}
} else {
// Signs are different, use the sign from the bigger (absolute value)
// of the two numbers and subtract the smaller one.
unsafe {
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() > other.abs_size() {
(self.ptr.get(), self.size, other.ptr.get(), other.size)
} else if self.abs_size() < other.abs_size() {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.size, self.ptr.get(), self.size)
} else {
match self.abs_cmp(other) {
Ordering::Equal => {
// They're equal, but opposite signs, so the result
// will be zero, clear `self` and return
self.size = 0;
return;
}
Ordering::Greater =>
(self.ptr.get(), self.size, other.ptr.get(), other.size),
Ordering::Less =>
(other.ptr.get(), other.size, self.ptr.get(), self.size)
}
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let _borrow = ll::sub(ptr,
xp, xs.abs(),
yp, ys.abs());
// There shouldn't be any borrow
debug_assert!(_borrow == 0);
self.size = xs;
self.normalize();
debug_assert!(self.abs_size() > 0);
}
}
}
}
impl<'a> Add<&'a Int> for Int {
type Output = Int;
#[inline]
fn add(mut self, other: &'a Int) -> Int {
self += other;
self
}
}
impl<'a> Add<Int> for &'a Int {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
// Forward to other + self
other.add(self)
}
}
impl Add<Int> for Int {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
// Check for self or other being zero.
if self.sign() == 0 {
return other;
}
if other.sign() == 0 {
return self;
}
let (x, y) = if self.abs_size() >= other.abs_size() {
(self, &other)
} else {
(other, &self)
};
return x.add(y);
}
}
impl AddAssign<Int> for Int {
#[inline]
fn add_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this + other;
}
}
impl<'a, 'b> Add<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn add(self, other: &'a Int) -> Int {
if self.sign() == 0 {
return other.clone();
}
if other.sign() == 0 {
return self.clone();
}
// Clone the bigger of the two
if self.abs_size() >= other.abs_size() {
self.clone().add(other)
} else {
other.clone().add(self)
}
}
}
impl SubAssign<Limb> for Int {
fn sub_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 { return; }
// No capacity means `self` is zero. Just push the limb.
if self.cap == 0 {
self.push(other);
self.size = -1;
return;
}
// This is zero, but has allocated space, so just store `other`
if self.size == 0 {
unsafe {
*self.ptr.get_mut() = other;
self.size = -1;
}
return;
}
// `self` is non-zero, reuse the storage for the result.
unsafe {
let sign = self.sign();
let size = self.abs_size();
let ptr = self.ptr.get_mut() as *mut Limb;
// Self is negative, just "add" `other`
if sign == -1 {
let carry = ll::add_1(ptr, ptr, size, other);
if carry != 0 {
self.push(carry);
}
} else {
// Self is positive, subtract other from self
let carry = ll::sub_1(ptr, ptr, size, other);
self.normalize();
if carry != 0 {
// There was a carry, ignore it but flip the sign on self
self.size = -self.abs_size();
}
}
}
debug_assert!(self.well_formed());
}
}
impl Sub<Limb> for Int {
type Output = Int;
#[inline]
fn sub(mut self, other: Limb) -> Int {
self -= other;
self
}
}
impl<'a> SubAssign<&'a Int> for Int {
fn sub_assign(&mut self, other: &'a Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
// LHS is zero, set self to the negation of the RHS
if self.sign() == 0 {
self.clone_from(other);
self.size *= -1;
return;
}
// RHS is zero, do nothing
if other.sign() == 0 {
return;
}
if self.sign() == other.sign() {
unsafe {
// Signs are the same, subtract the smaller one from
// the bigger one and adjust the sign as appropriate
let (xp, xs, yp, ys, flip): (*const Limb, _, *const Limb, _, _) = match self.abs_cmp(other) {
Ordering::Equal => {
// x - x, just return zero
self.size = 0;
return;
}
Ordering::Less => {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.size, self.ptr.get(), self.size, true)
}
Ordering::Greater =>
(self.ptr.get(), self.size, other.ptr.get(), other.size, false)
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let _borrow = ll::sub(ptr, xp, xs.abs(), yp, ys.abs());
debug_assert!(_borrow == 0);
self.size = if flip {
xs * -1
} else {
xs
};
}
self.normalize();
} else { // Different signs
if self.sign() == -1 {
// self is negative, use addition and negation
self.size *= -1;
*self += other;
self.size *= -1;
} else {
unsafe {
// Other is negative, handle as addition
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::add(ptr, xp, xs, yp, ys);
self.size = xs;
self.normalize();
if carry != 0 {
self.push(carry);
}
}
}
}
}
}
impl<'a> Sub<&'a Int> for Int {
type Output = Int;
#[inline]
fn sub(mut self, other: &'a Int) -> Int {
self -= other;
self
}
}
impl<'a> Sub<Int> for &'a Int {
type Output = Int;
#[inline]
fn sub(self, mut other: Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
other.clone_from(self);
return other;
}
-(other.sub(self))
}
}
impl Sub<Int> for Int {
type Output = Int;
#[inline]
fn sub(self, other: Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
return self;
}
self.sub(&other)
}
}
impl SubAssign<Int> for Int {
#[inline]
fn sub_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this - other;
}
}
impl<'a, 'b> Sub<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn sub(self, other: &'a Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
return self.clone();
}
self.clone().sub(other)
}
}
impl MulAssign<Limb> for Int {
fn mul_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 || self.sign() == 0 {
self.size = 0;
return;
}
if other == 1 {
return;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::mul_1(ptr, ptr, self.abs_size(), other);
if carry != 0 {
self.push(carry);
}
}
}
}
impl Mul<Limb> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: Limb) -> Int {
self *= other;
self
}
}
impl<'a, 'b> Mul<&'a Int> for &'b Int {
type Output = Int;
fn mul(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
// This is the main function, since in the general case
// we need to allocate space for the return. Special cases
// where this isn't necessary are handled in the other impls
// 0 * x = 0
if self.sign() == 0 || other.sign() == 0 {
return Int::zero();
}
let out_sign = self.sign() * other.sign();
if self.abs_size() == 1 {
unsafe {
let mut ret = other.clone() * *self.ptr.get();
let size = ret.abs_size();
ret.size = size * out_sign;
return ret;
}
}
if other.abs_size() == 1 {
unsafe {
let mut ret = self.clone() * *other.ptr.get();
let size = ret.abs_size();
ret.size = size * out_sign;
return ret;
}
}
let out_size = self.abs_size() + other.abs_size();
let mut out = Int::with_capacity(out_size as u32);
out.size = out_size * out_sign;
unsafe {
let (xp, xs, yp, ys) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
ll::mul(out.ptr.get_mut(), xp, xs, yp, ys);
// Top limb may be zero
out.normalize();
return out;
}
}
}
impl<'a> Mul<&'a Int> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: &'a Int) -> Int {
// `other` is zero
if other.sign() == 0 {
self.size = 0;
return self;
}
// `other` is a single limb, reuse the allocation of self
if other.abs_size() == 1 {
unsafe {
let mut out = self * *other.ptr.get();
out.size *= other.sign();
return out;
}
}
// Forward to the by-reference impl
(&self) * other
}
}
impl<'a> Mul<Int> for &'a Int {
type Output = Int;
#[inline]
fn mul(self, other: Int) -> Int {
// Swap arguments
other * self
}
}
impl Mul<Int> for Int {
type Output = Int;
fn mul(mut self, other: Int) -> Int {
if self.sign() == 0 || other.sign() == 0 {
self.size = 0;
return self;
}
// One of them is a single limb big, so we can re-use the
// allocation of the other
if self.abs_size() == 1 {
let val = unsafe { *self.ptr.get() };
let mut out = other * val;
out.size *= self.sign();
return out;
}
if other.abs_size() == 1 {
let val = unsafe { *other.ptr.get() };
let mut out = self * val;
out.size *= other.sign();
return out;
}
// Still need to allocate for the result, just forward to
// the by-reference impl
(&self) * (&other)
}
}
impl<'a> MulAssign<&'a Int> for Int {
#[inline]
fn mul_assign(&mut self, other: &'a Int) {
// Temporarily extract self as a value, then overwrite it with the result
// of the multiplication
let this = std::mem::replace(self, Int::zero());
*self = this * other;
}
}
impl MulAssign<Int> for Int {
#[inline]
fn mul_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this * other;
}
}
impl DivAssign<Limb> for Int {
fn div_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
// Ignore the remainder
ll::divrem_1(ptr, 0, ptr, self.abs_size(), other);
// Adjust the size if necessary
self.normalize();
}
}
}
impl Div<Limb> for Int {
type Output = Int;
#[inline]
fn div(mut self, other: Limb) -> Int {
self /= other;
self
}
}
impl<'a, 'b> Div<&'a Int> for &'b Int {
type Output = Int;
fn div(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
ll::divide_by_zero();
}
if other.abs_size() == 1 {
let l = unsafe { *other.ptr.get() };
let out_sign = self.sign() * other.sign();
let mut out = self.clone() / l;
out.size = out.abs_size() * out_sign;
return out;
}
self.divmod(other).0
}
}
impl<'a> Div<&'a Int> for Int {
type Output = Int;
#[inline]
fn div(self, other: &'a Int) -> Int {
(&self) / other
}
}
impl<'a> Div<Int> for &'a Int {
type Output = Int;
#[inline]
fn div(self, other: Int) -> Int {
self / (&other)
}
}
impl Div<Int> for Int {
type Output = Int;
#[inline]
fn div(self, other: Int) -> Int {
(&self) / (&other)
}
}
impl<'a> DivAssign<&'a Int> for Int {
#[inline]
fn div_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this / other;
}
}
impl DivAssign<Int> for Int {
#[inline]
fn div_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this / other;
}
}
impl RemAssign<Limb> for Int {
#[inline]
fn rem_assign(&mut self, other: Limb) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Rem<Limb> for Int {
type Output = Int;
fn rem(mut self, other: Limb) -> Int {
debug_assert!(self.well_formed());
if other == 0 {
ll::divide_by_zero();
}
// x % 1 == 0, 0 % n == 0
if other == 1 || self.sign() == 0 {
self.size = 0;
return self;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let rem = ll::divrem_1(ptr, 0, ptr, self.abs_size(), other);
// Reuse the space from `self`, taking the sign from the numerator
// Since `rem` has to satisfy `N = QD + R` and D is always positive,
// `R` will always be the same sign as the numerator.
*self.ptr.get_mut() = rem;
let sign = self.sign();
self.size = sign;
self.normalize();
if self.cap > 8 {
// Shrink self, since it's at least 8 times bigger than necessary
self.shrink_to_fit();
}
}
return self;
}
}
// TODO: There's probably too much cloning happening here, need to figure out
// the best way of avoiding over-copying.
impl<'a, 'b> Rem<&'a Int> for &'b Int {
type Output = Int;
fn rem(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
ll::divide_by_zero();
}
if other.abs_size() == 1 {
let l = unsafe { *other.ptr.get() };
return self.clone() % l;
}
self.divmod(other).1
}
}
impl<'a> Rem<&'a Int> for Int {
type Output = Int;
#[inline]
fn rem(self, other: &'a Int) -> Int {
(&self) % other
}
}
impl<'a> Rem<Int> for &'a Int {
type Output = Int;
#[inline]
fn rem(self, other: Int) -> Int {
self % (&other)
}
}
impl Rem<Int> for Int {
type Output = Int;
#[inline]
fn rem(self, other: Int) -> Int {
(&self) % (&other)
}
}
impl RemAssign<Int> for Int {
#[inline]
fn rem_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl<'a> RemAssign<&'a Int> for Int {
#[inline]
fn rem_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Neg for Int {
type Output = Int;
#[inline]
fn neg(mut self) -> Int {
debug_assert!(self.well_formed());
self.size *= -1;
self
}
}
impl<'a> Neg for &'a Int {
type Output = Int;
#[inline]
fn neg(self) -> Int {
self.clone().neg()
}
}
impl Shl<usize> for Int {
type Output = Int;
#[inline]
fn shl(mut self, mut cnt: usize) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 { return self; }
if cnt >= Limb::BITS as usize {
let extra_limbs = (cnt / Limb::BITS as usize) as u32;
debug_assert!(extra_limbs >= 1);
cnt = cnt % Limb::BITS as usize;
let size = self.abs_size() as u32;
// Extend for the extra limbs, then another one for any potential extra limbs
self.ensure_capacity(extra_limbs + size + 1);
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let shift = ptr.offset(extra_limbs as isize);
ll::copy_decr(ptr, shift, self.abs_size());
ll::zero(ptr, extra_limbs as i32);
}
self.size += (extra_limbs as i32) * self.sign();
}
debug_assert!(cnt < Limb::BITS as usize);
if cnt == 0 { return self; }
let size = self.abs_size();
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let c = ll::shl(ptr, ptr, size, cnt as u32);
if c > 0 {
self.push(c);
}
}
return self;
}
}
impl<'a> Shl<usize> for &'a Int {
type Output = Int;
#[inline]
fn shl(self, cnt: usize) -> Int {
self.clone() << cnt
}
}
impl ShlAssign<usize> for Int {
#[inline]
fn shl_assign(&mut self, other: usize) {
let this = std::mem::replace(self, Int::zero());
*self = this << other;
}
}
impl Shr<usize> for Int {
type Output = Int;
#[inline]
fn shr(mut self, mut cnt: usize) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 { return self; }
if cnt >= Limb::BITS as usize {
let removed_limbs = (cnt / Limb::BITS as usize) as u32;
let size = self.abs_size();
if removed_limbs as i32 >= size {
return Int::zero();
}
debug_assert!(removed_limbs > 0);
cnt = cnt % Limb::BITS as usize;
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let shift = self.ptr.offset(removed_limbs as isize);
// Shift down a whole number of limbs
ll::copy_incr(shift, ptr, size);
// Zero out the high limbs
ll::zero(ptr.offset((size - (removed_limbs as i32)) as isize),
removed_limbs as i32);
self.size -= (removed_limbs as i32) * self.sign();
}
}
debug_assert!(cnt < Limb::BITS as usize);
if cnt == 0 { return self; }
let size = self.abs_size();
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
ll::shr(ptr, ptr, size, cnt as u32);
self.normalize();
}
return self;
}
}
impl<'a> Shr<usize> for &'a Int {
type Output = Int;
#[inline]
fn shr(self, other: usize) -> Int {
self.clone() >> other
}
}
impl ShrAssign<usize> for Int {
#[inline]
fn shr_assign(&mut self, other: usize) {
let this = std::mem::replace(self, Int::zero());
*self = this >> other;
}
}
struct ComplementSplit {
ptr: *const Limb,
split_idx: i32,
len: i32
}
impl ComplementSplit {
fn low_len(&self) -> i32 { self.split_idx }
fn has_high_limbs(&self) -> bool {
self.split_idx + 1 < self.len
}
fn high_ptr(&self) -> *const Limb {
debug_assert!(self.has_high_limbs());
unsafe {
self.ptr.offset((self.split_idx + 1) as isize)
}
}
fn high_len(&self) -> i32 { self.len - (self.split_idx + 1) }
unsafe fn split_limb(&self) -> Limb {
*self.ptr.offset(self.split_idx as isize)
}
}
/*
* Helper function for the bitwise operations below.
*
* The bitwise operations act as if the numbers are stored as two's complement integers, rather
* than the signed magnitude representation that is actually used. Since converting to and from a
* two's complement representation would be horribly inefficient, we split the number into three
* segments: A number of high limbs, a single limb, the remaining zero limbs. The first segment is
* the limbs that would be inverted in a two's complement form, the single limb is the limb
* containing the first `1` bit. By definition, the remaining limbs must all be zero.
*
* This works due to the fact that `-n == !n + 1`. Consider the following bitstring, with 4-bit
* limbs:
*
* 0011 0011 1101 1000 1100 0000 0000
*
* The two's complement of this number (with an additional "sign" bit) is:
*
* 1 1100 1100 0010 0111 0100 0000 0000
*
* As you can see, all the trailing zeros are preserved and the remaining bits are all inverted
* with the exception of the first `1` bit. Since we prefer to work with whole limbs and not
* individual bits we can simply take the two's complement of the limb containing that bit
* directly.
*/
unsafe fn complement_split(np: *const Limb, len: i32) -> ComplementSplit {
debug_assert!(len > 0);
let bit_idx = ll::scan_1(np, len);
let split_idx = (bit_idx / (Limb::BITS as u32)) as i32;
ComplementSplit {
ptr: np,
split_idx: split_idx,
len: len
}
}
impl<'a> BitAnd<&'a Int> for Int {
type Output = Int;
fn bitand(mut self, other: &'a Int) -> Int {
unsafe {
let other_sign = other.sign();
let self_sign = self.sign();
// x & 0 == 0
if other_sign == 0 || self_sign == 0 {
self.size = 0;
return self;
}
// Special case -1 as the two's complement is all 1s
if *other == -1 {
return self;
}
if self == -1 {
self.clone_from(other);
return self;
}
let self_ptr = self.ptr.get_mut() as *mut Limb;
let other_ptr = other.ptr.get() as *const Limb;
// Nice easy case both are positive
if other_sign > 0 && self_sign > 0 {
let size = std::cmp::min(self.abs_size(), other.abs_size());
ll::and_n(self_ptr, self_ptr, other_ptr, size);
self.size = size;
self.normalize();
return self;
}
// Both are negative
if other_sign == self_sign {
let size = std::cmp::max(self.abs_size(), other.abs_size());
self.ensure_capacity(size as u32);
// Copy the high limbs from other to self, if self is smaller than other
if size > self.abs_size() {
ll::copy_rest(other_ptr, self_ptr, size, self.abs_size());
}
self.size = -size;
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
let self_split = complement_split(self_ptr, min_size);
let other_split = complement_split(other_ptr, min_size);
let mut zero_limbs = std::cmp::max(self_split.low_len(), other_split.low_len());
if zero_limbs > 0 {
ll::zero(self_ptr, zero_limbs);
}
// If the limb we split it is different for self and other, it'd be
// zeroed out by the above step
if self_split.low_len() == other_split.low_len() {
let split_ptr = self_ptr.offset(self_split.low_len() as isize);
*split_ptr = -(*split_ptr) & -(*other_ptr.offset(self_split.low_len() as isize));
zero_limbs += 1;
}
if zero_limbs < min_size {
let high_limbs = min_size - zero_limbs;
// Use de Morgan's Rule: !x & !y == !(x | y)
let self_ptr = self_ptr.offset(zero_limbs as isize);
let other_ptr = other_ptr.offset(zero_limbs as isize);
ll::nor_n(self_ptr, self_ptr, other_ptr, high_limbs);
}
self.normalize();
return self;
}
// If we got here one is positive, the other is negative
let (xp, yp, n) = if other_sign < 0 {
(self_ptr as *const Limb, other_ptr, self.abs_size())
} else {
if other.abs_size() > self.abs_size() {
self.ensure_capacity(other.abs_size() as u32);
// Copy the high limbs from other to self
ll::copy_rest(other_ptr, self_ptr, other.abs_size(), self.abs_size());
}
(other_ptr, self_ptr as *const Limb, other.abs_size())
};
// x > 0, y < 0
let self_ptr = self.ptr.get_mut() as *mut Limb;
let y_split = complement_split(yp, n);
let split = y_split.split_idx as isize;
ll::zero(self_ptr, y_split.low_len());
*self_ptr.offset(split) = *xp.offset(split) & -y_split.split_limb();
if y_split.has_high_limbs() {
ll::and_not_n(self_ptr.offset(split + 1), xp.offset(split + 1), y_split.high_ptr(),
y_split.high_len());
}
self.size = n;
self.normalize();
return self;
}
}
}
impl<'a> BitAnd<Int> for &'a Int {
type Output = Int;
#[inline]
fn bitand(self, other: Int) -> Int {
other.bitand(self)
}
}
impl<'a, 'b> BitAnd<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn bitand(self, other: &'a Int) -> Int {
self.clone().bitand(other)
}
}
impl BitAnd<Int> for Int {
type Output = Int;
#[inline]
fn bitand(self, other: Int) -> Int {
self.bitand(&other)
}
}
impl BitAndAssign<Int> for Int {
#[inline]
fn bitand_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this & other;
}
}
impl<'a> BitAndAssign<&'a Int> for Int {
#[inline]
fn bitand_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this & other;
}
}
impl<'a> BitOr<&'a Int> for Int {
type Output = Int;
fn bitor(mut self, other: &'a Int) -> Int {
unsafe {
if *other == 0 {
return self;
}
if self == 0 {
self.clone_from(other);
return self;
}
if *other == -1 || self == -1 {
self.size = -1;
*self.ptr.get_mut() = Limb(1);
return self;
}
let self_sign = self.sign();
let other_sign = other.sign();
let self_ptr = self.ptr.get_mut() as *mut Limb;
let other_ptr = other.ptr.get() as *const Limb;
if self_sign > 0 && other_sign > 0 {
let size = std::cmp::max(self.abs_size(), other.abs_size());
self.ensure_capacity(size as u32);
if size > self.abs_size() {
ll::copy_rest(other_ptr, self_ptr, size, self.abs_size());
}
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
ll::or_n(self_ptr, self_ptr, other_ptr, min_size);
self.size = size;
return self;
}
if self_sign == other_sign {
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
let self_split = complement_split(self_ptr, min_size);
let other_split = complement_split(other_ptr, min_size);
if self_split.low_len() > other_split.low_len() {
let mut p = self_ptr.offset(other_split.low_len() as isize);
*p = -other_split.split_limb();
p = p.offset(1);
let mut o = other_ptr.offset((other_split.low_len() + 1) as isize);
let mut n = (self_split.low_len() - other_split.low_len()) - 1;
while n > 0 {
*p = !(*o);
p = p.offset(1);
o = o.offset(1);
n -= 1;
}
}
let low_limbs = std::cmp::max(self_split.low_len(), other_split.low_len()) + 1;
if low_limbs < min_size {
let high_limbs = min_size - low_limbs;
let o = other_ptr.offset(low_limbs as isize);
let s = self_ptr.offset(low_limbs as isize);
// de Morgan's Rule: !x | !y == !(x & y)
ll::nand_n(s, s, o, high_limbs);
}
self.size = -min_size;
self.normalize();
return self;
}
// If we got here one is positive, the other is negative
let n = std::cmp::max(other.abs_size(), self.abs_size());
self.ensure_capacity(n as u32);
let (xp, yp) = if other_sign < 0 {
(self_ptr as *const Limb, other_ptr)
} else {
(other_ptr, self_ptr as *const Limb)
};
// x > 0, y < 0
let y_split = complement_split(yp, n);
let split = y_split.low_len() as isize;
if xp != self_ptr {
ll::copy_incr(xp, self_ptr, y_split.low_len());
}
*self_ptr.offset(split) = *xp.offset(split) | -y_split.split_limb();
if y_split.has_high_limbs() {
ll::or_not_n(self_ptr.offset(split + 1), xp.offset(split + 1), y_split.high_ptr(),
y_split.high_len());
}
self.size = -n;
self.normalize();
return self;
}
}
}
impl<'a> BitOr<Int> for &'a Int {
type Output = Int;
#[inline]
fn bitor(self, other: Int) -> Int {
other.bitor(self)
}
}
impl<'a, 'b> BitOr<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn bitor(self, other: &'a Int) -> Int {
self.clone().bitor(other)
}
}
impl BitOr<Int> for Int {
type Output = Int;
#[inline]
fn bitor(self, other: Int) -> Int {
self.bitor(&other)
}
}
impl BitOrAssign<Int> for Int {
#[inline]
fn bitor_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this | other;
}
}
impl<'a> BitOrAssign<&'a Int> for Int {
#[inline]
fn bitor_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this | other;
}
}
macro_rules! impl_arith_prim (
(signed $t:ty) => (
// Limbs are unsigned, so make sure we account for the sign
// when $t is signed
impl Add<$t> for Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
if other == 0 {
return self;
}
if other < 0 {
return self - Limb(other.abs() as BaseInt);
}
return self + Limb(other as BaseInt);
}
}
impl AddAssign<$t> for Int {
#[inline]
fn add_assign(&mut self, other: $t) {
if other < 0 {
*self -= Limb(other.abs() as BaseInt);
} else if other > 0 {
*self += Limb(other as BaseInt);
}
}
}
impl Sub<$t> for Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
if other == 0 {
return self;
}
if other < 0 {
return self + Limb(other.abs() as BaseInt);
}
return self - Limb(other as BaseInt);
}
}
impl SubAssign<$t> for Int {
#[inline]
fn sub_assign(&mut self, other: $t) {
if other < 0 {
*self += Limb(other.abs() as BaseInt);
} else if other > 0 {
*self -= Limb(other as BaseInt);
}
}
}
impl Mul<$t> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: $t) -> Int {
self *= other;
self
}
}
impl MulAssign<$t> for Int {
#[inline]
fn mul_assign(&mut self, other: $t) {
if other == 0 {
self.size = 0;
} else if other == -1 {
self.negate();
} else if other < 0 {
self.negate();
*self *= Limb(other.abs() as BaseInt);
} else {
*self *= Limb(other as BaseInt);
}
}
}
impl DivAssign<$t> for Int {
#[inline]
fn div_assign(&mut self, other: $t) {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return;
}
if other == -1 {
self.negate();
} else if other < 0 {
self.negate();
*self /= Limb(other.abs() as BaseInt);
} else {
*self /= Limb(other as BaseInt);
}
}
}
impl Div<$t> for Int {
type Output = Int;
#[inline]
fn div(mut self, other: $t) -> Int {
self /= other;
self
}
}
impl RemAssign<$t> for Int {
#[inline]
fn rem_assign(&mut self, other: $t) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Rem<$t> for Int {
type Output = Int;
#[inline]
fn rem(mut self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 ||other == -1 || self.sign() == 0 {
self.size = 0;
return self;
}
return self % Limb(other.abs() as BaseInt);
}
}
impl_arith_prim!(common $t);
);
(unsigned $t:ty) => (
impl Add<$t> for Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
if other == 0 {
return self;
}
return self + Limb(other as BaseInt);
}
}
impl AddAssign<$t> for Int {
#[inline]
fn add_assign(&mut self, other: $t) {
if other != 0 {
*self += Limb(other as BaseInt);
}
}
}
impl Sub<$t> for Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
if other == 0 {
return self;
}
return self - Limb(other as BaseInt);
}
}
impl SubAssign<$t> for Int {
#[inline]
fn sub_assign(&mut self, other: $t) {
if other != 0 {
*self -= Limb(other as BaseInt);
}
}
}
impl Mul<$t> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: $t) -> Int {
if other == 0 {
self.size = 0;
return self;
}
if other == 1 || self.sign() == 0 {
return self;
}
return self * Limb(other as BaseInt);
}
}
impl MulAssign<$t> for Int {
#[inline]
fn mul_assign(&mut self, other: $t) {
if other == 0 {
self.size = 0;
} else if other > 1 && self.sign() != 0 {
*self *= Limb(other as BaseInt);
}
}
}
impl Div<$t> for Int {
type Output = Int;
#[inline]
fn div(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return self;
}
return self / Limb(other as BaseInt);
}
}
impl DivAssign<$t> for Int {
#[inline]
fn div_assign(&mut self, other: $t) {
if other == 0 {
ll::divide_by_zero();
} else if other > 1 && self.sign() != 0 {
*self /= Limb(other as BaseInt);
}
}
}
impl Rem<$t> for Int {
type Output = Int;
#[inline]
fn rem(mut self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
self.size = 0;
return self;
}
return self % Limb(other as BaseInt);
}
}
impl RemAssign<$t> for Int {
#[inline]
fn rem_assign(&mut self, other: $t) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl_arith_prim!(common $t);
);
(common $t:ty) => (
// Common impls, these should just forward to the above
// impls
impl<'a> Add<$t> for &'a Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
self.clone() + other
}
}
impl Add<Int> for $t {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
return other + self;
}
}
impl<'a> Add<&'a Int> for $t {
type Output = Int;
#[inline]
fn add(self, other: &'a Int) -> Int {
other.clone() + self
}
}
impl<'a> Sub<$t> for &'a Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
self.clone() - other
}
}
impl Sub<Int> for $t {
type Output = Int;
#[inline]
fn sub(self, other: Int) -> Int {
-other + self
}
}
impl<'a> Sub<&'a Int> for $t {
type Output = Int;
#[inline]
fn sub(self, other: &'a Int) -> Int {
-(other - self)
}
}
impl<'a> Mul<$t> for &'a Int {
type Output = Int;
#[inline]
fn mul(self, other: $t) -> Int {
return self.clone() * other;
}
}
impl Mul<Int> for $t {
type Output = Int;
#[inline]
fn mul(self, other: Int) -> Int {
other * self
}
}
impl<'a> Mul<&'a Int> for $t {
type Output = Int;
#[inline]
fn mul(self, other: &'a Int) -> Int {
// Check for zero here to avoid cloning unnecessarily
if self == 0 { return Int::zero() };
other.clone() * self
}
}
impl<'a> Div<$t> for &'a Int {
type Output = Int;
#[inline]
fn div(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
return self.clone() / other;
}
}
impl Div<Int> for $t {
type Output = Int;
#[inline]
fn div(self, mut other: Int) -> Int {
if self == 0 {
other.size = 0;
return other;
}
if other.sign() == 0 {
ll::divide_by_zero();
}
// There's probably a better way of doing this, but
// I don't see n / <bigint> being common in code
Int::from(self) / other
}
}
impl<'a> Div<&'a Int> for $t {
type Output = Int;
#[inline]
fn div(self, other: &'a Int) -> Int {
if self == 0 { return Int::zero() };
if other.sign() == 0 {
ll::divide_by_zero();
}
self / other.clone()
}
}
impl<'a> Rem<$t> for &'a Int {
type Output = Int;
#[inline]
fn rem(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if self.sign() == 0 || other == 1 {
return Int::zero()
};
return self.clone() % other;
}
}
impl Rem<Int> for $t {
type Output = Int;
#[inline]
fn rem(self, mut other: Int) -> Int {
if self == 0 || other == 1 {
other.size = 0;
return other;
}
if other.sign() == 0 {
ll::divide_by_zero();
}
// There's probably a better way of doing this, but
// I don't see n % <bigint> being common in code
Int::from(self) % other
}
}
impl<'a> Rem<&'a Int> for $t {
type Output = Int;
#[inline]
fn rem(self, other: &'a Int) -> Int {
if self == 0 { return Int::zero() };
if other.sign() == 0 {
ll::divide_by_zero();
}
self % other.clone()
}
}
)
);
// Implement for `i32` which is the fallback type, usize and the base integer type.
// No more than this because the rest of Rust doesn't much coercion for integer types,
// but allocating an entire multiple-precision `Int` to do `+ 1` seems silly.
impl_arith_prim!(signed i32);
impl_arith_prim!(unsigned usize);
impl_arith_prim!(unsigned BaseInt);
impl PartialEq<i32> for Int {
#[inline]
fn eq(&self, &other: &i32) -> bool {
let sign = self.sign();
// equals zero
if sign == 0 || other == 0 {
return other == sign;
}
// Differing signs
if sign < 0 && other > 0 || sign > 0 && other < 0 {
return false;
}
// We can't fall back to the `== Limb` impl when self is negative
// since it'll fail because of signs
if sign < 0 {
if self.abs_size() > 1 { return false; }
unsafe {
return *self.ptr.get() == (other.abs() as BaseInt);
}
}
self.eq(&Limb(other.abs() as BaseInt))
}
}
impl PartialEq<Int> for i32 {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl PartialOrd<i32> for Int {
#[inline]
fn partial_cmp(&self, &other: &i32) -> Option<Ordering> {
let self_sign = self.sign();
let other_sign = if other < 0 {
-1
} else if other > 0 {
1
} else {
0
};
// Both are equal
if self_sign == 0 && other_sign == 0 {
return Some(Ordering::Equal);
}
let ord = if self_sign > other_sign {
Ordering::Greater
} else if self_sign < other_sign {
Ordering::Less
} else { // Now both signs are the same, and non-zero
if self_sign < 0 {
if self.abs_size() > 1 {
Ordering::Less
} else {
self.to_single_limb().cmp(&Limb(other.abs() as BaseInt)).reverse()
}
} else {
return self.partial_cmp(&Limb(other.abs() as BaseInt));
}
};
Some(ord)
}
}
impl PartialOrd<Int> for i32 {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
other.partial_cmp(self).map(|o| o.reverse())
}
}
impl PartialEq<usize> for Int {
#[inline]
fn eq(&self, &other: &usize) -> bool {
return self.eq(&Limb(other as BaseInt));
}
}
impl PartialEq<Int> for usize {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl PartialOrd<usize> for Int {
#[inline]
fn partial_cmp(&self, &other: &usize) -> Option<Ordering> {
self.partial_cmp(&Limb(other as BaseInt))
}
}
impl PartialOrd<Int> for usize {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
Limb(*self as BaseInt).partial_cmp(other)
}
}
macro_rules! impl_from_prim (
(signed $($t:ty),*) => {
$(impl ::std::convert::From<$t> for Int {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(val: $t) -> Int {
if val == 0 {
return Int::zero();
} if val == <$t>::min_value() {
let shift = val.trailing_zeros() as usize;
let mut i = Int::one();
i = i << shift;
return -i;
}
// Handle i64/u64 on 32-bit platforms.
if std::mem::size_of::<$t>() > std::mem::size_of::<BaseInt>() {
let vabs = val.abs();
let mask : BaseInt = !0;
let vlow = vabs & (mask as $t);
let vhigh = vabs >> Limb::BITS;
let low_limb = Limb(vlow as BaseInt);
let high_limb = Limb(vhigh as BaseInt);
let mut i = Int::from_single_limb(low_limb);
if high_limb != 0 {
i.push(high_limb);
}
if val < 0 {
i.size *= -1;
}
return i;
} else {
let limb = Limb(val.abs() as BaseInt);
let mut i = Int::from_single_limb(limb);
if val < 0 {
i.size *= -1;
}
return i;
}
}
})*
};
(unsigned $($t:ty),*) => {
$(impl ::std::convert::From<$t> for Int {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(val: $t) -> Int {
if val == 0 {
return Int::zero();
}
// Handle i64/u64 on 32-bit platforms.
if std::mem::size_of::<$t>() > std::mem::size_of::<BaseInt>() {
let mask : BaseInt = !0;
let vlow = val & (mask as $t);
let vhigh = val >> Limb::BITS;
let low_limb = Limb(vlow as BaseInt);
let high_limb = Limb(vhigh as BaseInt);
let mut i = Int::from_single_limb(low_limb);
if high_limb != 0 {
i.push(high_limb);
}
return i;
} else {
let limb = Limb(val as BaseInt);
return Int::from_single_limb(limb);
}
}
})*
}
);
impl_from_prim!(signed i8, i16, i32, i64, isize);
impl_from_prim!(unsigned u8, u16, u32, u64, usize);
// Number formatting - There's not much difference between the impls,
// hence the macro
macro_rules! impl_fmt (
($t:path, $radix:expr, $upper:expr, $prefix:expr) => {
impl $t for Int {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s : &str = &self.to_str_radix($radix, $upper);
let is_positive = self.sign() >= 0;
// to_str_radix adds the sign if `self` is negative, but
// pad_integral adds it's own sign, so slice the sign off
if !is_positive {
s = &s[1..];
}
f.pad_integral(is_positive, $prefix, s)
}
}
};
($t:path, $radix:expr, $prefix:expr) => {
impl_fmt!($t, $radix, false, $prefix);
}
);
impl_fmt!(fmt::Binary, 2, "0b");
impl_fmt!(fmt::Octal, 8, "0o");
impl_fmt!(fmt::Display, 10, "");
impl_fmt!(fmt::Debug, 10, "");
impl_fmt!(fmt::LowerHex, 16, false, "0x");
impl_fmt!(fmt::UpperHex, 16, true, "0x");
// String parsing
#[derive(Debug, Clone, PartialEq)]
pub struct ParseIntError { kind: ErrorKind }
#[derive(Debug, Clone, PartialEq)]
enum ErrorKind {
Empty,
InvalidDigit
}
impl Error for ParseIntError {
fn description<'a>(&'a self) -> &'a str {
match self.kind {
ErrorKind::Empty => "cannot parse empty string",
ErrorKind::InvalidDigit => "invalid digit found in string"
}
}
}
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl FromStr for Int {
type Err = ParseIntError;
fn from_str(src: &str) -> Result<Int, ParseIntError> {
Int::from_str_radix(src, 10)
}
}
// Conversion *to* primitives via the From trait.
macro_rules! impl_from_for_prim (
(signed $($t:ty),*) => (
$(impl<'a> ::std::convert::From<&'a Int> for $t {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(i: &'a Int) -> $t {
let sign = i.sign() as $t;
if sign == 0 {
return 0;
}
if ::std::mem::size_of::<BaseInt>() < ::std::mem::size_of::<$t>() {
// Handle conversion where BaseInt = u32 and $t = i64
if i.abs_size() >= 2 { // Fallthrough if there's only one limb
let lower = i.to_single_limb().0 as $t;
let higher = unsafe { (*i.ptr.offset(1)).0 } as $t;
// Combine the two
let n : $t = lower | (higher << Limb::BITS);
// Apply the sign
return n.wrapping_mul(sign);
}
}
let n = i.to_single_limb().0;
// Using wrapping_mul to account for when the binary
// representation of n == $t::MIN
return (n as $t).wrapping_mul(sign);
}
})*
);
(unsigned $($t:ty),*) => (
$(impl<'a> ::std::convert::From<&'a Int> for $t {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(i: &'a Int) -> $t {
// This does the conversion ignoring the sign
if i.sign() == 0 {
return 0;
}
if ::std::mem::size_of::<BaseInt>() < ::std::mem::size_of::<$t>() {
// Handle conversion where BaseInt = u32 and $t = u64
if i.abs_size() >= 2 { // Fallthrough if there's only one limb
let lower = i.to_single_limb().0 as $t;
let higher = unsafe { (*i.ptr.offset(1)).0 } as $t;
// Combine the two
let n : $t = lower | (higher << Limb::BITS);
return n;
}
}
let n = i.to_single_limb().0;
return n as $t;
}
})*
)
);
impl_from_for_prim!(signed i8, i16, i32, i64, isize);
impl_from_for_prim!(unsigned u8, u16, u32, u64, usize);
impl std::num::Zero for Int {
fn zero() -> Int {
Int {
ptr: unsafe { Unique::new(alloc::heap::EMPTY as *mut Limb) },
size: 0,
cap: 0
}
}
}
impl std::num::One for Int {
fn one() -> Int {
Int::from(1)
}
}
impl std::iter::Step for Int {
fn step(&self, by: &Int) -> Option<Int> {
Some(self + by)
}
fn steps_between(start: &Int, end: &Int, by: &Int) -> Option<usize> {
if by.le(&0) { return None; }
let mut diff = (start - end).abs();
if by.ne(&1) {
diff = diff / by;
}
// Check to see if result fits in a usize
if diff > !0usize {
None
} else {
Some(usize::from(&diff))
}
}
}
/// Trait for generating random `Int`.
///
/// # Example
///
/// Generate a random `Int` of size `256` bits:
///
/// ```
/// extern crate rand;
/// extern crate ramp;
///
/// use ramp::RandomInt;
///
/// fn main() {
/// let mut rng = rand::thread_rng();
/// let big_i = rng.gen_int(256);
/// }
/// ```
pub trait RandomInt {
/// Generate a random unsigned `Int` of given bit size.
fn gen_uint(&mut self, bits: usize) -> Int;
/// Generate a random `Int` of given bit size.
fn gen_int(&mut self, bits: usize) -> Int;
/// Generate a random unsigned `Int` less than the given bound.
/// Fails when the bound is zero or negative.
fn gen_uint_below(&mut self, bound: &Int) -> Int;
/// Generate a random `Int` within the given range.
/// The lower bound is inclusive; the upper bound is exclusive.
/// Fails when the upper bound is not greater than the lower bound.
fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int;
}
impl<R: Rng> RandomInt for R {
fn gen_uint(&mut self, bits: usize) -> Int {
assert!(bits > 0);
let limbs = (bits / &Limb::BITS) as u32;
let rem = bits % &Limb::BITS;
let mut i = Int::with_capacity(limbs + 1);
for _ in (0 .. limbs) {
let limb = Limb(self.gen());
i.push(limb);
}
if rem > 0 {
let final_limb = Limb(self.gen());
i.push(final_limb >> (&Limb::BITS - rem));
}
i.normalize();
i
}
fn gen_int(&mut self, bits: usize) -> Int {
let i = self.gen_uint(bits);
let r = if i == Int::zero() {
// ...except that if the BigUint is zero, we need to try
// again with probability 0.5. This is because otherwise,
// the probability of generating a zero BigInt would be
// double that of any other number.
if self.gen() {
return self.gen_uint(bits);
} else {
i
}
} else if self.gen() {
-i
} else {
i
};
r
}
fn gen_uint_below(&mut self, bound: &Int) -> Int {
assert!(*bound > Int::zero());
let mut i = (*bound).clone();
i.normalize();
let lz = bound.to_single_limb().leading_zeros() as i32;
let bits = ((bound.abs_size() * Limb::BITS as i32) - lz) as usize;
loop {
let n = self.gen_uint(bits);
if n < *bound { return n; }
}
}
fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int {
assert!(*lbound < *ubound);
lbound + self.gen_uint_below(&(ubound - lbound))
}
}
#[cfg(test)]
mod test {
use std;
use std::hash::{Hash, Hasher};
use rand::{self, Rng};
use test::{self, Bencher};
use super::*;
use ll::limb::Limb;
use std::str::FromStr;
use std::num::Zero;
macro_rules! assert_mp_eq (
($l:expr, $r:expr) => (
{
let l : Int = $l;
let r : Int = $r;
if l != r {
println!("assertion failed: {} == {}", stringify!($l), stringify!($r));
panic!("{:} != {:}", l, r);
}
}
)
);
#[test]
fn from_string_10() {
let cases = [
("0", 0i32),
("123456", 123456),
("0123", 123),
("000000", 0),
("-0", 0),
("-1", -1),
("-123456", -123456),
("-0123", -123),
];
for &(s, n) in cases.iter() {
let i : Int = s.parse().unwrap();
assert_eq!(i, n);
}
}
#[test]
fn from_string_16() {
let cases = [
("0", 0i32),
("abcde", 0xabcde),
("0ABC", 0xabc),
("12AB34cd", 0x12ab34cd),
("-ABC", -0xabc),
("-0def", -0xdef),
];
for &(s, n) in cases.iter() {
let i : Int = Int::from_str_radix(s, 16).unwrap();
assert!(i == n, "Assertion failed: {:#x} != {:#x}", i, n);
}
}
#[test]
fn to_string_10() {
let cases = [
("0", Int::zero()),
("1", Int::from(1)),
("123", Int::from(123)),
("-456", Int::from(-456)),
("987654321012345678910111213",
Int::from_str("987654321012345678910111213").unwrap()),
];
for &(s, ref n) in cases.iter() {
assert_eq!(s, &n.to_string());
}
}
#[test]
fn to_string_16() {
let cases = [
("0", Int::zero()),
("1", Int::from(1)),
("-1", Int::from(-1)),
("abc", Int::from(0xabc)),
("-456", Int::from(-0x456)),
("987654321012345678910111213",
Int::from_str_radix("987654321012345678910111213", 16).unwrap()),
];
for &(s, ref n) in cases.iter() {
assert_eq!(s, &n.to_str_radix(16, false));
}
}
#[test]
fn pow() {
let bases = ["0", "1", "190000000000000", "192834857324591531",
"340282366920938463463374607431768211456", // 2**128
"100000000", "-1", "-100", "-200", "-192834857324591531",
"-431343873217510631841",
"-340282366920938463463374607431768211456"];
for b in bases.iter() {
let b : Int = b.parse().unwrap();
let mut x = Int::one();
for e in 0..512 {
let a = &b.pow(e);
// println!("b={}, e={}, a={}, x={}", &b, &e, &a, &x);
assert_mp_eq!(a.clone(), x.clone());
x = &x * &b
}
}
}
#[test]
fn add() {
let cases = [
("0", "0", "0"),
("1", "0", "1"),
("1", "1", "2"),
("190000000000000", "1", "190000000000001"),
("192834857324591531", "431343873217510631841", "431536708074835223372"),
("0", "-1", "-1"),
("1", "-1", "0"),
("100000000", "-1", "99999999"),
("-100", "-100", "-200"),
("-192834857324591531", "-431343873217510631841", "-431536708074835223372"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(l + r, a);
}
}
#[test]
fn sub() {
let cases = [
("0", "0", "0"),
("1", "0", "1"),
("1", "1", "0"),
("0", "1", "-1"),
("190000000000000", "1", "189999999999999"),
("192834857324591531", "431343873217510631841", "-431151038360186040310"),
("0", "-1", "1"),
("1", "-1", "2"),
("100000000", "-1", "100000001"),
("-100", "-100", "0"),
("-100", "100", "-200"),
("237", "236", "1"),
("-192834857324591531", "-431343873217510631841", "431151038360186040310")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(&l - &r, a.clone());
assert_mp_eq!(&l - r.clone(), a.clone());
assert_mp_eq!(l.clone() - &r, a.clone());
assert_mp_eq!(l - r, a);
}
}
#[test]
fn mul() {
let cases = [
("0", "0", "0"),
("1", "0", "0"),
("1", "1", "1"),
("1234", "-1", "-1234"),
("8", "9", "72"),
("-8", "-9", "72"),
("8", "-9", "-72"),
("1234567891011", "9876543210123", "12193263121400563935904353"),
("-1234567891011", "9876543210123", "-12193263121400563935904353"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(l * r, a);
}
}
#[test]
fn div() {
let cases = [
("1", "1", "1"),
("1234", "-1", "-1234"),
("8", "9", "0"),
("-9", "-3", "3"),
("1234567891011121314151617", "95123654789852856006", "12978"),
("-1234567891011121314151617", "95123654789852856006", "-12978"),
("-1198775410753307067346230628764044530011323809665206377243907561641040294348297309637331525393593945901384203950086960228531308793518800829453656715578105987032036211272103322425770761458186593",
"979504192721382235629958845425279521512826176107035761459344386626944187481828320416870752582555",
"-1223859397092234843008309150569447886995823751180958876260102037121722431272801092547910923059616")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l / &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn rem() {
let cases = [
("2", "1", "0"),
("1", "2", "1"),
("100", "2", "0"),
("100", "3", "1"),
("234129835798275032157029375235", "4382109473241242142341234", "2490861941946976021925083")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l % &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn bitand() {
let cases = [
("0", "543253451643657932075830214751263521", "0"),
("-1", "543253451643657932075830214751263521", "543253451643657932075830214751263521"),
("47398217493274092174042109472", "9843271092740214732017421", "152974816756326460458496"),
("87641324986400000000000", "31470973247490321000000000000000", "2398658832415825854464")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l & &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn bitor() {
let cases = [
("0", "543253451643657932075830214751263521", "543253451643657932075830214751263521"),
("-1", "543253451643657932075830214751263521", "-1"),
("47398217493274092174042109472", "9843271092740214732017421","47407907789550076062313668397"),
("87641324986400000000000", "31470973247490321000000000000000", "31470973332732987153984174145536"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l | &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn is_even() {
let cases = [
("0", true),
("1", false),
("47398217493274092174042109472", true),
("47398217493274092174042109471", false),
];
for &(v, even) in cases.iter() {
let val : Int = v.parse().unwrap();
assert_eq!(val.is_even(), even);
let val = -val;
assert_eq!(val.is_even(), even);
}
}
#[test]
fn trailing_zeros() {
let cases = [
("0", 0),
("1", 0),
("16", 4),
("3036937844145311324764506857395738547330878864826266812416", 100)
];
for &(v, count) in cases.iter() {
let val : Int = v.parse().unwrap();
assert_eq!(val.trailing_zeros(), count);
}
}
#[test]
fn arith_prim() {
// Test that the Int/prim overloads are working as expected
let x : Int = "100".parse().unwrap();
// Int op prim
assert_mp_eq!(&x + 1usize, "101".parse().unwrap());
assert_mp_eq!(&x - 1usize, "99".parse().unwrap());
assert_mp_eq!(&x + 1i32, "101".parse().unwrap());
assert_mp_eq!(&x - 1i32, "99".parse().unwrap());
assert_mp_eq!(&x + (-1i32), "99".parse().unwrap());
assert_mp_eq!(&x - (-1i32), "101".parse().unwrap());
assert_mp_eq!(&x * 2usize, "200".parse().unwrap());
assert_mp_eq!(&x * 2i32, "200".parse().unwrap());
assert_mp_eq!(&x * (-2i32), "-200".parse().unwrap());
assert_mp_eq!(&x / 2usize, "50".parse().unwrap());
assert_mp_eq!(&x / 2i32, "50".parse().unwrap());
assert_mp_eq!(&x / (-2i32), "-50".parse().unwrap());
assert_mp_eq!(&x % 2usize, "0".parse().unwrap());
assert_mp_eq!(&x % 2i32, "0".parse().unwrap());
assert_mp_eq!(&x % (-2i32), "0".parse().unwrap());
let x : Int = "5".parse().unwrap();
// prim op Int
assert_mp_eq!(1usize + &x, "6".parse().unwrap());
assert_mp_eq!(1usize - &x, "-4".parse().unwrap());
assert_mp_eq!(1i32 + &x, "6".parse().unwrap());
assert_mp_eq!(1i32 - &x, "-4".parse().unwrap());
assert_mp_eq!((-1i32) + &x, "4".parse().unwrap());
assert_mp_eq!((-1i32) - &x, "-6".parse().unwrap());
assert_mp_eq!(2usize * &x, "10".parse().unwrap());
assert_mp_eq!(2i32 * &x, "10".parse().unwrap());
assert_mp_eq!((-2i32) * &x, "-10".parse().unwrap());
assert_mp_eq!(20usize / &x, "4".parse().unwrap());
assert_mp_eq!(20i32 / &x, "4".parse().unwrap());
assert_mp_eq!((-20i32) / &x, "-4".parse().unwrap());
}
#[test]
fn int_from() {
let i = Int::from(::std::i64::MIN);
assert_eq!(i64::from(&i), ::std::i64::MIN);
let i = Int::from(::std::i32::MIN);
assert_eq!(i32::from(&i), ::std::i32::MIN);
let i = Int::from(::std::usize::MAX);
assert_eq!(usize::from(&i), ::std::usize::MAX);
}
const RAND_ITER : usize = 1000;
#[test]
fn div_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let x = rng.gen_int(640);
let y = rng.gen_int(320);
let (q, r) = x.divmod(&y);
let val = (q * &y) + r;
assert_mp_eq!(val, x);
}
}
#[test]
fn sqr_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let x = rng.gen_int(640);
let xs = x.square();
let xm = &x * &x;
assert_mp_eq!(xm, xs);
}
}
#[test]
fn shl_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let x = rng.gen_int(640);
let shift_1 = &x << 1;
let mul_2 = &x * 2;
assert_mp_eq!(shift_1, mul_2);
let shift_3 = &x << 3;
let mul_8 = &x * 8;
assert_mp_eq!(shift_3, mul_8);
}
}
#[test]
fn shl_rand_large() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let pow : usize = rng.gen_range(64, 8196);
let mul_by = Int::from(2).pow(pow);
let x = rng.gen_int(640);
let shift = &x << pow;
let mul = x * mul_by;
assert_mp_eq!(shift, mul);
}
}
#[test]
fn shr_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let pow : usize = rng.gen_range(64, 8196);
let x = rng.gen_int(640);
let shift_up = &x << pow;
let shift_down = shift_up >> pow;
assert_mp_eq!(shift_down, x);
}
}
#[test]
fn bitand_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let x = rng.gen_int(640);
let y = rng.gen_int(640);
let _ = x & y;
}
}
#[test]
fn hash_rand() {
let mut rng = rand::thread_rng();
for _ in (0..RAND_ITER) {
let x1 = rng.gen_int(640);
let x2 = x1.clone();
assert!(x1 == x2);
let mut hasher = std::hash::SipHasher::new();
x1.hash(&mut hasher);
let x1_hash = hasher.finish();
let mut hasher = std::hash::SipHasher::new();
x2.hash(&mut hasher);
let x2_hash = hasher.finish();
assert!(x1_hash == x2_hash);
}
}
#[test]
#[should_panic]
fn gen_uint_with_zero_bits() {
let mut rng = rand::thread_rng();
rng.gen_uint(0);
}
#[test]
#[should_panic]
fn gen_int_with_zero_bits() {
let mut rng = rand::thread_rng();
rng.gen_int(0);
}
#[test]
#[should_panic]
fn gen_uint_below_zero_or_negative() {
let mut rng = rand::thread_rng();
let i = Int::from(0);
rng.gen_uint_below(&i);
let j = Int::from(-1);
rng.gen_uint_below(&j);
}
#[test]
#[should_panic]
fn gen_int_range_zero() {
let mut rng = rand::thread_rng();
let b = Int::from(123);
rng.gen_int_range(&b, &b);
}
#[test]
#[should_panic]
fn gen_int_range_negative() {
let mut rng = rand::thread_rng();
let lb = Int::from(123);
let ub = Int::from(321);
rng.gen_int_range(&ub, &lb);
}
#[test]
fn gen_int_range() {
let mut rng = rand::thread_rng();
for _ in 0..10 {
let i = rng.gen_int_range(&Int::from(236), &Int::from(237));
assert_eq!(i, Int::from(236));
}
let l = Int::from(403469000 + 2352);
let u = Int::from(403469000 + 3513);
for _ in 0..1000 {
let n: Int = rng.gen_uint_below(&u);
assert!(n < u);
let n: Int = rng.gen_int_range(&l, &u);
assert!(n >= l);
assert!(n < u);
}
}
fn bench_add(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x + &y;
test::black_box(z);
});
}
#[bench]
fn bench_add_1_1(b: &mut Bencher) {
bench_add(b, 1, 1);
}
#[bench]
fn bench_add_10_10(b: &mut Bencher) {
bench_add(b, 10, 10);
}
#[bench]
fn bench_add_100_100(b: &mut Bencher) {
bench_add(b, 100, 100);
}
#[bench]
fn bench_add_1000_1000(b: &mut Bencher) {
bench_add(b, 1000, 1000);
}
#[bench]
fn bench_add_1000_10(b: &mut Bencher) {
bench_add(b, 1000, 10);
}
fn bench_mul(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x * &y;
test::black_box(z);
});
}
fn bench_pow(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y : usize = rng.gen_range(0, ys);
b.iter(|| {
let z = &x.pow(y);
test::black_box(z);
});
}
#[bench]
fn bench_mul_1_1(b: &mut Bencher) {
bench_mul(b, 1, 1);
}
#[bench]
fn bench_mul_10_10(b: &mut Bencher) {
bench_mul(b, 10, 10);
}
#[bench]
fn bench_mul_2_20(b: &mut Bencher) {
bench_mul(b, 2, 20);
}
#[bench]
fn bench_mul_50_50(b: &mut Bencher) {
bench_mul(b, 50, 50);
}
#[bench]
fn bench_mul_5_50(b: &mut Bencher) {
bench_mul(b, 5, 50);
}
#[bench]
fn bench_mul_250_250(b: &mut Bencher) {
bench_mul(b, 250, 250);
}
#[bench]
fn bench_mul_1000_1000(b: &mut Bencher) {
bench_mul(b, 1000, 1000);
}
#[bench]
fn bench_mul_50_1500(b: &mut Bencher) {
bench_mul(b, 50, 1500);
}
fn bench_sqr(b: &mut Bencher, xs: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
b.iter(|| {
let z = x.square();
test::black_box(z);
});
}
#[bench]
fn bench_sqr_1(b: &mut Bencher) {
bench_sqr(b, 1);
}
#[bench]
fn bench_sqr_10(b: &mut Bencher) {
bench_sqr(b, 10);
}
#[bench]
fn bench_sqr_50(b: &mut Bencher) {
bench_sqr(b, 50);
}
#[bench]
fn bench_sqr_250(b: &mut Bencher) {
bench_sqr(b, 250);
}
#[bench]
fn bench_sqr_1000(b: &mut Bencher) {
bench_sqr(b, 1000);
}
#[bench]
fn bench_pow_1_1(b: &mut Bencher) {
bench_pow(b, 1, 1);
}
#[bench]
fn bench_pow_10_10(b: &mut Bencher) {
bench_pow(b, 10, 10);
}
#[bench]
fn bench_pow_2_20(b: &mut Bencher) {
bench_pow(b, 2, 20);
}
#[bench]
fn bench_pow_50_50(b: &mut Bencher) {
bench_pow(b, 50, 50);
}
#[bench]
fn bench_pow_5_50(b: &mut Bencher) {
bench_mul(b, 5, 50);
}
#[bench]
fn bench_pow_250_250(b: &mut Bencher) {
bench_mul(b, 250, 250);
}
#[bench]
fn bench_pow_1000_1000(b: &mut Bencher) {
bench_mul(b, 1000, 1000);
}
#[bench]
fn bench_pow_50_1500(b: &mut Bencher) {
bench_mul(b, 50, 1500);
}
#[bench]
fn bench_factorial_100(b: &mut Bencher) {
b.iter(|| {
let mut i = Int::from(1);
for j in 2..100 {
i = i * j;
}
i = i * 100;
test::black_box(i);
});
}
#[bench]
fn bench_factorial_1000(b: &mut Bencher) {
b.iter(|| {
let mut i = Int::from(1);
for j in 2..1000 {
i = i * j;
}
i = i * 1000;
test::black_box(i);
});
}
fn bench_div(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x / &y;
test::black_box(z);
});
}
#[bench]
fn bench_div_1_1(b: &mut Bencher) {
bench_div(b, 1, 1);
}
#[bench]
fn bench_div_10_10(b: &mut Bencher) {
bench_div(b, 10, 10);
}
#[bench]
fn bench_div_20_2(b: &mut Bencher) {
bench_div(b, 20, 2);
}
#[bench]
fn bench_div_50_50(b: &mut Bencher) {
bench_div(b, 50, 50);
}
#[bench]
fn bench_div_50_5(b: &mut Bencher) {
bench_div(b, 50, 5);
}
#[bench]
fn bench_div_250_250(b: &mut Bencher) {
bench_div(b, 250, 250);
}
#[bench]
fn bench_div_1000_1000(b: &mut Bencher) {
bench_div(b, 1000, 1000);
}
}
Fix parens warnings
// Copyright 2015 The Ramp Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std;
use std::cmp::{
Ordering,
Ord, Eq,
PartialOrd, PartialEq
};
use std::error::Error;
use std::{fmt, hash};
use std::io;
use std::num::Zero;
use std::ops::{
Add, Sub, Mul, Div, Rem, Neg,
AddAssign, SubAssign, MulAssign, DivAssign, RemAssign,
Shl, Shr, BitAnd, BitOr,
ShlAssign, ShrAssign, BitAndAssign, BitOrAssign,
};
use std::ptr::Unique;
use std::str::FromStr;
use rand::Rng;
use alloc;
use ll;
use ll::limb::{BaseInt, Limb};
use alloc::raw_vec::RawVec;
/**
* An arbitrary-precision signed integer.
*
* This type grows to the size it needs to in order to store the result of any operation.
*
* ## Creation
*
* An `Int` can be constructed in a number of ways:
*
* - `Int::zero` and `Int::one` construct a zero- and one-valued `Int` respectively.
*
* - `Int::from` will convert from any primitive integer type to an `Int` of the same value
*
* ```
* # use ramp::Int;
* let four = Int::from(4);
* ```
*
* - `Int::from_str` (or `str::parse`) will attempt to convert from a string to an `Int`
*
* ```
* # use ramp::Int;
* # use std::str::FromStr;
* let i = Int::from_str("123456789").unwrap();
* ```
*
* ## Output
*
* `Int` supports all the formatting traits, allowing it to be used just like a regular integer
* when used in `format!` and similar macros. `Int` also supports conversion to primitive integer
* types, truncating if the `Int` cannot fit into the target type. Conversion to primtive integers
* is done with the `From` trait:
*
* ```
* # use ramp::Int;
* let big_i = Int::from(123456789);
* let i = i32::from(&big_i);
* assert_eq!(123456789, i);
* ```
*
* ## Usage
*
* `Int` has a number of operator overloads to make working with them as painless as possible.
*
* The most basic usage is simply `a + b` or similar. Assuming `a` and `b` are of type `Int`, this
* operation will consume both operands, reusing the storage from one of them. If you do not wish
* your operands to be moved, one or both of them can be references: `&a + &b` works as well, but
* requires an entire new `Int` to be allocated for the return value.
*
* There are also a overloads for a small number of primitive integer types, namely `i32` and
* `usize`. While automatic type widening isn't done in Rust in general, many operations are much
* more efficient when working with a single integer. This means you can do `a + 1` knowing that it
* will be performed as efficiently as possible. Comparison with these integer types is also
* possible, allowing checks for small constant values to be done easily:
*
* ```
* # use ramp::Int;
* let big_i = Int::from(123456789);
* assert!(big_i == 123456789);
* ```
*
* ### Semantics
*
* Addition, subtraction and multiplication follow the expected rules for integers. Division of two
* integers, `N / D` is defined as producing two values: a quotient, `Q`, and a remainder, `R`,
* such that the following equation holds: `N = Q*D + R`. The division operator itself returns `Q`
* while the remainder/modulo operator returns `R`.
*
* The "bit-shift" operations are defined as being multiplication and division by a power-of-two for
* shift-left and shift-right respectively. The sign of the number is unaffected.
*
* The remaining bitwise operands act as if the numbers are stored in two's complement format and as
* if the two inputs have the same number of bits.
*
*/
pub struct Int {
ptr: Unique<Limb>,
size: i32,
cap: u32
}
impl Int {
pub fn zero() -> Int {
<Int as Zero>::zero()
}
pub fn one() -> Int {
<Int as std::num::One>::one()
}
/// Creates a new Int from the given Limb.
pub fn from_single_limb(limb: Limb) -> Int {
let mut i = Int::with_capacity(1);
unsafe {
*i.ptr.get_mut() = limb;
}
i.size = 1;
i
}
/**
* Views the internal memory as a `RawVec`, which can be
* manipulated to change `self`'s allocation.
*/
fn with_raw_vec<F: FnOnce(&mut RawVec<Limb>)>(&mut self, f: F) {
unsafe {
let old_cap = self.cap as usize;
let mut vec = RawVec::from_raw_parts(self.ptr.get_mut(), old_cap);
// if `f` panics, let `vec` do the cleaning up, not self.
self.cap = 0;
f(&mut vec);
// update `self` for any changes that happened
self.ptr = Unique::new(vec.ptr());
let new_cap = vec.cap();
assert!(new_cap <= std::u32::MAX as usize);
self.cap = new_cap as u32;
// ownership has transferred back into `self`, so make
// sure that allocation isn't freed by `vec`.
std::mem::forget(vec);
if old_cap < new_cap {
// the allocation got larger, new Limbs should be
// zero.
let self_ptr = self.ptr.get_mut() as *mut _;
std::ptr::write_bytes(self_ptr.offset(old_cap as isize) as *mut u8,
0,
(new_cap - old_cap) * std::mem::size_of::<Limb>());
}
}
}
fn with_capacity(cap: u32) -> Int {
let mut ret = Int::zero();
if cap != 0 {
ret.with_raw_vec(|v| v.reserve_exact(0, cap as usize))
}
ret
}
/**
* Returns the sign of the Int as either -1, 0 or 1 for self being negative, zero
* or positive, respectively.
*/
#[inline(always)]
pub fn sign(&self) -> i32 {
if self.size == 0 {
0
} else if self.size < 0 {
-1
} else {
1
}
}
/**
* Consumes self and returns the absolute value
*/
#[inline]
pub fn abs(mut self) -> Int {
self.size = self.size.abs();
self
}
/**
* Returns the least-significant limb of self.
*/
#[inline]
pub fn to_single_limb(&self) -> Limb {
if self.sign() == 0 {
return Limb(0);
} else {
return unsafe { *self.ptr.get() };
}
}
#[inline(always)]
fn abs_size(&self) -> i32 {
self.size.abs()
}
/**
* Compare the absolute value of self to the absolute value of other,
* returning an Ordering with the result.
*/
pub fn abs_cmp(&self, other: &Int) -> Ordering {
if self.abs_size() > other.abs_size() {
Ordering::Greater
} else if self.abs_size() < other.abs_size() {
Ordering::Less
} else {
unsafe {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size())
}
}
}
/**
* Try to shrink the allocated data for this Int.
*/
pub fn shrink_to_fit(&mut self) {
let mut size = self.abs_size() as usize;
if (self.cap as usize) == size { return; } // already as small as possible
if size == 0 { size = 1; } // Keep space for at least one limb around
self.with_raw_vec(|v| {
v.shrink_to_fit(size);
})
}
/**
* Returns a string containing the value of self in base `base`. For bases greater than
* ten, if `upper` is true, upper-case letters are used, otherwise lower-case ones are used.
*
* Panics if `base` is less than two or greater than 36.
*/
pub fn to_str_radix(&self, base: u8, upper: bool) -> String {
if self.size == 0 {
return "0".to_string();
}
if base < 2 || base > 36 {
panic!("Invalid base: {}", base);
}
let size = self.abs_size();
let num_digits = unsafe {
ll::base::num_base_digits(self.ptr.get(), size - 1, base as u32)
};
let mut buf : Vec<u8> = Vec::with_capacity(num_digits);
self.write_radix(&mut buf, base, upper).unwrap();
unsafe { String::from_utf8_unchecked(buf) }
}
pub fn write_radix<W: io::Write>(&self, w: &mut W, base: u8, upper: bool) -> io::Result<()> {
debug_assert!(self.well_formed());
if self.sign() == -1 {
try!(w.write_all(b"-"));
}
let letter = if upper { b'A' } else { b'a' };
let size = self.abs_size();
unsafe {
ll::base::to_base(base as u32, self.ptr.get(), size, |b| {
if b < 10 {
w.write_all(&[b + b'0']).unwrap();
} else {
w.write_all(&[(b - 10) + letter]).unwrap();
}
});
}
Ok(())
}
/**
* Creates a new Int from the given string in base `base`.
*/
pub fn from_str_radix(mut src: &str, base: u8) -> Result<Int, ParseIntError> {
if base < 2 || base > 36 {
panic!("Invalid base: {}", base);
}
if src.len() == 0 {
return Err(ParseIntError { kind: ErrorKind::Empty });
}
let mut sign = 1;
if src.starts_with('-') {
sign = -1;
src = &src[1..];
}
if src.len() == 0 {
return Err(ParseIntError { kind: ErrorKind::Empty });
}
let mut buf = Vec::with_capacity(src.len());
for c in src.bytes() {
let b = match c {
b'0'...b'9' => c - b'0',
b'A'...b'Z' => (c - b'A') + 10,
b'a'...b'z' => (c - b'a') + 10,
_ => {
return Err(ParseIntError { kind: ErrorKind::InvalidDigit });
}
};
if b >= base { return Err(ParseIntError { kind: ErrorKind::InvalidDigit }); }
buf.push(b);
}
let num_digits = ll::base::base_digits_to_len(src.len(), base as u32);
let mut i = Int::with_capacity(num_digits as u32);
unsafe {
let size = ll::base::from_base(i.ptr.get_mut(), buf.as_ptr(), buf.len() as i32, base as u32);
i.size = (size as i32) * sign;
}
Ok(i)
}
/**
* Divide self by other, returning the quotient, Q, and remainder, R as (Q, R).
*
* With N = self, D = other, Q and R satisfy: `N = QD + R`.
*/
pub fn divmod(&self, other: &Int) -> (Int, Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
let out_size = if self.abs_size() < other.abs_size() {
1
} else {
(self.abs_size() - other.abs_size()) + 1
};
let out_sign = self.sign() * other.sign();
let mut q = Int::with_capacity(out_size as u32);
q.size = out_size * out_sign;
let mut r = Int::with_capacity(other.abs_size() as u32);
r.size = other.abs_size() * self.sign();
unsafe {
ll::divrem(q.ptr.get_mut(), r.ptr.get_mut(),
self.ptr.get(), self.abs_size(),
other.ptr.get(), other.abs_size());
}
q.normalize();
r.normalize();
(q, r)
}
/**
* Raises self to the power of exp
*/
pub fn pow(&self, exp: usize) -> Int {
debug_assert!(self.well_formed());
match exp {
0 => Int::one(),
1 => self.clone(),
2 => self.square(),
_ => {
let mut signum = self.sign();
if signum == 0 {
return Int::zero();
}
if exp & 1 == 0 {
signum = 1
}
let ret_sz = unsafe {
ll::pow::num_pow_limbs(self.ptr.get(), self.abs_size(), exp as u32)
};
let mut ret = Int::with_capacity(ret_sz as u32);
ret.size = ret_sz * signum;
unsafe {
ll::pow::pow(ret.ptr.get_mut(), self.ptr.get(), self.abs_size(), exp as u32);
}
ret.normalize();
ret
}
}
}
/**
* Returns the square of `self`.
*/
pub fn square(&self) -> Int {
debug_assert!(self.well_formed());
let s = self.sign();
if s == 0 {
Int::zero()
} else if self.abs_size() == 1 {
let a = self.clone() * self.to_single_limb();
if s == -1 {
a.abs()
} else if s == 1 {
a
} else {
unreachable!()
}
} else {
let sz = self.abs_size() * 2;
let mut ret = Int::with_capacity(sz as u32);
ret.size = sz;
unsafe {
ll::sqr(ret.ptr.get_mut(), self.ptr.get(), self.abs_size());
}
ret.normalize();
ret
}
}
// DESTRUCTIVE square. Is there a more idiomatic way of doing this?
pub fn dsquare(mut self) -> Int {
debug_assert!(self.well_formed());
let s = self.sign();
if s == 0 {
Int::zero()
} else if self.abs_size() == 1 {
let l = self.to_single_limb();
self = self * l;
if s == -1 {
self.abs()
} else if s == 1 {
self
} else {
unreachable!()
}
} else {
self.square()
}
}
/**
* Negates `self` in-place
*/
pub fn negate(&mut self) {
self.size *= -1;
}
/**
* Returns whether or not this number is even.
*
* Returns 0 if `self == 0`
*/
#[inline]
pub fn is_even(&self) -> bool {
debug_assert!(self.well_formed());
(self.to_single_limb().0 & 1) == 0
}
/**
* Returns the number of trailing zero bits in this number
*
* Returns 0 if `self == 0`
*/
#[inline]
pub fn trailing_zeros(&self) -> u32 {
debug_assert!(self.well_formed());
if self.sign() == 0 {
0
} else {
unsafe {
ll::scan_1(self.ptr.get(), self.abs_size())
}
}
}
fn ensure_capacity(&mut self, cap: u32) {
if cap > self.cap {
let old_cap = self.cap as usize;
self.with_raw_vec(|v| {
v.reserve_exact(old_cap, cap as usize - old_cap)
})
}
}
fn push(&mut self, limb: Limb) {
let new_size = (self.abs_size() + 1) as u32;
self.ensure_capacity(new_size);
unsafe {
let pos = self.abs_size() as isize;
*self.ptr.offset(pos) = limb;
// If it was previously empty, then just make it positive,
// otherwise maintain the signedness
if self.size == 0 {
self.size = 1;
} else {
self.size += self.sign();
}
}
}
/**
* Adjust the size field so the most significant limb is non-zero
*/
fn normalize(&mut self) {
if self.size == 0 { return }
let sign = self.sign();
unsafe {
while self.size != 0 &&
*self.ptr.offset((self.abs_size() - 1) as isize) == 0 {
self.size -= sign;
}
}
debug_assert!(self.well_formed());
}
/**
* Make sure the Int is "well-formed", i.e. that the size doesn't exceed the
* the capacity and that the most significant limb is non-zero
*/
fn well_formed(&self) -> bool {
if self.size == 0 { return true; }
if (self.abs_size() as u32) > self.cap {
return false;
}
let high_limb = unsafe {
*self.ptr.offset((self.abs_size() - 1) as isize)
};
return high_limb != 0;
}
}
impl Clone for Int {
fn clone(&self) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 {
return Int::zero();
}
let mut new = Int::with_capacity(self.abs_size() as u32);
unsafe {
ll::copy_incr(self.ptr.get(), new.ptr.get_mut(), self.abs_size());
}
new.size = self.size;
new
}
fn clone_from(&mut self, other: &Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
self.size = 0;
return;
}
self.ensure_capacity(other.abs_size() as u32);
unsafe {
ll::copy_incr(other.ptr.get(), self.ptr.get_mut(), other.abs_size());
self.size = other.size;
}
}
}
impl std::default::Default for Int {
#[inline]
fn default() -> Int {
Int::zero()
}
}
impl Drop for Int {
fn drop(&mut self) {
if self.cap > 0 {
unsafe {
drop(RawVec::from_raw_parts(self.ptr.get_mut(),
self.cap as usize));
}
self.cap = 0;
self.size = 0;
}
}
}
impl PartialEq<Int> for Int {
#[inline]
fn eq(&self, other: &Int) -> bool {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if self.size == other.size {
unsafe {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size()) == Ordering::Equal
}
} else {
false
}
}
}
impl PartialEq<Limb> for Int {
#[inline]
fn eq(&self, other: &Limb) -> bool {
if *other == 0 && self.size == 0 {
return true;
}
self.size == 1 && unsafe { *self.ptr.get() == *other }
}
}
impl PartialEq<Int> for Limb {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl Eq for Int { }
impl Ord for Int {
#[inline]
fn cmp(&self, other: &Int) -> Ordering {
if self.size < other.size {
Ordering::Less
} else if self.size > other.size {
Ordering::Greater
} else { // Same number of digits and same sign
// Check for zero
if self.size == 0 {
return Ordering::Equal;
}
unsafe {
// If both are positive, do `self cmp other`, if both are
// negative, do `other cmp self`
if self.sign() == 1 {
ll::cmp(self.ptr.get(), other.ptr.get(), self.abs_size())
} else {
ll::cmp(other.ptr.get(), self.ptr.get(), self.abs_size())
}
}
}
}
}
impl PartialOrd<Int> for Int {
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd<Limb> for Int {
#[inline]
fn partial_cmp(&self, other: &Limb) -> Option<Ordering> {
if self.eq(other) {
return Some(Ordering::Equal);
}
if self.size < 1 {
Some(Ordering::Less)
} else if self.size > 1 {
Some(Ordering::Greater)
} else {
unsafe {
self.ptr.get().partial_cmp(other)
}
}
}
}
impl PartialOrd<Int> for Limb {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
other.partial_cmp(self).map(|o| o.reverse())
}
}
impl hash::Hash for Int {
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
debug_assert!(self.well_formed());
self.sign().hash(state);
let mut size = self.abs_size();
unsafe {
let mut ptr = self.ptr.get() as *const Limb;
while size > 0 {
let l = *ptr;
l.hash(state);
ptr = ptr.offset(1);
size -= 1;
}
}
}
}
impl AddAssign<Limb> for Int {
fn add_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 { return; }
// No capacity means `self` is zero. Just push `other` into it
if self.cap == 0 {
self.push(other);
return;
}
// This is zero, but has allocated space, so just store `other`
if self.size == 0 {
unsafe {
*self.ptr.get_mut() = other;
self.size = 1;
}
}
// `self` is non-zero, reuse the storage for the result.
unsafe {
let sign = self.sign();
let size = self.abs_size();
let ptr = self.ptr.get_mut() as *mut Limb;
// Self is positive, just add `other`
if sign == 1 {
let carry = ll::add_1(ptr, ptr, size, other);
if carry != 0 {
self.push(carry);
}
} else {
// Self is negative, "subtract" other from self, basically doing:
// -(-self - other) == self + other
let borrow = ll::sub_1(ptr, ptr, size, other);
if borrow != 0 {
// There was a borrow, ignore it but flip the sign on self
self.size = self.abs_size();
}
}
}
}
}
impl Add<Limb> for Int {
type Output = Int;
#[inline]
fn add(mut self, other: Limb) -> Int {
self += other;
self
}
}
impl<'a> AddAssign<&'a Int> for Int {
fn add_assign(&mut self, other: &'a Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if self.sign() == 0 {
// Try to reuse the allocation from `self`
self.clone_from(other);
return;
}
if other.sign() == 0 {
return;
}
if self.sign() == other.sign() {
// Signs are the same, add the two numbers together and re-apply
// the sign after.
let sign = self.sign();
unsafe {
// There's a restriction that x-size >= y-size, we can swap the operands
// no problem, but we'd like to re-use `self`s memory if possible, so
// if `self` is the smaller of the two we make sure it has enough space
// for the result
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::add(ptr,
xp, xs,
yp, ys);
self.size = xs * sign;
self.normalize();
if carry != 0 {
self.push(carry);
}
}
} else {
// Signs are different, use the sign from the bigger (absolute value)
// of the two numbers and subtract the smaller one.
unsafe {
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() > other.abs_size() {
(self.ptr.get(), self.size, other.ptr.get(), other.size)
} else if self.abs_size() < other.abs_size() {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.size, self.ptr.get(), self.size)
} else {
match self.abs_cmp(other) {
Ordering::Equal => {
// They're equal, but opposite signs, so the result
// will be zero, clear `self` and return
self.size = 0;
return;
}
Ordering::Greater =>
(self.ptr.get(), self.size, other.ptr.get(), other.size),
Ordering::Less =>
(other.ptr.get(), other.size, self.ptr.get(), self.size)
}
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let _borrow = ll::sub(ptr,
xp, xs.abs(),
yp, ys.abs());
// There shouldn't be any borrow
debug_assert!(_borrow == 0);
self.size = xs;
self.normalize();
debug_assert!(self.abs_size() > 0);
}
}
}
}
impl<'a> Add<&'a Int> for Int {
type Output = Int;
#[inline]
fn add(mut self, other: &'a Int) -> Int {
self += other;
self
}
}
impl<'a> Add<Int> for &'a Int {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
// Forward to other + self
other.add(self)
}
}
impl Add<Int> for Int {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
// Check for self or other being zero.
if self.sign() == 0 {
return other;
}
if other.sign() == 0 {
return self;
}
let (x, y) = if self.abs_size() >= other.abs_size() {
(self, &other)
} else {
(other, &self)
};
return x.add(y);
}
}
impl AddAssign<Int> for Int {
#[inline]
fn add_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this + other;
}
}
impl<'a, 'b> Add<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn add(self, other: &'a Int) -> Int {
if self.sign() == 0 {
return other.clone();
}
if other.sign() == 0 {
return self.clone();
}
// Clone the bigger of the two
if self.abs_size() >= other.abs_size() {
self.clone().add(other)
} else {
other.clone().add(self)
}
}
}
impl SubAssign<Limb> for Int {
fn sub_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 { return; }
// No capacity means `self` is zero. Just push the limb.
if self.cap == 0 {
self.push(other);
self.size = -1;
return;
}
// This is zero, but has allocated space, so just store `other`
if self.size == 0 {
unsafe {
*self.ptr.get_mut() = other;
self.size = -1;
}
return;
}
// `self` is non-zero, reuse the storage for the result.
unsafe {
let sign = self.sign();
let size = self.abs_size();
let ptr = self.ptr.get_mut() as *mut Limb;
// Self is negative, just "add" `other`
if sign == -1 {
let carry = ll::add_1(ptr, ptr, size, other);
if carry != 0 {
self.push(carry);
}
} else {
// Self is positive, subtract other from self
let carry = ll::sub_1(ptr, ptr, size, other);
self.normalize();
if carry != 0 {
// There was a carry, ignore it but flip the sign on self
self.size = -self.abs_size();
}
}
}
debug_assert!(self.well_formed());
}
}
impl Sub<Limb> for Int {
type Output = Int;
#[inline]
fn sub(mut self, other: Limb) -> Int {
self -= other;
self
}
}
impl<'a> SubAssign<&'a Int> for Int {
fn sub_assign(&mut self, other: &'a Int) {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
// LHS is zero, set self to the negation of the RHS
if self.sign() == 0 {
self.clone_from(other);
self.size *= -1;
return;
}
// RHS is zero, do nothing
if other.sign() == 0 {
return;
}
if self.sign() == other.sign() {
unsafe {
// Signs are the same, subtract the smaller one from
// the bigger one and adjust the sign as appropriate
let (xp, xs, yp, ys, flip): (*const Limb, _, *const Limb, _, _) = match self.abs_cmp(other) {
Ordering::Equal => {
// x - x, just return zero
self.size = 0;
return;
}
Ordering::Less => {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.size, self.ptr.get(), self.size, true)
}
Ordering::Greater =>
(self.ptr.get(), self.size, other.ptr.get(), other.size, false)
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let _borrow = ll::sub(ptr, xp, xs.abs(), yp, ys.abs());
debug_assert!(_borrow == 0);
self.size = if flip {
xs * -1
} else {
xs
};
}
self.normalize();
} else { // Different signs
if self.sign() == -1 {
// self is negative, use addition and negation
self.size *= -1;
*self += other;
self.size *= -1;
} else {
unsafe {
// Other is negative, handle as addition
let (xp, xs, yp, ys): (*const Limb, _, *const Limb, _) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
self.ensure_capacity(other.abs_size() as u32);
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::add(ptr, xp, xs, yp, ys);
self.size = xs;
self.normalize();
if carry != 0 {
self.push(carry);
}
}
}
}
}
}
impl<'a> Sub<&'a Int> for Int {
type Output = Int;
#[inline]
fn sub(mut self, other: &'a Int) -> Int {
self -= other;
self
}
}
impl<'a> Sub<Int> for &'a Int {
type Output = Int;
#[inline]
fn sub(self, mut other: Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
other.clone_from(self);
return other;
}
-(other.sub(self))
}
}
impl Sub<Int> for Int {
type Output = Int;
#[inline]
fn sub(self, other: Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
return self;
}
self.sub(&other)
}
}
impl SubAssign<Int> for Int {
#[inline]
fn sub_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this - other;
}
}
impl<'a, 'b> Sub<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn sub(self, other: &'a Int) -> Int {
if self.sign() == 0 {
return -other;
}
if other.sign() == 0 {
return self.clone();
}
self.clone().sub(other)
}
}
impl MulAssign<Limb> for Int {
fn mul_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 || self.sign() == 0 {
self.size = 0;
return;
}
if other == 1 {
return;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let carry = ll::mul_1(ptr, ptr, self.abs_size(), other);
if carry != 0 {
self.push(carry);
}
}
}
}
impl Mul<Limb> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: Limb) -> Int {
self *= other;
self
}
}
impl<'a, 'b> Mul<&'a Int> for &'b Int {
type Output = Int;
fn mul(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
// This is the main function, since in the general case
// we need to allocate space for the return. Special cases
// where this isn't necessary are handled in the other impls
// 0 * x = 0
if self.sign() == 0 || other.sign() == 0 {
return Int::zero();
}
let out_sign = self.sign() * other.sign();
if self.abs_size() == 1 {
unsafe {
let mut ret = other.clone() * *self.ptr.get();
let size = ret.abs_size();
ret.size = size * out_sign;
return ret;
}
}
if other.abs_size() == 1 {
unsafe {
let mut ret = self.clone() * *other.ptr.get();
let size = ret.abs_size();
ret.size = size * out_sign;
return ret;
}
}
let out_size = self.abs_size() + other.abs_size();
let mut out = Int::with_capacity(out_size as u32);
out.size = out_size * out_sign;
unsafe {
let (xp, xs, yp, ys) = if self.abs_size() >= other.abs_size() {
(self.ptr.get(), self.abs_size(), other.ptr.get(), other.abs_size())
} else {
(other.ptr.get(), other.abs_size(), self.ptr.get(), self.abs_size())
};
ll::mul(out.ptr.get_mut(), xp, xs, yp, ys);
// Top limb may be zero
out.normalize();
return out;
}
}
}
impl<'a> Mul<&'a Int> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: &'a Int) -> Int {
// `other` is zero
if other.sign() == 0 {
self.size = 0;
return self;
}
// `other` is a single limb, reuse the allocation of self
if other.abs_size() == 1 {
unsafe {
let mut out = self * *other.ptr.get();
out.size *= other.sign();
return out;
}
}
// Forward to the by-reference impl
(&self) * other
}
}
impl<'a> Mul<Int> for &'a Int {
type Output = Int;
#[inline]
fn mul(self, other: Int) -> Int {
// Swap arguments
other * self
}
}
impl Mul<Int> for Int {
type Output = Int;
fn mul(mut self, other: Int) -> Int {
if self.sign() == 0 || other.sign() == 0 {
self.size = 0;
return self;
}
// One of them is a single limb big, so we can re-use the
// allocation of the other
if self.abs_size() == 1 {
let val = unsafe { *self.ptr.get() };
let mut out = other * val;
out.size *= self.sign();
return out;
}
if other.abs_size() == 1 {
let val = unsafe { *other.ptr.get() };
let mut out = self * val;
out.size *= other.sign();
return out;
}
// Still need to allocate for the result, just forward to
// the by-reference impl
(&self) * (&other)
}
}
impl<'a> MulAssign<&'a Int> for Int {
#[inline]
fn mul_assign(&mut self, other: &'a Int) {
// Temporarily extract self as a value, then overwrite it with the result
// of the multiplication
let this = std::mem::replace(self, Int::zero());
*self = this * other;
}
}
impl MulAssign<Int> for Int {
#[inline]
fn mul_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this * other;
}
}
impl DivAssign<Limb> for Int {
fn div_assign(&mut self, other: Limb) {
debug_assert!(self.well_formed());
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
// Ignore the remainder
ll::divrem_1(ptr, 0, ptr, self.abs_size(), other);
// Adjust the size if necessary
self.normalize();
}
}
}
impl Div<Limb> for Int {
type Output = Int;
#[inline]
fn div(mut self, other: Limb) -> Int {
self /= other;
self
}
}
impl<'a, 'b> Div<&'a Int> for &'b Int {
type Output = Int;
fn div(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
ll::divide_by_zero();
}
if other.abs_size() == 1 {
let l = unsafe { *other.ptr.get() };
let out_sign = self.sign() * other.sign();
let mut out = self.clone() / l;
out.size = out.abs_size() * out_sign;
return out;
}
self.divmod(other).0
}
}
impl<'a> Div<&'a Int> for Int {
type Output = Int;
#[inline]
fn div(self, other: &'a Int) -> Int {
(&self) / other
}
}
impl<'a> Div<Int> for &'a Int {
type Output = Int;
#[inline]
fn div(self, other: Int) -> Int {
self / (&other)
}
}
impl Div<Int> for Int {
type Output = Int;
#[inline]
fn div(self, other: Int) -> Int {
(&self) / (&other)
}
}
impl<'a> DivAssign<&'a Int> for Int {
#[inline]
fn div_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this / other;
}
}
impl DivAssign<Int> for Int {
#[inline]
fn div_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this / other;
}
}
impl RemAssign<Limb> for Int {
#[inline]
fn rem_assign(&mut self, other: Limb) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Rem<Limb> for Int {
type Output = Int;
fn rem(mut self, other: Limb) -> Int {
debug_assert!(self.well_formed());
if other == 0 {
ll::divide_by_zero();
}
// x % 1 == 0, 0 % n == 0
if other == 1 || self.sign() == 0 {
self.size = 0;
return self;
}
unsafe {
// Fetch the pointer first to make completely sure the compiler
// won't make bogus claims about nonaliasing due to the &mut
let ptr = self.ptr.get_mut() as *mut Limb;
let rem = ll::divrem_1(ptr, 0, ptr, self.abs_size(), other);
// Reuse the space from `self`, taking the sign from the numerator
// Since `rem` has to satisfy `N = QD + R` and D is always positive,
// `R` will always be the same sign as the numerator.
*self.ptr.get_mut() = rem;
let sign = self.sign();
self.size = sign;
self.normalize();
if self.cap > 8 {
// Shrink self, since it's at least 8 times bigger than necessary
self.shrink_to_fit();
}
}
return self;
}
}
// TODO: There's probably too much cloning happening here, need to figure out
// the best way of avoiding over-copying.
impl<'a, 'b> Rem<&'a Int> for &'b Int {
type Output = Int;
fn rem(self, other: &'a Int) -> Int {
debug_assert!(self.well_formed());
debug_assert!(other.well_formed());
if other.sign() == 0 {
ll::divide_by_zero();
}
if other.abs_size() == 1 {
let l = unsafe { *other.ptr.get() };
return self.clone() % l;
}
self.divmod(other).1
}
}
impl<'a> Rem<&'a Int> for Int {
type Output = Int;
#[inline]
fn rem(self, other: &'a Int) -> Int {
(&self) % other
}
}
impl<'a> Rem<Int> for &'a Int {
type Output = Int;
#[inline]
fn rem(self, other: Int) -> Int {
self % (&other)
}
}
impl Rem<Int> for Int {
type Output = Int;
#[inline]
fn rem(self, other: Int) -> Int {
(&self) % (&other)
}
}
impl RemAssign<Int> for Int {
#[inline]
fn rem_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl<'a> RemAssign<&'a Int> for Int {
#[inline]
fn rem_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Neg for Int {
type Output = Int;
#[inline]
fn neg(mut self) -> Int {
debug_assert!(self.well_formed());
self.size *= -1;
self
}
}
impl<'a> Neg for &'a Int {
type Output = Int;
#[inline]
fn neg(self) -> Int {
self.clone().neg()
}
}
impl Shl<usize> for Int {
type Output = Int;
#[inline]
fn shl(mut self, mut cnt: usize) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 { return self; }
if cnt >= Limb::BITS as usize {
let extra_limbs = (cnt / Limb::BITS as usize) as u32;
debug_assert!(extra_limbs >= 1);
cnt = cnt % Limb::BITS as usize;
let size = self.abs_size() as u32;
// Extend for the extra limbs, then another one for any potential extra limbs
self.ensure_capacity(extra_limbs + size + 1);
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let shift = ptr.offset(extra_limbs as isize);
ll::copy_decr(ptr, shift, self.abs_size());
ll::zero(ptr, extra_limbs as i32);
}
self.size += (extra_limbs as i32) * self.sign();
}
debug_assert!(cnt < Limb::BITS as usize);
if cnt == 0 { return self; }
let size = self.abs_size();
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let c = ll::shl(ptr, ptr, size, cnt as u32);
if c > 0 {
self.push(c);
}
}
return self;
}
}
impl<'a> Shl<usize> for &'a Int {
type Output = Int;
#[inline]
fn shl(self, cnt: usize) -> Int {
self.clone() << cnt
}
}
impl ShlAssign<usize> for Int {
#[inline]
fn shl_assign(&mut self, other: usize) {
let this = std::mem::replace(self, Int::zero());
*self = this << other;
}
}
impl Shr<usize> for Int {
type Output = Int;
#[inline]
fn shr(mut self, mut cnt: usize) -> Int {
debug_assert!(self.well_formed());
if self.sign() == 0 { return self; }
if cnt >= Limb::BITS as usize {
let removed_limbs = (cnt / Limb::BITS as usize) as u32;
let size = self.abs_size();
if removed_limbs as i32 >= size {
return Int::zero();
}
debug_assert!(removed_limbs > 0);
cnt = cnt % Limb::BITS as usize;
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
let shift = self.ptr.offset(removed_limbs as isize);
// Shift down a whole number of limbs
ll::copy_incr(shift, ptr, size);
// Zero out the high limbs
ll::zero(ptr.offset((size - (removed_limbs as i32)) as isize),
removed_limbs as i32);
self.size -= (removed_limbs as i32) * self.sign();
}
}
debug_assert!(cnt < Limb::BITS as usize);
if cnt == 0 { return self; }
let size = self.abs_size();
unsafe {
let ptr = self.ptr.get_mut() as *mut Limb;
ll::shr(ptr, ptr, size, cnt as u32);
self.normalize();
}
return self;
}
}
impl<'a> Shr<usize> for &'a Int {
type Output = Int;
#[inline]
fn shr(self, other: usize) -> Int {
self.clone() >> other
}
}
impl ShrAssign<usize> for Int {
#[inline]
fn shr_assign(&mut self, other: usize) {
let this = std::mem::replace(self, Int::zero());
*self = this >> other;
}
}
struct ComplementSplit {
ptr: *const Limb,
split_idx: i32,
len: i32
}
impl ComplementSplit {
fn low_len(&self) -> i32 { self.split_idx }
fn has_high_limbs(&self) -> bool {
self.split_idx + 1 < self.len
}
fn high_ptr(&self) -> *const Limb {
debug_assert!(self.has_high_limbs());
unsafe {
self.ptr.offset((self.split_idx + 1) as isize)
}
}
fn high_len(&self) -> i32 { self.len - (self.split_idx + 1) }
unsafe fn split_limb(&self) -> Limb {
*self.ptr.offset(self.split_idx as isize)
}
}
/*
* Helper function for the bitwise operations below.
*
* The bitwise operations act as if the numbers are stored as two's complement integers, rather
* than the signed magnitude representation that is actually used. Since converting to and from a
* two's complement representation would be horribly inefficient, we split the number into three
* segments: A number of high limbs, a single limb, the remaining zero limbs. The first segment is
* the limbs that would be inverted in a two's complement form, the single limb is the limb
* containing the first `1` bit. By definition, the remaining limbs must all be zero.
*
* This works due to the fact that `-n == !n + 1`. Consider the following bitstring, with 4-bit
* limbs:
*
* 0011 0011 1101 1000 1100 0000 0000
*
* The two's complement of this number (with an additional "sign" bit) is:
*
* 1 1100 1100 0010 0111 0100 0000 0000
*
* As you can see, all the trailing zeros are preserved and the remaining bits are all inverted
* with the exception of the first `1` bit. Since we prefer to work with whole limbs and not
* individual bits we can simply take the two's complement of the limb containing that bit
* directly.
*/
unsafe fn complement_split(np: *const Limb, len: i32) -> ComplementSplit {
debug_assert!(len > 0);
let bit_idx = ll::scan_1(np, len);
let split_idx = (bit_idx / (Limb::BITS as u32)) as i32;
ComplementSplit {
ptr: np,
split_idx: split_idx,
len: len
}
}
impl<'a> BitAnd<&'a Int> for Int {
type Output = Int;
fn bitand(mut self, other: &'a Int) -> Int {
unsafe {
let other_sign = other.sign();
let self_sign = self.sign();
// x & 0 == 0
if other_sign == 0 || self_sign == 0 {
self.size = 0;
return self;
}
// Special case -1 as the two's complement is all 1s
if *other == -1 {
return self;
}
if self == -1 {
self.clone_from(other);
return self;
}
let self_ptr = self.ptr.get_mut() as *mut Limb;
let other_ptr = other.ptr.get() as *const Limb;
// Nice easy case both are positive
if other_sign > 0 && self_sign > 0 {
let size = std::cmp::min(self.abs_size(), other.abs_size());
ll::and_n(self_ptr, self_ptr, other_ptr, size);
self.size = size;
self.normalize();
return self;
}
// Both are negative
if other_sign == self_sign {
let size = std::cmp::max(self.abs_size(), other.abs_size());
self.ensure_capacity(size as u32);
// Copy the high limbs from other to self, if self is smaller than other
if size > self.abs_size() {
ll::copy_rest(other_ptr, self_ptr, size, self.abs_size());
}
self.size = -size;
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
let self_split = complement_split(self_ptr, min_size);
let other_split = complement_split(other_ptr, min_size);
let mut zero_limbs = std::cmp::max(self_split.low_len(), other_split.low_len());
if zero_limbs > 0 {
ll::zero(self_ptr, zero_limbs);
}
// If the limb we split it is different for self and other, it'd be
// zeroed out by the above step
if self_split.low_len() == other_split.low_len() {
let split_ptr = self_ptr.offset(self_split.low_len() as isize);
*split_ptr = -(*split_ptr) & -(*other_ptr.offset(self_split.low_len() as isize));
zero_limbs += 1;
}
if zero_limbs < min_size {
let high_limbs = min_size - zero_limbs;
// Use de Morgan's Rule: !x & !y == !(x | y)
let self_ptr = self_ptr.offset(zero_limbs as isize);
let other_ptr = other_ptr.offset(zero_limbs as isize);
ll::nor_n(self_ptr, self_ptr, other_ptr, high_limbs);
}
self.normalize();
return self;
}
// If we got here one is positive, the other is negative
let (xp, yp, n) = if other_sign < 0 {
(self_ptr as *const Limb, other_ptr, self.abs_size())
} else {
if other.abs_size() > self.abs_size() {
self.ensure_capacity(other.abs_size() as u32);
// Copy the high limbs from other to self
ll::copy_rest(other_ptr, self_ptr, other.abs_size(), self.abs_size());
}
(other_ptr, self_ptr as *const Limb, other.abs_size())
};
// x > 0, y < 0
let self_ptr = self.ptr.get_mut() as *mut Limb;
let y_split = complement_split(yp, n);
let split = y_split.split_idx as isize;
ll::zero(self_ptr, y_split.low_len());
*self_ptr.offset(split) = *xp.offset(split) & -y_split.split_limb();
if y_split.has_high_limbs() {
ll::and_not_n(self_ptr.offset(split + 1), xp.offset(split + 1), y_split.high_ptr(),
y_split.high_len());
}
self.size = n;
self.normalize();
return self;
}
}
}
impl<'a> BitAnd<Int> for &'a Int {
type Output = Int;
#[inline]
fn bitand(self, other: Int) -> Int {
other.bitand(self)
}
}
impl<'a, 'b> BitAnd<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn bitand(self, other: &'a Int) -> Int {
self.clone().bitand(other)
}
}
impl BitAnd<Int> for Int {
type Output = Int;
#[inline]
fn bitand(self, other: Int) -> Int {
self.bitand(&other)
}
}
impl BitAndAssign<Int> for Int {
#[inline]
fn bitand_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this & other;
}
}
impl<'a> BitAndAssign<&'a Int> for Int {
#[inline]
fn bitand_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this & other;
}
}
impl<'a> BitOr<&'a Int> for Int {
type Output = Int;
fn bitor(mut self, other: &'a Int) -> Int {
unsafe {
if *other == 0 {
return self;
}
if self == 0 {
self.clone_from(other);
return self;
}
if *other == -1 || self == -1 {
self.size = -1;
*self.ptr.get_mut() = Limb(1);
return self;
}
let self_sign = self.sign();
let other_sign = other.sign();
let self_ptr = self.ptr.get_mut() as *mut Limb;
let other_ptr = other.ptr.get() as *const Limb;
if self_sign > 0 && other_sign > 0 {
let size = std::cmp::max(self.abs_size(), other.abs_size());
self.ensure_capacity(size as u32);
if size > self.abs_size() {
ll::copy_rest(other_ptr, self_ptr, size, self.abs_size());
}
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
ll::or_n(self_ptr, self_ptr, other_ptr, min_size);
self.size = size;
return self;
}
if self_sign == other_sign {
let min_size = std::cmp::min(self.abs_size(), other.abs_size());
let self_split = complement_split(self_ptr, min_size);
let other_split = complement_split(other_ptr, min_size);
if self_split.low_len() > other_split.low_len() {
let mut p = self_ptr.offset(other_split.low_len() as isize);
*p = -other_split.split_limb();
p = p.offset(1);
let mut o = other_ptr.offset((other_split.low_len() + 1) as isize);
let mut n = (self_split.low_len() - other_split.low_len()) - 1;
while n > 0 {
*p = !(*o);
p = p.offset(1);
o = o.offset(1);
n -= 1;
}
}
let low_limbs = std::cmp::max(self_split.low_len(), other_split.low_len()) + 1;
if low_limbs < min_size {
let high_limbs = min_size - low_limbs;
let o = other_ptr.offset(low_limbs as isize);
let s = self_ptr.offset(low_limbs as isize);
// de Morgan's Rule: !x | !y == !(x & y)
ll::nand_n(s, s, o, high_limbs);
}
self.size = -min_size;
self.normalize();
return self;
}
// If we got here one is positive, the other is negative
let n = std::cmp::max(other.abs_size(), self.abs_size());
self.ensure_capacity(n as u32);
let (xp, yp) = if other_sign < 0 {
(self_ptr as *const Limb, other_ptr)
} else {
(other_ptr, self_ptr as *const Limb)
};
// x > 0, y < 0
let y_split = complement_split(yp, n);
let split = y_split.low_len() as isize;
if xp != self_ptr {
ll::copy_incr(xp, self_ptr, y_split.low_len());
}
*self_ptr.offset(split) = *xp.offset(split) | -y_split.split_limb();
if y_split.has_high_limbs() {
ll::or_not_n(self_ptr.offset(split + 1), xp.offset(split + 1), y_split.high_ptr(),
y_split.high_len());
}
self.size = -n;
self.normalize();
return self;
}
}
}
impl<'a> BitOr<Int> for &'a Int {
type Output = Int;
#[inline]
fn bitor(self, other: Int) -> Int {
other.bitor(self)
}
}
impl<'a, 'b> BitOr<&'a Int> for &'b Int {
type Output = Int;
#[inline]
fn bitor(self, other: &'a Int) -> Int {
self.clone().bitor(other)
}
}
impl BitOr<Int> for Int {
type Output = Int;
#[inline]
fn bitor(self, other: Int) -> Int {
self.bitor(&other)
}
}
impl BitOrAssign<Int> for Int {
#[inline]
fn bitor_assign(&mut self, other: Int) {
let this = std::mem::replace(self, Int::zero());
*self = this | other;
}
}
impl<'a> BitOrAssign<&'a Int> for Int {
#[inline]
fn bitor_assign(&mut self, other: &'a Int) {
let this = std::mem::replace(self, Int::zero());
*self = this | other;
}
}
macro_rules! impl_arith_prim (
(signed $t:ty) => (
// Limbs are unsigned, so make sure we account for the sign
// when $t is signed
impl Add<$t> for Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
if other == 0 {
return self;
}
if other < 0 {
return self - Limb(other.abs() as BaseInt);
}
return self + Limb(other as BaseInt);
}
}
impl AddAssign<$t> for Int {
#[inline]
fn add_assign(&mut self, other: $t) {
if other < 0 {
*self -= Limb(other.abs() as BaseInt);
} else if other > 0 {
*self += Limb(other as BaseInt);
}
}
}
impl Sub<$t> for Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
if other == 0 {
return self;
}
if other < 0 {
return self + Limb(other.abs() as BaseInt);
}
return self - Limb(other as BaseInt);
}
}
impl SubAssign<$t> for Int {
#[inline]
fn sub_assign(&mut self, other: $t) {
if other < 0 {
*self += Limb(other.abs() as BaseInt);
} else if other > 0 {
*self -= Limb(other as BaseInt);
}
}
}
impl Mul<$t> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: $t) -> Int {
self *= other;
self
}
}
impl MulAssign<$t> for Int {
#[inline]
fn mul_assign(&mut self, other: $t) {
if other == 0 {
self.size = 0;
} else if other == -1 {
self.negate();
} else if other < 0 {
self.negate();
*self *= Limb(other.abs() as BaseInt);
} else {
*self *= Limb(other as BaseInt);
}
}
}
impl DivAssign<$t> for Int {
#[inline]
fn div_assign(&mut self, other: $t) {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return;
}
if other == -1 {
self.negate();
} else if other < 0 {
self.negate();
*self /= Limb(other.abs() as BaseInt);
} else {
*self /= Limb(other as BaseInt);
}
}
}
impl Div<$t> for Int {
type Output = Int;
#[inline]
fn div(mut self, other: $t) -> Int {
self /= other;
self
}
}
impl RemAssign<$t> for Int {
#[inline]
fn rem_assign(&mut self, other: $t) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl Rem<$t> for Int {
type Output = Int;
#[inline]
fn rem(mut self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 ||other == -1 || self.sign() == 0 {
self.size = 0;
return self;
}
return self % Limb(other.abs() as BaseInt);
}
}
impl_arith_prim!(common $t);
);
(unsigned $t:ty) => (
impl Add<$t> for Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
if other == 0 {
return self;
}
return self + Limb(other as BaseInt);
}
}
impl AddAssign<$t> for Int {
#[inline]
fn add_assign(&mut self, other: $t) {
if other != 0 {
*self += Limb(other as BaseInt);
}
}
}
impl Sub<$t> for Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
if other == 0 {
return self;
}
return self - Limb(other as BaseInt);
}
}
impl SubAssign<$t> for Int {
#[inline]
fn sub_assign(&mut self, other: $t) {
if other != 0 {
*self -= Limb(other as BaseInt);
}
}
}
impl Mul<$t> for Int {
type Output = Int;
#[inline]
fn mul(mut self, other: $t) -> Int {
if other == 0 {
self.size = 0;
return self;
}
if other == 1 || self.sign() == 0 {
return self;
}
return self * Limb(other as BaseInt);
}
}
impl MulAssign<$t> for Int {
#[inline]
fn mul_assign(&mut self, other: $t) {
if other == 0 {
self.size = 0;
} else if other > 1 && self.sign() != 0 {
*self *= Limb(other as BaseInt);
}
}
}
impl Div<$t> for Int {
type Output = Int;
#[inline]
fn div(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
return self;
}
return self / Limb(other as BaseInt);
}
}
impl DivAssign<$t> for Int {
#[inline]
fn div_assign(&mut self, other: $t) {
if other == 0 {
ll::divide_by_zero();
} else if other > 1 && self.sign() != 0 {
*self /= Limb(other as BaseInt);
}
}
}
impl Rem<$t> for Int {
type Output = Int;
#[inline]
fn rem(mut self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if other == 1 || self.sign() == 0 {
self.size = 0;
return self;
}
return self % Limb(other as BaseInt);
}
}
impl RemAssign<$t> for Int {
#[inline]
fn rem_assign(&mut self, other: $t) {
let this = std::mem::replace(self, Int::zero());
*self = this % other;
}
}
impl_arith_prim!(common $t);
);
(common $t:ty) => (
// Common impls, these should just forward to the above
// impls
impl<'a> Add<$t> for &'a Int {
type Output = Int;
#[inline]
fn add(self, other: $t) -> Int {
self.clone() + other
}
}
impl Add<Int> for $t {
type Output = Int;
#[inline]
fn add(self, other: Int) -> Int {
return other + self;
}
}
impl<'a> Add<&'a Int> for $t {
type Output = Int;
#[inline]
fn add(self, other: &'a Int) -> Int {
other.clone() + self
}
}
impl<'a> Sub<$t> for &'a Int {
type Output = Int;
#[inline]
fn sub(self, other: $t) -> Int {
self.clone() - other
}
}
impl Sub<Int> for $t {
type Output = Int;
#[inline]
fn sub(self, other: Int) -> Int {
-other + self
}
}
impl<'a> Sub<&'a Int> for $t {
type Output = Int;
#[inline]
fn sub(self, other: &'a Int) -> Int {
-(other - self)
}
}
impl<'a> Mul<$t> for &'a Int {
type Output = Int;
#[inline]
fn mul(self, other: $t) -> Int {
return self.clone() * other;
}
}
impl Mul<Int> for $t {
type Output = Int;
#[inline]
fn mul(self, other: Int) -> Int {
other * self
}
}
impl<'a> Mul<&'a Int> for $t {
type Output = Int;
#[inline]
fn mul(self, other: &'a Int) -> Int {
// Check for zero here to avoid cloning unnecessarily
if self == 0 { return Int::zero() };
other.clone() * self
}
}
impl<'a> Div<$t> for &'a Int {
type Output = Int;
#[inline]
fn div(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
return self.clone() / other;
}
}
impl Div<Int> for $t {
type Output = Int;
#[inline]
fn div(self, mut other: Int) -> Int {
if self == 0 {
other.size = 0;
return other;
}
if other.sign() == 0 {
ll::divide_by_zero();
}
// There's probably a better way of doing this, but
// I don't see n / <bigint> being common in code
Int::from(self) / other
}
}
impl<'a> Div<&'a Int> for $t {
type Output = Int;
#[inline]
fn div(self, other: &'a Int) -> Int {
if self == 0 { return Int::zero() };
if other.sign() == 0 {
ll::divide_by_zero();
}
self / other.clone()
}
}
impl<'a> Rem<$t> for &'a Int {
type Output = Int;
#[inline]
fn rem(self, other: $t) -> Int {
if other == 0 {
ll::divide_by_zero();
}
if self.sign() == 0 || other == 1 {
return Int::zero()
};
return self.clone() % other;
}
}
impl Rem<Int> for $t {
type Output = Int;
#[inline]
fn rem(self, mut other: Int) -> Int {
if self == 0 || other == 1 {
other.size = 0;
return other;
}
if other.sign() == 0 {
ll::divide_by_zero();
}
// There's probably a better way of doing this, but
// I don't see n % <bigint> being common in code
Int::from(self) % other
}
}
impl<'a> Rem<&'a Int> for $t {
type Output = Int;
#[inline]
fn rem(self, other: &'a Int) -> Int {
if self == 0 { return Int::zero() };
if other.sign() == 0 {
ll::divide_by_zero();
}
self % other.clone()
}
}
)
);
// Implement for `i32` which is the fallback type, usize and the base integer type.
// No more than this because the rest of Rust doesn't much coercion for integer types,
// but allocating an entire multiple-precision `Int` to do `+ 1` seems silly.
impl_arith_prim!(signed i32);
impl_arith_prim!(unsigned usize);
impl_arith_prim!(unsigned BaseInt);
impl PartialEq<i32> for Int {
#[inline]
fn eq(&self, &other: &i32) -> bool {
let sign = self.sign();
// equals zero
if sign == 0 || other == 0 {
return other == sign;
}
// Differing signs
if sign < 0 && other > 0 || sign > 0 && other < 0 {
return false;
}
// We can't fall back to the `== Limb` impl when self is negative
// since it'll fail because of signs
if sign < 0 {
if self.abs_size() > 1 { return false; }
unsafe {
return *self.ptr.get() == (other.abs() as BaseInt);
}
}
self.eq(&Limb(other.abs() as BaseInt))
}
}
impl PartialEq<Int> for i32 {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl PartialOrd<i32> for Int {
#[inline]
fn partial_cmp(&self, &other: &i32) -> Option<Ordering> {
let self_sign = self.sign();
let other_sign = if other < 0 {
-1
} else if other > 0 {
1
} else {
0
};
// Both are equal
if self_sign == 0 && other_sign == 0 {
return Some(Ordering::Equal);
}
let ord = if self_sign > other_sign {
Ordering::Greater
} else if self_sign < other_sign {
Ordering::Less
} else { // Now both signs are the same, and non-zero
if self_sign < 0 {
if self.abs_size() > 1 {
Ordering::Less
} else {
self.to_single_limb().cmp(&Limb(other.abs() as BaseInt)).reverse()
}
} else {
return self.partial_cmp(&Limb(other.abs() as BaseInt));
}
};
Some(ord)
}
}
impl PartialOrd<Int> for i32 {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
other.partial_cmp(self).map(|o| o.reverse())
}
}
impl PartialEq<usize> for Int {
#[inline]
fn eq(&self, &other: &usize) -> bool {
return self.eq(&Limb(other as BaseInt));
}
}
impl PartialEq<Int> for usize {
#[inline]
fn eq(&self, other: &Int) -> bool {
other.eq(self)
}
}
impl PartialOrd<usize> for Int {
#[inline]
fn partial_cmp(&self, &other: &usize) -> Option<Ordering> {
self.partial_cmp(&Limb(other as BaseInt))
}
}
impl PartialOrd<Int> for usize {
#[inline]
fn partial_cmp(&self, other: &Int) -> Option<Ordering> {
Limb(*self as BaseInt).partial_cmp(other)
}
}
macro_rules! impl_from_prim (
(signed $($t:ty),*) => {
$(impl ::std::convert::From<$t> for Int {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(val: $t) -> Int {
if val == 0 {
return Int::zero();
} if val == <$t>::min_value() {
let shift = val.trailing_zeros() as usize;
let mut i = Int::one();
i = i << shift;
return -i;
}
// Handle i64/u64 on 32-bit platforms.
if std::mem::size_of::<$t>() > std::mem::size_of::<BaseInt>() {
let vabs = val.abs();
let mask : BaseInt = !0;
let vlow = vabs & (mask as $t);
let vhigh = vabs >> Limb::BITS;
let low_limb = Limb(vlow as BaseInt);
let high_limb = Limb(vhigh as BaseInt);
let mut i = Int::from_single_limb(low_limb);
if high_limb != 0 {
i.push(high_limb);
}
if val < 0 {
i.size *= -1;
}
return i;
} else {
let limb = Limb(val.abs() as BaseInt);
let mut i = Int::from_single_limb(limb);
if val < 0 {
i.size *= -1;
}
return i;
}
}
})*
};
(unsigned $($t:ty),*) => {
$(impl ::std::convert::From<$t> for Int {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(val: $t) -> Int {
if val == 0 {
return Int::zero();
}
// Handle i64/u64 on 32-bit platforms.
if std::mem::size_of::<$t>() > std::mem::size_of::<BaseInt>() {
let mask : BaseInt = !0;
let vlow = val & (mask as $t);
let vhigh = val >> Limb::BITS;
let low_limb = Limb(vlow as BaseInt);
let high_limb = Limb(vhigh as BaseInt);
let mut i = Int::from_single_limb(low_limb);
if high_limb != 0 {
i.push(high_limb);
}
return i;
} else {
let limb = Limb(val as BaseInt);
return Int::from_single_limb(limb);
}
}
})*
}
);
impl_from_prim!(signed i8, i16, i32, i64, isize);
impl_from_prim!(unsigned u8, u16, u32, u64, usize);
// Number formatting - There's not much difference between the impls,
// hence the macro
macro_rules! impl_fmt (
($t:path, $radix:expr, $upper:expr, $prefix:expr) => {
impl $t for Int {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s : &str = &self.to_str_radix($radix, $upper);
let is_positive = self.sign() >= 0;
// to_str_radix adds the sign if `self` is negative, but
// pad_integral adds it's own sign, so slice the sign off
if !is_positive {
s = &s[1..];
}
f.pad_integral(is_positive, $prefix, s)
}
}
};
($t:path, $radix:expr, $prefix:expr) => {
impl_fmt!($t, $radix, false, $prefix);
}
);
impl_fmt!(fmt::Binary, 2, "0b");
impl_fmt!(fmt::Octal, 8, "0o");
impl_fmt!(fmt::Display, 10, "");
impl_fmt!(fmt::Debug, 10, "");
impl_fmt!(fmt::LowerHex, 16, false, "0x");
impl_fmt!(fmt::UpperHex, 16, true, "0x");
// String parsing
#[derive(Debug, Clone, PartialEq)]
pub struct ParseIntError { kind: ErrorKind }
#[derive(Debug, Clone, PartialEq)]
enum ErrorKind {
Empty,
InvalidDigit
}
impl Error for ParseIntError {
fn description<'a>(&'a self) -> &'a str {
match self.kind {
ErrorKind::Empty => "cannot parse empty string",
ErrorKind::InvalidDigit => "invalid digit found in string"
}
}
}
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl FromStr for Int {
type Err = ParseIntError;
fn from_str(src: &str) -> Result<Int, ParseIntError> {
Int::from_str_radix(src, 10)
}
}
// Conversion *to* primitives via the From trait.
macro_rules! impl_from_for_prim (
(signed $($t:ty),*) => (
$(impl<'a> ::std::convert::From<&'a Int> for $t {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(i: &'a Int) -> $t {
let sign = i.sign() as $t;
if sign == 0 {
return 0;
}
if ::std::mem::size_of::<BaseInt>() < ::std::mem::size_of::<$t>() {
// Handle conversion where BaseInt = u32 and $t = i64
if i.abs_size() >= 2 { // Fallthrough if there's only one limb
let lower = i.to_single_limb().0 as $t;
let higher = unsafe { (*i.ptr.offset(1)).0 } as $t;
// Combine the two
let n : $t = lower | (higher << Limb::BITS);
// Apply the sign
return n.wrapping_mul(sign);
}
}
let n = i.to_single_limb().0;
// Using wrapping_mul to account for when the binary
// representation of n == $t::MIN
return (n as $t).wrapping_mul(sign);
}
})*
);
(unsigned $($t:ty),*) => (
$(impl<'a> ::std::convert::From<&'a Int> for $t {
#[allow(exceeding_bitshifts)] // False positives for the larger-than BaseInt case
fn from(i: &'a Int) -> $t {
// This does the conversion ignoring the sign
if i.sign() == 0 {
return 0;
}
if ::std::mem::size_of::<BaseInt>() < ::std::mem::size_of::<$t>() {
// Handle conversion where BaseInt = u32 and $t = u64
if i.abs_size() >= 2 { // Fallthrough if there's only one limb
let lower = i.to_single_limb().0 as $t;
let higher = unsafe { (*i.ptr.offset(1)).0 } as $t;
// Combine the two
let n : $t = lower | (higher << Limb::BITS);
return n;
}
}
let n = i.to_single_limb().0;
return n as $t;
}
})*
)
);
impl_from_for_prim!(signed i8, i16, i32, i64, isize);
impl_from_for_prim!(unsigned u8, u16, u32, u64, usize);
impl std::num::Zero for Int {
fn zero() -> Int {
Int {
ptr: unsafe { Unique::new(alloc::heap::EMPTY as *mut Limb) },
size: 0,
cap: 0
}
}
}
impl std::num::One for Int {
fn one() -> Int {
Int::from(1)
}
}
impl std::iter::Step for Int {
fn step(&self, by: &Int) -> Option<Int> {
Some(self + by)
}
fn steps_between(start: &Int, end: &Int, by: &Int) -> Option<usize> {
if by.le(&0) { return None; }
let mut diff = (start - end).abs();
if by.ne(&1) {
diff = diff / by;
}
// Check to see if result fits in a usize
if diff > !0usize {
None
} else {
Some(usize::from(&diff))
}
}
}
/// Trait for generating random `Int`.
///
/// # Example
///
/// Generate a random `Int` of size `256` bits:
///
/// ```
/// extern crate rand;
/// extern crate ramp;
///
/// use ramp::RandomInt;
///
/// fn main() {
/// let mut rng = rand::thread_rng();
/// let big_i = rng.gen_int(256);
/// }
/// ```
pub trait RandomInt {
/// Generate a random unsigned `Int` of given bit size.
fn gen_uint(&mut self, bits: usize) -> Int;
/// Generate a random `Int` of given bit size.
fn gen_int(&mut self, bits: usize) -> Int;
/// Generate a random unsigned `Int` less than the given bound.
/// Fails when the bound is zero or negative.
fn gen_uint_below(&mut self, bound: &Int) -> Int;
/// Generate a random `Int` within the given range.
/// The lower bound is inclusive; the upper bound is exclusive.
/// Fails when the upper bound is not greater than the lower bound.
fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int;
}
impl<R: Rng> RandomInt for R {
fn gen_uint(&mut self, bits: usize) -> Int {
assert!(bits > 0);
let limbs = (bits / &Limb::BITS) as u32;
let rem = bits % &Limb::BITS;
let mut i = Int::with_capacity(limbs + 1);
for _ in 0..limbs {
let limb = Limb(self.gen());
i.push(limb);
}
if rem > 0 {
let final_limb = Limb(self.gen());
i.push(final_limb >> (&Limb::BITS - rem));
}
i.normalize();
i
}
fn gen_int(&mut self, bits: usize) -> Int {
let i = self.gen_uint(bits);
let r = if i == Int::zero() {
// ...except that if the BigUint is zero, we need to try
// again with probability 0.5. This is because otherwise,
// the probability of generating a zero BigInt would be
// double that of any other number.
if self.gen() {
return self.gen_uint(bits);
} else {
i
}
} else if self.gen() {
-i
} else {
i
};
r
}
fn gen_uint_below(&mut self, bound: &Int) -> Int {
assert!(*bound > Int::zero());
let mut i = (*bound).clone();
i.normalize();
let lz = bound.to_single_limb().leading_zeros() as i32;
let bits = ((bound.abs_size() * Limb::BITS as i32) - lz) as usize;
loop {
let n = self.gen_uint(bits);
if n < *bound { return n; }
}
}
fn gen_int_range(&mut self, lbound: &Int, ubound: &Int) -> Int {
assert!(*lbound < *ubound);
lbound + self.gen_uint_below(&(ubound - lbound))
}
}
#[cfg(test)]
mod test {
use std;
use std::hash::{Hash, Hasher};
use rand::{self, Rng};
use test::{self, Bencher};
use super::*;
use ll::limb::Limb;
use std::str::FromStr;
use std::num::Zero;
macro_rules! assert_mp_eq (
($l:expr, $r:expr) => (
{
let l : Int = $l;
let r : Int = $r;
if l != r {
println!("assertion failed: {} == {}", stringify!($l), stringify!($r));
panic!("{:} != {:}", l, r);
}
}
)
);
#[test]
fn from_string_10() {
let cases = [
("0", 0i32),
("123456", 123456),
("0123", 123),
("000000", 0),
("-0", 0),
("-1", -1),
("-123456", -123456),
("-0123", -123),
];
for &(s, n) in cases.iter() {
let i : Int = s.parse().unwrap();
assert_eq!(i, n);
}
}
#[test]
fn from_string_16() {
let cases = [
("0", 0i32),
("abcde", 0xabcde),
("0ABC", 0xabc),
("12AB34cd", 0x12ab34cd),
("-ABC", -0xabc),
("-0def", -0xdef),
];
for &(s, n) in cases.iter() {
let i : Int = Int::from_str_radix(s, 16).unwrap();
assert!(i == n, "Assertion failed: {:#x} != {:#x}", i, n);
}
}
#[test]
fn to_string_10() {
let cases = [
("0", Int::zero()),
("1", Int::from(1)),
("123", Int::from(123)),
("-456", Int::from(-456)),
("987654321012345678910111213",
Int::from_str("987654321012345678910111213").unwrap()),
];
for &(s, ref n) in cases.iter() {
assert_eq!(s, &n.to_string());
}
}
#[test]
fn to_string_16() {
let cases = [
("0", Int::zero()),
("1", Int::from(1)),
("-1", Int::from(-1)),
("abc", Int::from(0xabc)),
("-456", Int::from(-0x456)),
("987654321012345678910111213",
Int::from_str_radix("987654321012345678910111213", 16).unwrap()),
];
for &(s, ref n) in cases.iter() {
assert_eq!(s, &n.to_str_radix(16, false));
}
}
#[test]
fn pow() {
let bases = ["0", "1", "190000000000000", "192834857324591531",
"340282366920938463463374607431768211456", // 2**128
"100000000", "-1", "-100", "-200", "-192834857324591531",
"-431343873217510631841",
"-340282366920938463463374607431768211456"];
for b in bases.iter() {
let b : Int = b.parse().unwrap();
let mut x = Int::one();
for e in 0..512 {
let a = &b.pow(e);
// println!("b={}, e={}, a={}, x={}", &b, &e, &a, &x);
assert_mp_eq!(a.clone(), x.clone());
x = &x * &b
}
}
}
#[test]
fn add() {
let cases = [
("0", "0", "0"),
("1", "0", "1"),
("1", "1", "2"),
("190000000000000", "1", "190000000000001"),
("192834857324591531", "431343873217510631841", "431536708074835223372"),
("0", "-1", "-1"),
("1", "-1", "0"),
("100000000", "-1", "99999999"),
("-100", "-100", "-200"),
("-192834857324591531", "-431343873217510631841", "-431536708074835223372"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(l + r, a);
}
}
#[test]
fn sub() {
let cases = [
("0", "0", "0"),
("1", "0", "1"),
("1", "1", "0"),
("0", "1", "-1"),
("190000000000000", "1", "189999999999999"),
("192834857324591531", "431343873217510631841", "-431151038360186040310"),
("0", "-1", "1"),
("1", "-1", "2"),
("100000000", "-1", "100000001"),
("-100", "-100", "0"),
("-100", "100", "-200"),
("237", "236", "1"),
("-192834857324591531", "-431343873217510631841", "431151038360186040310")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(&l - &r, a.clone());
assert_mp_eq!(&l - r.clone(), a.clone());
assert_mp_eq!(l.clone() - &r, a.clone());
assert_mp_eq!(l - r, a);
}
}
#[test]
fn mul() {
let cases = [
("0", "0", "0"),
("1", "0", "0"),
("1", "1", "1"),
("1234", "-1", "-1234"),
("8", "9", "72"),
("-8", "-9", "72"),
("8", "-9", "-72"),
("1234567891011", "9876543210123", "12193263121400563935904353"),
("-1234567891011", "9876543210123", "-12193263121400563935904353"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
assert_mp_eq!(l * r, a);
}
}
#[test]
fn div() {
let cases = [
("1", "1", "1"),
("1234", "-1", "-1234"),
("8", "9", "0"),
("-9", "-3", "3"),
("1234567891011121314151617", "95123654789852856006", "12978"),
("-1234567891011121314151617", "95123654789852856006", "-12978"),
("-1198775410753307067346230628764044530011323809665206377243907561641040294348297309637331525393593945901384203950086960228531308793518800829453656715578105987032036211272103322425770761458186593",
"979504192721382235629958845425279521512826176107035761459344386626944187481828320416870752582555",
"-1223859397092234843008309150569447886995823751180958876260102037121722431272801092547910923059616")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l / &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn rem() {
let cases = [
("2", "1", "0"),
("1", "2", "1"),
("100", "2", "0"),
("100", "3", "1"),
("234129835798275032157029375235", "4382109473241242142341234", "2490861941946976021925083")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l % &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn bitand() {
let cases = [
("0", "543253451643657932075830214751263521", "0"),
("-1", "543253451643657932075830214751263521", "543253451643657932075830214751263521"),
("47398217493274092174042109472", "9843271092740214732017421", "152974816756326460458496"),
("87641324986400000000000", "31470973247490321000000000000000", "2398658832415825854464")
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l & &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn bitor() {
let cases = [
("0", "543253451643657932075830214751263521", "543253451643657932075830214751263521"),
("-1", "543253451643657932075830214751263521", "-1"),
("47398217493274092174042109472", "9843271092740214732017421","47407907789550076062313668397"),
("87641324986400000000000", "31470973247490321000000000000000", "31470973332732987153984174145536"),
];
for &(l, r, a) in cases.iter() {
let l : Int = l.parse().unwrap();
let r : Int = r.parse().unwrap();
let a : Int = a.parse().unwrap();
let val = &l | &r;
assert_mp_eq!(val, a);
}
}
#[test]
fn is_even() {
let cases = [
("0", true),
("1", false),
("47398217493274092174042109472", true),
("47398217493274092174042109471", false),
];
for &(v, even) in cases.iter() {
let val : Int = v.parse().unwrap();
assert_eq!(val.is_even(), even);
let val = -val;
assert_eq!(val.is_even(), even);
}
}
#[test]
fn trailing_zeros() {
let cases = [
("0", 0),
("1", 0),
("16", 4),
("3036937844145311324764506857395738547330878864826266812416", 100)
];
for &(v, count) in cases.iter() {
let val : Int = v.parse().unwrap();
assert_eq!(val.trailing_zeros(), count);
}
}
#[test]
fn arith_prim() {
// Test that the Int/prim overloads are working as expected
let x : Int = "100".parse().unwrap();
// Int op prim
assert_mp_eq!(&x + 1usize, "101".parse().unwrap());
assert_mp_eq!(&x - 1usize, "99".parse().unwrap());
assert_mp_eq!(&x + 1i32, "101".parse().unwrap());
assert_mp_eq!(&x - 1i32, "99".parse().unwrap());
assert_mp_eq!(&x + (-1i32), "99".parse().unwrap());
assert_mp_eq!(&x - (-1i32), "101".parse().unwrap());
assert_mp_eq!(&x * 2usize, "200".parse().unwrap());
assert_mp_eq!(&x * 2i32, "200".parse().unwrap());
assert_mp_eq!(&x * (-2i32), "-200".parse().unwrap());
assert_mp_eq!(&x / 2usize, "50".parse().unwrap());
assert_mp_eq!(&x / 2i32, "50".parse().unwrap());
assert_mp_eq!(&x / (-2i32), "-50".parse().unwrap());
assert_mp_eq!(&x % 2usize, "0".parse().unwrap());
assert_mp_eq!(&x % 2i32, "0".parse().unwrap());
assert_mp_eq!(&x % (-2i32), "0".parse().unwrap());
let x : Int = "5".parse().unwrap();
// prim op Int
assert_mp_eq!(1usize + &x, "6".parse().unwrap());
assert_mp_eq!(1usize - &x, "-4".parse().unwrap());
assert_mp_eq!(1i32 + &x, "6".parse().unwrap());
assert_mp_eq!(1i32 - &x, "-4".parse().unwrap());
assert_mp_eq!((-1i32) + &x, "4".parse().unwrap());
assert_mp_eq!((-1i32) - &x, "-6".parse().unwrap());
assert_mp_eq!(2usize * &x, "10".parse().unwrap());
assert_mp_eq!(2i32 * &x, "10".parse().unwrap());
assert_mp_eq!((-2i32) * &x, "-10".parse().unwrap());
assert_mp_eq!(20usize / &x, "4".parse().unwrap());
assert_mp_eq!(20i32 / &x, "4".parse().unwrap());
assert_mp_eq!((-20i32) / &x, "-4".parse().unwrap());
}
#[test]
fn int_from() {
let i = Int::from(::std::i64::MIN);
assert_eq!(i64::from(&i), ::std::i64::MIN);
let i = Int::from(::std::i32::MIN);
assert_eq!(i32::from(&i), ::std::i32::MIN);
let i = Int::from(::std::usize::MAX);
assert_eq!(usize::from(&i), ::std::usize::MAX);
}
const RAND_ITER : usize = 1000;
#[test]
fn div_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let x = rng.gen_int(640);
let y = rng.gen_int(320);
let (q, r) = x.divmod(&y);
let val = (q * &y) + r;
assert_mp_eq!(val, x);
}
}
#[test]
fn sqr_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let x = rng.gen_int(640);
let xs = x.square();
let xm = &x * &x;
assert_mp_eq!(xm, xs);
}
}
#[test]
fn shl_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let x = rng.gen_int(640);
let shift_1 = &x << 1;
let mul_2 = &x * 2;
assert_mp_eq!(shift_1, mul_2);
let shift_3 = &x << 3;
let mul_8 = &x * 8;
assert_mp_eq!(shift_3, mul_8);
}
}
#[test]
fn shl_rand_large() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let pow : usize = rng.gen_range(64, 8196);
let mul_by = Int::from(2).pow(pow);
let x = rng.gen_int(640);
let shift = &x << pow;
let mul = x * mul_by;
assert_mp_eq!(shift, mul);
}
}
#[test]
fn shr_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let pow : usize = rng.gen_range(64, 8196);
let x = rng.gen_int(640);
let shift_up = &x << pow;
let shift_down = shift_up >> pow;
assert_mp_eq!(shift_down, x);
}
}
#[test]
fn bitand_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let x = rng.gen_int(640);
let y = rng.gen_int(640);
let _ = x & y;
}
}
#[test]
fn hash_rand() {
let mut rng = rand::thread_rng();
for _ in 0..RAND_ITER {
let x1 = rng.gen_int(640);
let x2 = x1.clone();
assert!(x1 == x2);
let mut hasher = std::hash::SipHasher::new();
x1.hash(&mut hasher);
let x1_hash = hasher.finish();
let mut hasher = std::hash::SipHasher::new();
x2.hash(&mut hasher);
let x2_hash = hasher.finish();
assert!(x1_hash == x2_hash);
}
}
#[test]
#[should_panic]
fn gen_uint_with_zero_bits() {
let mut rng = rand::thread_rng();
rng.gen_uint(0);
}
#[test]
#[should_panic]
fn gen_int_with_zero_bits() {
let mut rng = rand::thread_rng();
rng.gen_int(0);
}
#[test]
#[should_panic]
fn gen_uint_below_zero_or_negative() {
let mut rng = rand::thread_rng();
let i = Int::from(0);
rng.gen_uint_below(&i);
let j = Int::from(-1);
rng.gen_uint_below(&j);
}
#[test]
#[should_panic]
fn gen_int_range_zero() {
let mut rng = rand::thread_rng();
let b = Int::from(123);
rng.gen_int_range(&b, &b);
}
#[test]
#[should_panic]
fn gen_int_range_negative() {
let mut rng = rand::thread_rng();
let lb = Int::from(123);
let ub = Int::from(321);
rng.gen_int_range(&ub, &lb);
}
#[test]
fn gen_int_range() {
let mut rng = rand::thread_rng();
for _ in 0..10 {
let i = rng.gen_int_range(&Int::from(236), &Int::from(237));
assert_eq!(i, Int::from(236));
}
let l = Int::from(403469000 + 2352);
let u = Int::from(403469000 + 3513);
for _ in 0..1000 {
let n: Int = rng.gen_uint_below(&u);
assert!(n < u);
let n: Int = rng.gen_int_range(&l, &u);
assert!(n >= l);
assert!(n < u);
}
}
fn bench_add(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x + &y;
test::black_box(z);
});
}
#[bench]
fn bench_add_1_1(b: &mut Bencher) {
bench_add(b, 1, 1);
}
#[bench]
fn bench_add_10_10(b: &mut Bencher) {
bench_add(b, 10, 10);
}
#[bench]
fn bench_add_100_100(b: &mut Bencher) {
bench_add(b, 100, 100);
}
#[bench]
fn bench_add_1000_1000(b: &mut Bencher) {
bench_add(b, 1000, 1000);
}
#[bench]
fn bench_add_1000_10(b: &mut Bencher) {
bench_add(b, 1000, 10);
}
fn bench_mul(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x * &y;
test::black_box(z);
});
}
fn bench_pow(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y : usize = rng.gen_range(0, ys);
b.iter(|| {
let z = &x.pow(y);
test::black_box(z);
});
}
#[bench]
fn bench_mul_1_1(b: &mut Bencher) {
bench_mul(b, 1, 1);
}
#[bench]
fn bench_mul_10_10(b: &mut Bencher) {
bench_mul(b, 10, 10);
}
#[bench]
fn bench_mul_2_20(b: &mut Bencher) {
bench_mul(b, 2, 20);
}
#[bench]
fn bench_mul_50_50(b: &mut Bencher) {
bench_mul(b, 50, 50);
}
#[bench]
fn bench_mul_5_50(b: &mut Bencher) {
bench_mul(b, 5, 50);
}
#[bench]
fn bench_mul_250_250(b: &mut Bencher) {
bench_mul(b, 250, 250);
}
#[bench]
fn bench_mul_1000_1000(b: &mut Bencher) {
bench_mul(b, 1000, 1000);
}
#[bench]
fn bench_mul_50_1500(b: &mut Bencher) {
bench_mul(b, 50, 1500);
}
fn bench_sqr(b: &mut Bencher, xs: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
b.iter(|| {
let z = x.square();
test::black_box(z);
});
}
#[bench]
fn bench_sqr_1(b: &mut Bencher) {
bench_sqr(b, 1);
}
#[bench]
fn bench_sqr_10(b: &mut Bencher) {
bench_sqr(b, 10);
}
#[bench]
fn bench_sqr_50(b: &mut Bencher) {
bench_sqr(b, 50);
}
#[bench]
fn bench_sqr_250(b: &mut Bencher) {
bench_sqr(b, 250);
}
#[bench]
fn bench_sqr_1000(b: &mut Bencher) {
bench_sqr(b, 1000);
}
#[bench]
fn bench_pow_1_1(b: &mut Bencher) {
bench_pow(b, 1, 1);
}
#[bench]
fn bench_pow_10_10(b: &mut Bencher) {
bench_pow(b, 10, 10);
}
#[bench]
fn bench_pow_2_20(b: &mut Bencher) {
bench_pow(b, 2, 20);
}
#[bench]
fn bench_pow_50_50(b: &mut Bencher) {
bench_pow(b, 50, 50);
}
#[bench]
fn bench_pow_5_50(b: &mut Bencher) {
bench_mul(b, 5, 50);
}
#[bench]
fn bench_pow_250_250(b: &mut Bencher) {
bench_mul(b, 250, 250);
}
#[bench]
fn bench_pow_1000_1000(b: &mut Bencher) {
bench_mul(b, 1000, 1000);
}
#[bench]
fn bench_pow_50_1500(b: &mut Bencher) {
bench_mul(b, 50, 1500);
}
#[bench]
fn bench_factorial_100(b: &mut Bencher) {
b.iter(|| {
let mut i = Int::from(1);
for j in 2..100 {
i = i * j;
}
i = i * 100;
test::black_box(i);
});
}
#[bench]
fn bench_factorial_1000(b: &mut Bencher) {
b.iter(|| {
let mut i = Int::from(1);
for j in 2..1000 {
i = i * j;
}
i = i * 1000;
test::black_box(i);
});
}
fn bench_div(b: &mut Bencher, xs: usize, ys: usize) {
let mut rng = rand::thread_rng();
let x = rng.gen_int(xs * Limb::BITS);
let y = rng.gen_int(ys * Limb::BITS);
b.iter(|| {
let z = &x / &y;
test::black_box(z);
});
}
#[bench]
fn bench_div_1_1(b: &mut Bencher) {
bench_div(b, 1, 1);
}
#[bench]
fn bench_div_10_10(b: &mut Bencher) {
bench_div(b, 10, 10);
}
#[bench]
fn bench_div_20_2(b: &mut Bencher) {
bench_div(b, 20, 2);
}
#[bench]
fn bench_div_50_50(b: &mut Bencher) {
bench_div(b, 50, 50);
}
#[bench]
fn bench_div_50_5(b: &mut Bencher) {
bench_div(b, 50, 5);
}
#[bench]
fn bench_div_250_250(b: &mut Bencher) {
bench_div(b, 250, 250);
}
#[bench]
fn bench_div_1000_1000(b: &mut Bencher) {
bench_div(b, 1000, 1000);
}
}
|
#[macro_export]
macro_rules! approve {
($actual: ident) => {
{
use std::fs;
use std::fs::{File, PathExt};
use std::io::{Read, Write};
use std::path::Path;
use std::process::Command;
let mut backtrace = vec![];
::std::rt::backtrace::write(&mut backtrace);
let s = String::from_utf8(backtrace).unwrap();
let method_name = s
.as_str()
.lines()
.skip(2)
.next()
.unwrap()
.split("-")
.last()
.unwrap()
.split(":")
.next()
.unwrap()
.trim_left_matches(" "); // FIXME: Handle all results/options
let approvals_dirname = "approvals";
let approvals_dir = Path::new(approvals_dirname);
if !approvals_dir.exists() {
match fs::create_dir(approvals_dir) {
Err(err) => panic!("Failed to create directory for approvals data: {:?}", err),
_ => {}
}
} else if !approvals_dir.is_dir() {
panic!("Path for approvals data is not a directory")
}
let expected_filename = format!("{}/{}_expected.txt", approvals_dirname, method_name);
let expected_path = Path::new(&expected_filename);
let expected = match File::open(expected_path) {
Ok(mut f) => {
let mut data = String::with_capacity($actual.len());
match f.read_to_string(&mut data) {
Err(err) => panic!("Failed to read expected data: {:?}", err),
_ => {}
}
data.trim_right_matches("\n").to_string() // Removing LF in the end
},
Err(open_err) => {
match File::create(expected_path) {
Ok(_) => String::new(),
Err(create_err) => panic!("Failed to open file '{:?}'.\nOpen error: {:?}.\nCreate error: {:?}", expected_path, open_err, create_err)
}
}
};
if $actual != expected {
let actual_filename = format!("{}/{}_actual.txt", approvals_dirname, method_name);
let mut actual_file = match File::create(actual_filename.clone()) {
Ok(f) => f,
Err(err) => panic!("Failed to create temp file: {:?}", err)
};
match actual_file.write_all($actual.as_bytes()) {
Err(err) => panic!("Failed to write actual data for comparing: {:?}", err),
_ => {}
}
let diff_tool = "vimdiff"; // FIXME: Configure
let output = match
Command::new(diff_tool).arg(::std::ffi::OsStr::new(actual_filename.as_str()))
.arg(expected_path.as_os_str())
.spawn() {
Ok(p) => p.wait_with_output(),
Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err)
};
match output {
Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err),
_ => {}
}
fs::remove_file(actual_filename);
panic!("strings are not equal")
}
}
}
}
Trimming LF in the end for actual and expected
#[macro_export]
macro_rules! approve {
($actual: ident) => {
{
use std::fs;
use std::fs::{File, PathExt};
use std::io::{Read, Write};
use std::path::Path;
use std::process::Command;
let mut backtrace = vec![];
::std::rt::backtrace::write(&mut backtrace);
let s = String::from_utf8(backtrace).unwrap();
let method_name = s
.as_str()
.lines()
.skip(2)
.next()
.unwrap()
.split("-")
.last()
.unwrap()
.split(":")
.next()
.unwrap()
.trim_left_matches(" "); // FIXME: Handle all results/options
let approvals_dirname = "approvals";
let approvals_dir = Path::new(approvals_dirname);
if !approvals_dir.exists() {
match fs::create_dir(approvals_dir) {
Err(err) => panic!("Failed to create directory for approvals data: {:?}", err),
_ => {}
}
} else if !approvals_dir.is_dir() {
panic!("Path for approvals data is not a directory")
}
let expected_filename = format!("{}/{}_expected.txt", approvals_dirname, method_name);
let expected_path = Path::new(&expected_filename);
let expected = match File::open(expected_path) {
Ok(mut f) => {
let mut data = String::with_capacity($actual.len());
match f.read_to_string(&mut data) {
Err(err) => panic!("Failed to read expected data: {:?}", err),
_ => {}
}
data
},
Err(open_err) => {
match File::create(expected_path) {
Ok(_) => String::new(),
Err(create_err) => panic!("Failed to open file '{:?}'.\nOpen error: {:?}.\nCreate error: {:?}", expected_path, open_err, create_err)
}
}
};
if $actual.trim_right_matches("\n") != expected.trim_right_matches("\n") {
let actual_filename = format!("{}/{}_actual.txt", approvals_dirname, method_name);
let mut actual_file = match File::create(actual_filename.clone()) {
Ok(f) => f,
Err(err) => panic!("Failed to create temp file: {:?}", err)
};
match actual_file.write_all($actual.as_bytes()) {
Err(err) => panic!("Failed to write actual data for comparing: {:?}", err),
_ => {}
}
let diff_tool = "vimdiff"; // FIXME: Configure
let output = match
Command::new(diff_tool).arg(::std::ffi::OsStr::new(actual_filename.as_str()))
.arg(expected_path.as_os_str())
.spawn() {
Ok(p) => p.wait_with_output(),
Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err)
};
match output {
Err(err) => panic!("Failed to launch diff tool '{}': {:?}", diff_tool, err),
_ => {}
}
fs::remove_file(actual_filename);
panic!("strings are not equal")
}
}
}
}
|
//! # The `type_operators` macro - a DSL for declaring type operators and type-level logic in Rust.
//!
//! This crate contains a macro for declaring type operators in Rust. Type operators are like functions
//! which act at the type level. The `type_operators` macro works by translating a LISP-y DSL into a big mess of
//! traits and impls with associated types.
//!
//! # The DSL
//!
//! Let's take a look at this fairly small example:
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//! type_operators! {
//! [A, B, C, D, E]
//!
//! data Nat {
//! P,
//! I(Nat = P),
//! O(Nat = P),
//! }
//! }
//! # fn main() {}
//! ```
//!
//! There are two essential things to note in this example. The first is the "gensym list" - Rust does
//! not currently have a way to generate unique identifiers, so we have to supply our own. It is on *you*
//! to avoid clashes between these pseudo-gensyms and the names of the structs involved! If we put `P`, `I`, or `O`
//! into the gensym list, things could get really bad! We'd get type errors at compile-time stemming from trait
//! bounds, coming from the definitions of type operators later. Thankfully, the gensym list can be fairly small
//! and usually never uses more than two or three symbols.
//!
//! The second thing is the `data` declaration. This declares a group of structs which fall under a marker trait.
//! In our case, `Nat` is the marker trait generated and `P`, `I`, and `O` are the structs generated. This example
//! shows an implementation of natural numbers (positive integers, including zero) which are represented as types.
//! So, `P` indicates the end of a natural number - think of it as a sort of nil; we're working with a linked list
//! here, at the type level. So, `I<P>` would represent "one plus twice `P`", which of course comes out to `1`;
//! `O<P>` would represent "twice `P`", which of course comes out to zero. If we look at `I` and `O` as bits of a
//! binary number, we come out with a sort of reversed binary representation where the "bit" furthest to the left
//! is the least significant bit. As such, `O<O<I>>` represents `4`, `I<O<O<I>>>` represents `9`, and so on.
//!
//! When we write `I(Nat = P)`, the `= P` denotes a default. This lets us write `I`, and have it be inferred to be
//! `I<P>`, which is probably what you mean if you just write `I` alone. `Nat` gives a trait bound. To better demonstrate,
//! here is (roughly) what the above invocation of `type_operators` expands to:
//!
//! ```rust
//! # use std::marker::PhantomData;
//!
//! pub trait Nat {}
//!
//! pub struct P;
//! impl Nat for P {}
//!
//! pub struct I<A: Nat = P>(PhantomData<(A)>);
//! impl<A: Nat> Nat for I<A> {}
//!
//! pub struct O<A: Nat = P>(PhantomData<(A)>);
//! impl<A: Nat> Nat for O<A> {}
//! # fn main() {}
//! ```
//!
//! The `Undefined` value looks a little silly, but it allows for the definition of division in a way which uses
//! type-level comparison and branching. More on that later.
//!
//! The above definition has a problem. We cannot *fold* our type-level representation down into a numerical representation.
//! That makes our type-level natural numbers useless! That's why `type_operators` provides another way of defining
//! type-level representations, the `concrete` declaration:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate type_operators;
//!
//! type_operators! {
//! [A, B, C, D, E]
//!
//! concrete Nat => usize {
//! P => 0,
//! I(N: Nat = P) => 1 + 2 * N,
//! O(N: Nat = P) => 2 * N,
//! Undefined => panic!("Undefined type-level arithmetic result!"),
//! }
//! }
//! # fn main() {}
//! ```
//!
//! This adds an associated function to the `Nat` trait called `reify`, which allows you to turn your type-level
//! representations into concrete values of type `usize` (in this case.) If you've ever seen primitive-recursive
//! functions, then this should look a bit familiar to you - it's reminiscent of a recursion scheme, which is a
//! way of recursing over a value to map it into something else. (See also "catamorphism".) It should be fairly
//! obvious how this works, but if not, here's a breakdown:
//!
//! - `P` always represents zero, so we say that `P => 0`. Simple.
//! - `I` represents double its argument plus one. If we annotate our macro's definition with a variable `N`,
//! then `type_operators` will automatically call `N::reify()` and substitute that value for your `N` in the
//! expression you give it. So, in this way, we define the reification of `I` to be one plus two times the
//! value that `N` reifies to.
//! - `O` represents double its argument, so this one's straightforward - it's like `I`, but without the `1 +`.
//!
//! Okay. So now that we've got that under our belts, let's dive into something a bit more complex: let's define
//! a type operator for addition.
//!
//! `type_operators` allows you to define recursive functions. Speaking generally, that's what you'll really need
//! to pull this off whatever you do. (And speaking precisely, this whole approach was inspired by primitive-recursion.)
//! So let's think about how we can add two binary numbers, starting at the least-significant bit:
//! - Obviously, `P + P` should be `P`, since zero plus zero is zero.
//! - What about `P + O<N>`, for any natural number `N`? Well, that should be `O<N>`. Same with `I<N>`. As a matter of
//! fact, now it looks pretty obvious that whenever we have `P` on one side, we should just say that whatever's on the
//! other side is the result.
//! So our little table of operations now looks like:
//! ```text
//! [P, P] => P
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! ```
//! Now you're probably saying, "whoa! That doesn't look like Rust at all! Back up!" And that's because it *isn't.* I made
//! a little LISP-like dialect to describe Rust types for this project because it makes things a lot easier to parse in
//! macros; specifically, each little atomic type can be wrapped up in a pair of parentheses, while with angle brackets,
//! Rust has to parse them as separate tokens. In this setup, `(O N)` means `O<N>`,
//! just `P` alone means `P`, etc. etc. The notation `[X, Y] => Z` means "given inputs `X` and `Y`, produce output `Z`." So
//! it's a sort of pattern-matching.
//!
//! Now let's look at the more complex cases. We need to cover all the parts where combinations of `O<N>` and `I<N>` are
//! added together.
//! - `O<M> + O<N>` should come out to `O<M + N>`. This is a fairly intuitive result, but we can describe it mathematically
//! as `2 * m + 2 * n == 2 * (m + n)`. So, it's the distributive law, and most importantly, it cuts down on the *structure*
//! of the arguments - we go from adding `O<M>` and `O<N>` to `M` and `N`, whatever they are, and `M` and `N` are clearly
//! less complex than `O<M>` and `O<N>`. If we always see that our outputs have less complexity than the inputs, then we're
//! that much closer to a proof that our little type operator always terminates with a result!
//! - `I<M> + O<N>` and `O<M> + I<N>` should come out to `I<M + N>`. Again, fairly intuitive. We have `1 + 2 * m + 2 * n`,
//! which we can package up into `1 + 2 * (m + n)`.
//! - `I<M> + I<N>` is the trickiest part here. We have `1 + 2 * m + 1 + 2 * m == 2 + 2 * m + 2 * n == 2 * (1 + m + n)`. We
//! can implement this as `I<I + M + N>`, but we can do a little bit better. More on that later, we'll head with the simpler
//! implementation for now.
//!
//! Let's add these to the table:
//! ```text
//! [P, P] => P
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! // New:
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# I M) N))
//! ```
//! Here's something new: the `(# ...)` notation. This tells the macro, "hey, we wanna recurse." It's really shorthand
//! for a slightly more complex piece of notation, but they both have one thing in common - *when type_operators processes
//! the `(# ...)` notation, it uses it to calculate trait bounds.* This is because your type operator won't compile unless
//! it's absolutely certain that `(# M N)` will actually have a defined result. At an even higher level, this is the reason
//! I wish Rust had "closed type families" - if `P`, `I`, and `O` were in a closed type family `Nat`, Rust could check at compile-time
//! and be absolutely sure that `(# M N)` existed for all `M` and `N` that are in the `Nat` family.
//!
//! So then. Let's load this into an invocation of `type_operators` to see how it looks like. It's pretty close to the table,
//! but with a couple additions (I'm leaving out `Undefined` for now because it's not yet relevant):
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//!
//! type_operators! {
//! [A, B, C, D, E]
//!
//! concrete Nat => usize {
//! P => 0,
//! I(N: Nat = P) => 1 + 2 * N,
//! O(N: Nat = P) => 2 * N,
//! }
//!
//! (Sum) Adding(Nat, Nat): Nat {
//! [P, P] => P
//! forall (N: Nat) {
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! }
//! forall (N: Nat, M: Nat) {
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# M N) I))
//! }
//! }
//! }
//! # fn main() {}
//! ```
//!
//! There are several things to note. First, the definition `(Sum) Adding(Nat, Nat): Nat`. This says,
//! "this type operator takes two `Nat`s as input and outputs a `Nat`." Since addition is implemented
//! as a recursive trait under the hood, this means we get a trait definition of the form:
//!
//! ```rust
//! # pub trait Nat {}
//! pub trait Adding<A: Nat>: Nat {
//! type Output: Nat;
//! }
//! ```
//!
//! The `(Sum)` bit declares a nice, convenient alias for us, so that instead of typing `<X as Adding<Y>>::Output`
//! to get the sum of two numbers, we can instead type `Sum<X, Y>`. Much neater.
//!
//! Second, the "quantifier" sections (the parts with `forall`) avoid Rust complaining about "undeclared type variables." In any given
//! generic `impl`, we have to worry about declaring what type variables/generic type parameters we can use in
//! that `impl`. The `forall` bit modifies the prelude of the `impl`. For example, `forall (N: Nat)` causes all the
//! `impl`s inside its little block to be declared as `impl<N: Nat> ...` instead of `impl ...`, so that we can use
//! `N` as a variable inside those expressions.
//!
//! That just about wraps up our short introduction. To finish, here are the rest of the notations specific to our
//! little LISP-y dialect, all of which can only be used on the right-hand side of a rule in the DSL:
//!
//! - `(@TypeOperator ...)` invokes another type operator (can be the original caller!) and generates the proper trait bounds.
//! - `(% ...)` is like `(# ...)`, but does not generate any trait bounds.
//! - `(& <type> where (<where_clause>) (<where_clause>) ...)` allows for the definition of custom `where` clauses for a given
//! `impl`. It can appear anywhere in the right-hand side of a rule in the DSL, but in general should probably always be
//! written at the top-level for consistency.
//!
//! In addition, it is possible to use attributes such as `#[derive(...)]` or `#[cfg(...)]` on `data` and `concrete` definitions
//! as well as individual elements inside them. In addition, attributes can be added to the `impl`s for rules. For example:
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//! # use std::fmt::Debug;
//! type_operators! {
//! [A, B, C, D, E]
//!
//! data Nat: Default + Debug where #[derive(Default, Debug)] {
//! P,
//! I(Nat = P),
//! O(Nat = P),
//! #[cfg(features = "specialization")]
//! Error,
//! #[cfg(features = "specialization")]
//! DEFAULT,
//! }
//!
//! (Sum) Adding(Nat, Nat): Nat {
//! [P, P] => P
//! forall (N: Nat) {
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! }
//! forall (N: Nat, M: Nat) {
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# M N) I))
//!
//! #[cfg(features = "specialization")] {
//! {M, N} => Error
//! }
//! }
//! }
//! }
//! # fn main() {}
//! ```
//!
//! Note the block `#[cfg(features = "specialization")] { ... }`. This tells `type_operators!` to add the attribute
//! `#[cfg(features = "specialization")]` to every `impl` declared inside. It's also worth noting that adding derives
//! to every single statement inside a `concrete` or `data` declaration can be done as shown above with a `where`
//! clause-like structure - the reason we have to do this is because if we were allowed to define it the intuitive
//! way, there would be no easy way to extract doc comments on the group trait (thanks to macro parsing ambiguities.)
//!
//! Current bugs/improvements to be made:
//! - Bounds in type operators are currently restricted to identifiers only - they should be augmented with a LISP-like
//! dialect similar to the rest of the macro system.
//!
//! If questions are had, I may be found either at my email (which is listed on GitHub) or on the `#rust` IRC, where I go by
//! the nick `sleffy`.
//!
/// The `All` trait provides a workaround to the current parsing problem of a lack of truly unbounded type operator
/// arguments. It's implemented for all types.
pub trait All {}
impl<T> All for T {}
/// The `type_operators` macro does a lot of different things. Specifically, there are two things
/// it's meant to do:
/// 1. Make declaring closed type families easier. (Although they never *really* end up closed... Good enough.)
/// 2. Make declaring type operators easier. (Although there are still a lotta problems with this.)
///
/// By "closed type family" here, I mean a family of structs which have a marker trait indicating that they
/// "belong" to the family. A sort of type-level enum, if you will (if only something like that could truly
/// exist in Rust some day!) And by "type operator", I mean a sort of function which acts on types and returns
/// a type. In the following example, the natural numbers (encoded in binary here) are our "closed type family",
/// and addition, subtraction, multiplication, division, etc. etc. are all our type operators.
///
/// You should probably read the top-level documentation before you look at this more complex example.
///
/// ```
/// # #[macro_use]
/// # extern crate type_operators;
///
/// type_operators! {
/// [A, B, C, D, E] // The gensym list. Be careful not to have these collide with your struct names!
///
/// // If I used `data` instead of concrete, no automatic `reify` function would be provided.
/// // But since I did, we have a sort of inductive thing going on here, by which we can transform
/// // any instance of this type into the reified version.
///
/// // data Nat {
/// // P,
/// // I(Nat = P),
/// // O(Nat = P),
/// // }
///
/// concrete Nat => usize {
/// P => 0,
/// I(N: Nat = P) => 1 + 2 * N,
/// O(N: Nat = P) => 2 * N,
/// Undefined => panic!("Undefined type-level arithmetic result!"),
/// }
///
/// // It's not just for natural numbers! Yes, we can do all sorts of logic here. However, in
/// // this example, `Bool` is used later on in implementations that are hidden from you due
/// // to their complexity.
/// concrete Bool => bool {
/// False => false,
/// True => true,
/// }
///
/// (Pred) Predecessor(Nat): Nat {
/// [Undefined] => Undefined
/// [P] => Undefined
/// forall (N: Nat) {
/// [(O N)] => (I (# N))
/// [(I N)] => (O N)
/// }
/// }
///
/// (Succ) Successor(Nat): Nat {
/// [Undefined] => Undefined
/// [P] => I
/// forall (N: Nat) {
/// [(O N)] => (I N)
/// [(I N)] => (O (# N))
/// }
/// }
///
/// (Sum) Adding(Nat, Nat): Nat {
/// [P, P] => P
/// forall (N: Nat) {
/// [(O N), P] => (O N)
/// [(I N), P] => (I N)
/// [P, (O N)] => (O N)
/// [P, (I N)] => (I N)
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (O (# M N))
/// [(I M), (O N)] => (I (# M N))
/// [(O M), (I N)] => (I (# M N))
/// [(I M), (I N)] => (O (# (# M N) I))
/// }
/// }
///
/// (Difference) Subtracting(Nat, Nat): Nat {
/// forall (N: Nat) {
/// [N, P] => N
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (O (# M N))
/// [(I M), (O N)] => (I (# M N))
/// [(O M), (I N)] => (I (# (# M N) I))
/// [(I M), (I N)] => (O (# M N))
/// }
/// }
///
/// (Product) Multiplying(Nat, Nat): Nat {
/// forall (N: Nat) {
/// [P, N] => P
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), N] => (# M (O N))
/// [(I M), N] => (@Adding N (# M (O N)))
/// }
/// }
///
/// (If) NatIf(Bool, Nat, Nat): Nat {
/// forall (T: Nat, U: Nat) {
/// [True, T, U] => T
/// [False, T, U] => U
/// }
/// }
///
/// (NatIsUndef) NatIsUndefined(Nat): Bool {
/// [Undefined] => True
/// [P] => False
/// forall (M: Nat) {
/// [(O M)] => False
/// [(I M)] => False
/// }
/// }
///
/// (NatUndef) NatUndefined(Nat, Nat): Nat {
/// forall (M: Nat) {
/// [Undefined, M] => Undefined
/// [P, M] => M
/// }
/// forall (M: Nat, N: Nat) {
/// [(O N), M] => M
/// [(I N), M] => M
/// }
/// }
///
/// (TotalDifference) TotalSubtracting(Nat, Nat): Nat {
/// [P, P] => P
/// [Undefined, P] => Undefined
/// forall (N: Nat) {
/// [N, Undefined] => Undefined
/// [P, (O N)] => (# P N)
/// [P, (I N)] => Undefined
/// [(O N), P] => (O N)
/// [(I N), P] => (I N)
/// [Undefined, (O N)] => Undefined
/// [Undefined, (I N)] => Undefined
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (@NatUndefined (# M N) (O (# M N)))
/// [(I M), (O N)] => (@NatUndefined (# M N) (I (# M N)))
/// [(O M), (I N)] => (@NatUndefined (# (# M N) I) (I (# (# M N) I)))
/// [(I M), (I N)] => (@NatUndefined (# M N) (O (# M N)))
/// }
/// }
///
/// (Quotient) Quotienting(Nat, Nat): Nat {
/// forall (D: Nat) {
/// [Undefined, D] => Undefined
/// [P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) O (@Successor (# (@TotalSubtracting P D) D)))
/// }
/// forall (N: Nat, D: Nat) {
/// [(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) O (@Successor (# (@TotalSubtracting (O N) D) D)))
/// [(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) O (@Successor (# (@TotalSubtracting (I N) D) D)))
/// }
/// }
///
/// (Remainder) Remaindering(Nat, Nat): Nat {
/// forall (D: Nat) {
/// [Undefined, D] => Undefined
/// [P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) P (# (@TotalSubtracting P D) D))
/// }
/// forall (N: Nat, D: Nat) {
/// [(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) (O N) (# (@TotalSubtracting (O N) D) D))
/// [(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) (I O) (# (@TotalSubtracting (I N) D) D))
/// }
/// }
/// }
///
/// # fn main() {
/// assert_eq!(<I<I> as Nat>::reify(), 3);
/// assert_eq!(<I<O<I>> as Nat>::reify(), 5);
/// assert_eq!(<Sum<I<O<I>>, I<I>> as Nat>::reify(), 8);
/// assert_eq!(<Difference<I<I>, O<I>> as Nat>::reify(), 1);
/// assert_eq!(<Difference<O<O<O<I>>>, I<I>> as Nat>::reify(), 5);
/// assert_eq!(<Product<I<I>, I<O<I>>> as Nat>::reify(), 15);
/// assert_eq!(<Quotient<I<I>, O<I>> as Nat>::reify(), 1);
/// assert_eq!(<Remainder<I<O<O<I>>>, O<O<I>>> as Nat>::reify(), 1);
/// # }
/// ```
#[macro_export]
macro_rules! type_operators {
($gensym:tt $(#$docs:tt)* data $name:ident: $fbound:ident $(+ $bound:ident)* where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {}
_tlsm_data!([$name ($fbound $(+ $bound)*) [] $($attr)*] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {}
_tlsm_data!([$name () [] $($attr)*] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident: $fbound:ident $(+ $bound:ident)* { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {}
_tlsm_data!([$name ($fbound $(+ $bound)*) []] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {}
_tlsm_data!([$name () []] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident: $fbound:ident $(+ $bound:ident)* => $output:ty where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {
fn reify() -> $output;
}
_tlsm_concrete!([$name ($fbound $(+ $bound)*) [] $($attr)*] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident => $output:ty where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {
fn reify() -> $output;
}
_tlsm_concrete!([$name () [] $($attr)*] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident: $fbound:ident $(+ $bound:ident)* => $output:ty { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {
fn reify() -> $output;
}
_tlsm_concrete!([$name ($fbound $(+ $bound)*) []] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident => $output:ty { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {
fn reify() -> $output;
}
_tlsm_concrete!([$name () []] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* ($alias:ident) $machine:ident ($($kind:tt)*): $out:tt where $(#$attr:tt)* { $($states:tt)* } $($rest:tt)*) => {
_tlsm_machine!([$($docs)*] [$($attr)*] $alias $machine $gensym [$($kind)*] [] $out);
_tlsm_states!($machine [$($attr)*] $($states)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* ($alias:ident) $machine:ident ($($kind:tt)*): $out:tt { $($states:tt)* } $($rest:tt)*) => {
_tlsm_machine!([$($docs)*] [] $alias $machine $gensym [$($kind)*] [] $out);
_tlsm_states!($machine [] $($states)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt) => {};
}
#[macro_export]
macro_rules! _tlsm_parse_type {
((@ $external:ident $arg:tt $($more:tt)+)) => {
<_tlsm_parse_type!($arg) as $external< $(_tlsm_parse_type!($more)),+ >>::Output
};
((@ $external:ident $arg:tt)) => {
<_tlsm_parse_type!($arg) as $external>::Output
};
(($parameterized:ident $($arg:tt)*)) => {
$parameterized<$(_tlsm_parse_type!($arg)),*>
};
($constant:ident) => {
$constant
};
}
#[macro_export]
macro_rules! _tlsm_states {
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (& $arg:tt where $($extra:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo [$($bounds)* $($extra)*] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$($queue:tt)*] (% $arg:tt $($more:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (# $arg:tt $($more:tt)+)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg):
$machine< $(_tlsm_states!(@output $machine $more)),+ >)] [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (@ $external:ident $arg:tt $($more:tt)+)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg):
$external< $(_tlsm_states!(@output $machine $more)),+ >)] [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (# $arg:tt)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg): $machine)] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (@ $external:ident $arg:tt)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg): $external)] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$($queue:tt)*] ($parameterized:ident $arg:tt $($args:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($args)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$next:tt $($queue:tt)*] $constant:ident) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($queue)*] $next);
};
(@bounds $attrs:tt $machine:ident { $($implinfo:tt)* } $bounds:tt [] $constant:ident) => {
_tlsm_states!(@implement $attrs $machine $bounds $($implinfo)*);
};
(@maybedefault $attrs:tt $machine:ident $quantified:tt [$($input:tt)*] => $output:tt) => {
_tlsm_states!(@bounds $attrs $machine { [] $quantified [$($input)*] => $output } [] [] $output);
};
(@maybedefault $attrs:tt $machine:ident $quantified:tt {$($input:tt)*} => $output:tt) => {
_tlsm_states!(@bounds $attrs $machine { [default] $quantified [$($input)*] => $output } [] [] $output);
};
(@dispatchgroup $attrs:tt $machine:ident $quantified:tt $($head:tt $body:tt $tail:tt)*) => {
$(_tlsm_states!(@dispatch $attrs $machine $quantified $head $body $tail);)*
};
(@dispatch [$($attr:meta)*] $machine:ident $quantified:tt # [$newattr:meta] { $($head:tt $body:tt $tail:tt)* }) => {
_tlsm_states!(@dispatchgroup [$($attr)* $newattr] $machine $quantified $($head $body $tail)*);
};
(@dispatch $attrs:tt $machine:ident ($(($lsym:ident: $lbound:tt))*) forall ($($rsym:ident: $rbound:tt),*) { $($head:tt $body:tt $tail:tt)* }) => {
_tlsm_states!(@dispatchgroup $attrs $machine ($(($lsym: $lbound))* $(($rsym: $rbound))*) $($head $body $tail)*);
};
(@dispatch $attrs:tt $machine:ident $quantified:tt $input:tt => $output:tt) => {
_tlsm_states!(@maybedefault $attrs $machine $quantified $input => $output);
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] () [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] () [$head:tt] => $output:tt) => {
$(#[$attr])*
impl $machine for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] () [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] () [$head:tt] => $output:tt) => {
$(#[$attr])*
impl $machine for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@output $machine:ident (& $arg:tt $($extra:tt)*)) => {
_tlsm_states!(@output $machine $arg)
};
(@output $machine:ident (# $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $machine< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (# $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $machine>::Output
};
(@output $machine:ident (% $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $machine< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (% $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $machine>::Output
};
(@output $machine:ident (@ $external:ident $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $external< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (@ $external:ident $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $external>::Output
};
(@output $machine:ident ($parameterized:ident $($arg:tt)+)) => {
$parameterized<$(_tlsm_states!(@output $machine $arg)),+>
};
(@output $machine:ident $constant:ident) => {
$constant
};
(@reduceattrs [$($attr:tt)*] [$($specific:tt)*] $machine:ident $head:tt $body:tt $tail:tt) => {
_tlsm_states!(@dispatch [$($attr)* $($specific)*] $machine () $head $body $tail);
};
($machine:ident $attrs:tt $($(# $specific:tt)* $head:tt $body:tt $tail:tt)*) => {
$(_tlsm_states!(@reduceattrs $attrs [$($specific)*] $machine $head $body $tail);)*
};
}
#[macro_export]
macro_rules! _tlsm_machine {
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [$($kinds)+] [$($accum)* ($ksym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [] [$($accum)* ($ksym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt, $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt, $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [$($kinds)+] [$($accum)* ($ksym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [] [$($accum)* ($ksym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym: $kind)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym: $kind)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym: $kind)] $out);
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] _) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] _) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] ($parameterized:ident $($param:tt)*)) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output: $parameterized<$(_tlsm_parse_type!($param)),*>;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] ($parameterized:ident $($param:tt)*)) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output: $parameterized<$(_tlsm_parse_type!($param)),*>;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] $out:ident) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output: $out;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] $out:ident) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output: $out;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
}
#[macro_export]
macro_rules! _tlsm_meta_filter_struct {
([$($preceding:tt)*] #[struct: $attr:meta] $($more:tt)*) => (_tlsm_meta_filter_struct!([$($preceding)* #[$attr]] $($more)*););
([$($preceding:tt)*] #$attr:tt $($more:tt)*) => (_tlsm_meta_filter_struct!([$($preceding)* #$attr] $($more)*););
([$($preceding:tt)*] $($decl:tt)*) => ($($preceding)* $($decl)*);
}
#[macro_export]
macro_rules! _tlsm_meta_filter_impl {
([$($preceding:tt)*] #[impl: $attr:meta] $($more:tt)*) => (_tlsm_meta_filter_impl!([$($preceding)* #[$attr]] $($more)*););
($preceding:tt #[derive $traits:tt] $($more:tt)*) => (_tlsm_meta_filter_impl!($preceding $($more)*);); // Friends don't let friends derive drunk!
([$($preceding:tt)*] #$attr:tt $($more:tt)*) => (_tlsm_meta_filter_impl!([$($preceding)* #$attr] $($more)*););
([$($preceding:tt)*] $($decl:tt)*) => ($($preceding)* $($decl)*);
}
#[macro_export]
macro_rules! _tlsm_data {
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] _ $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym)] [$($bounds)* ($gensym)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym: $kind = $default)] [$($bounds)* ($gensym: $kind)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym: $kind)] [$($bounds)* ($gensym: $kind)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] @parameterized $name:ident $gensyms:tt [$(($asym:ident $($args:tt)*))*] [$(($bsym:ident $($bounds:tt)*))*] [$(($($phantom:tt)*))*]) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name < $($asym $($args)*),* >($(::std::marker::PhantomData<$($phantom)*>),*);
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl< $($bsym $($bounds)*),* > $group for $name<$($($phantom)*),*> {}
}
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt # $nextspecific:tt $($rest:tt)*) => {
_tlsm_data!([$group $derives [$($specific)* $nextspecific] $($attr)*] $gensym $($rest)*);
};
([$group:ident () [$($specific:tt)*] $($attr:tt)*] $gensym:tt DEFAULT, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T {}
}
_tlsm_data!([$group () [] $($attr)*] $gensym $($rest)*);
};
([$group:ident ($fbound:ident $(+ $bound:ident)*) [$($specific:tt)*] $($attr:tt)*] $gensym:tt DEFAULT, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T where T: $fbound $(+ $bound)* {}
}
_tlsm_data!([$group ($fbound $(+ $bound)*) [] $($attr)*] $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt $name:ident, $($rest:tt)*) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name;
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl $group for $name {}
}
_tlsm_data!([$group $derives [] $($attr)*] $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt $name:ident($($args:tt)*), $($rest:tt)*) => {
_tlsm_data!([$group $derives [$($specific)*] $($attr)*] @parameterized $name $gensym [] [] [] $($args)*);
_tlsm_data!([$group $derives [] $($attr)*] $gensym $($rest)*);
};
($attrs:tt $gensym:tt) => {};
}
#[macro_export]
macro_rules! _tlsm_concrete {
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; $gensym:tt [$($args:tt)*] [$($bounds:tt)*] [$($syms:ident)*] $sym:ident: $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; $gensym [$($args)* ($sym: $kind = $default)] [$($bounds)* ($sym: $kind)] [$($syms)* $sym] $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; $gensym:tt [$($args:tt)*] [$($bounds:tt)*] [$($syms:ident)*] $sym:ident: $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; $gensym [$($args)* ($sym: $kind)] [$($bounds)* ($sym: $kind)] [$($syms)* $sym] $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] $syms:tt $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; [$($next),*] [$($args)* ($gensym: $kind = $default)] [$($bounds)* ($gensym: $kind)] $syms $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] $syms:tt $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; [$($next),*] [$($args)* ($gensym: $kind)] [$($bounds)* ($gensym: $kind)] $syms $($($rest)*),*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt # $nextspecific:tt $($rest:tt)*) => {
_tlsm_concrete!([$group $derives [$($specific)* $nextspecific] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; @parameterized $name:ident => $value:expr; $gensyms:tt [$(($tysym:ident: $($args:tt)*))*] [$(($bsym:ident: $bound:ident))*] [$($sym:ident)*]) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name < $($tysym: $($args)*),* >($(::std::marker::PhantomData<$tysym>),*);
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl< $($bsym: $bound),* > $group for $name<$($bsym),*> {
#[allow(non_snake_case)]
fn reify() -> $output { $(let $sym = <$sym>::reify();)* $value }
}
}
};
([$group:ident () [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt DEFAULT => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T {
default fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group () [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident ($fbound:ident $(+ $bound:ident)*) [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt DEFAULT => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T where T: $fbound $(+ $bound)* {
default fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group ($fbound $(+ $bound)*) [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt $name:ident => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name;
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl $group for $name {
fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group $derives [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt $name:ident($($args:tt)*) => $value:expr, $($rest:tt)*) => {
_tlsm_concrete!([$group $derives [$($specific)*] $($attr)*] $output; @parameterized $name => $value; $gensym [] [] [] $($args)*);
_tlsm_concrete!([$group $derives [] $($attr)*] $output; $gensym $($rest)*);
};
($attrs:tt $output:ty; $gensym:tt) => {};
}
#[cfg(test)]
mod tests_1 {
use super::*;
type_operators! {
[A, B, C, D, E]
concrete Nat => usize {
P => 0,
I(N: Nat = P) => 1 + 2 * N,
O(N: Nat = P) => 2 * N,
Undefined => panic!("Undefined type-level arithmetic result!"),
}
// It's not just for natural numbers! Yes, we can do all sorts of logic here. However, in
// this example, `Bool` is used later on in implementations that are hidden from you due
// to their complexity.
concrete Bool => bool {
False => false,
True => true,
}
(Pred) Predecessor(Nat): Nat {
[Undefined] => Undefined
[P] => Undefined
forall (N: Nat) {
[(O N)] => (I (# N))
[(I N)] => (O N)
}
}
(Succ) Successor(Nat): Nat {
[Undefined] => Undefined
[P] => I
forall (N: Nat) {
[(O N)] => (I N)
[(I N)] => (O (# N))
}
}
(Sum) Adding(Nat, Nat): Nat {
[P, P] => P
forall (N: Nat) {
[(O N), P] => (O N)
[(I N), P] => (I N)
[P, (O N)] => (O N)
[P, (I N)] => (I N)
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (O (# M N))
[(I M), (O N)] => (I (# M N))
[(O M), (I N)] => (I (# M N))
[(I M), (I N)] => (O (# (# M N) I))
}
}
(Difference) Subtracting(Nat, Nat): Nat {
forall (N: Nat) {
[N, P] => N
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (O (# M N))
[(I M), (O N)] => (I (# M N))
[(O M), (I N)] => (I (# (# M N) I))
[(I M), (I N)] => (O (# M N))
}
}
(Product) Multiplying(Nat, Nat): Nat {
forall (N: Nat) {
[P, N] => P
}
forall (N: Nat, M: Nat) {
[(O M), N] => (# M (O N))
[(I M), N] => (@Adding N (# M (O N)))
}
}
(If) NatIf(Bool, Nat, Nat): Nat {
forall (T: Nat, U: Nat) {
[True, T, U] => T
[False, T, U] => U
}
}
(NatIsUndef) NatIsUndefined(Nat): Bool {
[Undefined] => True
[P] => False
forall (M: Nat) {
[(O M)] => False
[(I M)] => False
}
}
(NatUndef) NatUndefined(Nat, Nat): Nat {
forall (M: Nat) {
[Undefined, M] => Undefined
[P, M] => M
}
forall (M: Nat, N: Nat) {
[(O N), M] => M
[(I N), M] => M
}
}
(TotalDifference) TotalSubtracting(Nat, Nat): Nat {
[P, P] => P
[Undefined, P] => Undefined
forall (N: Nat) {
[N, Undefined] => Undefined
[P, (O N)] => (# P N)
[P, (I N)] => Undefined
[(O N), P] => (O N)
[(I N), P] => (I N)
[Undefined, (O N)] => Undefined
[Undefined, (I N)] => Undefined
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (@NatUndefined (# M N) (O (# M N)))
[(I M), (O N)] => (@NatUndefined (# M N) (I (# M N)))
[(O M), (I N)] => (@NatUndefined (# (# M N) I) (I (# (# M N) I)))
[(I M), (I N)] => (@NatUndefined (# M N) (O (# M N)))
}
}
(Quotient) Quotienting(Nat, Nat): Nat {
forall (D: Nat) {
[Undefined, D] => Undefined
[P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) O (@Successor (# (@TotalSubtracting P D) D)))
}
forall (N: Nat, D: Nat) {
[(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) O (@Successor (# (@TotalSubtracting (O N) D) D)))
[(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) O (@Successor (# (@TotalSubtracting (I N) D) D)))
}
}
(Remainder) Remaindering(Nat, Nat): Nat {
forall (D: Nat) {
[Undefined, D] => Undefined
[P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) P (# (@TotalSubtracting P D) D))
}
forall (N: Nat, D: Nat) {
[(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) (O N) (# (@TotalSubtracting (O N) D) D))
[(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) (I O) (# (@TotalSubtracting (I N) D) D))
}
}
}
fn invariants() {
assert_eq!(<I<I> as Nat>::reify(), 3);
assert_eq!(<I<O<I>> as Nat>::reify(), 5);
assert_eq!(<Sum<I<O<I>>, I<I>> as Nat>::reify(), 8);
assert_eq!(<Difference<I<I>, O<I>> as Nat>::reify(), 1);
assert_eq!(<Difference<O<O<O<I>>>, I<I>> as Nat>::reify(), 5);
assert_eq!(<Product<I<I>, I<O<I>>> as Nat>::reify(), 15);
assert_eq!(<Quotient<I<I>, O<I>> as Nat>::reify(), 1);
assert_eq!(<Remainder<I<O<O<I>>>, O<O<I>>> as Nat>::reify(), 1);
}
}
#[cfg(test)]
mod tests_2 {
use super::*;
type_operators! {
[A, B, C, D, E]
data Nat {
P,
I(Nat = P),
O(Nat = P),
}
}
}
Allow `All` to apply to unsized types
//! # The `type_operators` macro - a DSL for declaring type operators and type-level logic in Rust.
//!
//! This crate contains a macro for declaring type operators in Rust. Type operators are like functions
//! which act at the type level. The `type_operators` macro works by translating a LISP-y DSL into a big mess of
//! traits and impls with associated types.
//!
//! # The DSL
//!
//! Let's take a look at this fairly small example:
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//! type_operators! {
//! [A, B, C, D, E]
//!
//! data Nat {
//! P,
//! I(Nat = P),
//! O(Nat = P),
//! }
//! }
//! # fn main() {}
//! ```
//!
//! There are two essential things to note in this example. The first is the "gensym list" - Rust does
//! not currently have a way to generate unique identifiers, so we have to supply our own. It is on *you*
//! to avoid clashes between these pseudo-gensyms and the names of the structs involved! If we put `P`, `I`, or `O`
//! into the gensym list, things could get really bad! We'd get type errors at compile-time stemming from trait
//! bounds, coming from the definitions of type operators later. Thankfully, the gensym list can be fairly small
//! and usually never uses more than two or three symbols.
//!
//! The second thing is the `data` declaration. This declares a group of structs which fall under a marker trait.
//! In our case, `Nat` is the marker trait generated and `P`, `I`, and `O` are the structs generated. This example
//! shows an implementation of natural numbers (positive integers, including zero) which are represented as types.
//! So, `P` indicates the end of a natural number - think of it as a sort of nil; we're working with a linked list
//! here, at the type level. So, `I<P>` would represent "one plus twice `P`", which of course comes out to `1`;
//! `O<P>` would represent "twice `P`", which of course comes out to zero. If we look at `I` and `O` as bits of a
//! binary number, we come out with a sort of reversed binary representation where the "bit" furthest to the left
//! is the least significant bit. As such, `O<O<I>>` represents `4`, `I<O<O<I>>>` represents `9`, and so on.
//!
//! When we write `I(Nat = P)`, the `= P` denotes a default. This lets us write `I`, and have it be inferred to be
//! `I<P>`, which is probably what you mean if you just write `I` alone. `Nat` gives a trait bound. To better demonstrate,
//! here is (roughly) what the above invocation of `type_operators` expands to:
//!
//! ```rust
//! # use std::marker::PhantomData;
//!
//! pub trait Nat {}
//!
//! pub struct P;
//! impl Nat for P {}
//!
//! pub struct I<A: Nat = P>(PhantomData<(A)>);
//! impl<A: Nat> Nat for I<A> {}
//!
//! pub struct O<A: Nat = P>(PhantomData<(A)>);
//! impl<A: Nat> Nat for O<A> {}
//! # fn main() {}
//! ```
//!
//! The `Undefined` value looks a little silly, but it allows for the definition of division in a way which uses
//! type-level comparison and branching. More on that later.
//!
//! The above definition has a problem. We cannot *fold* our type-level representation down into a numerical representation.
//! That makes our type-level natural numbers useless! That's why `type_operators` provides another way of defining
//! type-level representations, the `concrete` declaration:
//!
//! ```rust
//! # #[macro_use]
//! # extern crate type_operators;
//!
//! type_operators! {
//! [A, B, C, D, E]
//!
//! concrete Nat => usize {
//! P => 0,
//! I(N: Nat = P) => 1 + 2 * N,
//! O(N: Nat = P) => 2 * N,
//! Undefined => panic!("Undefined type-level arithmetic result!"),
//! }
//! }
//! # fn main() {}
//! ```
//!
//! This adds an associated function to the `Nat` trait called `reify`, which allows you to turn your type-level
//! representations into concrete values of type `usize` (in this case.) If you've ever seen primitive-recursive
//! functions, then this should look a bit familiar to you - it's reminiscent of a recursion scheme, which is a
//! way of recursing over a value to map it into something else. (See also "catamorphism".) It should be fairly
//! obvious how this works, but if not, here's a breakdown:
//!
//! - `P` always represents zero, so we say that `P => 0`. Simple.
//! - `I` represents double its argument plus one. If we annotate our macro's definition with a variable `N`,
//! then `type_operators` will automatically call `N::reify()` and substitute that value for your `N` in the
//! expression you give it. So, in this way, we define the reification of `I` to be one plus two times the
//! value that `N` reifies to.
//! - `O` represents double its argument, so this one's straightforward - it's like `I`, but without the `1 +`.
//!
//! Okay. So now that we've got that under our belts, let's dive into something a bit more complex: let's define
//! a type operator for addition.
//!
//! `type_operators` allows you to define recursive functions. Speaking generally, that's what you'll really need
//! to pull this off whatever you do. (And speaking precisely, this whole approach was inspired by primitive-recursion.)
//! So let's think about how we can add two binary numbers, starting at the least-significant bit:
//! - Obviously, `P + P` should be `P`, since zero plus zero is zero.
//! - What about `P + O<N>`, for any natural number `N`? Well, that should be `O<N>`. Same with `I<N>`. As a matter of
//! fact, now it looks pretty obvious that whenever we have `P` on one side, we should just say that whatever's on the
//! other side is the result.
//! So our little table of operations now looks like:
//! ```text
//! [P, P] => P
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! ```
//! Now you're probably saying, "whoa! That doesn't look like Rust at all! Back up!" And that's because it *isn't.* I made
//! a little LISP-like dialect to describe Rust types for this project because it makes things a lot easier to parse in
//! macros; specifically, each little atomic type can be wrapped up in a pair of parentheses, while with angle brackets,
//! Rust has to parse them as separate tokens. In this setup, `(O N)` means `O<N>`,
//! just `P` alone means `P`, etc. etc. The notation `[X, Y] => Z` means "given inputs `X` and `Y`, produce output `Z`." So
//! it's a sort of pattern-matching.
//!
//! Now let's look at the more complex cases. We need to cover all the parts where combinations of `O<N>` and `I<N>` are
//! added together.
//! - `O<M> + O<N>` should come out to `O<M + N>`. This is a fairly intuitive result, but we can describe it mathematically
//! as `2 * m + 2 * n == 2 * (m + n)`. So, it's the distributive law, and most importantly, it cuts down on the *structure*
//! of the arguments - we go from adding `O<M>` and `O<N>` to `M` and `N`, whatever they are, and `M` and `N` are clearly
//! less complex than `O<M>` and `O<N>`. If we always see that our outputs have less complexity than the inputs, then we're
//! that much closer to a proof that our little type operator always terminates with a result!
//! - `I<M> + O<N>` and `O<M> + I<N>` should come out to `I<M + N>`. Again, fairly intuitive. We have `1 + 2 * m + 2 * n`,
//! which we can package up into `1 + 2 * (m + n)`.
//! - `I<M> + I<N>` is the trickiest part here. We have `1 + 2 * m + 1 + 2 * m == 2 + 2 * m + 2 * n == 2 * (1 + m + n)`. We
//! can implement this as `I<I + M + N>`, but we can do a little bit better. More on that later, we'll head with the simpler
//! implementation for now.
//!
//! Let's add these to the table:
//! ```text
//! [P, P] => P
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! // New:
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# I M) N))
//! ```
//! Here's something new: the `(# ...)` notation. This tells the macro, "hey, we wanna recurse." It's really shorthand
//! for a slightly more complex piece of notation, but they both have one thing in common - *when type_operators processes
//! the `(# ...)` notation, it uses it to calculate trait bounds.* This is because your type operator won't compile unless
//! it's absolutely certain that `(# M N)` will actually have a defined result. At an even higher level, this is the reason
//! I wish Rust had "closed type families" - if `P`, `I`, and `O` were in a closed type family `Nat`, Rust could check at compile-time
//! and be absolutely sure that `(# M N)` existed for all `M` and `N` that are in the `Nat` family.
//!
//! So then. Let's load this into an invocation of `type_operators` to see how it looks like. It's pretty close to the table,
//! but with a couple additions (I'm leaving out `Undefined` for now because it's not yet relevant):
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//!
//! type_operators! {
//! [A, B, C, D, E]
//!
//! concrete Nat => usize {
//! P => 0,
//! I(N: Nat = P) => 1 + 2 * N,
//! O(N: Nat = P) => 2 * N,
//! }
//!
//! (Sum) Adding(Nat, Nat): Nat {
//! [P, P] => P
//! forall (N: Nat) {
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! }
//! forall (N: Nat, M: Nat) {
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# M N) I))
//! }
//! }
//! }
//! # fn main() {}
//! ```
//!
//! There are several things to note. First, the definition `(Sum) Adding(Nat, Nat): Nat`. This says,
//! "this type operator takes two `Nat`s as input and outputs a `Nat`." Since addition is implemented
//! as a recursive trait under the hood, this means we get a trait definition of the form:
//!
//! ```rust
//! # pub trait Nat {}
//! pub trait Adding<A: Nat>: Nat {
//! type Output: Nat;
//! }
//! ```
//!
//! The `(Sum)` bit declares a nice, convenient alias for us, so that instead of typing `<X as Adding<Y>>::Output`
//! to get the sum of two numbers, we can instead type `Sum<X, Y>`. Much neater.
//!
//! Second, the "quantifier" sections (the parts with `forall`) avoid Rust complaining about "undeclared type variables." In any given
//! generic `impl`, we have to worry about declaring what type variables/generic type parameters we can use in
//! that `impl`. The `forall` bit modifies the prelude of the `impl`. For example, `forall (N: Nat)` causes all the
//! `impl`s inside its little block to be declared as `impl<N: Nat> ...` instead of `impl ...`, so that we can use
//! `N` as a variable inside those expressions.
//!
//! That just about wraps up our short introduction. To finish, here are the rest of the notations specific to our
//! little LISP-y dialect, all of which can only be used on the right-hand side of a rule in the DSL:
//!
//! - `(@TypeOperator ...)` invokes another type operator (can be the original caller!) and generates the proper trait bounds.
//! - `(% ...)` is like `(# ...)`, but does not generate any trait bounds.
//! - `(& <type> where (<where_clause>) (<where_clause>) ...)` allows for the definition of custom `where` clauses for a given
//! `impl`. It can appear anywhere in the right-hand side of a rule in the DSL, but in general should probably always be
//! written at the top-level for consistency.
//!
//! In addition, it is possible to use attributes such as `#[derive(...)]` or `#[cfg(...)]` on `data` and `concrete` definitions
//! as well as individual elements inside them. In addition, attributes can be added to the `impl`s for rules. For example:
//!
//! ```rust
//! # #[macro_use] extern crate type_operators;
//! # use std::fmt::Debug;
//! type_operators! {
//! [A, B, C, D, E]
//!
//! data Nat: Default + Debug where #[derive(Default, Debug)] {
//! P,
//! I(Nat = P),
//! O(Nat = P),
//! #[cfg(features = "specialization")]
//! Error,
//! #[cfg(features = "specialization")]
//! DEFAULT,
//! }
//!
//! (Sum) Adding(Nat, Nat): Nat {
//! [P, P] => P
//! forall (N: Nat) {
//! [(O N), P] => (O N)
//! [(I N), P] => (I N)
//! [P, (O N)] => (O N)
//! [P, (I N)] => (I N)
//! }
//! forall (N: Nat, M: Nat) {
//! [(O M), (O N)] => (O (# M N))
//! [(I M), (O N)] => (I (# M N))
//! [(O M), (I N)] => (I (# M N))
//! [(I M), (I N)] => (O (# (# M N) I))
//!
//! #[cfg(features = "specialization")] {
//! {M, N} => Error
//! }
//! }
//! }
//! }
//! # fn main() {}
//! ```
//!
//! Note the block `#[cfg(features = "specialization")] { ... }`. This tells `type_operators!` to add the attribute
//! `#[cfg(features = "specialization")]` to every `impl` declared inside. It's also worth noting that adding derives
//! to every single statement inside a `concrete` or `data` declaration can be done as shown above with a `where`
//! clause-like structure - the reason we have to do this is because if we were allowed to define it the intuitive
//! way, there would be no easy way to extract doc comments on the group trait (thanks to macro parsing ambiguities.)
//!
//! Current bugs/improvements to be made:
//! - Bounds in type operators are currently restricted to identifiers only - they should be augmented with a LISP-like
//! dialect similar to the rest of the macro system.
//!
//! If questions are had, I may be found either at my email (which is listed on GitHub) or on the `#rust` IRC, where I go by
//! the nick `sleffy`.
//!
/// The `All` trait provides a workaround to the current parsing problem of a lack of truly unbounded type operator
/// arguments. It's implemented for all types.
pub trait All {}
impl<T: ?Sized> All for T {}
/// The `type_operators` macro does a lot of different things. Specifically, there are two things
/// it's meant to do:
/// 1. Make declaring closed type families easier. (Although they never *really* end up closed... Good enough.)
/// 2. Make declaring type operators easier. (Although there are still a lotta problems with this.)
///
/// By "closed type family" here, I mean a family of structs which have a marker trait indicating that they
/// "belong" to the family. A sort of type-level enum, if you will (if only something like that could truly
/// exist in Rust some day!) And by "type operator", I mean a sort of function which acts on types and returns
/// a type. In the following example, the natural numbers (encoded in binary here) are our "closed type family",
/// and addition, subtraction, multiplication, division, etc. etc. are all our type operators.
///
/// You should probably read the top-level documentation before you look at this more complex example.
///
/// ```
/// # #[macro_use]
/// # extern crate type_operators;
///
/// type_operators! {
/// [A, B, C, D, E] // The gensym list. Be careful not to have these collide with your struct names!
///
/// // If I used `data` instead of concrete, no automatic `reify` function would be provided.
/// // But since I did, we have a sort of inductive thing going on here, by which we can transform
/// // any instance of this type into the reified version.
///
/// // data Nat {
/// // P,
/// // I(Nat = P),
/// // O(Nat = P),
/// // }
///
/// concrete Nat => usize {
/// P => 0,
/// I(N: Nat = P) => 1 + 2 * N,
/// O(N: Nat = P) => 2 * N,
/// Undefined => panic!("Undefined type-level arithmetic result!"),
/// }
///
/// // It's not just for natural numbers! Yes, we can do all sorts of logic here. However, in
/// // this example, `Bool` is used later on in implementations that are hidden from you due
/// // to their complexity.
/// concrete Bool => bool {
/// False => false,
/// True => true,
/// }
///
/// (Pred) Predecessor(Nat): Nat {
/// [Undefined] => Undefined
/// [P] => Undefined
/// forall (N: Nat) {
/// [(O N)] => (I (# N))
/// [(I N)] => (O N)
/// }
/// }
///
/// (Succ) Successor(Nat): Nat {
/// [Undefined] => Undefined
/// [P] => I
/// forall (N: Nat) {
/// [(O N)] => (I N)
/// [(I N)] => (O (# N))
/// }
/// }
///
/// (Sum) Adding(Nat, Nat): Nat {
/// [P, P] => P
/// forall (N: Nat) {
/// [(O N), P] => (O N)
/// [(I N), P] => (I N)
/// [P, (O N)] => (O N)
/// [P, (I N)] => (I N)
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (O (# M N))
/// [(I M), (O N)] => (I (# M N))
/// [(O M), (I N)] => (I (# M N))
/// [(I M), (I N)] => (O (# (# M N) I))
/// }
/// }
///
/// (Difference) Subtracting(Nat, Nat): Nat {
/// forall (N: Nat) {
/// [N, P] => N
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (O (# M N))
/// [(I M), (O N)] => (I (# M N))
/// [(O M), (I N)] => (I (# (# M N) I))
/// [(I M), (I N)] => (O (# M N))
/// }
/// }
///
/// (Product) Multiplying(Nat, Nat): Nat {
/// forall (N: Nat) {
/// [P, N] => P
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), N] => (# M (O N))
/// [(I M), N] => (@Adding N (# M (O N)))
/// }
/// }
///
/// (If) NatIf(Bool, Nat, Nat): Nat {
/// forall (T: Nat, U: Nat) {
/// [True, T, U] => T
/// [False, T, U] => U
/// }
/// }
///
/// (NatIsUndef) NatIsUndefined(Nat): Bool {
/// [Undefined] => True
/// [P] => False
/// forall (M: Nat) {
/// [(O M)] => False
/// [(I M)] => False
/// }
/// }
///
/// (NatUndef) NatUndefined(Nat, Nat): Nat {
/// forall (M: Nat) {
/// [Undefined, M] => Undefined
/// [P, M] => M
/// }
/// forall (M: Nat, N: Nat) {
/// [(O N), M] => M
/// [(I N), M] => M
/// }
/// }
///
/// (TotalDifference) TotalSubtracting(Nat, Nat): Nat {
/// [P, P] => P
/// [Undefined, P] => Undefined
/// forall (N: Nat) {
/// [N, Undefined] => Undefined
/// [P, (O N)] => (# P N)
/// [P, (I N)] => Undefined
/// [(O N), P] => (O N)
/// [(I N), P] => (I N)
/// [Undefined, (O N)] => Undefined
/// [Undefined, (I N)] => Undefined
/// }
/// forall (N: Nat, M: Nat) {
/// [(O M), (O N)] => (@NatUndefined (# M N) (O (# M N)))
/// [(I M), (O N)] => (@NatUndefined (# M N) (I (# M N)))
/// [(O M), (I N)] => (@NatUndefined (# (# M N) I) (I (# (# M N) I)))
/// [(I M), (I N)] => (@NatUndefined (# M N) (O (# M N)))
/// }
/// }
///
/// (Quotient) Quotienting(Nat, Nat): Nat {
/// forall (D: Nat) {
/// [Undefined, D] => Undefined
/// [P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) O (@Successor (# (@TotalSubtracting P D) D)))
/// }
/// forall (N: Nat, D: Nat) {
/// [(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) O (@Successor (# (@TotalSubtracting (O N) D) D)))
/// [(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) O (@Successor (# (@TotalSubtracting (I N) D) D)))
/// }
/// }
///
/// (Remainder) Remaindering(Nat, Nat): Nat {
/// forall (D: Nat) {
/// [Undefined, D] => Undefined
/// [P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) P (# (@TotalSubtracting P D) D))
/// }
/// forall (N: Nat, D: Nat) {
/// [(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) (O N) (# (@TotalSubtracting (O N) D) D))
/// [(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) (I O) (# (@TotalSubtracting (I N) D) D))
/// }
/// }
/// }
///
/// # fn main() {
/// assert_eq!(<I<I> as Nat>::reify(), 3);
/// assert_eq!(<I<O<I>> as Nat>::reify(), 5);
/// assert_eq!(<Sum<I<O<I>>, I<I>> as Nat>::reify(), 8);
/// assert_eq!(<Difference<I<I>, O<I>> as Nat>::reify(), 1);
/// assert_eq!(<Difference<O<O<O<I>>>, I<I>> as Nat>::reify(), 5);
/// assert_eq!(<Product<I<I>, I<O<I>>> as Nat>::reify(), 15);
/// assert_eq!(<Quotient<I<I>, O<I>> as Nat>::reify(), 1);
/// assert_eq!(<Remainder<I<O<O<I>>>, O<O<I>>> as Nat>::reify(), 1);
/// # }
/// ```
#[macro_export]
macro_rules! type_operators {
($gensym:tt $(#$docs:tt)* data $name:ident: $fbound:ident $(+ $bound:ident)* where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {}
_tlsm_data!([$name ($fbound $(+ $bound)*) [] $($attr)*] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {}
_tlsm_data!([$name () [] $($attr)*] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident: $fbound:ident $(+ $bound:ident)* { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {}
_tlsm_data!([$name ($fbound $(+ $bound)*) []] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* data $name:ident { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {}
_tlsm_data!([$name () []] $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident: $fbound:ident $(+ $bound:ident)* => $output:ty where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {
fn reify() -> $output;
}
_tlsm_concrete!([$name ($fbound $(+ $bound)*) [] $($attr)*] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident => $output:ty where $(#$attr:tt)+ { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {
fn reify() -> $output;
}
_tlsm_concrete!([$name () [] $($attr)*] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident: $fbound:ident $(+ $bound:ident)* => $output:ty { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name: $fbound $(+ $bound)* {
fn reify() -> $output;
}
_tlsm_concrete!([$name ($fbound $(+ $bound)*) []] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* concrete $name:ident => $output:ty { $($stuff:tt)* } $($rest:tt)*) => {
$(#$docs)*
pub trait $name {
fn reify() -> $output;
}
_tlsm_concrete!([$name () []] $output; $gensym $($stuff)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* ($alias:ident) $machine:ident ($($kind:tt)*): $out:tt where $(#$attr:tt)* { $($states:tt)* } $($rest:tt)*) => {
_tlsm_machine!([$($docs)*] [$($attr)*] $alias $machine $gensym [$($kind)*] [] $out);
_tlsm_states!($machine [$($attr)*] $($states)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt $(#$docs:tt)* ($alias:ident) $machine:ident ($($kind:tt)*): $out:tt { $($states:tt)* } $($rest:tt)*) => {
_tlsm_machine!([$($docs)*] [] $alias $machine $gensym [$($kind)*] [] $out);
_tlsm_states!($machine [] $($states)*);
type_operators!($gensym $($rest)*);
};
($gensym:tt) => {};
}
#[macro_export]
macro_rules! _tlsm_parse_type {
((@ $external:ident $arg:tt $($more:tt)+)) => {
<_tlsm_parse_type!($arg) as $external< $(_tlsm_parse_type!($more)),+ >>::Output
};
((@ $external:ident $arg:tt)) => {
<_tlsm_parse_type!($arg) as $external>::Output
};
(($parameterized:ident $($arg:tt)*)) => {
$parameterized<$(_tlsm_parse_type!($arg)),*>
};
($constant:ident) => {
$constant
};
}
#[macro_export]
macro_rules! _tlsm_states {
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (& $arg:tt where $($extra:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo [$($bounds)* $($extra)*] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$($queue:tt)*] (% $arg:tt $($more:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (# $arg:tt $($more:tt)+)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg):
$machine< $(_tlsm_states!(@output $machine $more)),+ >)] [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (@ $external:ident $arg:tt $($more:tt)+)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg):
$external< $(_tlsm_states!(@output $machine $more)),+ >)] [$($more)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (# $arg:tt)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg): $machine)] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt [$($bounds:tt)*] [$($queue:tt)*] (@ $external:ident $arg:tt)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo
[$($bounds)* (_tlsm_states!(@output $machine $arg): $external)] [$($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$($queue:tt)*] ($parameterized:ident $arg:tt $($args:tt)*)) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($args)* $($queue)*] $arg);
};
(@bounds $attrs:tt $machine:ident $implinfo:tt $bounds:tt [$next:tt $($queue:tt)*] $constant:ident) => {
_tlsm_states!(@bounds $attrs $machine $implinfo $bounds [$($queue)*] $next);
};
(@bounds $attrs:tt $machine:ident { $($implinfo:tt)* } $bounds:tt [] $constant:ident) => {
_tlsm_states!(@implement $attrs $machine $bounds $($implinfo)*);
};
(@maybedefault $attrs:tt $machine:ident $quantified:tt [$($input:tt)*] => $output:tt) => {
_tlsm_states!(@bounds $attrs $machine { [] $quantified [$($input)*] => $output } [] [] $output);
};
(@maybedefault $attrs:tt $machine:ident $quantified:tt {$($input:tt)*} => $output:tt) => {
_tlsm_states!(@bounds $attrs $machine { [default] $quantified [$($input)*] => $output } [] [] $output);
};
(@dispatchgroup $attrs:tt $machine:ident $quantified:tt $($head:tt $body:tt $tail:tt)*) => {
$(_tlsm_states!(@dispatch $attrs $machine $quantified $head $body $tail);)*
};
(@dispatch [$($attr:meta)*] $machine:ident $quantified:tt # [$newattr:meta] { $($head:tt $body:tt $tail:tt)* }) => {
_tlsm_states!(@dispatchgroup [$($attr)* $newattr] $machine $quantified $($head $body $tail)*);
};
(@dispatch $attrs:tt $machine:ident ($(($lsym:ident: $lbound:tt))*) forall ($($rsym:ident: $rbound:tt),*) { $($head:tt $body:tt $tail:tt)* }) => {
_tlsm_states!(@dispatchgroup $attrs $machine ($(($lsym: $lbound))* $(($rsym: $rbound))*) $($head $body $tail)*);
};
(@dispatch $attrs:tt $machine:ident $quantified:tt $input:tt => $output:tt) => {
_tlsm_states!(@maybedefault $attrs $machine $quantified $input => $output);
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] () [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [$(($($constraint:tt)*))+] [$($default:tt)*] () [$head:tt] => $output:tt) => {
$(#[$attr])*
impl $machine for _tlsm_parse_type!($head) where $($($constraint)*),+
{
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] ($(($sym:ident: $bound:ident))+) [$head:tt] => $output:tt) => {
$(#[$attr])*
impl<$($sym: $bound),+> $machine for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] () [$head:tt $(, $input:tt)+] => $output:tt) => {
$(#[$attr])*
impl $machine< $(_tlsm_parse_type!($input)),+ > for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@implement [$($attr:meta)*] $machine:ident [] [$($default:tt)*] () [$head:tt] => $output:tt) => {
$(#[$attr])*
impl $machine for _tlsm_parse_type!($head) {
$($default)* type Output = _tlsm_states!(@output $machine $output);
}
};
(@output $machine:ident (& $arg:tt $($extra:tt)*)) => {
_tlsm_states!(@output $machine $arg)
};
(@output $machine:ident (# $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $machine< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (# $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $machine>::Output
};
(@output $machine:ident (% $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $machine< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (% $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $machine>::Output
};
(@output $machine:ident (@ $external:ident $arg:tt $($more:tt)+)) => {
<_tlsm_states!(@output $machine $arg) as $external< $(_tlsm_states!(@output $machine $more)),+ >>::Output
};
(@output $machine:ident (@ $external:ident $arg:tt)) => {
<_tlsm_states!(@output $machine $arg) as $external>::Output
};
(@output $machine:ident ($parameterized:ident $($arg:tt)+)) => {
$parameterized<$(_tlsm_states!(@output $machine $arg)),+>
};
(@output $machine:ident $constant:ident) => {
$constant
};
(@reduceattrs [$($attr:tt)*] [$($specific:tt)*] $machine:ident $head:tt $body:tt $tail:tt) => {
_tlsm_states!(@dispatch [$($attr)* $($specific)*] $machine () $head $body $tail);
};
($machine:ident $attrs:tt $($(# $specific:tt)* $head:tt $body:tt $tail:tt)*) => {
$(_tlsm_states!(@reduceattrs $attrs [$($specific)*] $machine $head $body $tail);)*
};
}
#[macro_export]
macro_rules! _tlsm_machine {
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [_] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _ , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [$($kinds)+] [$($accum)* ($ksym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: _] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [] [$($accum)* ($ksym)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt, $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt, $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [$($kinds)+] [$($accum)* ($ksym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt] [$($accum:tt)*] $out:tt) => {
First parameter cannot be named; use Self instead.
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident $gensym:tt [$ksym:ident: $kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine $gensym [] [$($accum)* ($ksym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym: $kind)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt , $($kinds:tt)+] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [$($kinds)+] [$($accum)* ($gensym: $kind)] $out);
};
([$($docs:tt)*] $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont [$($docs)*] $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym: $kind)] $out);
};
(@cont $docs:tt $attrs:tt $alias:ident $machine:ident [$gensym:ident $(, $gensyms:ident)*] [$kind:tt] [$($accum:tt)*] $out:tt) => {
_tlsm_machine!(@cont $docs $attrs $alias $machine [$($gensyms),*] [] [$($accum)* ($gensym: $kind)] $out);
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] _) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] _) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] ($parameterized:ident $($param:tt)*)) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output: $parameterized<$(_tlsm_parse_type!($param)),*>;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] ($parameterized:ident $($param:tt)*)) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output: $parameterized<$(_tlsm_parse_type!($param)),*>;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*) $(($sym:ident $($bound:tt)*))+] $out:ident) => {
$(#$docs)*
$(#$attr)*
pub trait $machine < $($sym $($bound)*),+ > $($fbound)* {
type Output: $out;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* $(, $sym $($bound)*)+ > = <$fsym as $machine< $($sym),+ >>::Output;
};
(@cont [$($docs:tt)*] [$($attr:tt)*] $alias:ident $machine:ident $gensym:tt [] [($fsym:ident $($fbound:tt)*)] $out:ident) => {
$(#$docs)*
$(#$attr)*
pub trait $machine $($fbound)* {
type Output: $out;
}
$(#$attr)*
pub type $alias < $fsym $($fbound)* > = <$fsym as $machine>::Output;
};
}
#[macro_export]
macro_rules! _tlsm_meta_filter_struct {
([$($preceding:tt)*] #[struct: $attr:meta] $($more:tt)*) => (_tlsm_meta_filter_struct!([$($preceding)* #[$attr]] $($more)*););
([$($preceding:tt)*] #$attr:tt $($more:tt)*) => (_tlsm_meta_filter_struct!([$($preceding)* #$attr] $($more)*););
([$($preceding:tt)*] $($decl:tt)*) => ($($preceding)* $($decl)*);
}
#[macro_export]
macro_rules! _tlsm_meta_filter_impl {
([$($preceding:tt)*] #[impl: $attr:meta] $($more:tt)*) => (_tlsm_meta_filter_impl!([$($preceding)* #[$attr]] $($more)*););
($preceding:tt #[derive $traits:tt] $($more:tt)*) => (_tlsm_meta_filter_impl!($preceding $($more)*);); // Friends don't let friends derive drunk!
([$($preceding:tt)*] #$attr:tt $($more:tt)*) => (_tlsm_meta_filter_impl!([$($preceding)* #$attr] $($more)*););
([$($preceding:tt)*] $($decl:tt)*) => ($($preceding)* $($decl)*);
}
#[macro_export]
macro_rules! _tlsm_data {
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] _ $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym)] [$($bounds)* ($gensym)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym: $kind = $default)] [$($bounds)* ($gensym: $kind)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
($attrs:tt @parameterized $name:ident [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] [$($phantom:tt)*] $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_data!($attrs @parameterized $name [$($next),*] [$($args)* ($gensym: $kind)] [$($bounds)* ($gensym: $kind)] [$($phantom)* ($gensym)] $($($rest)*),*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] @parameterized $name:ident $gensyms:tt [$(($asym:ident $($args:tt)*))*] [$(($bsym:ident $($bounds:tt)*))*] [$(($($phantom:tt)*))*]) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name < $($asym $($args)*),* >($(::std::marker::PhantomData<$($phantom)*>),*);
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl< $($bsym $($bounds)*),* > $group for $name<$($($phantom)*),*> {}
}
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt # $nextspecific:tt $($rest:tt)*) => {
_tlsm_data!([$group $derives [$($specific)* $nextspecific] $($attr)*] $gensym $($rest)*);
};
([$group:ident () [$($specific:tt)*] $($attr:tt)*] $gensym:tt DEFAULT, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T {}
}
_tlsm_data!([$group () [] $($attr)*] $gensym $($rest)*);
};
([$group:ident ($fbound:ident $(+ $bound:ident)*) [$($specific:tt)*] $($attr:tt)*] $gensym:tt DEFAULT, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T where T: $fbound $(+ $bound)* {}
}
_tlsm_data!([$group ($fbound $(+ $bound)*) [] $($attr)*] $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt $name:ident, $($rest:tt)*) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name;
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl $group for $name {}
}
_tlsm_data!([$group $derives [] $($attr)*] $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $gensym:tt $name:ident($($args:tt)*), $($rest:tt)*) => {
_tlsm_data!([$group $derives [$($specific)*] $($attr)*] @parameterized $name $gensym [] [] [] $($args)*);
_tlsm_data!([$group $derives [] $($attr)*] $gensym $($rest)*);
};
($attrs:tt $gensym:tt) => {};
}
#[macro_export]
macro_rules! _tlsm_concrete {
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; $gensym:tt [$($args:tt)*] [$($bounds:tt)*] [$($syms:ident)*] $sym:ident: $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; $gensym [$($args)* ($sym: $kind = $default)] [$($bounds)* ($sym: $kind)] [$($syms)* $sym] $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; $gensym:tt [$($args:tt)*] [$($bounds:tt)*] [$($syms:ident)*] $sym:ident: $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; $gensym [$($args)* ($sym: $kind)] [$($bounds)* ($sym: $kind)] [$($syms)* $sym] $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] $syms:tt $kind:ident = $default:ty $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; [$($next),*] [$($args)* ($gensym: $kind = $default)] [$($bounds)* ($gensym: $kind)] $syms $($($rest)*),*);
};
($attrs:tt $output:ty; @parameterized $name:ident => $value:expr; [$gensym:ident $(, $next:ident)*] [$($args:tt)*] [$($bounds:tt)*] $syms:tt $kind:ident $(, $($rest:tt)*)*) => {
_tlsm_concrete!($attrs $output; @parameterized $name => $value; [$($next),*] [$($args)* ($gensym: $kind)] [$($bounds)* ($gensym: $kind)] $syms $($($rest)*),*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt # $nextspecific:tt $($rest:tt)*) => {
_tlsm_concrete!([$group $derives [$($specific)* $nextspecific] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; @parameterized $name:ident => $value:expr; $gensyms:tt [$(($tysym:ident: $($args:tt)*))*] [$(($bsym:ident: $bound:ident))*] [$($sym:ident)*]) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name < $($tysym: $($args)*),* >($(::std::marker::PhantomData<$tysym>),*);
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl< $($bsym: $bound),* > $group for $name<$($bsym),*> {
#[allow(non_snake_case)]
fn reify() -> $output { $(let $sym = <$sym>::reify();)* $value }
}
}
};
([$group:ident () [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt DEFAULT => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T {
default fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group () [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident ($fbound:ident $(+ $bound:ident)*) [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt DEFAULT => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl<T> $group for T where T: $fbound $(+ $bound)* {
default fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group ($fbound $(+ $bound)*) [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt $name:ident => $value:expr, $($rest:tt)*) => {
_tlsm_meta_filter_struct! { []
$(#$attr)*
$(#$specific)*
pub struct $name;
}
_tlsm_meta_filter_impl! { []
$(#$attr)*
$(#$specific)*
impl $group for $name {
fn reify() -> $output { $value }
}
}
_tlsm_concrete!([$group $derives [] $($attr)*] $output; $gensym $($rest)*);
};
([$group:ident $derives:tt [$($specific:tt)*] $($attr:tt)*] $output:ty; $gensym:tt $name:ident($($args:tt)*) => $value:expr, $($rest:tt)*) => {
_tlsm_concrete!([$group $derives [$($specific)*] $($attr)*] $output; @parameterized $name => $value; $gensym [] [] [] $($args)*);
_tlsm_concrete!([$group $derives [] $($attr)*] $output; $gensym $($rest)*);
};
($attrs:tt $output:ty; $gensym:tt) => {};
}
#[cfg(test)]
mod tests_1 {
use super::*;
type_operators! {
[A, B, C, D, E]
concrete Nat => usize {
P => 0,
I(N: Nat = P) => 1 + 2 * N,
O(N: Nat = P) => 2 * N,
Undefined => panic!("Undefined type-level arithmetic result!"),
}
// It's not just for natural numbers! Yes, we can do all sorts of logic here. However, in
// this example, `Bool` is used later on in implementations that are hidden from you due
// to their complexity.
concrete Bool => bool {
False => false,
True => true,
}
(Pred) Predecessor(Nat): Nat {
[Undefined] => Undefined
[P] => Undefined
forall (N: Nat) {
[(O N)] => (I (# N))
[(I N)] => (O N)
}
}
(Succ) Successor(Nat): Nat {
[Undefined] => Undefined
[P] => I
forall (N: Nat) {
[(O N)] => (I N)
[(I N)] => (O (# N))
}
}
(Sum) Adding(Nat, Nat): Nat {
[P, P] => P
forall (N: Nat) {
[(O N), P] => (O N)
[(I N), P] => (I N)
[P, (O N)] => (O N)
[P, (I N)] => (I N)
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (O (# M N))
[(I M), (O N)] => (I (# M N))
[(O M), (I N)] => (I (# M N))
[(I M), (I N)] => (O (# (# M N) I))
}
}
(Difference) Subtracting(Nat, Nat): Nat {
forall (N: Nat) {
[N, P] => N
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (O (# M N))
[(I M), (O N)] => (I (# M N))
[(O M), (I N)] => (I (# (# M N) I))
[(I M), (I N)] => (O (# M N))
}
}
(Product) Multiplying(Nat, Nat): Nat {
forall (N: Nat) {
[P, N] => P
}
forall (N: Nat, M: Nat) {
[(O M), N] => (# M (O N))
[(I M), N] => (@Adding N (# M (O N)))
}
}
(If) NatIf(Bool, Nat, Nat): Nat {
forall (T: Nat, U: Nat) {
[True, T, U] => T
[False, T, U] => U
}
}
(NatIsUndef) NatIsUndefined(Nat): Bool {
[Undefined] => True
[P] => False
forall (M: Nat) {
[(O M)] => False
[(I M)] => False
}
}
(NatUndef) NatUndefined(Nat, Nat): Nat {
forall (M: Nat) {
[Undefined, M] => Undefined
[P, M] => M
}
forall (M: Nat, N: Nat) {
[(O N), M] => M
[(I N), M] => M
}
}
(TotalDifference) TotalSubtracting(Nat, Nat): Nat {
[P, P] => P
[Undefined, P] => Undefined
forall (N: Nat) {
[N, Undefined] => Undefined
[P, (O N)] => (# P N)
[P, (I N)] => Undefined
[(O N), P] => (O N)
[(I N), P] => (I N)
[Undefined, (O N)] => Undefined
[Undefined, (I N)] => Undefined
}
forall (N: Nat, M: Nat) {
[(O M), (O N)] => (@NatUndefined (# M N) (O (# M N)))
[(I M), (O N)] => (@NatUndefined (# M N) (I (# M N)))
[(O M), (I N)] => (@NatUndefined (# (# M N) I) (I (# (# M N) I)))
[(I M), (I N)] => (@NatUndefined (# M N) (O (# M N)))
}
}
(Quotient) Quotienting(Nat, Nat): Nat {
forall (D: Nat) {
[Undefined, D] => Undefined
[P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) O (@Successor (# (@TotalSubtracting P D) D)))
}
forall (N: Nat, D: Nat) {
[(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) O (@Successor (# (@TotalSubtracting (O N) D) D)))
[(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) O (@Successor (# (@TotalSubtracting (I N) D) D)))
}
}
(Remainder) Remaindering(Nat, Nat): Nat {
forall (D: Nat) {
[Undefined, D] => Undefined
[P, D] => (@NatIf (@NatIsUndefined (@TotalSubtracting P D)) P (# (@TotalSubtracting P D) D))
}
forall (N: Nat, D: Nat) {
[(O N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (O N) D)) (O N) (# (@TotalSubtracting (O N) D) D))
[(I N), D] => (@NatIf (@NatIsUndefined (@TotalSubtracting (I N) D)) (I O) (# (@TotalSubtracting (I N) D) D))
}
}
}
fn invariants() {
assert_eq!(<I<I> as Nat>::reify(), 3);
assert_eq!(<I<O<I>> as Nat>::reify(), 5);
assert_eq!(<Sum<I<O<I>>, I<I>> as Nat>::reify(), 8);
assert_eq!(<Difference<I<I>, O<I>> as Nat>::reify(), 1);
assert_eq!(<Difference<O<O<O<I>>>, I<I>> as Nat>::reify(), 5);
assert_eq!(<Product<I<I>, I<O<I>>> as Nat>::reify(), 15);
assert_eq!(<Quotient<I<I>, O<I>> as Nat>::reify(), 1);
assert_eq!(<Remainder<I<O<O<I>>>, O<O<I>>> as Nat>::reify(), 1);
}
}
#[cfg(test)]
mod tests_2 {
use super::*;
type_operators! {
[A, B, C, D, E]
data Nat {
P,
I(Nat = P),
O(Nat = P),
}
}
}
|
pub mod graph {
use std::collections::HashMap;
struct Graph {
elements: i64,
vertices: HashMap<i64, Box<Vertex>>,
}
impl Graph {
fn new() -> Box<Graph> {
let vertices: HashMap<i64, Box<Vertex>> = HashMap::new();
Box::new(Graph{elements:0, vertices:vertices})
}
fn add_vertex(&mut self) -> VertexProxy {
let new_id = self.elements + 1;
self.elements += 1;
let v = Vertex::new(new_id);
let ptr: *const Box<Vertex> = &v as *const Box<Vertex>;
self .vertices.insert(new_id, v);
// return the proxy which knows it's own id
VertexProxy{id:new_id, v: ptr}
}
}
struct Vertex {
id: i64,
edges: *mut Vec<Edge>,
}
impl Vertex {
fn new(id: i64) -> Box<Vertex> {
let mut edges : Vec<Edge> = Vec::new();
let edges_ptr : *mut Vec<Edge> = &mut edges;
let vertex = Vertex{id:id, edges:edges_ptr};
let mut v = Box::new(vertex);
return v;
}
fn query(self) {
}
}
#[derive(Debug)]
struct VertexProxy {
id: i64,
v: *const Box<Vertex>,
}
//let i: u32 = 1;
//// explicit cast
//let p_imm: *const u32 = &i as *const u32;
//let mut m: u32 = 2;
//// implicit coercion
//let p_mut: *mut u32 = &mut m;
//
//unsafe {
//let ref_imm: &u32 = &*p_imm;
//let ref_mut: &mut u32 = &mut *p_mut;
//}
impl VertexProxy {
fn add_edge(& self, to_vertex: &VertexProxy) {
unsafe {
let in_vertex = &* self .v;
let out_vertex = &*to_vertex.v;
}
// create the edge
let e = Edge{from_vertex: self.v,
to_vertex: to_vertex.v};
}
}
struct Edge {
from_vertex: *const Box<Vertex>,
to_vertex: *const Box<Vertex>
}
#[test]
fn test_unsafe_vertex() {
let mut g = Graph::new();
let mut v1 = g.add_vertex();
assert!(v1.id == 1);
let mut v2 = g.add_vertex();
assert!(v2.id == 2);
}
#[test]
fn test_add_edge() {
let mut g = Graph::new();
let mut v1 = g.add_vertex();
let mut v2 = g.add_vertex();
v2.add_edge(&v2);
}
}
clearing warnings
pub mod graph {
use std::collections::HashMap;
pub struct Graph {
elements: i64,
vertices: HashMap<i64, Box<Vertex>>,
}
impl Graph {
pub fn new() -> Box<Graph> {
let vertices: HashMap<i64, Box<Vertex>> = HashMap::new();
Box::new(Graph{elements:0, vertices:vertices})
}
pub fn add_vertex(&mut self) -> VertexProxy {
let new_id = self.elements + 1;
self.elements += 1;
let v = Vertex::new(new_id);
let ptr: *const Box<Vertex> = &v as *const Box<Vertex>;
self .vertices.insert(new_id, v);
// return the proxy which knows it's own id
VertexProxy{id:new_id, v: ptr}
}
}
struct Vertex {
id: i64,
edges: *mut Vec<Edge>,
}
impl Vertex {
pub fn new(id: i64) -> Box<Vertex> {
let mut edges : Vec<Edge> = Vec::new();
let edges_ptr : *mut Vec<Edge> = &mut edges;
let vertex = Vertex{id:id, edges:edges_ptr};
let mut v = Box::new(vertex);
return v;
}
}
#[derive(Debug)]
pub struct VertexProxy {
id: i64,
v: *const Box<Vertex>,
}
//let i: u32 = 1;
//// explicit cast
//let p_imm: *const u32 = &i as *const u32;
//let mut m: u32 = 2;
//// implicit coercion
//let p_mut: *mut u32 = &mut m;
//
//unsafe {
//let ref_imm: &u32 = &*p_imm;
//let ref_mut: &mut u32 = &mut *p_mut;
//}
impl VertexProxy {
pub fn add_edge(& self, to_vertex: &VertexProxy) {
unsafe {
let in_vertex = &* self .v;
let out_vertex = &*to_vertex.v;
}
// create the edge
let e = Edge{from_vertex: self.v,
to_vertex: to_vertex.v};
}
pub fn query(self) {
}
}
struct Edge {
from_vertex: *const Box<Vertex>,
to_vertex: *const Box<Vertex>
}
#[test]
fn test_unsafe_vertex() {
let mut g = Graph::new();
let v1 = g.add_vertex();
assert!(v1.id == 1);
let v2 = g.add_vertex();
assert!(v2.id == 2);
}
#[test]
fn test_add_edge() {
let mut g = Graph::new();
let v1 = g.add_vertex();
let v2 = g.add_vertex();
v2.add_edge(&v2);
}
}
|
// I have no idea what I'm doing with these attributes. Are we using
// semantic versioning? Some packages include their full github URL.
// Documentation for this stuff is extremely scarce.
#[crate_id = "quickcheck#0.1.0"];
#[crate_type = "lib"];
#[license = "UNLICENSE"];
#[doc(html_root_url = "http://burntsushi.net/rustdoc/quickcheck")];
//! This crate is a port of
//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).
extern crate collections;
pub use arbitrary::{Arbitrary, Gen, StdGen, arbitrary, default_gen, gen};
pub use shrink::{ObjIter, Shrink};
pub use tester::{Testable, TestResult, Status};
mod arbitrary;
mod shrink;
mod tester {
use std::fmt::Show;
use super::{Arbitrary, Gen};
fn arby<A: Arbitrary, G: Gen>(g: &mut G) -> A { Arbitrary::arbitrary(g) }
#[deriving(Clone, Show)]
pub struct TestResult {
priv status: Status,
priv arguments: ~[~str],
}
#[deriving(Clone, Show)]
pub enum Status { Pass, Fail, Discard }
impl TestResult {
pub fn passed() -> ~TestResult { TestResult::from_bool(true) }
pub fn failed() -> ~TestResult { TestResult::from_bool(false) }
pub fn discard() -> ~TestResult {
~TestResult { status: Discard, arguments: ~[] }
}
pub fn from_bool(b: bool) -> ~TestResult {
~TestResult { status: if b { Pass } else { Fail }, arguments: ~[] }
}
}
pub trait Testable {
fn result<G: Gen>(&self, &mut G) -> ~TestResult;
}
impl Testable for bool {
fn result<G: Gen>(&self, _: &mut G) -> ~TestResult {
TestResult::from_bool(*self)
}
}
impl Testable for ~TestResult {
fn result<G: Gen>(&self, _: &mut G) -> ~TestResult { self.clone() }
}
// I should really figure out how to use macros. This is painful.
// N.B. This isn't needed in Haskell because it's currying by default!
// Perhaps there is a way to circumvent this in Rust too (without macros),
// but I'm not sure.
impl<A: Testable> Testable for 'static || -> A {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
(*self)().result(g)
}
}
impl<A: Arbitrary + Show, B: Testable> Testable for 'static |A| -> B {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let a: A = Arbitrary::arbitrary(g);
let arg: ~str = a.to_str();
let mut r: ~TestResult = (*self)(a).result(g);
r.arguments.unshift(arg);
r
}
}
impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
Testable for 'static |A, B| -> C {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b): (A, B) = (arby(g), arby(g));
let (a_arg, b_arg) = (a.to_str(), b.to_str());
let mut r: ~TestResult = (*self)(a, b).result(g);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Arbitrary + Show,
B: Arbitrary + Show,
C: Arbitrary + Show,
D: Testable>
Testable for 'static |A, B, C| -> D {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
let mut r: ~TestResult = (*self)(a, b, c).result(g);
r.arguments.unshift(c_arg);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Testable> Testable for fn() -> A {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
(*self)().result(g)
}
}
impl<A: Arbitrary + Show, B: Testable> Testable for fn(A) -> B {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let a: A = Arbitrary::arbitrary(g);
let arg: ~str = a.to_str();
let mut r: ~TestResult = (*self)(a).result(g);
r.arguments.unshift(arg);
r
}
}
impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
Testable for fn(A, B) -> C {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b): (A, B) = (arby(g), arby(g));
let (a_arg, b_arg) = (a.to_str(), b.to_str());
let mut r: ~TestResult = (*self)(a, b).result(g);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Arbitrary + Show,
B: Arbitrary + Show,
C: Arbitrary + Show,
D: Testable>
Testable for fn(A, B, C) -> D {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
let mut r: ~TestResult = (*self)(a, b, c).result(g);
r.arguments.unshift(c_arg);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
}
#[cfg(test)]
mod test {
use std::iter;
use super::{Testable, TestResult, default_gen};
#[test]
fn reverse_reverse() {
let g = &mut default_gen();
fn revrev(xs: ~[uint]) -> bool {
let rev = xs.clone().move_rev_iter().to_owned_vec()
.move_rev_iter().to_owned_vec();
xs == rev
}
for _ in iter::range(0, 10) {
debug!("{}", (revrev).result(g));
}
}
#[test]
fn reverse_single() {
let g = &mut default_gen();
fn rev_single(xs: ~[uint]) -> ~TestResult {
if xs.len() != 1 {
return TestResult::discard()
}
return TestResult::from_bool(
xs.clone().move_rev_iter().to_owned_vec()
==
xs.clone().move_rev_iter().to_owned_vec()
)
}
for _ in iter::range(0, 10) {
debug!("{}", (rev_single).result(g));
}
}
#[test]
fn reverse_app() {
let g = &mut default_gen();
fn revapp(xs: ~[uint], ys: ~[uint]) -> bool {
let app = ::std::vec::append(xs.clone(), ys);
let app_rev = app.move_rev_iter().to_owned_vec();
let rxs = xs.clone().move_rev_iter().to_owned_vec();
let rys = ys.clone().move_rev_iter().to_owned_vec();
let rev_app = ::std::vec::append(rys, rxs);
app_rev == rev_app
}
for _ in iter::range(0, 10) {
debug!("{}", (revapp).result(g));
}
}
}
Hide Status type.
// I have no idea what I'm doing with these attributes. Are we using
// semantic versioning? Some packages include their full github URL.
// Documentation for this stuff is extremely scarce.
#[crate_id = "quickcheck#0.1.0"];
#[crate_type = "lib"];
#[license = "UNLICENSE"];
#[doc(html_root_url = "http://burntsushi.net/rustdoc/quickcheck")];
//! This crate is a port of
//! [Haskell's QuickCheck](http://hackage.haskell.org/package/QuickCheck).
extern crate collections;
pub use arbitrary::{Arbitrary, Gen, StdGen, arbitrary, default_gen, gen};
pub use shrink::{ObjIter, Shrink};
pub use tester::{Testable, TestResult};
mod arbitrary;
mod shrink;
mod tester {
use std::fmt::Show;
use super::{Arbitrary, Gen};
fn arby<A: Arbitrary, G: Gen>(g: &mut G) -> A { Arbitrary::arbitrary(g) }
#[deriving(Clone, Show)]
pub struct TestResult {
priv status: Status,
priv arguments: ~[~str],
}
#[deriving(Clone, Show)]
priv enum Status { Pass, Fail, Discard }
impl TestResult {
pub fn passed() -> ~TestResult { TestResult::from_bool(true) }
pub fn failed() -> ~TestResult { TestResult::from_bool(false) }
pub fn discard() -> ~TestResult {
~TestResult { status: Discard, arguments: ~[] }
}
pub fn from_bool(b: bool) -> ~TestResult {
~TestResult { status: if b { Pass } else { Fail }, arguments: ~[] }
}
}
pub trait Testable {
fn result<G: Gen>(&self, &mut G) -> ~TestResult;
}
impl Testable for bool {
fn result<G: Gen>(&self, _: &mut G) -> ~TestResult {
TestResult::from_bool(*self)
}
}
impl Testable for ~TestResult {
fn result<G: Gen>(&self, _: &mut G) -> ~TestResult { self.clone() }
}
// I should really figure out how to use macros. This is painful.
// N.B. This isn't needed in Haskell because it's currying by default!
// Perhaps there is a way to circumvent this in Rust too (without macros),
// but I'm not sure.
impl<A: Testable> Testable for 'static || -> A {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
(*self)().result(g)
}
}
impl<A: Arbitrary + Show, B: Testable> Testable for 'static |A| -> B {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let a: A = Arbitrary::arbitrary(g);
let arg: ~str = a.to_str();
let mut r: ~TestResult = (*self)(a).result(g);
r.arguments.unshift(arg);
r
}
}
impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
Testable for 'static |A, B| -> C {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b): (A, B) = (arby(g), arby(g));
let (a_arg, b_arg) = (a.to_str(), b.to_str());
let mut r: ~TestResult = (*self)(a, b).result(g);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Arbitrary + Show,
B: Arbitrary + Show,
C: Arbitrary + Show,
D: Testable>
Testable for 'static |A, B, C| -> D {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
let mut r: ~TestResult = (*self)(a, b, c).result(g);
r.arguments.unshift(c_arg);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Testable> Testable for fn() -> A {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
(*self)().result(g)
}
}
impl<A: Arbitrary + Show, B: Testable> Testable for fn(A) -> B {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let a: A = Arbitrary::arbitrary(g);
let arg: ~str = a.to_str();
let mut r: ~TestResult = (*self)(a).result(g);
r.arguments.unshift(arg);
r
}
}
impl<A: Arbitrary + Show, B: Arbitrary + Show, C: Testable>
Testable for fn(A, B) -> C {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b): (A, B) = (arby(g), arby(g));
let (a_arg, b_arg) = (a.to_str(), b.to_str());
let mut r: ~TestResult = (*self)(a, b).result(g);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
impl<A: Arbitrary + Show,
B: Arbitrary + Show,
C: Arbitrary + Show,
D: Testable>
Testable for fn(A, B, C) -> D {
fn result<G: Gen>(&self, g: &mut G) -> ~TestResult {
let (a, b, c): (A, B, C) = (arby(g), arby(g), arby(g));
let (a_arg, b_arg, c_arg) = (a.to_str(), b.to_str(), c.to_str());
let mut r: ~TestResult = (*self)(a, b, c).result(g);
r.arguments.unshift(c_arg);
r.arguments.unshift(b_arg);
r.arguments.unshift(a_arg);
r
}
}
}
#[cfg(test)]
mod test {
use std::iter;
use super::{Testable, TestResult, default_gen};
#[test]
fn reverse_reverse() {
let g = &mut default_gen();
fn revrev(xs: ~[uint]) -> bool {
let rev = xs.clone().move_rev_iter().to_owned_vec()
.move_rev_iter().to_owned_vec();
xs == rev
}
for _ in iter::range(0, 10) {
debug!("{}", (revrev).result(g));
}
}
#[test]
fn reverse_single() {
let g = &mut default_gen();
fn rev_single(xs: ~[uint]) -> ~TestResult {
if xs.len() != 1 {
return TestResult::discard()
}
return TestResult::from_bool(
xs.clone().move_rev_iter().to_owned_vec()
==
xs.clone().move_rev_iter().to_owned_vec()
)
}
for _ in iter::range(0, 10) {
debug!("{}", (rev_single).result(g));
}
}
#[test]
fn reverse_app() {
let g = &mut default_gen();
fn revapp(xs: ~[uint], ys: ~[uint]) -> bool {
let app = ::std::vec::append(xs.clone(), ys);
let app_rev = app.move_rev_iter().to_owned_vec();
let rxs = xs.clone().move_rev_iter().to_owned_vec();
let rys = ys.clone().move_rev_iter().to_owned_vec();
let rev_app = ::std::vec::append(rys, rxs);
app_rev == rev_app
}
for _ in iter::range(0, 10) {
debug!("{}", (revapp).result(g));
}
}
}
|
//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
extern crate libc;
/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
get_num_cpus()
}
#[cfg(windows)]
fn get_num_cpus() -> usize {
unsafe {
let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
libc::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
}
}
#[cfg(
any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"
)
)]
fn get_num_cpus() -> usize {
use libc::{c_int, c_uint};
use libc::funcs::bsd44::sysctl;
//XXX: uplift to libc?
const CTL_HW: c_int = 6;
const HW_AVAILCPU: c_int = 25;
const HW_NCPU: c_int = 3;
let mut cpus: c_uint = 0;
let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];
unsafe {
sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
}
if cpus < 1 {
mib[1] = HW_NCPU;
unsafe {
sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
}
if cpus < 1 {
cpus = 1;
}
}
cpus as usize
}
#[cfg(target_os= "linux")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(84) as usize
}
}
#[cfg(target_os = "nacl")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(1) as usize
}
}
#[cfg(
any(
target_os = "macos",
target_os = "ios"
)
)]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(58) as usize
}
}
#[test]
fn lower_bound() {
assert!(get() > 0);
}
#[test]
fn upper_bound() {
assert!(get() < 236_451);
}
Add Android version of get_num_cpus
//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
extern crate libc;
/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
get_num_cpus()
}
#[cfg(windows)]
fn get_num_cpus() -> usize {
unsafe {
let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
libc::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
}
}
#[cfg(
any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"
)
)]
fn get_num_cpus() -> usize {
use libc::{c_int, c_uint};
use libc::funcs::bsd44::sysctl;
//XXX: uplift to libc?
const CTL_HW: c_int = 6;
const HW_AVAILCPU: c_int = 25;
const HW_NCPU: c_int = 3;
let mut cpus: c_uint = 0;
let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];
unsafe {
sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
}
if cpus < 1 {
mib[1] = HW_NCPU;
unsafe {
sysctl(mib.as_mut_ptr(), 2, &mut cpus, &mut CPUS_SIZE, &mut (), 0);
}
if cpus < 1 {
cpus = 1;
}
}
cpus as usize
}
#[cfg(target_os= "linux")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(84) as usize
}
}
#[cfg(target_os= "android")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(97) as usize
}
}
#[cfg(target_os = "nacl")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(1) as usize
}
}
#[cfg(
any(
target_os = "macos",
target_os = "ios"
)
)]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(58) as usize
}
}
#[test]
fn lower_bound() {
assert!(get() > 0);
}
#[test]
fn upper_bound() {
assert!(get() < 236_451);
}
|
// {{{ Crate docs
//! # Slog - Structured, extensible, composable logging for Rust
//!
//! `slog-rs` is an ecosystem of reusable components for structured, extensible,
//! composable logging for Rust.
//!
//! `slog` is `slog-rs`'s main crate providing core components shared between
//! all other parts of `slog-rs` ecosystem.
//!
//! This is auto-generated technical documentation of `slog`. For information
//! about project organization, development, help, etc. please see
//! [slog github page](https://github.com/slog-rs/slog)
//!
//! ## Core advantages over `log` crate
//!
//! * **extensible** - `slog` crate provides core functionality: very basic
//! and portable standard feature-set based on open `trait`s. This allows
//! implementing new features that can be independently published.
//! * **composable** - `trait`s that `slog` exposes to provide extensibility
//! are designed to be easy to efficiently reuse and combine. By combining
//! different functionalities every application can specify when, where and
//! how exactly process logging data from the application and it's
//! dependencies.
//! * **flexible** - `slog` does not constrain logging to just one globally
//! registered backend. Parts of your application can handle logging
//! in a customized way, or completely independently.
//! * **structured** and both **human and machine readable** - By keeping the
//! key-value data format and retaining its type information, meaning of logging
//! data is preserved. Data can be serialized to machine readable formats like
//! JSON and send it to data-mining system for further analysis etc. On the
//! other hand, when presenting on screen, logging information can be presented
//! in aesthetically pleasing and easy to understand way.
//! * **contextual** - `slog`'s `Logger` objects carry set of key-value data
//! pairs that contains the context of logging - information that otherwise
//! would have to be repeated in every logging statement.
//!
//! ## `slog` features
//!
//! * performance oriented; read [what makes slog
//! fast](https://github.com/slog-rs/slog/wiki/What-makes-slog-fast) and see:
//! [slog bench log](https://github.com/dpc/slog-rs/wiki/Bench-log)
//! * lazily evaluation through closure values
//! * async IO support included: see [`slog-async`
//! crate](https://docs.rs/slog-async)
//! * `#![no_std]` support (with opt-out `std` cargo feature flag)
//! * tree-structured loggers
//! * modular, lightweight and very extensible
//! * tiny core crate that does not pull any dependencies
//! * feature-crates for specific functionality
//! * using `slog` in library does not force users of the library to use slog
//! (but provides additional functionality); see [example how to use
//! `slog` in library](https://github.com/slog-rs/example-lib)
//! * backward and forward compatibility with `log` crate:
//! see [`slog-stdlog` crate](https://docs.rs/slog-stdlog)
//! * convenience crates:
//! * logging-scopes for implicit `Logger` passing: see
//! [slog-scope crate](https://docs.rs/slog-scope)
//! * many existing core&community provided features:
//! * multiple outputs
//! * filtering control
//! * compile-time log level filter using cargo features (same as in `log`
//! crate)
//! * by level, msg, and any other meta-data
//! * [`slog-envlogger`](https://github.com/slog-rs/envlogger) - port of
//! `env_logger`
//! * terminal output, with color support: see [`slog-term`
//! crate](docs.r/slog-term)
//! * [json](https://docs.rs/slog-json)
//! * [bunyan](https://docs.rs/slog-bunyan)
//! * [syslog](https://docs.rs/slog-syslog)
//! and [journald](https://docs.rs/slog-journald) support
//! * run-time configuration:
//! * run-time behavior change;
//! see [slog-atomic](https://docs.rs/slog-atomic)
//! * run-time configuration; see
//! [slog-config crate](https://docs.rs/slog-config)
//!
//!
//! [env_logger]: https://crates.io/crates/env_logger
//!
//! ## Notable details
//!
//! **Note:** At compile time `slog` by default removes trace and debug level
//! statements in release builds, and trace level records in debug builds. This
//! makes `trace` and `debug` level logging records practically free, which
//! should encourage using them freely. If you want to enable trace/debug
//! messages or raise the compile time logging level limit, use the following in
//! your `Cargo.toml`:
//!
//! ```norust
//! slog = { version = ... ,
//! features = ["max_level_trace", "release_max_level_warn"] }
//! ```
//!
//! Root drain (passed to `Logger::root`) must be one that does not ever return
//! errors. This forces user to pick error handing strategy.
//! `Drain::fuse()` or `Drain::ignore_res()`.
//!
//! [env_logger]: https://crates.io/crates/env_logger
//! [fn-overv]: https://github.com/dpc/slog-rs/wiki/Functional-overview
//! [atomic-switch]: https://docs.rs/slog-atomic/
//!
//! ## Where to start
//!
//! [`Drain`](trait.Drain.html), [`Logger`](struct.Logger.html) and
//! [`log` macro](macro.log.html) are the most important elements of
//! slog. Make sure to read their respective documentation
//!
//! Typically the biggest problem is creating a `Drain`
//!
//!
//! ### Logging to the terminal
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! ### Logging to a file
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use std::fs::OpenOptions;
//! use slog::Drain;
//!
//! fn main() {
//! let log_path = "target/your_log_file_path.log";
//! let file = OpenOptions::new()
//! .create(true)
//! .write(true)
//! .truncate(true)
//! .open(log_path)
//! .unwrap();
//!
//! let decorator = slog_term::PlainDecorator::new(file);
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! You can consider using `slog-json` instead of `slog-term`.
//! `slog-term` only coincidently fits the role of a file output format. A
//! proper `slog-file` crate with suitable format, log file rotation and other
//! file-logging related features would be awesome. Contributions are welcome!
//!
//! ### Change logging level at runtime
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! use std::sync::{Arc, atomic};
//! use std::sync::atomic::Ordering;
//! use std::result;
//!
//! /// Custom Drain logic
//! struct RuntimeLevelFilter<D>{
//! drain: D,
//! on: Arc<atomic::AtomicBool>,
//! }
//!
//! impl<D> Drain for RuntimeLevelFilter<D>
//! where D : Drain {
//! type Ok = Option<D::Ok>;
//! type Err = Option<D::Err>;
//!
//! fn log(&self,
//! record: &slog::Record,
//! values: &slog::OwnedKVList)
//! -> result::Result<Self::Ok, Self::Err> {
//! let current_level = if self.on.load(Ordering::Relaxed) {
//! slog::Level::Trace
//! } else {
//! slog::Level::Info
//! };
//!
//! if record.level().is_at_least(current_level) {
//! self.drain.log(
//! record,
//! values
//! )
//! .map(Some)
//! .map_err(Some)
//! } else {
//! Ok(None)
//! }
//! }
//! }
//!
//! fn main() {
//! // atomic variable controlling logging level
//! let on = Arc::new(atomic::AtomicBool::new(false));
//!
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build();
//! let drain = RuntimeLevelFilter {
//! drain: drain,
//! on: on.clone(),
//! }.fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//!
//! // switch level in your code
//! on.store(true, Ordering::Relaxed);
//! }
//! ```
//!
//! Why is this not an existing crate? Because there are multiple ways to
//! achieve the same result, and each application might come with it's own
//! variation. Supporting a more general solution is a maintenance effort.
//! There is also nothing stopping anyone from publishing their own crate
//! implementing it.
//!
//! Alternative to the above aproach is `slog-atomic` crate. It implements
//! swapping whole parts of `Drain` logging hierarchy.
//!
//! ## Examples & help
//!
//! Basic examples that are kept up-to-date are typically stored in
//! respective git repository, under `examples/` subdirectory. Eg.
//! [slog-term examples](https://github.com/slog-rs/term/tree/master/examples).
//!
//! [slog-rs wiki pages](https://github.com/slog-rs/slog/wiki) contain
//! some pages about `slog-rs` technical details.
//!
//! Source code of other [software using
//! slog-rs](https://crates.io/crates/slog/reverse_dependencies) can
//! be an useful reference.
//!
//! Visit [slog-rs gitter channel](https://gitter.im/slog-rs/slog) for immediate
//! help.
//!
//! ## Migrating from slog v1 to slog v2
//!
//! ### Key-value pairs come now after format string
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//!
//! fn main() {
//! let drain = slog::Discard;
//! let root = slog::Logger::root(drain, o!());
//! info!(root, "formatted: {}", 1; "log-key" => true);
//! }
//! ```
//!
//! See more information about format at [`log`](macro.log.html).
//!
//! ### `slog-streamer` is gone
//!
//! Create simple terminal logger like this:
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//!
//! ### Logging macros now takes ownership of values.
//!
//! Pass them by reference: `&x`.
//!
// }}}
// {{{ Imports & meta
#![cfg_attr(not(feature = "std"), feature(alloc))]
#![cfg_attr(not(feature = "std"), feature(collections))]
#![warn(missing_docs)]
#![no_std]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
extern crate collections;
#[macro_use]
#[cfg(feature = "std")]
extern crate std;
#[cfg(not(feature = "std"))]
use alloc::arc::Arc;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::rc::Rc;
#[cfg(not(feature = "std"))]
use collections::string::String;
#[cfg(feature = "serde")]
extern crate erased_serde;
use core::{convert, fmt, result};
use core::str::FromStr;
#[cfg(feature = "std")]
use std::boxed::Box;
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(feature = "std")]
use std::string::String;
#[cfg(feature = "std")]
use std::sync::Arc;
// }}}
// {{{ Macros
/// Macro for building group of key-value pairs:
/// [`OwnedKV`](struct.OwnedKV.html)
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let _root = slog::Logger::root(
/// drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// }
/// ```
#[macro_export]
macro_rules! o(
($($args:tt)*) => {
$crate::OwnedKV(kv!($($args)*))
};
);
/// Macro for building group of key-value pairs (alias)
///
/// Use in case of macro name collisions
#[macro_export]
macro_rules! slog_o(
($($args:tt)*) => {
$crate::OwnedKV(slog_kv!($($args)*))
};
);
/// Macro for building group of key-value pairs in
/// [`BorrowedKV`](struct.BorrowedKV.html)
///
/// In most circumstances using this macro directly is unnecessary and `info!`
/// and other wrappers over `log!` should be used instead.
#[macro_export]
macro_rules! b(
($($args:tt)*) => {
$crate::BorrowedKV(&kv!($($args)*))
};
);
/// Alias of `b`
#[macro_export]
macro_rules! slog_b(
($($args:tt)*) => {
$crate::BorrowedKV(&slog_kv!($($args)*))
};
);
/// Macro for build `KV` implementing type
///
/// You probably want to use `o!` or `b!` instead.
#[macro_export]
macro_rules! kv(
(@ $args_ready:expr; $k:expr => %$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => ?$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => $v:expr) => {
kv!(@ ($crate::SingleKV($k, $v), $args_ready); )
};
(@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, $v), $args_ready); $($args)* )
};
(@ $args_ready:expr; $kv:expr) => {
kv!(@ ($kv, $args_ready); )
};
(@ $args_ready:expr; $kv:expr, $($args:tt)* ) => {
kv!(@ ($kv, $args_ready); $($args)* )
};
(@ $args_ready:expr; ) => {
$args_ready
};
(@ $args_ready:expr;, ) => {
$args_ready
};
($($args:tt)*) => {
kv!(@ (); $($args)*)
};
);
/// Alias of `kv`
#[macro_export]
macro_rules! slog_kv(
(@ $args_ready:expr; $k:expr => %$v:expr) => {
slog_kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
slog_kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => ?$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => $v:expr) => {
slog_kv!(@ ($crate::SingleKV($k, $v), $args_ready); )
};
(@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
slog_kv!(@ ($crate::SingleKV($k, $v), $args_ready); $($args)* )
};
(@ $args_ready:expr; $slog_kv:expr) => {
slog_kv!(@ ($slog_kv, $args_ready); )
};
(@ $args_ready:expr; $slog_kv:expr, $($args:tt)* ) => {
slog_kv!(@ ($slog_kv, $args_ready); $($args)* )
};
(@ $args_ready:expr; ) => {
$args_ready
};
(@ $args_ready:expr;, ) => {
$args_ready
};
($($args:tt)*) => {
slog_kv!(@ (); $($args)*)
};
);
#[macro_export]
/// Create `RecordStatic` at the given code location
macro_rules! record_static(
($lvl:expr, $tag:expr,) => { record_static!($lvl, $tag) };
($lvl:expr, $tag:expr) => {{
static LOC : $crate::RecordLocation = $crate::RecordLocation {
file: file!(),
line: line!(),
column: column!(),
function: "",
module: module_path!(),
};
$crate::RecordStatic {
location : &LOC,
level: $lvl,
tag : $tag,
}
}};
);
#[macro_export]
/// Create `RecordStatic` at the given code location (alias)
macro_rules! slog_record_static(
($lvl:expr, $tag:expr,) => { slog_record_static!($lvl, $tag) };
($lvl:expr, $tag:expr) => {{
static LOC : $crate::RecordLocation = $crate::RecordLocation {
file: file!(),
line: line!(),
column: column!(),
function: "",
module: module_path!(),
};
$crate::RecordStatic {
location : &LOC,
level: $lvl,
tag: $tag,
}
}};
);
#[macro_export]
/// Create `Record` at the given code location
macro_rules! record(
($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
record!($lvl, $tag, $args, $b)
};
($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
#[allow(dead_code)]
static RS : $crate::RecordStatic<'static> = record_static!($lvl, $tag);
$crate::Record::new(&RS, $args, $b)
}};
);
#[macro_export]
/// Create `Record` at the given code location (alias)
macro_rules! slog_record(
($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
slog_record!($lvl, $tag, $args, $b)
};
($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
static RS : $crate::RecordStatic<'static> = slog_record_static!($lvl,
$tag);
$crate::Record::new(&RS, $args, $b)
}};
);
/// Log message a logging record
///
/// Use wrappers `error!`, `warn!` etc. instead
///
/// The `max_level_*` and `release_max_level*` cargo features can be used to
/// statically disable logging at various levels. See [slog notable
/// details](index.html#notable-details)
///
/// Use [version with longer name](macro.slog_log.html) if you want to prevent
/// clash with legacy `log` crate macro names.
///
/// ## Supported invocations
///
/// ### Simple
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "test info log"; "log-key" => true);
/// }
/// ```
///
/// Note that `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain, o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "test info log");
/// }
/// ```
///
/// ### `fmt::Arguments` support:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "formatted: {}", 1; "log-key" => true);
/// }
/// ```
///
/// Note that that `;` separates formatting string from key value pairs.
///
/// Again, `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain, o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "formatted: {}", 1);
/// }
/// ```
///
/// Note: use formatting support only when it really makes sense. Eg. logging
/// message like `"found {} keys"` is against structured logging. It should be
/// `"found keys", "count" => keys_num` instead, so that data is clearly named,
/// typed and separated from the message.
///
/// ### Tags
///
/// All above versions can be supplemented with a tag - string literal prefixed
/// with `#`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// let ops = 3;
/// info!(
/// root,
/// #"performance-metric", "thread speed"; "ops_per_sec" => ops
/// );
/// }
/// ```
///
/// See `Record::tag()` for more information about tags.
///
/// ### Own implementations of `KV` and `Value`
///
/// List of key value pairs is a comma separated list of key-values. Typically,
/// a designed syntax is used in form of `k => v` where `k` can be any type
/// that implements `Value` type.
///
/// It's possible to directly specify type that implements `KV` trait without
/// `=>` syntax.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// use slog::*;
///
/// fn main() {
/// struct MyKV;
/// struct MyV;
///
/// impl KV for MyKV {
/// fn serialize(&self,
/// _record: &Record,
/// serializer: &mut Serializer)
/// -> Result {
/// serializer.emit_u32("MyK", 16)
/// }
/// }
///
/// impl Value for MyV {
/// fn serialize(&self,
/// _record: &Record,
/// key : Key,
/// serializer: &mut Serializer)
/// -> Result {
/// serializer.emit_u32("MyKV", 16)
/// }
/// }
///
/// let drain = slog::Discard;
///
/// let root = slog::Logger::root(drain, o!(MyKV));
///
/// info!(
/// root,
/// "testing MyV"; "MyV" => MyV
/// );
/// }
/// ```
///
/// ### `fmt::Display` and `fmt::Debug` values
///
/// Value of any type that implements `std::fmt::Display` can be prefixed with
/// `%` in `k => v` expression to use it's text representation returned by
/// `format_args!("{}", v)`. This is especially useful for errors. Not that
/// this does not allocate any `String` since it operates on `fmt::Arguments`.
///
/// Similarly to use `std::fmt::Debug` value can be prefixed with `?`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use std::fmt::Write;
///
/// fn main() {
/// let drain = slog::Discard;
/// let log = slog::Logger::root(drain, o!());
///
/// let mut output = String::new();
///
/// if let Err(e) = write!(&mut output, "write to string") {
/// error!(log, "write failed"; "err" => %e);
/// }
/// }
/// ```
#[macro_export]
macro_rules! log(
(2 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
$l.log(&record!($lvl, $tag, &format_args!($msg_fmt, $($fmt)*), b!($($args)*)))
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
log!(1 @ { $($fmt)* $f }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
log!(1 @ { }, $l, $lvl, $tag, $($args)*)
}
};
);
/// Log message a logging record (alias)
///
/// Prefer [shorter version](macro.log.html), unless it clashes with
/// existing `log` crate macro.
///
/// See [`log`](macro.log.html) for documentation.
///
/// ```
/// #[macro_use(slog_o,slog_b,slog_record,slog_record_static,slog_log,slog_info,slog_kv)]
/// extern crate slog;
///
/// fn main() {
/// let log = slog::Logger::root(slog::Discard, slog_o!());
///
/// slog_info!(log, "some interesting info"; "where" => "right here");
/// }
/// ```
#[macro_export]
macro_rules! slog_log(
(2 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
$l.log(&slog_record!($lvl, $tag, &format_args!($msg_fmt, $($fmt)*), slog_b!($($args)*)))
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
slog_log!(1 @ { $($fmt)* $f }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
slog_log!(1 @ { }, $l, $lvl, $tag, $($args)*)
}
};
);
/// Log critical level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! crit(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Critical, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Critical, "", $($args)+)
};
);
/// Log critical level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_crit(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Critical, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Critical, "", $($args)+)
};
);
/// Log error level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! error(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Error, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Error, "", $($args)+)
};
);
/// Log error level record
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_error(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Error, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Error, "", $($args)+)
};
);
/// Log warning level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! warn(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Warning, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Warning, "", $($args)+)
};
);
/// Log warning level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_warn(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Warning, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Warning, "", $($args)+)
};
);
/// Log info level record
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! info(
($l:expr, #$tag:expr, $($args:tt)*) => {
log!($l, $crate::Level::Info, $tag, $($args)*)
};
($l:expr, $($args:tt)*) => {
log!($l, $crate::Level::Info, "", $($args)*)
};
);
/// Log info level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_info(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Info, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Info, "", $($args)+)
};
);
/// Log debug level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! debug(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Debug, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Debug, "", $($args)+)
};
);
/// Log debug level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_debug(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Debug, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Debug, "", $($args)+)
};
);
/// Log trace level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! trace(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Trace, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Trace, "", $($args)+)
};
);
/// Log trace level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_trace(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Trace, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Trace, "", $($args)+)
};
($($args:tt)+) => {
slog_log!($crate::Level::Trace, $($args)+)
};
);
// }}}
// {{{ Logger
/// Logging handle used to execute logging statements
///
/// In an essence `Logger` instance holds two pieces of information:
///
/// * drain - destination where to forward logging `Record`s for
/// processing.
/// * context - list of key-value pairs associated with it.
///
/// Root `Logger` is created with a `Drain` that will be cloned to every
/// member of it's hierarchy.
///
/// Child `Logger` are built from existing ones, and inherit their key-value
/// pairs, which can be supplemented with additional ones.
///
/// Cloning existing loggers and creating new ones is cheap. Loggers can be
/// freely passed around the code and between threads.
///
/// `Logger`s are `Sync+Send` - there's no need to synchronize accesses to them,
/// as they can accept logging records from multiple threads at once. They can
/// be sent to any thread. Because of that they require the `Drain` to be
/// `Sync+Sync` as well. Not all `Drain`s are `Sync` or `Send` but they can
/// often be made so by wrapping in a `Mutex` and/or `Arc`.
///
/// `Logger` implements `Drain` trait. Any logging `Record` delivered to
/// a `Logger` functioning as a `Drain`, will be delivered to it's `Drain`
/// with existing key-value pairs appended to the `Logger`s key-value pairs.
/// By itself it's effectively very similar to `Logger` being an ancestor
/// of `Logger` that originated the logging `Record`. Combined with other
/// `Drain`s, allows custom processing logic for a sub-tree of a whole logging
/// tree.
///
/// Logger is parametrized over type of a `Drain` associated with it (`D`). It
/// default to type-erased version so `Logger` without any type annotation
/// means `Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>`. See
/// `Logger::root_typed` and `Logger::to_erased` for more information.
#[derive(Clone)]
pub struct Logger<D = Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
drain: D,
list: OwnedKVList,
}
impl<D> Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
/// Build a root `Logger`
///
/// Root logger starts a new tree associated with a given `Drain`. Root
/// logger drain must return no errors. See `Drain::ignore_res()` and
/// `Drain::fuse()`.
///
/// All children and their children (and so on), form one logging tree
/// sharing a common drain. See `Logger::new`.
///
/// This version (as opposed to `Logger:root_typed`) will take `drain` and
/// made it into `Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>`.
/// This is typically the most convenient way to work with `Logger`s.
///
/// Use `o!` macro to build `OwnedKV` object.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let _root = slog::Logger::root(
/// slog::Discard,
/// o!("key1" => "value1", "key2" => "value2"),
/// );
/// }
/// ```
pub fn root<T>(drain: D, values: OwnedKV<T>) -> Logger
where
D: 'static + SendSyncRefUnwindSafeDrain<Err = Never, Ok = ()>,
T: SendSyncRefUnwindSafeKV + 'static,
{
Logger {
drain: Arc::new(drain) as
Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
list: OwnedKVList::root(values),
}
}
/// Build a root `Logger` that retains `drain` type
///
/// Unlike `Logger::root`, this constructor retains the type of a `drain`,
/// which allows highest performance possible by eliminating indirect call
/// on `Drain::log`, and allowing monomorphization of `Logger` and `Drain`
/// objects.
///
/// If you don't understand the implications, you should probably just
/// ignore it.
///
/// See `Logger:into_erased` and `Logger::to_erased` for conversion from
/// type returned by this function to version that would be returned by
/// `Logger::root`.
pub fn root_typed<T>(drain: D, values: OwnedKV<T>) -> Logger<D>
where
D: 'static + SendSyncUnwindSafeDrain<Err = Never, Ok = ()> + Sized,
T: SendSyncRefUnwindSafeKV + 'static,
{
Logger {
drain: drain,
list: OwnedKVList::root(values),
}
}
/// Build a child logger
///
/// Child logger inherits all existing key-value pairs from its parent and
/// supplements them with additional ones.
///
/// Use `o!` macro to build `OwnedKV` object.
///
/// ### Drain cloning (`D : Clone` requirement)
///
/// All children, their children and so on, form one tree sharing a
/// common drain. This drain, will be `Clone`d when this method is called.
/// That is why `Clone` must be implemented for `D` in `Logger<D>::new`.
///
/// For some `Drain` types `Clone` is cheap or even free (a no-op). This is
/// the case for any `Logger` returned by `Logger::root` and it's children.
///
/// When using `Logger::root_typed`, it's possible that cloning might be
/// expensive, or even impossible.
///
/// The reason why wrapping in an `Arc` is not done internally, and exposed
/// to the user is performance. Calling `Drain::log` through an `Arc` is
/// tiny bit slower than doing it directly.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let root = slog::Logger::root(slog::Discard,
/// o!("key1" => "value1", "key2" => "value2"));
/// let _log = root.new(o!("key" => "value"));
/// }
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub fn new<T>(&self, values: OwnedKV<T>) -> Logger<D>
where
T: SendSyncRefUnwindSafeKV + 'static,
D: Clone,
{
Logger {
drain: self.drain.clone(),
list: OwnedKVList::new(values, self.list.node.clone()),
}
}
/// Log one logging `Record`
///
/// Use specific logging functions instead. See `log!` macro
/// documentation.
#[inline]
pub fn log(&self, record: &Record) {
let _ = self.drain.log(record, &self.list);
}
/// Get list of key-value pairs assigned to this `Logger`
pub fn list(&self) -> &OwnedKVList {
&self.list
}
/// Convert to default, "erased" type:
/// `Logger<Arc<SendSyncUnwindSafeDrain>>`
///
/// Useful to adapt `Logger<D : Clone>` to an interface expecting
/// `Logger<Arc<...>>`.
///
/// Note that calling on a `Logger<Arc<...>>` will convert it to
/// `Logger<Arc<Arc<...>>>` which is not optimal. This might be fixed when
/// Rust gains trait implementation specialization.
pub fn into_erased(
self,
) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendRefUnwindSafeDrain + 'static,
{
Logger {
drain: Arc::new(self.drain) as
Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
list: self.list,
}
}
/// Create a copy with "erased" type
///
/// See `into_erased`
pub fn to_erased(
&self,
) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendRefUnwindSafeDrain + 'static + Clone,
{
self.clone().into_erased()
}
}
impl<D> fmt::Debug for Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "Logger{:?}", self.list));
Ok(())
}
}
impl<D> Drain for Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let chained = OwnedKVList {
node: Arc::new(MultiListNode {
next_node: values.node.clone(),
node: self.list.node.clone(),
}),
};
self.drain.log(record, &chained)
}
}
// }}}
// {{{ Drain
/// Logging drain
///
/// `Drain`s typically mean destination for logs, but `slog` generalizes the
/// term.
///
/// `Drain`s are responsible for handling logging statements (`Record`s) from
/// `Logger`s associated with them: filtering, modifying, formatting
/// and writing the log records into given destination(s).
///
/// It's a typical pattern to parametrize `Drain`s over `Drain` traits to allow
/// composing `Drain`s.
///
/// Implementing this trait allows writing custom `Drain`s. Slog users should
/// not be afraid of implementing their own `Drain`s. Any custom log handling
/// logic should be implemented as a `Drain`.
pub trait Drain {
/// Type returned by this drain
///
/// It can be useful in some circumstances, but rarely. It will probably
/// default to `()` once https://github.com/rust-lang/rust/issues/29661 is
/// stable.
type Ok;
/// Type of potential errors that can be returned by this `Drain`
type Err;
/// Handle one logging statement (`Record`)
///
/// Every logging `Record` built from a logging statement (eg.
/// `info!(...)`), and key-value lists of a `Logger` it was executed on
/// will be passed to the root drain registered during `Logger::root`.
///
/// Typically `Drain`s:
///
/// * pass this information (or not) to the sub-logger(s) (filters)
/// * format and write the information the a destination (writers)
/// * deal with the errors returned from the sub-logger(s)
fn log(
&self,
record: &Record,
values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err>;
/// Pass `Drain` through a closure, eg. to wrap
/// into another `Drain`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::*;
///
/// fn main() {
/// let _drain = Discard.map(Fuse);
/// }
/// ```
fn map<F, R>(self, f: F) -> R
where
Self: Sized,
F: FnOnce(Self) -> R,
{
f(self)
}
/// Filter logging records passed to `Drain`
///
/// Wrap `Self` in `Filter`
///
/// This will convert `self` to a `Drain that ignores `Record`s
/// for which `f` returns false.
fn filter<F>(self, f: F) -> Filter<Self, F>
where
Self: Sized,
F: FilterFn,
{
Filter::new(self, f)
}
/// Filter logging records passed to `Drain` (by level)
///
/// Wrap `Self` in `LevelFilter`
///
/// This will convert `self` to a `Drain that ignores `Record`s of
/// logging lever smaller than `level`.
fn filter_level(self, level: Level) -> LevelFilter<Self>
where
Self: Sized,
{
LevelFilter(self, level)
}
/// Map logging errors returned by this drain
///
/// `f` is a closure that takes `Drain::Err` returned by a given
/// drain, and returns new error of potentially different type
fn map_err<F, E>(self, f: F) -> MapError<Self, E>
where
Self: Sized,
F: MapErrFn<Self::Err, E>,
{
MapError::new(self, f)
}
/// Ignore results returned by this drain
///
/// Wrap `Self` in `IgnoreResult`
fn ignore_res(self) -> IgnoreResult<Self>
where
Self: Sized,
{
IgnoreResult::new(self)
}
/// Make `Self` panic when returning any errors
///
/// Wrap `Self` in `Map`
fn fuse(self) -> Fuse<Self>
where
Self::Err: fmt::Debug,
Self: Sized,
{
self.map(Fuse)
}
}
#[cfg(feature = "std")]
/// `Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafe: Send + Sync + UnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafe for T
where
T: Send + Sync + UnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync + UnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafeDrain for T
where
T: Drain + Send + Sync + UnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncRefUnwindSafeDrain for T
where
T: Drain + Send + Sync + RefUnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>
: 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(EI) -> EO {
}
#[cfg(feature = "std")]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
T: 'static + Sync + Send + ?Sized + UnwindSafe + RefUnwindSafe + Fn(EI) -> EO,
{
}
#[cfg(feature = "std")]
/// Function that can be used in `Filter` drain
pub trait FilterFn
: 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(&Record) -> bool {
}
#[cfg(feature = "std")]
impl<T> FilterFn for T
where
T: 'static
+ Sync
+ Send
+ ?Sized
+ UnwindSafe
+ RefUnwindSafe
+ Fn(&Record) -> bool,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncUnwindSafeDrain for T
where
T: Drain + Send + Sync + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncRefUnwindSafeDrain for T
where
T: Drain + Send + Sync + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendRefUnwindSafeDrain for T
where
T: Drain + Send + RefUnwindSafe + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send {}
#[cfg(not(feature = "std"))]
impl<T> SendRefUnwindSafeDrain for T
where
T: Drain + Send + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>: 'static + Sync + Send + Fn(EI) -> EO {}
#[cfg(not(feature = "std"))]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
T: 'static + Sync + Send + ?Sized + Fn(EI) -> EO,
{
}
#[cfg(not(feature = "std"))]
/// Function that can be used in `Filter` drain
pub trait FilterFn: 'static + Sync + Send + Fn(&Record) -> bool {}
#[cfg(not(feature = "std"))]
impl<T> FilterFn for T
where
T: 'static + Sync + Send + ?Sized + Fn(&Record) -> bool,
{
}
impl<D: Drain + ?Sized> Drain for Box<D> {
type Ok = D::Ok;
type Err = D::Err;
fn log(
&self,
record: &Record,
o: &OwnedKVList,
) -> result::Result<Self::Ok, D::Err> {
(**self).log(record, o)
}
}
impl<D: Drain + ?Sized> Drain for Arc<D> {
type Ok = D::Ok;
type Err = D::Err;
fn log(
&self,
record: &Record,
o: &OwnedKVList,
) -> result::Result<Self::Ok, D::Err> {
(**self).log(record, o)
}
}
/// `Drain` discarding everything
///
/// `/dev/null` of `Drain`s
#[derive(Debug, Copy, Clone)]
pub struct Discard;
impl Drain for Discard {
type Ok = ();
type Err = Never;
fn log(&self, _: &Record, _: &OwnedKVList) -> result::Result<(), Never> {
Ok(())
}
}
/// `Drain` filtering records
///
/// Wraps another `Drain` and passes `Record`s to it, only if they satisfy a
/// given condition.
#[derive(Debug, Clone)]
pub struct Filter<D: Drain, F>(pub D, pub F)
where
F: Fn(&Record) -> bool + 'static + Send + Sync;
impl<D: Drain, F> Filter<D, F>
where
F: FilterFn,
{
/// Create `Filter` wrapping given `drain`
pub fn new(drain: D, cond: F) -> Self {
Filter(drain, cond)
}
}
impl<D: Drain, F> Drain for Filter<D, F>
where
F: FilterFn,
{
type Ok = Option<D::Ok>;
type Err = D::Err;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
if (self.1)(record) {
Ok(Some(self.0.log(record, logger_values)?))
} else {
Ok(None)
}
}
}
/// `Drain` filtering records by `Record` logging level
///
/// Wraps a drain and passes records to it, only
/// if their level is at least given level.
///
/// TODO: Remove this type. This drain is a special case of `Filter`, but
/// because `Filter` can not use static dispatch ATM due to Rust limitations
/// that will be lifted in the future, it is a standalone type.
/// Reference: https://github.com/rust-lang/rust/issues/34511
#[derive(Debug, Clone)]
pub struct LevelFilter<D: Drain>(pub D, pub Level);
impl<D: Drain> LevelFilter<D> {
/// Create `LevelFilter`
pub fn new(drain: D, level: Level) -> Self {
LevelFilter(drain, level)
}
}
impl<D: Drain> Drain for LevelFilter<D> {
type Ok = Option<D::Ok>;
type Err = D::Err;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
if record.level().is_at_least(self.1) {
Ok(Some(self.0.log(record, logger_values)?))
} else {
Ok(None)
}
}
}
/// `Drain` mapping error returned by another `Drain`
///
/// See `Drain::map_err` for convenience function.
pub struct MapError<D: Drain, E> {
drain: D,
// eliminated dynamic dispatch, after rust learns `-> impl Trait`
map_fn: Box<MapErrFn<D::Err, E, Output = E>>,
}
impl<D: Drain, E> MapError<D, E> {
/// Create `Filter` wrapping given `drain`
pub fn new<F>(drain: D, map_fn: F) -> Self
where
F: MapErrFn<<D as Drain>::Err, E>,
{
MapError {
drain: drain,
map_fn: Box::new(map_fn),
}
}
}
impl<D: Drain, E> Drain for MapError<D, E> {
type Ok = D::Ok;
type Err = E;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
self.drain
.log(record, logger_values)
.map_err(|e| (self.map_fn)(e))
}
}
/// `Drain` duplicating records into two other `Drain`s
///
/// Can be nested for more than two outputs.
#[derive(Debug, Clone)]
pub struct Duplicate<D1: Drain, D2: Drain>(pub D1, pub D2);
impl<D1: Drain, D2: Drain> Duplicate<D1, D2> {
/// Create `Duplicate`
pub fn new(drain1: D1, drain2: D2) -> Self {
Duplicate(drain1, drain2)
}
}
impl<D1: Drain, D2: Drain> Drain for Duplicate<D1, D2> {
type Ok = (D1::Ok, D2::Ok);
type Err = (
result::Result<D1::Ok, D1::Err>,
result::Result<D2::Ok, D2::Err>,
);
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let res1 = self.0.log(record, logger_values);
let res2 = self.1.log(record, logger_values);
match (res1, res2) {
(Ok(o1), Ok(o2)) => Ok((o1, o2)),
(r1, r2) => Err((r1, r2)),
}
}
}
/// `Drain` panicking on error
///
/// `Logger` requires a root drain to handle all errors (`Drain::Error == ()`),
/// `Fuse` will wrap a `Drain` and panic if it returns any errors.
///
/// Note: `Drain::Err` must implement `Display` (for displaying on panick). It's
/// easy to create own `Fuse` drain if this requirement can't be fulfilled.
#[derive(Debug, Clone)]
pub struct Fuse<D: Drain>(pub D)
where
D::Err: fmt::Debug;
impl<D: Drain> Fuse<D>
where
D::Err: fmt::Debug,
{
/// Create `Fuse` wrapping given `drain`
pub fn new(drain: D) -> Self {
Fuse(drain)
}
}
impl<D: Drain> Drain for Fuse<D>
where
D::Err: fmt::Debug,
{
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Never> {
let _ = self.0
.log(record, logger_values)
.unwrap_or_else(|e| panic!("slog::Fuse Drain: {:?}", e));
Ok(())
}
}
/// `Drain` ignoring result
///
/// `Logger` requires a root drain to handle all errors (`Drain::Err=()`), and
/// returns nothing (`Drain::Ok=()`) `IgnoreResult` will ignore any result
/// returned by the `Drain` it wraps.
#[derive(Clone)]
pub struct IgnoreResult<D: Drain> {
drain: D,
}
impl<D: Drain> IgnoreResult<D> {
/// Create `IgnoreResult` wrapping `drain`
pub fn new(drain: D) -> Self {
IgnoreResult { drain: drain }
}
}
impl<D: Drain> Drain for IgnoreResult<D> {
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<(), Never> {
let _ = self.drain.log(record, logger_values);
Ok(())
}
}
/// Error returned by `Mutex<D : Drain>`
#[cfg(feature = "std")]
#[derive(Clone)]
pub enum MutexDrainError<D: Drain> {
/// Error acquiring mutex
Mutex,
/// Error returned by drain
Drain(D::Err),
}
#[cfg(feature = "std")]
impl<D> fmt::Debug for MutexDrainError<D>
where
D: Drain,
D::Err: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
match *self {
MutexDrainError::Mutex => write!(f, "MutexDrainError::Mutex"),
MutexDrainError::Drain(ref e) => e.fmt(f),
}
}
}
#[cfg(feature = "std")]
impl<D> std::error::Error for MutexDrainError<D>
where
D: Drain,
D::Err: fmt::Debug + fmt::Display + std::error::Error,
{
fn description(&self) -> &str {
match *self {
MutexDrainError::Mutex => "Mutex acquire failed",
MutexDrainError::Drain(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
MutexDrainError::Mutex => None,
MutexDrainError::Drain(ref e) => Some(e),
}
}
}
#[cfg(feature = "std")]
impl<'a, D: Drain> From<std::sync::PoisonError<std::sync::MutexGuard<'a, D>>>
for MutexDrainError<D> {
fn from(
_: std::sync::PoisonError<std::sync::MutexGuard<'a, D>>,
) -> MutexDrainError<D> {
MutexDrainError::Mutex
}
}
#[cfg(feature = "std")]
impl<D: Drain> fmt::Display for MutexDrainError<D>
where
D::Err: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
match *self {
MutexDrainError::Mutex => write!(f, "MutexError"),
MutexDrainError::Drain(ref e) => write!(f, "{}", e),
}
}
}
#[cfg(feature = "std")]
impl<D: Drain> Drain for std::sync::Mutex<D> {
type Ok = D::Ok;
type Err = MutexDrainError<D>;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let d = self.lock()?;
d.log(record, logger_values).map_err(MutexDrainError::Drain)
}
}
// }}}
// {{{ Level & FilterLevel
/// Official capitalized logging (and logging filtering) level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_NAMES: [&'static str; 7] =
["OFF", "CRITICAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
/// Official capitalized logging (and logging filtering) short level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_SHORT_NAMES: [&'static str; 7] =
["OFF", "CRIT", "ERRO", "WARN", "INFO", "DEBG", "TRCE"];
/// Logging level associated with a logging `Record`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Level {
/// Critical
Critical,
/// Error
Error,
/// Warning
Warning,
/// Info
Info,
/// Debug
Debug,
/// Trace
Trace,
}
/// Logging filtering level
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum FilterLevel {
/// Log nothing
Off,
/// Log critical level only
Critical,
/// Log only error level and above
Error,
/// Log only warning level and above
Warning,
/// Log only info level and above
Info,
/// Log only debug level and above
Debug,
/// Log everything
Trace,
}
impl Level {
/// Convert to `str` from `LOG_LEVEL_SHORT_NAMES`
pub fn as_short_str(&self) -> &'static str {
LOG_LEVEL_SHORT_NAMES[self.as_usize()]
}
/// Convert to `str` from `LOG_LEVEL_NAMES`
pub fn as_str(&self) -> &'static str {
LOG_LEVEL_NAMES[self.as_usize()]
}
/// Cast `Level` to ordering integer
///
/// `Critical` is the smallest and `Trace` the biggest value
#[inline]
pub fn as_usize(&self) -> usize {
match *self {
Level::Critical => 1,
Level::Error => 2,
Level::Warning => 3,
Level::Info => 4,
Level::Debug => 5,
Level::Trace => 6,
}
}
/// Get a `Level` from an `usize`
///
/// This complements `as_usize`
#[inline]
pub fn from_usize(u: usize) -> Option<Level> {
match u {
1 => Some(Level::Critical),
2 => Some(Level::Error),
3 => Some(Level::Warning),
4 => Some(Level::Info),
5 => Some(Level::Debug),
6 => Some(Level::Trace),
_ => None,
}
}
}
impl FilterLevel {
/// Convert to `usize` value
///
/// `Off` is 0, and `Trace` 6
#[inline]
pub fn as_usize(&self) -> usize {
match *self {
FilterLevel::Off => 0,
FilterLevel::Critical => 1,
FilterLevel::Error => 2,
FilterLevel::Warning => 3,
FilterLevel::Info => 4,
FilterLevel::Debug => 5,
FilterLevel::Trace => 6,
}
}
/// Get a `FilterLevel` from an `usize`
///
/// This complements `as_usize`
#[inline]
pub fn from_usize(u: usize) -> Option<FilterLevel> {
match u {
0 => Some(FilterLevel::Off),
1 => Some(FilterLevel::Critical),
2 => Some(FilterLevel::Error),
3 => Some(FilterLevel::Warning),
4 => Some(FilterLevel::Info),
5 => Some(FilterLevel::Debug),
6 => Some(FilterLevel::Trace),
_ => None,
}
}
/// Maximum logging level (log everything)
#[inline]
pub fn max() -> Self {
FilterLevel::Trace
}
/// Minimum logging level (log nothing)
#[inline]
pub fn min() -> Self {
FilterLevel::Off
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
static ASCII_LOWERCASE_MAP: [u8; 256] =
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, b' ', b'!', b'"', b'#',
b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';',
b'<', b'=', b'>', b'?', b'@', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's',
b't', b'u', b'v', b'w', b'x', b'y', b'z', b'[', b'\\', b']', b'^', b'_',
b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k',
b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb,
0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3,
0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb,
0xfc, 0xfd, 0xfe, 0xff];
impl FromStr for Level {
type Err = ();
fn from_str(level: &str) -> core::result::Result<Level, ()> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| {
name.as_bytes().iter().zip(level.as_bytes().iter()).all(
|(a, b)| {
ASCII_LOWERCASE_MAP[*a as usize] ==
ASCII_LOWERCASE_MAP[*b as usize]
},
)
})
.map(|p| Level::from_usize(p).unwrap())
.ok_or(())
}
}
impl FromStr for FilterLevel {
type Err = ();
fn from_str(level: &str) -> core::result::Result<FilterLevel, ()> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| {
name.as_bytes().iter().zip(level.as_bytes().iter()).all(
|(a, b)| {
ASCII_LOWERCASE_MAP[*a as usize] ==
ASCII_LOWERCASE_MAP[*b as usize]
},
)
})
.map(|p| FilterLevel::from_usize(p).unwrap())
.ok_or(())
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_short_str())
}
}
impl Level {
/// Returns true if `self` is at least `level` logging level
#[inline]
pub fn is_at_least(&self, level: Self) -> bool {
self.as_usize() <= level.as_usize()
}
}
#[test]
fn level_at_least() {
assert!(Level::Debug.is_at_least(Level::Debug));
assert!(Level::Debug.is_at_least(Level::Trace));
assert!(!Level::Debug.is_at_least(Level::Info));
}
#[test]
fn filterlevel_sanity() {
assert!(Level::Critical.as_usize() > FilterLevel::Off.as_usize());
assert!(Level::Critical.as_usize() == FilterLevel::Critical.as_usize());
assert!(Level::Trace.as_usize() == FilterLevel::Trace.as_usize());
}
#[test]
fn level_from_str() {
assert_eq!("info".parse::<FilterLevel>().unwrap(), FilterLevel::Info);
}
// }}}
// {{{ Record
#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct RecordLocation {
/// File
pub file: &'static str,
/// Line
pub line: u32,
/// Column (currently not implemented)
pub column: u32,
/// Function (currently not implemented)
pub function: &'static str,
/// Module
pub module: &'static str,
}
#[doc(hidden)]
/// Information that can be static in the given record thus allowing to optimize
/// record creation to be done mostly at compile-time.
///
/// This is not cosidered a part of stable API, and macros should be used
/// instead.
pub struct RecordStatic<'a> {
/// Code location
pub location: &'a RecordLocation,
/// Tag
pub tag: &'a str,
/// Logging level
pub level: Level,
}
/// One logging record
///
/// Corresponds to one logging statement like `info!(...)` and carries all it's
/// data: eg. message, immediate key-value pairs and key-value pairs of `Logger`
/// used to execute it.
///
/// Record is passed to a `Logger`, which delivers it to it's own `Drain`,
/// where actual logging processing is implemented.
pub struct Record<'a> {
rstatic: &'a RecordStatic<'a>,
msg: &'a fmt::Arguments<'a>,
kv: BorrowedKV<'a>,
}
impl<'a> Record<'a> {
/// Create a new `Record`
///
/// This function is not considered a part of stable API
#[inline]
#[doc(hidden)]
pub fn new(
s: &'a RecordStatic<'a>,
msg: &'a fmt::Arguments<'a>,
kv: BorrowedKV<'a>,
) -> Self {
Record {
rstatic: s,
msg: msg,
kv: kv,
}
}
/// Get a log record message
pub fn msg(&self) -> &fmt::Arguments {
self.msg
}
/// Get record logging level
pub fn level(&self) -> Level {
self.rstatic.level
}
/// Get line number
pub fn line(&self) -> u32 {
self.rstatic.location.line
}
/// Get line number
pub fn location(&self) -> &RecordLocation {
self.rstatic.location
}
/// Get error column
pub fn column(&self) -> u32 {
self.rstatic.location.column
}
/// Get file path
pub fn file(&self) -> &'static str {
self.rstatic.location.file
}
/// Get tag
///
/// Tag is information that can be attached to `Record` that is not meant
/// to be part of the norma key-value pairs, but only as an ad-hoc control
/// flag for quick lookup in the `Drain`s. As such should be used carefully
/// and mostly in application code (as opposed to libraries) - where tag
/// meaning across the system can be coordinated. When used in libraries,
/// make sure to prefix is with something reasonably distinct, like create
/// name.
pub fn tag(&self) -> &str {
self.rstatic.tag
}
/// Get module
pub fn module(&self) -> &'static str {
self.rstatic.location.module
}
/// Get function (placeholder)
///
/// There's currently no way to obtain that information
/// in Rust at compile time, so it is not implemented.
///
/// It will be implemented at first opportunity, and
/// it will not be considered a breaking change.
pub fn function(&self) -> &'static str {
self.rstatic.location.function
}
/// Get key-value pairs
pub fn kv(&self) -> BorrowedKV {
BorrowedKV(self.kv.0)
}
}
// }}}
// {{{ Serializer
macro_rules! impl_default_as_fmt{
($t:ty, $f:ident) => {
/// Emit $t
fn $f(&mut self, key : Key, val : $t)
-> Result {
self.emit_arguments(key, &format_args!("{}", val))
}
};
}
/// Serializer
///
/// Drains using `Format` will internally use
/// types implementing this trait.
pub trait Serializer {
/// Emit usize
impl_default_as_fmt!(usize, emit_usize);
/// Emit isize
impl_default_as_fmt!(isize, emit_isize);
/// Emit bool
impl_default_as_fmt!(bool, emit_bool);
/// Emit char
impl_default_as_fmt!(char, emit_char);
/// Emit u8
impl_default_as_fmt!(u8, emit_u8);
/// Emit i8
impl_default_as_fmt!(i8, emit_i8);
/// Emit u16
impl_default_as_fmt!(u16, emit_u16);
/// Emit i16
impl_default_as_fmt!(i16, emit_i16);
/// Emit u32
impl_default_as_fmt!(u32, emit_u32);
/// Emit i32
impl_default_as_fmt!(i32, emit_i32);
/// Emit f32
impl_default_as_fmt!(f32, emit_f32);
/// Emit u64
impl_default_as_fmt!(u64, emit_u64);
/// Emit i64
impl_default_as_fmt!(i64, emit_i64);
/// Emit f64
impl_default_as_fmt!(f64, emit_f64);
/// Emit str
impl_default_as_fmt!(&str, emit_str);
/// Emit `()`
fn emit_unit(&mut self, key: Key) -> Result {
self.emit_arguments(key, &format_args!("()"))
}
/// Emit `None`
fn emit_none(&mut self, key: Key) -> Result {
self.emit_arguments(key, &format_args!(""))
}
/// Emit `fmt::Arguments`
///
/// This is the only method that has to implemented, but for performance and
/// to retain type information most serious `Serializer`s will want to
/// implement all other methods as well.
fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result;
/// Emit a value implementing
/// [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html)
///
/// This is especially useful for composite values, eg. structs as Json values, or sequences.
///
/// To prevent pulling-in `serde` dependency, this is an extension behind a
/// `serde` feature flag.
///
/// The value needs to implement `SerdeValue`.
#[cfg(feature = "serde")]
fn emit_serde(&mut self, key: Key, value: &SerdeValue) -> Result where Self:
Sized {
value.serialize_fallback(key, self)
}
}
/// Serializer to closure adapter.
///
/// Formats all arguments as `fmt::Arguments` and passes them to a given closure.
struct AsFmtSerializer<F>(pub F)
where
F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result;
impl<F> Serializer for AsFmtSerializer<F>
where
F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result,
{
fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result {
(self.0)(key, *val)
}
}
// }}}
// {{{ serde
/// A value that can be serialized via serde
///
/// This is useful for implementing nested values, like sequences or structures.
#[cfg(feature = "serde")]
pub trait SerdeValue : erased_serde::Serialize {
/// Serialize the value in a way that is compatible with `slog::Serializer`s
/// that do not support serde.
///
/// The implementation should *not* call `slog::Serialize::serialize`
/// on itself, as it will lead to infinite recursion.
///
/// Default implementation is provided, but it returns error, so use it
/// only for internal types in systems and libraries where `serde` is always
/// enabled.
fn serialize_fallback(&self, _key: Key, _serializer: &mut Serializer) -> Result<()> {
Err(Error::Other)
}
/// Convert to `erased_serialize::Serialize` of the underlying value,
/// so `slog::Serializer`s can use it to serialize via `serde`.
fn as_serde(&self) -> &erased_serde::Serialize;
/// Convert to a boxed value that can be sent across threads
///
/// This enables functionality like `slog-async` and similar.
fn to_sendable(&self) -> Box<SerdeValue + Send + 'static>;
}
/*
impl<T> SerdeValue for T where T: erased_serde::Serialize + Clone + Send {
fn serialize(&self, serializer: &erased_serde::Serializer) -> Result<()> {
match self.serialize(serializer) {
Err(_) => Err(Error::Other),
Ok(_) => Ok(()),
}
}
fn to_boxed(&self) -> Box<SerdeValue + Send + 'static> {
Box::new(self.clone())
}
}
*/
/*
#[cfg(feature = "serde")]
impl<T> SerdeValue for T where T: erased_serde::Serialize + Clone + Send {
fn serialize(&self, serializer: &erased_serde::Serializer) -> Result<()> {
match self.serialize(serializer) {
Err(_) => Err(Error::Other),
Ok(_) => Ok(()),
}
}
fn to_boxed(&self) -> Box<SerdeValue> {
Box::new(self.clone())
}
}
*/
// }}}
// {{{ Key
/// Key type (alias for &'static str)
pub type Key = &'static str;
// }}}
// {{{ Value
/// Value that can be serialized
pub trait Value {
/// Serialize self into `Serializer`
///
/// Structs implementing this trait should generally
/// only call respective methods of `serializer`.
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result;
}
impl<'a, V> Value for &'a V
where
V: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(*self).serialize(record, key, serializer)
}
}
macro_rules! impl_value_for{
($t:ty, $f:ident) => {
impl Value for $t {
fn serialize(&self,
_record : &Record,
key : Key,
serializer : &mut Serializer
) -> Result {
serializer.$f(key, *self)
}
}
};
}
impl_value_for!(usize, emit_usize);
impl_value_for!(isize, emit_isize);
impl_value_for!(bool, emit_bool);
impl_value_for!(char, emit_char);
impl_value_for!(u8, emit_u8);
impl_value_for!(i8, emit_i8);
impl_value_for!(u16, emit_u16);
impl_value_for!(i16, emit_i16);
impl_value_for!(u32, emit_u32);
impl_value_for!(i32, emit_i32);
impl_value_for!(f32, emit_f32);
impl_value_for!(u64, emit_u64);
impl_value_for!(i64, emit_i64);
impl_value_for!(f64, emit_f64);
impl Value for () {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_unit(key)
}
}
impl Value for str {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_str(key, self)
}
}
impl<'a> Value for fmt::Arguments<'a> {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_arguments(key, self)
}
}
impl Value for String {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_str(key, self.as_str())
}
}
impl<T: Value> Value for Option<T> {
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
match *self {
Some(ref s) => s.serialize(record, key, serializer),
None => serializer.emit_none(key),
}
}
}
impl<T> Value for Box<T>
where
T: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for Arc<T>
where
T: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for Rc<T>
where
T: Value,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for core::num::Wrapping<T>
where
T: Value,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, key, serializer)
}
}
impl<'a> Value for std::path::Display<'a>
{
fn serialize(&self,
_record: &Record,
key: Key,
serializer: &mut Serializer)
-> Result {
serializer.emit_arguments(key, &format_args!("{}", *self))
}
}
/// Explicit lazy-closure `Value`
pub struct FnValue<V: Value, F>(pub F)
where
F: for<'c, 'd> Fn(&'c Record<'d>) -> V;
impl<'a, V: 'a + Value, F> Value for FnValue<V, F>
where
F: 'a + for<'c, 'd> Fn(&'c Record<'d>) -> V,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(self.0)(record).serialize(record, key, serializer)
}
}
#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Old name of `PushFnValueSerializer`
pub type PushFnSerializer<'a> = PushFnValueSerializer<'a>;
/// Handle passed to `PushFnValue` closure
///
/// It makes sure only one value is serialized, and will automatically emit
/// `()` if nothing else was serialized.
pub struct PushFnValueSerializer<'a> {
record: &'a Record<'a>,
key: Key,
serializer: &'a mut Serializer,
done: bool,
}
impl<'a> PushFnValueSerializer<'a> {
#[deprecated(note = "Renamed to `emit`")]
/// Emit a value
pub fn serialize<'b, S: 'b + Value>(self, s: S) -> Result {
self.emit(s)
}
/// Emit a value
///
/// This consumes `self` to prevent serializing one value multiple times
pub fn emit<'b, S: 'b + Value>(mut self, s: S) -> Result {
self.done = true;
s.serialize(self.record, self.key, self.serializer)
}
}
impl<'a> Drop for PushFnValueSerializer<'a> {
fn drop(&mut self) {
if !self.done {
// unfortunately this gives no change to return serialization errors
let _ = self.serializer.emit_unit(self.key);
}
}
}
/// Lazy `Value` that writes to Serializer
///
/// It's more ergonomic for closures used as lazy values to return type
/// implementing `Serialize`, but sometimes that forces an allocation (eg.
/// `String`s)
///
/// In some cases it might make sense for another closure form to be used - one
/// taking a serializer as an argument, which avoids lifetimes / allocation
/// issues.
///
/// Generally this method should be used if it avoids a big allocation of
/// `Serialize`-implementing type in performance-critical logging statement.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::{PushFnValue, Logger, Discard};
///
/// fn main() {
/// // Create a logger with a key-value printing
/// // `file:line` string value for every logging statement.
/// // `Discard` `Drain` used for brevity.
/// let root = Logger::root(Discard, o!(
/// "source_location" => PushFnValue(|record , s| {
/// s.serialize(
/// format_args!(
/// "{}:{}",
/// record.file(),
/// record.line(),
/// )
/// )
/// })
/// ));
/// }
/// ```
pub struct PushFnValue<F>(pub F)
where
F: 'static + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result;
impl<F> Value for PushFnValue<F>
where
F: 'static + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
let ser = PushFnValueSerializer {
record: record,
key: key,
serializer: serializer,
done: false,
};
(self.0)(record, ser)
}
}
// }}}
// {{{ KV
/// Key-value pair(s)
///
/// Zero, one or more key value pairs chained together
///
/// Any logging data must implement this trait for
/// slog to be able to use it.
///
/// Types implementing this trait can emit multiple key-value pairs. The order
/// of emitting them should be consistent with the way key-value pair hierarchy
/// is traversed: from data most specific to the logging context to the most
/// general one. Or in other words: from newest to oldest.
pub trait KV {
/// Serialize self into `Serializer`
///
/// `KV` should call respective `Serializer` methods
/// for each key-value pair it contains.
fn serialize(&self, record: &Record, serializer: &mut Serializer)
-> Result;
}
impl<'a, T> KV for &'a T
where
T: KV,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
#[cfg(feature = "std")]
/// Thread-local safety bound for `KV`
///
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncRefUnwindSafeKV for T
where
T: KV + Send + Sync + RefUnwindSafe + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncRefUnwindSafeKV for T
where
T: KV + Send + Sync + ?Sized,
{
}
/// Single pair `Key` and `Value`
pub struct SingleKV<V>(pub Key, pub V)
where
V: Value;
impl<V> KV for SingleKV<V>
where
V: Value,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.1.serialize(record, self.0, serializer)
}
}
impl KV for () {
fn serialize(
&self,
_record: &Record,
_serializer: &mut Serializer,
) -> Result {
Ok(())
}
}
impl<T: KV, R: KV> KV for (T, R) {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.0.serialize(record, serializer));
self.1.serialize(record, serializer)
}
}
impl<T> KV for Box<T>
where
T: KV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
impl<T> KV for Arc<T>
where
T: KV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
impl<T> KV for OwnedKV<T>
where
T: SendSyncRefUnwindSafeKV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, serializer)
}
}
impl<'a> KV for BorrowedKV<'a> {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, serializer)
}
}
// }}}
// {{{ OwnedKV
/// Owned KV
///
/// "Owned" means that the contained data (key-value pairs) can belong
/// to a `Logger` and thus must be thread-safe (`'static`, `Send`, `Sync`)
///
/// Zero, one or more owned key-value pairs.
///
/// Can be constructed with [`o!` macro](macro.o.html).
pub struct OwnedKV<T>(
#[doc(hidden)]
/// The exact details of that it are not considered public
/// and stable API. `slog_o` or `o` macro should be used
/// instead to create `OwnedKV` instances.
pub T,
)
where
T: SendSyncRefUnwindSafeKV + ?Sized;
// }}}
// {{{ BorrowedKV
/// Borrowed `KV`
///
/// "Borrowed" means that the data is only a temporary
/// referenced (`&T`) and can't be stored directly.
///
/// Zero, one or more borrowed key-value pairs.
///
/// Can be constructed with [`b!` macro](macro.b.html).
pub struct BorrowedKV<'a>(
/// The exact details of it function are not
/// considered public and stable API. `log` and other
/// macros should be used instead to create
/// `BorrowedKV` instances.
#[doc(hidden)]
pub &'a KV,
);
// }}}
// {{{ OwnedKVList
struct OwnedKVListNode<T>
where
T: SendSyncRefUnwindSafeKV + 'static,
{
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
kv: T,
}
struct MultiListNode {
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}
/// Chain of `SyncMultiSerialize`-s of a `Logger` and its ancestors
#[derive(Clone)]
pub struct OwnedKVList {
node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}
impl<T> KV for OwnedKVListNode<T>
where
T: SendSyncRefUnwindSafeKV + 'static,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.kv.serialize(record, serializer));
try!(self.next_node.serialize(record, serializer));
Ok(())
}
}
impl KV for MultiListNode {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.next_node.serialize(record, serializer));
try!(self.node.serialize(record, serializer));
Ok(())
}
}
impl KV for OwnedKVList {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.node.serialize(record, serializer));
Ok(())
}
}
impl fmt::Debug for OwnedKVList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "("));
let mut i = 0;
{
let mut as_str_ser = AsFmtSerializer(|key, _val| {
if i != 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", key));
i += 1;
Ok(())
});
let record_static = record_static!(Level::Trace, "");
try!(
self.node
.serialize(
&Record::new(
&record_static,
&format_args!(""),
BorrowedKV(&STATIC_TERMINATOR_UNIT)
),
&mut as_str_ser
)
.map_err(|_| fmt::Error)
);
}
try!(write!(f, ")"));
Ok(())
}
}
impl OwnedKVList {
/// New `OwnedKVList` node without a parent (root)
fn root<T>(values: OwnedKV<T>) -> Self
where
T: SendSyncRefUnwindSafeKV + 'static,
{
OwnedKVList {
node: Arc::new(OwnedKVListNode {
next_node: Arc::new(()),
kv: values.0,
}),
}
}
/// New `OwnedKVList` node with an existing parent
fn new<T>(
values: OwnedKV<T>,
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
) -> Self
where
T: SendSyncRefUnwindSafeKV + 'static,
{
OwnedKVList {
node: Arc::new(OwnedKVListNode {
next_node: next_node,
kv: values.0,
}),
}
}
}
impl<T> convert::From<OwnedKV<T>> for OwnedKVList
where
T: SendSyncRefUnwindSafeKV + 'static,
{
fn from(from: OwnedKV<T>) -> Self {
OwnedKVList::root(from)
}
}
// }}}
// {{{ Error
#[derive(Debug)]
#[cfg(feature = "std")]
/// Serialization Error
pub enum Error {
/// `io::Error` (not available in ![no_std] mode)
Io(std::io::Error),
/// `fmt::Error`
Fmt(std::fmt::Error),
/// Other error
Other,
}
#[derive(Debug)]
#[cfg(not(feature = "std"))]
/// Serialization Error
pub enum Error {
/// `fmt::Error`
Fmt(core::fmt::Error),
/// Other error
Other,
}
/// Serialization `Result`
pub type Result<T = ()> = result::Result<T, Error>;
#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
Error::Io(err)
}
}
impl From<core::fmt::Error> for Error {
fn from(_: core::fmt::Error) -> Error {
Error::Other
}
}
#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
fn from(e: Error) -> std::io::Error {
match e {
Error::Io(e) => e,
Error::Fmt(_) => std::io::Error::new(
std::io::ErrorKind::Other,
"formatting error",
),
Error::Other => {
std::io::Error::new(std::io::ErrorKind::Other, "other error")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Io(ref e) => e.description(),
Error::Fmt(_) => "formatting error",
Error::Other => "serialization error",
}
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
Error::Io(ref e) => Some(e),
Error::Fmt(ref e) => Some(e),
Error::Other => None,
}
}
}
#[cfg(feature = "std")]
impl core::fmt::Display for Error {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> std::fmt::Result {
match *self {
Error::Io(ref e) => e.fmt(fmt),
Error::Fmt(ref e) => e.fmt(fmt),
Error::Other => fmt.write_str("Other serialization error"),
}
}
}
// }}}
// {{{ Misc
/// This type is here just to abstract away lack of `!` type support in stable
/// rust during time of the release. It will be switched to `!` at some point
/// and `Never` should not be considered "stable" API.
#[doc(hidden)]
pub type Never = private::NeverStruct;
mod private {
#[doc(hidden)]
#[derive(Debug)]
pub struct NeverStruct(());
}
/// This is not part of "stable" API
#[doc(hidden)]
pub static STATIC_TERMINATOR_UNIT: () = ();
#[allow(unknown_lints)]
#[allow(inline_always)]
#[inline(always)]
#[doc(hidden)]
/// Not an API
///
/// Generally it's a bad idea to depend on static logging level
/// in your code. Use closures to perform operations lazily
/// only when logging actually takes place.
pub fn __slog_static_max_level() -> FilterLevel {
if !cfg!(debug_assertions) {
if cfg!(feature = "release_max_level_off") {
return FilterLevel::Off;
} else if cfg!(feature = "release_max_level_error") {
return FilterLevel::Error;
} else if cfg!(feature = "release_max_level_warn") {
return FilterLevel::Warning;
} else if cfg!(feature = "release_max_level_info") {
return FilterLevel::Info;
} else if cfg!(feature = "release_max_level_debug") {
return FilterLevel::Debug;
} else if cfg!(feature = "release_max_level_trace") {
return FilterLevel::Trace;
}
}
if cfg!(feature = "max_level_off") {
FilterLevel::Off
} else if cfg!(feature = "max_level_error") {
FilterLevel::Error
} else if cfg!(feature = "max_level_warn") {
FilterLevel::Warning
} else if cfg!(feature = "max_level_info") {
FilterLevel::Info
} else if cfg!(feature = "max_level_debug") {
FilterLevel::Debug
} else if cfg!(feature = "max_level_trace") {
FilterLevel::Trace
} else {
if !cfg!(debug_assertions) {
FilterLevel::Info
} else {
FilterLevel::Debug
}
}
}
// }}}
// {{{ Slog v1 Compat
#[deprecated(note = "Renamed to `Value`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type Serialize = Value;
#[deprecated(note = "Renamed to `PushFnValue`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type PushLazy<T> = PushFnValue<T>;
#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type ValueSerializer<'a> = PushFnValueSerializer<'a>;
#[deprecated(note = "Renamed to `OwnedKVList`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type OwnedKeyValueList = OwnedKVList;
#[deprecated(note = "Content of ser module moved to main namespace")]
/// Compatibility name to ease upgrading from `slog v1`
pub mod ser {
#[allow(deprecated)]
pub use super::{OwnedKeyValueList, PushLazy, Serialize, Serializer,
ValueSerializer};
}
// }}}
// {{{ Test
#[cfg(test)]
mod tests;
// }}}
// vim: foldmethod=marker foldmarker={{{,}}}
Fixup serde to allow use in slog-json
// {{{ Crate docs
//! # Slog - Structured, extensible, composable logging for Rust
//!
//! `slog-rs` is an ecosystem of reusable components for structured, extensible,
//! composable logging for Rust.
//!
//! `slog` is `slog-rs`'s main crate providing core components shared between
//! all other parts of `slog-rs` ecosystem.
//!
//! This is auto-generated technical documentation of `slog`. For information
//! about project organization, development, help, etc. please see
//! [slog github page](https://github.com/slog-rs/slog)
//!
//! ## Core advantages over `log` crate
//!
//! * **extensible** - `slog` crate provides core functionality: very basic
//! and portable standard feature-set based on open `trait`s. This allows
//! implementing new features that can be independently published.
//! * **composable** - `trait`s that `slog` exposes to provide extensibility
//! are designed to be easy to efficiently reuse and combine. By combining
//! different functionalities every application can specify when, where and
//! how exactly process logging data from the application and it's
//! dependencies.
//! * **flexible** - `slog` does not constrain logging to just one globally
//! registered backend. Parts of your application can handle logging
//! in a customized way, or completely independently.
//! * **structured** and both **human and machine readable** - By keeping the
//! key-value data format and retaining its type information, meaning of logging
//! data is preserved. Data can be serialized to machine readable formats like
//! JSON and send it to data-mining system for further analysis etc. On the
//! other hand, when presenting on screen, logging information can be presented
//! in aesthetically pleasing and easy to understand way.
//! * **contextual** - `slog`'s `Logger` objects carry set of key-value data
//! pairs that contains the context of logging - information that otherwise
//! would have to be repeated in every logging statement.
//!
//! ## `slog` features
//!
//! * performance oriented; read [what makes slog
//! fast](https://github.com/slog-rs/slog/wiki/What-makes-slog-fast) and see:
//! [slog bench log](https://github.com/dpc/slog-rs/wiki/Bench-log)
//! * lazily evaluation through closure values
//! * async IO support included: see [`slog-async`
//! crate](https://docs.rs/slog-async)
//! * `#![no_std]` support (with opt-out `std` cargo feature flag)
//! * tree-structured loggers
//! * modular, lightweight and very extensible
//! * tiny core crate that does not pull any dependencies
//! * feature-crates for specific functionality
//! * using `slog` in library does not force users of the library to use slog
//! (but provides additional functionality); see [example how to use
//! `slog` in library](https://github.com/slog-rs/example-lib)
//! * backward and forward compatibility with `log` crate:
//! see [`slog-stdlog` crate](https://docs.rs/slog-stdlog)
//! * convenience crates:
//! * logging-scopes for implicit `Logger` passing: see
//! [slog-scope crate](https://docs.rs/slog-scope)
//! * many existing core&community provided features:
//! * multiple outputs
//! * filtering control
//! * compile-time log level filter using cargo features (same as in `log`
//! crate)
//! * by level, msg, and any other meta-data
//! * [`slog-envlogger`](https://github.com/slog-rs/envlogger) - port of
//! `env_logger`
//! * terminal output, with color support: see [`slog-term`
//! crate](docs.r/slog-term)
//! * [json](https://docs.rs/slog-json)
//! * [bunyan](https://docs.rs/slog-bunyan)
//! * [syslog](https://docs.rs/slog-syslog)
//! and [journald](https://docs.rs/slog-journald) support
//! * run-time configuration:
//! * run-time behavior change;
//! see [slog-atomic](https://docs.rs/slog-atomic)
//! * run-time configuration; see
//! [slog-config crate](https://docs.rs/slog-config)
//!
//!
//! [env_logger]: https://crates.io/crates/env_logger
//!
//! ## Notable details
//!
//! **Note:** At compile time `slog` by default removes trace and debug level
//! statements in release builds, and trace level records in debug builds. This
//! makes `trace` and `debug` level logging records practically free, which
//! should encourage using them freely. If you want to enable trace/debug
//! messages or raise the compile time logging level limit, use the following in
//! your `Cargo.toml`:
//!
//! ```norust
//! slog = { version = ... ,
//! features = ["max_level_trace", "release_max_level_warn"] }
//! ```
//!
//! Root drain (passed to `Logger::root`) must be one that does not ever return
//! errors. This forces user to pick error handing strategy.
//! `Drain::fuse()` or `Drain::ignore_res()`.
//!
//! [env_logger]: https://crates.io/crates/env_logger
//! [fn-overv]: https://github.com/dpc/slog-rs/wiki/Functional-overview
//! [atomic-switch]: https://docs.rs/slog-atomic/
//!
//! ## Where to start
//!
//! [`Drain`](trait.Drain.html), [`Logger`](struct.Logger.html) and
//! [`log` macro](macro.log.html) are the most important elements of
//! slog. Make sure to read their respective documentation
//!
//! Typically the biggest problem is creating a `Drain`
//!
//!
//! ### Logging to the terminal
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! ### Logging to a file
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use std::fs::OpenOptions;
//! use slog::Drain;
//!
//! fn main() {
//! let log_path = "target/your_log_file_path.log";
//! let file = OpenOptions::new()
//! .create(true)
//! .write(true)
//! .truncate(true)
//! .open(log_path)
//! .unwrap();
//!
//! let decorator = slog_term::PlainDecorator::new(file);
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//! You can consider using `slog-json` instead of `slog-term`.
//! `slog-term` only coincidently fits the role of a file output format. A
//! proper `slog-file` crate with suitable format, log file rotation and other
//! file-logging related features would be awesome. Contributions are welcome!
//!
//! ### Change logging level at runtime
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! use std::sync::{Arc, atomic};
//! use std::sync::atomic::Ordering;
//! use std::result;
//!
//! /// Custom Drain logic
//! struct RuntimeLevelFilter<D>{
//! drain: D,
//! on: Arc<atomic::AtomicBool>,
//! }
//!
//! impl<D> Drain for RuntimeLevelFilter<D>
//! where D : Drain {
//! type Ok = Option<D::Ok>;
//! type Err = Option<D::Err>;
//!
//! fn log(&self,
//! record: &slog::Record,
//! values: &slog::OwnedKVList)
//! -> result::Result<Self::Ok, Self::Err> {
//! let current_level = if self.on.load(Ordering::Relaxed) {
//! slog::Level::Trace
//! } else {
//! slog::Level::Info
//! };
//!
//! if record.level().is_at_least(current_level) {
//! self.drain.log(
//! record,
//! values
//! )
//! .map(Some)
//! .map_err(Some)
//! } else {
//! Ok(None)
//! }
//! }
//! }
//!
//! fn main() {
//! // atomic variable controlling logging level
//! let on = Arc::new(atomic::AtomicBool::new(false));
//!
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build();
//! let drain = RuntimeLevelFilter {
//! drain: drain,
//! on: on.clone(),
//! }.fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//!
//! // switch level in your code
//! on.store(true, Ordering::Relaxed);
//! }
//! ```
//!
//! Why is this not an existing crate? Because there are multiple ways to
//! achieve the same result, and each application might come with it's own
//! variation. Supporting a more general solution is a maintenance effort.
//! There is also nothing stopping anyone from publishing their own crate
//! implementing it.
//!
//! Alternative to the above aproach is `slog-atomic` crate. It implements
//! swapping whole parts of `Drain` logging hierarchy.
//!
//! ## Examples & help
//!
//! Basic examples that are kept up-to-date are typically stored in
//! respective git repository, under `examples/` subdirectory. Eg.
//! [slog-term examples](https://github.com/slog-rs/term/tree/master/examples).
//!
//! [slog-rs wiki pages](https://github.com/slog-rs/slog/wiki) contain
//! some pages about `slog-rs` technical details.
//!
//! Source code of other [software using
//! slog-rs](https://crates.io/crates/slog/reverse_dependencies) can
//! be an useful reference.
//!
//! Visit [slog-rs gitter channel](https://gitter.im/slog-rs/slog) for immediate
//! help.
//!
//! ## Migrating from slog v1 to slog v2
//!
//! ### Key-value pairs come now after format string
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//!
//! fn main() {
//! let drain = slog::Discard;
//! let root = slog::Logger::root(drain, o!());
//! info!(root, "formatted: {}", 1; "log-key" => true);
//! }
//! ```
//!
//! See more information about format at [`log`](macro.log.html).
//!
//! ### `slog-streamer` is gone
//!
//! Create simple terminal logger like this:
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_term;
//! extern crate slog_async;
//!
//! use slog::Drain;
//!
//! fn main() {
//! let decorator = slog_term::TermDecorator::new().build();
//! let drain = slog_term::FullFormat::new(decorator).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//!
//! let _log = slog::Logger::root(drain, o!());
//! }
//! ```
//!
//!
//! ### Logging macros now takes ownership of values.
//!
//! Pass them by reference: `&x`.
//!
// }}}
// {{{ Imports & meta
#![cfg_attr(not(feature = "std"), feature(alloc))]
#![cfg_attr(not(feature = "std"), feature(collections))]
#![warn(missing_docs)]
#![no_std]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
extern crate collections;
#[macro_use]
#[cfg(feature = "std")]
extern crate std;
#[cfg(not(feature = "std"))]
use alloc::arc::Arc;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::rc::Rc;
#[cfg(not(feature = "std"))]
use collections::string::String;
#[cfg(feature = "serde")]
extern crate erased_serde;
use core::{convert, fmt, result};
use core::str::FromStr;
#[cfg(feature = "std")]
use std::boxed::Box;
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(feature = "std")]
use std::string::String;
#[cfg(feature = "std")]
use std::sync::Arc;
// }}}
// {{{ Macros
/// Macro for building group of key-value pairs:
/// [`OwnedKV`](struct.OwnedKV.html)
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let _root = slog::Logger::root(
/// drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// }
/// ```
#[macro_export]
macro_rules! o(
($($args:tt)*) => {
$crate::OwnedKV(kv!($($args)*))
};
);
/// Macro for building group of key-value pairs (alias)
///
/// Use in case of macro name collisions
#[macro_export]
macro_rules! slog_o(
($($args:tt)*) => {
$crate::OwnedKV(slog_kv!($($args)*))
};
);
/// Macro for building group of key-value pairs in
/// [`BorrowedKV`](struct.BorrowedKV.html)
///
/// In most circumstances using this macro directly is unnecessary and `info!`
/// and other wrappers over `log!` should be used instead.
#[macro_export]
macro_rules! b(
($($args:tt)*) => {
$crate::BorrowedKV(&kv!($($args)*))
};
);
/// Alias of `b`
#[macro_export]
macro_rules! slog_b(
($($args:tt)*) => {
$crate::BorrowedKV(&slog_kv!($($args)*))
};
);
/// Macro for build `KV` implementing type
///
/// You probably want to use `o!` or `b!` instead.
#[macro_export]
macro_rules! kv(
(@ $args_ready:expr; $k:expr => %$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => ?$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => $v:expr) => {
kv!(@ ($crate::SingleKV($k, $v), $args_ready); )
};
(@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, $v), $args_ready); $($args)* )
};
(@ $args_ready:expr; $kv:expr) => {
kv!(@ ($kv, $args_ready); )
};
(@ $args_ready:expr; $kv:expr, $($args:tt)* ) => {
kv!(@ ($kv, $args_ready); $($args)* )
};
(@ $args_ready:expr; ) => {
$args_ready
};
(@ $args_ready:expr;, ) => {
$args_ready
};
($($args:tt)*) => {
kv!(@ (); $($args)*)
};
);
/// Alias of `kv`
#[macro_export]
macro_rules! slog_kv(
(@ $args_ready:expr; $k:expr => %$v:expr) => {
slog_kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => %$v:expr, $($args:tt)* ) => {
slog_kv!(@ ($crate::SingleKV($k, format_args!("{}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => ?$v:expr) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); )
};
(@ $args_ready:expr; $k:expr => ?$v:expr, $($args:tt)* ) => {
kv!(@ ($crate::SingleKV($k, format_args!("{:?}", $v)), $args_ready); $($args)* )
};
(@ $args_ready:expr; $k:expr => $v:expr) => {
slog_kv!(@ ($crate::SingleKV($k, $v), $args_ready); )
};
(@ $args_ready:expr; $k:expr => $v:expr, $($args:tt)* ) => {
slog_kv!(@ ($crate::SingleKV($k, $v), $args_ready); $($args)* )
};
(@ $args_ready:expr; $slog_kv:expr) => {
slog_kv!(@ ($slog_kv, $args_ready); )
};
(@ $args_ready:expr; $slog_kv:expr, $($args:tt)* ) => {
slog_kv!(@ ($slog_kv, $args_ready); $($args)* )
};
(@ $args_ready:expr; ) => {
$args_ready
};
(@ $args_ready:expr;, ) => {
$args_ready
};
($($args:tt)*) => {
slog_kv!(@ (); $($args)*)
};
);
#[macro_export]
/// Create `RecordStatic` at the given code location
macro_rules! record_static(
($lvl:expr, $tag:expr,) => { record_static!($lvl, $tag) };
($lvl:expr, $tag:expr) => {{
static LOC : $crate::RecordLocation = $crate::RecordLocation {
file: file!(),
line: line!(),
column: column!(),
function: "",
module: module_path!(),
};
$crate::RecordStatic {
location : &LOC,
level: $lvl,
tag : $tag,
}
}};
);
#[macro_export]
/// Create `RecordStatic` at the given code location (alias)
macro_rules! slog_record_static(
($lvl:expr, $tag:expr,) => { slog_record_static!($lvl, $tag) };
($lvl:expr, $tag:expr) => {{
static LOC : $crate::RecordLocation = $crate::RecordLocation {
file: file!(),
line: line!(),
column: column!(),
function: "",
module: module_path!(),
};
$crate::RecordStatic {
location : &LOC,
level: $lvl,
tag: $tag,
}
}};
);
#[macro_export]
/// Create `Record` at the given code location
macro_rules! record(
($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
record!($lvl, $tag, $args, $b)
};
($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
#[allow(dead_code)]
static RS : $crate::RecordStatic<'static> = record_static!($lvl, $tag);
$crate::Record::new(&RS, $args, $b)
}};
);
#[macro_export]
/// Create `Record` at the given code location (alias)
macro_rules! slog_record(
($lvl:expr, $tag:expr, $args:expr, $b:expr,) => {
slog_record!($lvl, $tag, $args, $b)
};
($lvl:expr, $tag:expr, $args:expr, $b:expr) => {{
static RS : $crate::RecordStatic<'static> = slog_record_static!($lvl,
$tag);
$crate::Record::new(&RS, $args, $b)
}};
);
/// Log message a logging record
///
/// Use wrappers `error!`, `warn!` etc. instead
///
/// The `max_level_*` and `release_max_level*` cargo features can be used to
/// statically disable logging at various levels. See [slog notable
/// details](index.html#notable-details)
///
/// Use [version with longer name](macro.slog_log.html) if you want to prevent
/// clash with legacy `log` crate macro names.
///
/// ## Supported invocations
///
/// ### Simple
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "test info log"; "log-key" => true);
/// }
/// ```
///
/// Note that `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain, o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "test info log");
/// }
/// ```
///
/// ### `fmt::Arguments` support:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "formatted: {}", 1; "log-key" => true);
/// }
/// ```
///
/// Note that that `;` separates formatting string from key value pairs.
///
/// Again, `"key" => value` part is optional:
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(
/// drain, o!("key1" => "value1", "key2" => "value2")
/// );
/// info!(root, "formatted: {}", 1);
/// }
/// ```
///
/// Note: use formatting support only when it really makes sense. Eg. logging
/// message like `"found {} keys"` is against structured logging. It should be
/// `"found keys", "count" => keys_num` instead, so that data is clearly named,
/// typed and separated from the message.
///
/// ### Tags
///
/// All above versions can be supplemented with a tag - string literal prefixed
/// with `#`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let drain = slog::Discard;
/// let root = slog::Logger::root(drain,
/// o!("key1" => "value1", "key2" => "value2")
/// );
/// let ops = 3;
/// info!(
/// root,
/// #"performance-metric", "thread speed"; "ops_per_sec" => ops
/// );
/// }
/// ```
///
/// See `Record::tag()` for more information about tags.
///
/// ### Own implementations of `KV` and `Value`
///
/// List of key value pairs is a comma separated list of key-values. Typically,
/// a designed syntax is used in form of `k => v` where `k` can be any type
/// that implements `Value` type.
///
/// It's possible to directly specify type that implements `KV` trait without
/// `=>` syntax.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// use slog::*;
///
/// fn main() {
/// struct MyKV;
/// struct MyV;
///
/// impl KV for MyKV {
/// fn serialize(&self,
/// _record: &Record,
/// serializer: &mut Serializer)
/// -> Result {
/// serializer.emit_u32("MyK", 16)
/// }
/// }
///
/// impl Value for MyV {
/// fn serialize(&self,
/// _record: &Record,
/// key : Key,
/// serializer: &mut Serializer)
/// -> Result {
/// serializer.emit_u32("MyKV", 16)
/// }
/// }
///
/// let drain = slog::Discard;
///
/// let root = slog::Logger::root(drain, o!(MyKV));
///
/// info!(
/// root,
/// "testing MyV"; "MyV" => MyV
/// );
/// }
/// ```
///
/// ### `fmt::Display` and `fmt::Debug` values
///
/// Value of any type that implements `std::fmt::Display` can be prefixed with
/// `%` in `k => v` expression to use it's text representation returned by
/// `format_args!("{}", v)`. This is especially useful for errors. Not that
/// this does not allocate any `String` since it operates on `fmt::Arguments`.
///
/// Similarly to use `std::fmt::Debug` value can be prefixed with `?`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use std::fmt::Write;
///
/// fn main() {
/// let drain = slog::Discard;
/// let log = slog::Logger::root(drain, o!());
///
/// let mut output = String::new();
///
/// if let Err(e) = write!(&mut output, "write to string") {
/// error!(log, "write failed"; "err" => %e);
/// }
/// }
/// ```
#[macro_export]
macro_rules! log(
(2 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
$l.log(&record!($lvl, $tag, &format_args!($msg_fmt, $($fmt)*), b!($($args)*)))
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
log!(1 @ { $($fmt)* $f }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
log!(1 @ { }, $l, $lvl, $tag, $($args)*)
}
};
);
/// Log message a logging record (alias)
///
/// Prefer [shorter version](macro.log.html), unless it clashes with
/// existing `log` crate macro.
///
/// See [`log`](macro.log.html) for documentation.
///
/// ```
/// #[macro_use(slog_o,slog_b,slog_record,slog_record_static,slog_log,slog_info,slog_kv)]
/// extern crate slog;
///
/// fn main() {
/// let log = slog::Logger::root(slog::Discard, slog_o!());
///
/// slog_info!(log, "some interesting info"; "where" => "right here");
/// }
/// ```
#[macro_export]
macro_rules! slog_log(
(2 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $($args:tt)*) => {
$l.log(&slog_record!($lvl, $tag, &format_args!($msg_fmt, $($fmt)*), slog_b!($($args)*)))
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, ; $($args:tt)*) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr, $f:tt $($args:tt)*) => {
slog_log!(1 @ { $($fmt)* $f }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr; $($args:tt)*) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt, $($args)*)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr,) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
(1 @ { $($fmt:tt)* }, $l:expr, $lvl:expr, $tag:expr, $msg_fmt:expr) => {
slog_log!(2 @ { $($fmt)* }, $l, $lvl, $tag, $msg_fmt,)
};
($l:expr, $lvl:expr, $tag:expr, $($args:tt)*) => {
if $lvl.as_usize() <= $crate::__slog_static_max_level().as_usize() {
slog_log!(1 @ { }, $l, $lvl, $tag, $($args)*)
}
};
);
/// Log critical level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! crit(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Critical, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Critical, "", $($args)+)
};
);
/// Log critical level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_crit(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Critical, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Critical, "", $($args)+)
};
);
/// Log error level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! error(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Error, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Error, "", $($args)+)
};
);
/// Log error level record
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_error(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Error, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Error, "", $($args)+)
};
);
/// Log warning level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! warn(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Warning, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Warning, "", $($args)+)
};
);
/// Log warning level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_warn(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Warning, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Warning, "", $($args)+)
};
);
/// Log info level record
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! info(
($l:expr, #$tag:expr, $($args:tt)*) => {
log!($l, $crate::Level::Info, $tag, $($args)*)
};
($l:expr, $($args:tt)*) => {
log!($l, $crate::Level::Info, "", $($args)*)
};
);
/// Log info level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_info(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Info, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Info, "", $($args)+)
};
);
/// Log debug level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! debug(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Debug, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Debug, "", $($args)+)
};
);
/// Log debug level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_debug(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Debug, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Debug, "", $($args)+)
};
);
/// Log trace level record
///
/// See `log` for documentation.
#[macro_export]
macro_rules! trace(
($l:expr, #$tag:expr, $($args:tt)+) => {
log!($l, $crate::Level::Trace, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
log!($l, $crate::Level::Trace, "", $($args)+)
};
);
/// Log trace level record (alias)
///
/// Prefer shorter version, unless it clashes with
/// existing `log` crate macro.
///
/// See `slog_log` for documentation.
#[macro_export]
macro_rules! slog_trace(
($l:expr, #$tag:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Trace, $tag, $($args)+)
};
($l:expr, $($args:tt)+) => {
slog_log!($l, $crate::Level::Trace, "", $($args)+)
};
($($args:tt)+) => {
slog_log!($crate::Level::Trace, $($args)+)
};
);
// }}}
// {{{ Logger
/// Logging handle used to execute logging statements
///
/// In an essence `Logger` instance holds two pieces of information:
///
/// * drain - destination where to forward logging `Record`s for
/// processing.
/// * context - list of key-value pairs associated with it.
///
/// Root `Logger` is created with a `Drain` that will be cloned to every
/// member of it's hierarchy.
///
/// Child `Logger` are built from existing ones, and inherit their key-value
/// pairs, which can be supplemented with additional ones.
///
/// Cloning existing loggers and creating new ones is cheap. Loggers can be
/// freely passed around the code and between threads.
///
/// `Logger`s are `Sync+Send` - there's no need to synchronize accesses to them,
/// as they can accept logging records from multiple threads at once. They can
/// be sent to any thread. Because of that they require the `Drain` to be
/// `Sync+Sync` as well. Not all `Drain`s are `Sync` or `Send` but they can
/// often be made so by wrapping in a `Mutex` and/or `Arc`.
///
/// `Logger` implements `Drain` trait. Any logging `Record` delivered to
/// a `Logger` functioning as a `Drain`, will be delivered to it's `Drain`
/// with existing key-value pairs appended to the `Logger`s key-value pairs.
/// By itself it's effectively very similar to `Logger` being an ancestor
/// of `Logger` that originated the logging `Record`. Combined with other
/// `Drain`s, allows custom processing logic for a sub-tree of a whole logging
/// tree.
///
/// Logger is parametrized over type of a `Drain` associated with it (`D`). It
/// default to type-erased version so `Logger` without any type annotation
/// means `Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>`. See
/// `Logger::root_typed` and `Logger::to_erased` for more information.
#[derive(Clone)]
pub struct Logger<D = Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
drain: D,
list: OwnedKVList,
}
impl<D> Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
/// Build a root `Logger`
///
/// Root logger starts a new tree associated with a given `Drain`. Root
/// logger drain must return no errors. See `Drain::ignore_res()` and
/// `Drain::fuse()`.
///
/// All children and their children (and so on), form one logging tree
/// sharing a common drain. See `Logger::new`.
///
/// This version (as opposed to `Logger:root_typed`) will take `drain` and
/// made it into `Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>`.
/// This is typically the most convenient way to work with `Logger`s.
///
/// Use `o!` macro to build `OwnedKV` object.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let _root = slog::Logger::root(
/// slog::Discard,
/// o!("key1" => "value1", "key2" => "value2"),
/// );
/// }
/// ```
pub fn root<T>(drain: D, values: OwnedKV<T>) -> Logger
where
D: 'static + SendSyncRefUnwindSafeDrain<Err = Never, Ok = ()>,
T: SendSyncRefUnwindSafeKV + 'static,
{
Logger {
drain: Arc::new(drain) as
Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
list: OwnedKVList::root(values),
}
}
/// Build a root `Logger` that retains `drain` type
///
/// Unlike `Logger::root`, this constructor retains the type of a `drain`,
/// which allows highest performance possible by eliminating indirect call
/// on `Drain::log`, and allowing monomorphization of `Logger` and `Drain`
/// objects.
///
/// If you don't understand the implications, you should probably just
/// ignore it.
///
/// See `Logger:into_erased` and `Logger::to_erased` for conversion from
/// type returned by this function to version that would be returned by
/// `Logger::root`.
pub fn root_typed<T>(drain: D, values: OwnedKV<T>) -> Logger<D>
where
D: 'static + SendSyncUnwindSafeDrain<Err = Never, Ok = ()> + Sized,
T: SendSyncRefUnwindSafeKV + 'static,
{
Logger {
drain: drain,
list: OwnedKVList::root(values),
}
}
/// Build a child logger
///
/// Child logger inherits all existing key-value pairs from its parent and
/// supplements them with additional ones.
///
/// Use `o!` macro to build `OwnedKV` object.
///
/// ### Drain cloning (`D : Clone` requirement)
///
/// All children, their children and so on, form one tree sharing a
/// common drain. This drain, will be `Clone`d when this method is called.
/// That is why `Clone` must be implemented for `D` in `Logger<D>::new`.
///
/// For some `Drain` types `Clone` is cheap or even free (a no-op). This is
/// the case for any `Logger` returned by `Logger::root` and it's children.
///
/// When using `Logger::root_typed`, it's possible that cloning might be
/// expensive, or even impossible.
///
/// The reason why wrapping in an `Arc` is not done internally, and exposed
/// to the user is performance. Calling `Drain::log` through an `Arc` is
/// tiny bit slower than doing it directly.
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
/// let root = slog::Logger::root(slog::Discard,
/// o!("key1" => "value1", "key2" => "value2"));
/// let _log = root.new(o!("key" => "value"));
/// }
#[cfg_attr(feature = "cargo-clippy", allow(wrong_self_convention))]
pub fn new<T>(&self, values: OwnedKV<T>) -> Logger<D>
where
T: SendSyncRefUnwindSafeKV + 'static,
D: Clone,
{
Logger {
drain: self.drain.clone(),
list: OwnedKVList::new(values, self.list.node.clone()),
}
}
/// Log one logging `Record`
///
/// Use specific logging functions instead. See `log!` macro
/// documentation.
#[inline]
pub fn log(&self, record: &Record) {
let _ = self.drain.log(record, &self.list);
}
/// Get list of key-value pairs assigned to this `Logger`
pub fn list(&self) -> &OwnedKVList {
&self.list
}
/// Convert to default, "erased" type:
/// `Logger<Arc<SendSyncUnwindSafeDrain>>`
///
/// Useful to adapt `Logger<D : Clone>` to an interface expecting
/// `Logger<Arc<...>>`.
///
/// Note that calling on a `Logger<Arc<...>>` will convert it to
/// `Logger<Arc<Arc<...>>>` which is not optimal. This might be fixed when
/// Rust gains trait implementation specialization.
pub fn into_erased(
self,
) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendRefUnwindSafeDrain + 'static,
{
Logger {
drain: Arc::new(self.drain) as
Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>,
list: self.list,
}
}
/// Create a copy with "erased" type
///
/// See `into_erased`
pub fn to_erased(
&self,
) -> Logger<Arc<SendSyncRefUnwindSafeDrain<Ok = (), Err = Never>>>
where
D: SendRefUnwindSafeDrain + 'static + Clone,
{
self.clone().into_erased()
}
}
impl<D> fmt::Debug for Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "Logger{:?}", self.list));
Ok(())
}
}
impl<D> Drain for Logger<D>
where
D: SendSyncUnwindSafeDrain<Ok = (), Err = Never>,
{
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let chained = OwnedKVList {
node: Arc::new(MultiListNode {
next_node: values.node.clone(),
node: self.list.node.clone(),
}),
};
self.drain.log(record, &chained)
}
}
// }}}
// {{{ Drain
/// Logging drain
///
/// `Drain`s typically mean destination for logs, but `slog` generalizes the
/// term.
///
/// `Drain`s are responsible for handling logging statements (`Record`s) from
/// `Logger`s associated with them: filtering, modifying, formatting
/// and writing the log records into given destination(s).
///
/// It's a typical pattern to parametrize `Drain`s over `Drain` traits to allow
/// composing `Drain`s.
///
/// Implementing this trait allows writing custom `Drain`s. Slog users should
/// not be afraid of implementing their own `Drain`s. Any custom log handling
/// logic should be implemented as a `Drain`.
pub trait Drain {
/// Type returned by this drain
///
/// It can be useful in some circumstances, but rarely. It will probably
/// default to `()` once https://github.com/rust-lang/rust/issues/29661 is
/// stable.
type Ok;
/// Type of potential errors that can be returned by this `Drain`
type Err;
/// Handle one logging statement (`Record`)
///
/// Every logging `Record` built from a logging statement (eg.
/// `info!(...)`), and key-value lists of a `Logger` it was executed on
/// will be passed to the root drain registered during `Logger::root`.
///
/// Typically `Drain`s:
///
/// * pass this information (or not) to the sub-logger(s) (filters)
/// * format and write the information the a destination (writers)
/// * deal with the errors returned from the sub-logger(s)
fn log(
&self,
record: &Record,
values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err>;
/// Pass `Drain` through a closure, eg. to wrap
/// into another `Drain`.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::*;
///
/// fn main() {
/// let _drain = Discard.map(Fuse);
/// }
/// ```
fn map<F, R>(self, f: F) -> R
where
Self: Sized,
F: FnOnce(Self) -> R,
{
f(self)
}
/// Filter logging records passed to `Drain`
///
/// Wrap `Self` in `Filter`
///
/// This will convert `self` to a `Drain that ignores `Record`s
/// for which `f` returns false.
fn filter<F>(self, f: F) -> Filter<Self, F>
where
Self: Sized,
F: FilterFn,
{
Filter::new(self, f)
}
/// Filter logging records passed to `Drain` (by level)
///
/// Wrap `Self` in `LevelFilter`
///
/// This will convert `self` to a `Drain that ignores `Record`s of
/// logging lever smaller than `level`.
fn filter_level(self, level: Level) -> LevelFilter<Self>
where
Self: Sized,
{
LevelFilter(self, level)
}
/// Map logging errors returned by this drain
///
/// `f` is a closure that takes `Drain::Err` returned by a given
/// drain, and returns new error of potentially different type
fn map_err<F, E>(self, f: F) -> MapError<Self, E>
where
Self: Sized,
F: MapErrFn<Self::Err, E>,
{
MapError::new(self, f)
}
/// Ignore results returned by this drain
///
/// Wrap `Self` in `IgnoreResult`
fn ignore_res(self) -> IgnoreResult<Self>
where
Self: Sized,
{
IgnoreResult::new(self)
}
/// Make `Self` panic when returning any errors
///
/// Wrap `Self` in `Map`
fn fuse(self) -> Fuse<Self>
where
Self::Err: fmt::Debug,
Self: Sized,
{
self.map(Fuse)
}
}
#[cfg(feature = "std")]
/// `Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafe: Send + Sync + UnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafe for T
where
T: Send + Sync + UnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync + UnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncUnwindSafeDrain for T
where
T: Drain + Send + Sync + UnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncRefUnwindSafeDrain for T
where
T: Drain + Send + Sync + RefUnwindSafe + ?Sized,
{
}
#[cfg(feature = "std")]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>
: 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(EI) -> EO {
}
#[cfg(feature = "std")]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
T: 'static + Sync + Send + ?Sized + UnwindSafe + RefUnwindSafe + Fn(EI) -> EO,
{
}
#[cfg(feature = "std")]
/// Function that can be used in `Filter` drain
pub trait FilterFn
: 'static + Sync + Send + UnwindSafe + RefUnwindSafe + Fn(&Record) -> bool {
}
#[cfg(feature = "std")]
impl<T> FilterFn for T
where
T: 'static
+ Sync
+ Send
+ ?Sized
+ UnwindSafe
+ RefUnwindSafe
+ Fn(&Record) -> bool,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + UnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncUnwindSafeDrain: Drain + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncUnwindSafeDrain for T
where
T: Drain + Send + Sync + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + Sync + RefUnwindSafe` bound
///
/// This type is used to enforce `Drain`s associated with `Logger`s
/// are thread-safe.
pub trait SendSyncRefUnwindSafeDrain: Drain + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncRefUnwindSafeDrain for T
where
T: Drain + Send + Sync + ?Sized,
{
}
#[cfg(feature = "std")]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendRefUnwindSafeDrain for T
where
T: Drain + Send + RefUnwindSafe + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// `Drain + Send + RefUnwindSafe` bound
pub trait SendRefUnwindSafeDrain: Drain + Send {}
#[cfg(not(feature = "std"))]
impl<T> SendRefUnwindSafeDrain for T
where
T: Drain + Send + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// Function that can be used in `MapErr` drain
pub trait MapErrFn<EI, EO>: 'static + Sync + Send + Fn(EI) -> EO {}
#[cfg(not(feature = "std"))]
impl<T, EI, EO> MapErrFn<EI, EO> for T
where
T: 'static + Sync + Send + ?Sized + Fn(EI) -> EO,
{
}
#[cfg(not(feature = "std"))]
/// Function that can be used in `Filter` drain
pub trait FilterFn: 'static + Sync + Send + Fn(&Record) -> bool {}
#[cfg(not(feature = "std"))]
impl<T> FilterFn for T
where
T: 'static + Sync + Send + ?Sized + Fn(&Record) -> bool,
{
}
impl<D: Drain + ?Sized> Drain for Box<D> {
type Ok = D::Ok;
type Err = D::Err;
fn log(
&self,
record: &Record,
o: &OwnedKVList,
) -> result::Result<Self::Ok, D::Err> {
(**self).log(record, o)
}
}
impl<D: Drain + ?Sized> Drain for Arc<D> {
type Ok = D::Ok;
type Err = D::Err;
fn log(
&self,
record: &Record,
o: &OwnedKVList,
) -> result::Result<Self::Ok, D::Err> {
(**self).log(record, o)
}
}
/// `Drain` discarding everything
///
/// `/dev/null` of `Drain`s
#[derive(Debug, Copy, Clone)]
pub struct Discard;
impl Drain for Discard {
type Ok = ();
type Err = Never;
fn log(&self, _: &Record, _: &OwnedKVList) -> result::Result<(), Never> {
Ok(())
}
}
/// `Drain` filtering records
///
/// Wraps another `Drain` and passes `Record`s to it, only if they satisfy a
/// given condition.
#[derive(Debug, Clone)]
pub struct Filter<D: Drain, F>(pub D, pub F)
where
F: Fn(&Record) -> bool + 'static + Send + Sync;
impl<D: Drain, F> Filter<D, F>
where
F: FilterFn,
{
/// Create `Filter` wrapping given `drain`
pub fn new(drain: D, cond: F) -> Self {
Filter(drain, cond)
}
}
impl<D: Drain, F> Drain for Filter<D, F>
where
F: FilterFn,
{
type Ok = Option<D::Ok>;
type Err = D::Err;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
if (self.1)(record) {
Ok(Some(self.0.log(record, logger_values)?))
} else {
Ok(None)
}
}
}
/// `Drain` filtering records by `Record` logging level
///
/// Wraps a drain and passes records to it, only
/// if their level is at least given level.
///
/// TODO: Remove this type. This drain is a special case of `Filter`, but
/// because `Filter` can not use static dispatch ATM due to Rust limitations
/// that will be lifted in the future, it is a standalone type.
/// Reference: https://github.com/rust-lang/rust/issues/34511
#[derive(Debug, Clone)]
pub struct LevelFilter<D: Drain>(pub D, pub Level);
impl<D: Drain> LevelFilter<D> {
/// Create `LevelFilter`
pub fn new(drain: D, level: Level) -> Self {
LevelFilter(drain, level)
}
}
impl<D: Drain> Drain for LevelFilter<D> {
type Ok = Option<D::Ok>;
type Err = D::Err;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
if record.level().is_at_least(self.1) {
Ok(Some(self.0.log(record, logger_values)?))
} else {
Ok(None)
}
}
}
/// `Drain` mapping error returned by another `Drain`
///
/// See `Drain::map_err` for convenience function.
pub struct MapError<D: Drain, E> {
drain: D,
// eliminated dynamic dispatch, after rust learns `-> impl Trait`
map_fn: Box<MapErrFn<D::Err, E, Output = E>>,
}
impl<D: Drain, E> MapError<D, E> {
/// Create `Filter` wrapping given `drain`
pub fn new<F>(drain: D, map_fn: F) -> Self
where
F: MapErrFn<<D as Drain>::Err, E>,
{
MapError {
drain: drain,
map_fn: Box::new(map_fn),
}
}
}
impl<D: Drain, E> Drain for MapError<D, E> {
type Ok = D::Ok;
type Err = E;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
self.drain
.log(record, logger_values)
.map_err(|e| (self.map_fn)(e))
}
}
/// `Drain` duplicating records into two other `Drain`s
///
/// Can be nested for more than two outputs.
#[derive(Debug, Clone)]
pub struct Duplicate<D1: Drain, D2: Drain>(pub D1, pub D2);
impl<D1: Drain, D2: Drain> Duplicate<D1, D2> {
/// Create `Duplicate`
pub fn new(drain1: D1, drain2: D2) -> Self {
Duplicate(drain1, drain2)
}
}
impl<D1: Drain, D2: Drain> Drain for Duplicate<D1, D2> {
type Ok = (D1::Ok, D2::Ok);
type Err = (
result::Result<D1::Ok, D1::Err>,
result::Result<D2::Ok, D2::Err>,
);
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let res1 = self.0.log(record, logger_values);
let res2 = self.1.log(record, logger_values);
match (res1, res2) {
(Ok(o1), Ok(o2)) => Ok((o1, o2)),
(r1, r2) => Err((r1, r2)),
}
}
}
/// `Drain` panicking on error
///
/// `Logger` requires a root drain to handle all errors (`Drain::Error == ()`),
/// `Fuse` will wrap a `Drain` and panic if it returns any errors.
///
/// Note: `Drain::Err` must implement `Display` (for displaying on panick). It's
/// easy to create own `Fuse` drain if this requirement can't be fulfilled.
#[derive(Debug, Clone)]
pub struct Fuse<D: Drain>(pub D)
where
D::Err: fmt::Debug;
impl<D: Drain> Fuse<D>
where
D::Err: fmt::Debug,
{
/// Create `Fuse` wrapping given `drain`
pub fn new(drain: D) -> Self {
Fuse(drain)
}
}
impl<D: Drain> Drain for Fuse<D>
where
D::Err: fmt::Debug,
{
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Never> {
let _ = self.0
.log(record, logger_values)
.unwrap_or_else(|e| panic!("slog::Fuse Drain: {:?}", e));
Ok(())
}
}
/// `Drain` ignoring result
///
/// `Logger` requires a root drain to handle all errors (`Drain::Err=()`), and
/// returns nothing (`Drain::Ok=()`) `IgnoreResult` will ignore any result
/// returned by the `Drain` it wraps.
#[derive(Clone)]
pub struct IgnoreResult<D: Drain> {
drain: D,
}
impl<D: Drain> IgnoreResult<D> {
/// Create `IgnoreResult` wrapping `drain`
pub fn new(drain: D) -> Self {
IgnoreResult { drain: drain }
}
}
impl<D: Drain> Drain for IgnoreResult<D> {
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<(), Never> {
let _ = self.drain.log(record, logger_values);
Ok(())
}
}
/// Error returned by `Mutex<D : Drain>`
#[cfg(feature = "std")]
#[derive(Clone)]
pub enum MutexDrainError<D: Drain> {
/// Error acquiring mutex
Mutex,
/// Error returned by drain
Drain(D::Err),
}
#[cfg(feature = "std")]
impl<D> fmt::Debug for MutexDrainError<D>
where
D: Drain,
D::Err: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
match *self {
MutexDrainError::Mutex => write!(f, "MutexDrainError::Mutex"),
MutexDrainError::Drain(ref e) => e.fmt(f),
}
}
}
#[cfg(feature = "std")]
impl<D> std::error::Error for MutexDrainError<D>
where
D: Drain,
D::Err: fmt::Debug + fmt::Display + std::error::Error,
{
fn description(&self) -> &str {
match *self {
MutexDrainError::Mutex => "Mutex acquire failed",
MutexDrainError::Drain(ref e) => e.description(),
}
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
MutexDrainError::Mutex => None,
MutexDrainError::Drain(ref e) => Some(e),
}
}
}
#[cfg(feature = "std")]
impl<'a, D: Drain> From<std::sync::PoisonError<std::sync::MutexGuard<'a, D>>>
for MutexDrainError<D> {
fn from(
_: std::sync::PoisonError<std::sync::MutexGuard<'a, D>>,
) -> MutexDrainError<D> {
MutexDrainError::Mutex
}
}
#[cfg(feature = "std")]
impl<D: Drain> fmt::Display for MutexDrainError<D>
where
D::Err: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
match *self {
MutexDrainError::Mutex => write!(f, "MutexError"),
MutexDrainError::Drain(ref e) => write!(f, "{}", e),
}
}
}
#[cfg(feature = "std")]
impl<D: Drain> Drain for std::sync::Mutex<D> {
type Ok = D::Ok;
type Err = MutexDrainError<D>;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> result::Result<Self::Ok, Self::Err> {
let d = self.lock()?;
d.log(record, logger_values).map_err(MutexDrainError::Drain)
}
}
// }}}
// {{{ Level & FilterLevel
/// Official capitalized logging (and logging filtering) level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_NAMES: [&'static str; 7] =
["OFF", "CRITICAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
/// Official capitalized logging (and logging filtering) short level names
///
/// In order of `as_usize()`.
pub static LOG_LEVEL_SHORT_NAMES: [&'static str; 7] =
["OFF", "CRIT", "ERRO", "WARN", "INFO", "DEBG", "TRCE"];
/// Logging level associated with a logging `Record`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Level {
/// Critical
Critical,
/// Error
Error,
/// Warning
Warning,
/// Info
Info,
/// Debug
Debug,
/// Trace
Trace,
}
/// Logging filtering level
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum FilterLevel {
/// Log nothing
Off,
/// Log critical level only
Critical,
/// Log only error level and above
Error,
/// Log only warning level and above
Warning,
/// Log only info level and above
Info,
/// Log only debug level and above
Debug,
/// Log everything
Trace,
}
impl Level {
/// Convert to `str` from `LOG_LEVEL_SHORT_NAMES`
pub fn as_short_str(&self) -> &'static str {
LOG_LEVEL_SHORT_NAMES[self.as_usize()]
}
/// Convert to `str` from `LOG_LEVEL_NAMES`
pub fn as_str(&self) -> &'static str {
LOG_LEVEL_NAMES[self.as_usize()]
}
/// Cast `Level` to ordering integer
///
/// `Critical` is the smallest and `Trace` the biggest value
#[inline]
pub fn as_usize(&self) -> usize {
match *self {
Level::Critical => 1,
Level::Error => 2,
Level::Warning => 3,
Level::Info => 4,
Level::Debug => 5,
Level::Trace => 6,
}
}
/// Get a `Level` from an `usize`
///
/// This complements `as_usize`
#[inline]
pub fn from_usize(u: usize) -> Option<Level> {
match u {
1 => Some(Level::Critical),
2 => Some(Level::Error),
3 => Some(Level::Warning),
4 => Some(Level::Info),
5 => Some(Level::Debug),
6 => Some(Level::Trace),
_ => None,
}
}
}
impl FilterLevel {
/// Convert to `usize` value
///
/// `Off` is 0, and `Trace` 6
#[inline]
pub fn as_usize(&self) -> usize {
match *self {
FilterLevel::Off => 0,
FilterLevel::Critical => 1,
FilterLevel::Error => 2,
FilterLevel::Warning => 3,
FilterLevel::Info => 4,
FilterLevel::Debug => 5,
FilterLevel::Trace => 6,
}
}
/// Get a `FilterLevel` from an `usize`
///
/// This complements `as_usize`
#[inline]
pub fn from_usize(u: usize) -> Option<FilterLevel> {
match u {
0 => Some(FilterLevel::Off),
1 => Some(FilterLevel::Critical),
2 => Some(FilterLevel::Error),
3 => Some(FilterLevel::Warning),
4 => Some(FilterLevel::Info),
5 => Some(FilterLevel::Debug),
6 => Some(FilterLevel::Trace),
_ => None,
}
}
/// Maximum logging level (log everything)
#[inline]
pub fn max() -> Self {
FilterLevel::Trace
}
/// Minimum logging level (log nothing)
#[inline]
pub fn min() -> Self {
FilterLevel::Off
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
static ASCII_LOWERCASE_MAP: [u8; 256] =
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, b' ', b'!', b'"', b'#',
b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';',
b'<', b'=', b'>', b'?', b'@', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's',
b't', b'u', b'v', b'w', b'x', b'y', b'z', b'[', b'\\', b']', b'^', b'_',
b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k',
b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb,
0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3,
0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb,
0xfc, 0xfd, 0xfe, 0xff];
impl FromStr for Level {
type Err = ();
fn from_str(level: &str) -> core::result::Result<Level, ()> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| {
name.as_bytes().iter().zip(level.as_bytes().iter()).all(
|(a, b)| {
ASCII_LOWERCASE_MAP[*a as usize] ==
ASCII_LOWERCASE_MAP[*b as usize]
},
)
})
.map(|p| Level::from_usize(p).unwrap())
.ok_or(())
}
}
impl FromStr for FilterLevel {
type Err = ();
fn from_str(level: &str) -> core::result::Result<FilterLevel, ()> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| {
name.as_bytes().iter().zip(level.as_bytes().iter()).all(
|(a, b)| {
ASCII_LOWERCASE_MAP[*a as usize] ==
ASCII_LOWERCASE_MAP[*b as usize]
},
)
})
.map(|p| FilterLevel::from_usize(p).unwrap())
.ok_or(())
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_short_str())
}
}
impl Level {
/// Returns true if `self` is at least `level` logging level
#[inline]
pub fn is_at_least(&self, level: Self) -> bool {
self.as_usize() <= level.as_usize()
}
}
#[test]
fn level_at_least() {
assert!(Level::Debug.is_at_least(Level::Debug));
assert!(Level::Debug.is_at_least(Level::Trace));
assert!(!Level::Debug.is_at_least(Level::Info));
}
#[test]
fn filterlevel_sanity() {
assert!(Level::Critical.as_usize() > FilterLevel::Off.as_usize());
assert!(Level::Critical.as_usize() == FilterLevel::Critical.as_usize());
assert!(Level::Trace.as_usize() == FilterLevel::Trace.as_usize());
}
#[test]
fn level_from_str() {
assert_eq!("info".parse::<FilterLevel>().unwrap(), FilterLevel::Info);
}
// }}}
// {{{ Record
#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct RecordLocation {
/// File
pub file: &'static str,
/// Line
pub line: u32,
/// Column (currently not implemented)
pub column: u32,
/// Function (currently not implemented)
pub function: &'static str,
/// Module
pub module: &'static str,
}
#[doc(hidden)]
/// Information that can be static in the given record thus allowing to optimize
/// record creation to be done mostly at compile-time.
///
/// This is not cosidered a part of stable API, and macros should be used
/// instead.
pub struct RecordStatic<'a> {
/// Code location
pub location: &'a RecordLocation,
/// Tag
pub tag: &'a str,
/// Logging level
pub level: Level,
}
/// One logging record
///
/// Corresponds to one logging statement like `info!(...)` and carries all it's
/// data: eg. message, immediate key-value pairs and key-value pairs of `Logger`
/// used to execute it.
///
/// Record is passed to a `Logger`, which delivers it to it's own `Drain`,
/// where actual logging processing is implemented.
pub struct Record<'a> {
rstatic: &'a RecordStatic<'a>,
msg: &'a fmt::Arguments<'a>,
kv: BorrowedKV<'a>,
}
impl<'a> Record<'a> {
/// Create a new `Record`
///
/// This function is not considered a part of stable API
#[inline]
#[doc(hidden)]
pub fn new(
s: &'a RecordStatic<'a>,
msg: &'a fmt::Arguments<'a>,
kv: BorrowedKV<'a>,
) -> Self {
Record {
rstatic: s,
msg: msg,
kv: kv,
}
}
/// Get a log record message
pub fn msg(&self) -> &fmt::Arguments {
self.msg
}
/// Get record logging level
pub fn level(&self) -> Level {
self.rstatic.level
}
/// Get line number
pub fn line(&self) -> u32 {
self.rstatic.location.line
}
/// Get line number
pub fn location(&self) -> &RecordLocation {
self.rstatic.location
}
/// Get error column
pub fn column(&self) -> u32 {
self.rstatic.location.column
}
/// Get file path
pub fn file(&self) -> &'static str {
self.rstatic.location.file
}
/// Get tag
///
/// Tag is information that can be attached to `Record` that is not meant
/// to be part of the norma key-value pairs, but only as an ad-hoc control
/// flag for quick lookup in the `Drain`s. As such should be used carefully
/// and mostly in application code (as opposed to libraries) - where tag
/// meaning across the system can be coordinated. When used in libraries,
/// make sure to prefix is with something reasonably distinct, like create
/// name.
pub fn tag(&self) -> &str {
self.rstatic.tag
}
/// Get module
pub fn module(&self) -> &'static str {
self.rstatic.location.module
}
/// Get function (placeholder)
///
/// There's currently no way to obtain that information
/// in Rust at compile time, so it is not implemented.
///
/// It will be implemented at first opportunity, and
/// it will not be considered a breaking change.
pub fn function(&self) -> &'static str {
self.rstatic.location.function
}
/// Get key-value pairs
pub fn kv(&self) -> BorrowedKV {
BorrowedKV(self.kv.0)
}
}
// }}}
// {{{ Serializer
macro_rules! impl_default_as_fmt{
($t:ty, $f:ident) => {
/// Emit $t
fn $f(&mut self, key : Key, val : $t)
-> Result {
self.emit_arguments(key, &format_args!("{}", val))
}
};
}
/// Serializer
///
/// Drains using `Format` will internally use
/// types implementing this trait.
pub trait Serializer {
/// Emit usize
impl_default_as_fmt!(usize, emit_usize);
/// Emit isize
impl_default_as_fmt!(isize, emit_isize);
/// Emit bool
impl_default_as_fmt!(bool, emit_bool);
/// Emit char
impl_default_as_fmt!(char, emit_char);
/// Emit u8
impl_default_as_fmt!(u8, emit_u8);
/// Emit i8
impl_default_as_fmt!(i8, emit_i8);
/// Emit u16
impl_default_as_fmt!(u16, emit_u16);
/// Emit i16
impl_default_as_fmt!(i16, emit_i16);
/// Emit u32
impl_default_as_fmt!(u32, emit_u32);
/// Emit i32
impl_default_as_fmt!(i32, emit_i32);
/// Emit f32
impl_default_as_fmt!(f32, emit_f32);
/// Emit u64
impl_default_as_fmt!(u64, emit_u64);
/// Emit i64
impl_default_as_fmt!(i64, emit_i64);
/// Emit f64
impl_default_as_fmt!(f64, emit_f64);
/// Emit str
impl_default_as_fmt!(&str, emit_str);
/// Emit `()`
fn emit_unit(&mut self, key: Key) -> Result {
self.emit_arguments(key, &format_args!("()"))
}
/// Emit `None`
fn emit_none(&mut self, key: Key) -> Result {
self.emit_arguments(key, &format_args!(""))
}
/// Emit `fmt::Arguments`
///
/// This is the only method that has to implemented, but for performance and
/// to retain type information most serious `Serializer`s will want to
/// implement all other methods as well.
fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result;
/// Emit a value implementing
/// [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html)
///
/// This is especially useful for composite values, eg. structs as Json values, or sequences.
///
/// To prevent pulling-in `serde` dependency, this is an extension behind a
/// `serde` feature flag.
///
/// The value needs to implement `SerdeValue`.
#[cfg(feature = "serde")]
fn emit_serde(&mut self, key: Key, value: &SerdeValue) -> Result {
// value.serialize_fallback(key, self)
Err(Error::Other)
}
}
/// Serializer to closure adapter.
///
/// Formats all arguments as `fmt::Arguments` and passes them to a given closure.
struct AsFmtSerializer<F>(pub F)
where
F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result;
impl<F> Serializer for AsFmtSerializer<F>
where
F: for<'a> FnMut(Key, fmt::Arguments<'a>) -> Result,
{
fn emit_arguments(&mut self, key: Key, val: &fmt::Arguments) -> Result {
(self.0)(key, *val)
}
}
// }}}
// {{{ serde
/// A value that can be serialized via serde
///
/// This is useful for implementing nested values, like sequences or structures.
#[cfg(feature = "serde")]
pub trait SerdeValue : erased_serde::Serialize {
/// Serialize the value in a way that is compatible with `slog::Serializer`s
/// that do not support serde.
///
/// The implementation should *not* call `slog::Serialize::serialize`
/// on itself, as it will lead to infinite recursion.
///
/// Default implementation is provided, but it returns error, so use it
/// only for internal types in systems and libraries where `serde` is always
/// enabled.
// fn serialize_fallback(&self, _key: Key, _serializer: &mut Serializer) -> Result<()> {
// Err(Error::Other)
// }
/// Convert to `erased_serialize::Serialize` of the underlying value,
/// so `slog::Serializer`s can use it to serialize via `serde`.
fn as_serde(&self) -> &erased_serde::Serialize;
/// Convert to a boxed value that can be sent across threads
///
/// This enables functionality like `slog-async` and similar.
fn to_sendable(&self) -> Box<SerdeValue + Send + 'static>;
}
// }}}
// {{{ Key
/// Key type (alias for &'static str)
pub type Key = &'static str;
// }}}
// {{{ Value
/// Value that can be serialized
pub trait Value {
/// Serialize self into `Serializer`
///
/// Structs implementing this trait should generally
/// only call respective methods of `serializer`.
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result;
}
impl<'a, V> Value for &'a V
where
V: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(*self).serialize(record, key, serializer)
}
}
macro_rules! impl_value_for{
($t:ty, $f:ident) => {
impl Value for $t {
fn serialize(&self,
_record : &Record,
key : Key,
serializer : &mut Serializer
) -> Result {
serializer.$f(key, *self)
}
}
};
}
impl_value_for!(usize, emit_usize);
impl_value_for!(isize, emit_isize);
impl_value_for!(bool, emit_bool);
impl_value_for!(char, emit_char);
impl_value_for!(u8, emit_u8);
impl_value_for!(i8, emit_i8);
impl_value_for!(u16, emit_u16);
impl_value_for!(i16, emit_i16);
impl_value_for!(u32, emit_u32);
impl_value_for!(i32, emit_i32);
impl_value_for!(f32, emit_f32);
impl_value_for!(u64, emit_u64);
impl_value_for!(i64, emit_i64);
impl_value_for!(f64, emit_f64);
impl Value for () {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_unit(key)
}
}
impl Value for str {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_str(key, self)
}
}
impl<'a> Value for fmt::Arguments<'a> {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_arguments(key, self)
}
}
impl Value for String {
fn serialize(
&self,
_record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
serializer.emit_str(key, self.as_str())
}
}
impl<T: Value> Value for Option<T> {
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
match *self {
Some(ref s) => s.serialize(record, key, serializer),
None => serializer.emit_none(key),
}
}
}
impl<T> Value for Box<T>
where
T: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for Arc<T>
where
T: Value + ?Sized,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for Rc<T>
where
T: Value,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, key, serializer)
}
}
impl<T> Value for core::num::Wrapping<T>
where
T: Value,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, key, serializer)
}
}
impl<'a> Value for std::path::Display<'a>
{
fn serialize(&self,
_record: &Record,
key: Key,
serializer: &mut Serializer)
-> Result {
serializer.emit_arguments(key, &format_args!("{}", *self))
}
}
/// Explicit lazy-closure `Value`
pub struct FnValue<V: Value, F>(pub F)
where
F: for<'c, 'd> Fn(&'c Record<'d>) -> V;
impl<'a, V: 'a + Value, F> Value for FnValue<V, F>
where
F: 'a + for<'c, 'd> Fn(&'c Record<'d>) -> V,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
(self.0)(record).serialize(record, key, serializer)
}
}
#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Old name of `PushFnValueSerializer`
pub type PushFnSerializer<'a> = PushFnValueSerializer<'a>;
/// Handle passed to `PushFnValue` closure
///
/// It makes sure only one value is serialized, and will automatically emit
/// `()` if nothing else was serialized.
pub struct PushFnValueSerializer<'a> {
record: &'a Record<'a>,
key: Key,
serializer: &'a mut Serializer,
done: bool,
}
impl<'a> PushFnValueSerializer<'a> {
#[deprecated(note = "Renamed to `emit`")]
/// Emit a value
pub fn serialize<'b, S: 'b + Value>(self, s: S) -> Result {
self.emit(s)
}
/// Emit a value
///
/// This consumes `self` to prevent serializing one value multiple times
pub fn emit<'b, S: 'b + Value>(mut self, s: S) -> Result {
self.done = true;
s.serialize(self.record, self.key, self.serializer)
}
}
impl<'a> Drop for PushFnValueSerializer<'a> {
fn drop(&mut self) {
if !self.done {
// unfortunately this gives no change to return serialization errors
let _ = self.serializer.emit_unit(self.key);
}
}
}
/// Lazy `Value` that writes to Serializer
///
/// It's more ergonomic for closures used as lazy values to return type
/// implementing `Serialize`, but sometimes that forces an allocation (eg.
/// `String`s)
///
/// In some cases it might make sense for another closure form to be used - one
/// taking a serializer as an argument, which avoids lifetimes / allocation
/// issues.
///
/// Generally this method should be used if it avoids a big allocation of
/// `Serialize`-implementing type in performance-critical logging statement.
///
/// ```
/// #[macro_use]
/// extern crate slog;
/// use slog::{PushFnValue, Logger, Discard};
///
/// fn main() {
/// // Create a logger with a key-value printing
/// // `file:line` string value for every logging statement.
/// // `Discard` `Drain` used for brevity.
/// let root = Logger::root(Discard, o!(
/// "source_location" => PushFnValue(|record , s| {
/// s.serialize(
/// format_args!(
/// "{}:{}",
/// record.file(),
/// record.line(),
/// )
/// )
/// })
/// ));
/// }
/// ```
pub struct PushFnValue<F>(pub F)
where
F: 'static + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result;
impl<F> Value for PushFnValue<F>
where
F: 'static + for<'c, 'd> Fn(&'c Record<'d>, PushFnValueSerializer<'c>) -> Result,
{
fn serialize(
&self,
record: &Record,
key: Key,
serializer: &mut Serializer,
) -> Result {
let ser = PushFnValueSerializer {
record: record,
key: key,
serializer: serializer,
done: false,
};
(self.0)(record, ser)
}
}
// }}}
// {{{ KV
/// Key-value pair(s)
///
/// Zero, one or more key value pairs chained together
///
/// Any logging data must implement this trait for
/// slog to be able to use it.
///
/// Types implementing this trait can emit multiple key-value pairs. The order
/// of emitting them should be consistent with the way key-value pair hierarchy
/// is traversed: from data most specific to the logging context to the most
/// general one. Or in other words: from newest to oldest.
pub trait KV {
/// Serialize self into `Serializer`
///
/// `KV` should call respective `Serializer` methods
/// for each key-value pair it contains.
fn serialize(&self, record: &Record, serializer: &mut Serializer)
-> Result;
}
impl<'a, T> KV for &'a T
where
T: KV,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
#[cfg(feature = "std")]
/// Thread-local safety bound for `KV`
///
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync + RefUnwindSafe {}
#[cfg(feature = "std")]
impl<T> SendSyncRefUnwindSafeKV for T
where
T: KV + Send + Sync + RefUnwindSafe + ?Sized,
{
}
#[cfg(not(feature = "std"))]
/// This type is used to enforce `KV`s stored in `Logger`s are thread-safe.
pub trait SendSyncRefUnwindSafeKV: KV + Send + Sync {}
#[cfg(not(feature = "std"))]
impl<T> SendSyncRefUnwindSafeKV for T
where
T: KV + Send + Sync + ?Sized,
{
}
/// Single pair `Key` and `Value`
pub struct SingleKV<V>(pub Key, pub V)
where
V: Value;
impl<V> KV for SingleKV<V>
where
V: Value,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.1.serialize(record, self.0, serializer)
}
}
impl KV for () {
fn serialize(
&self,
_record: &Record,
_serializer: &mut Serializer,
) -> Result {
Ok(())
}
}
impl<T: KV, R: KV> KV for (T, R) {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.0.serialize(record, serializer));
self.1.serialize(record, serializer)
}
}
impl<T> KV for Box<T>
where
T: KV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
impl<T> KV for Arc<T>
where
T: KV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
(**self).serialize(record, serializer)
}
}
impl<T> KV for OwnedKV<T>
where
T: SendSyncRefUnwindSafeKV + ?Sized,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, serializer)
}
}
impl<'a> KV for BorrowedKV<'a> {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
self.0.serialize(record, serializer)
}
}
// }}}
// {{{ OwnedKV
/// Owned KV
///
/// "Owned" means that the contained data (key-value pairs) can belong
/// to a `Logger` and thus must be thread-safe (`'static`, `Send`, `Sync`)
///
/// Zero, one or more owned key-value pairs.
///
/// Can be constructed with [`o!` macro](macro.o.html).
pub struct OwnedKV<T>(
#[doc(hidden)]
/// The exact details of that it are not considered public
/// and stable API. `slog_o` or `o` macro should be used
/// instead to create `OwnedKV` instances.
pub T,
)
where
T: SendSyncRefUnwindSafeKV + ?Sized;
// }}}
// {{{ BorrowedKV
/// Borrowed `KV`
///
/// "Borrowed" means that the data is only a temporary
/// referenced (`&T`) and can't be stored directly.
///
/// Zero, one or more borrowed key-value pairs.
///
/// Can be constructed with [`b!` macro](macro.b.html).
pub struct BorrowedKV<'a>(
/// The exact details of it function are not
/// considered public and stable API. `log` and other
/// macros should be used instead to create
/// `BorrowedKV` instances.
#[doc(hidden)]
pub &'a KV,
);
// }}}
// {{{ OwnedKVList
struct OwnedKVListNode<T>
where
T: SendSyncRefUnwindSafeKV + 'static,
{
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
kv: T,
}
struct MultiListNode {
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}
/// Chain of `SyncMultiSerialize`-s of a `Logger` and its ancestors
#[derive(Clone)]
pub struct OwnedKVList {
node: Arc<SendSyncRefUnwindSafeKV + 'static>,
}
impl<T> KV for OwnedKVListNode<T>
where
T: SendSyncRefUnwindSafeKV + 'static,
{
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.kv.serialize(record, serializer));
try!(self.next_node.serialize(record, serializer));
Ok(())
}
}
impl KV for MultiListNode {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.next_node.serialize(record, serializer));
try!(self.node.serialize(record, serializer));
Ok(())
}
}
impl KV for OwnedKVList {
fn serialize(
&self,
record: &Record,
serializer: &mut Serializer,
) -> Result {
try!(self.node.serialize(record, serializer));
Ok(())
}
}
impl fmt::Debug for OwnedKVList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "("));
let mut i = 0;
{
let mut as_str_ser = AsFmtSerializer(|key, _val| {
if i != 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", key));
i += 1;
Ok(())
});
let record_static = record_static!(Level::Trace, "");
try!(
self.node
.serialize(
&Record::new(
&record_static,
&format_args!(""),
BorrowedKV(&STATIC_TERMINATOR_UNIT)
),
&mut as_str_ser
)
.map_err(|_| fmt::Error)
);
}
try!(write!(f, ")"));
Ok(())
}
}
impl OwnedKVList {
/// New `OwnedKVList` node without a parent (root)
fn root<T>(values: OwnedKV<T>) -> Self
where
T: SendSyncRefUnwindSafeKV + 'static,
{
OwnedKVList {
node: Arc::new(OwnedKVListNode {
next_node: Arc::new(()),
kv: values.0,
}),
}
}
/// New `OwnedKVList` node with an existing parent
fn new<T>(
values: OwnedKV<T>,
next_node: Arc<SendSyncRefUnwindSafeKV + 'static>,
) -> Self
where
T: SendSyncRefUnwindSafeKV + 'static,
{
OwnedKVList {
node: Arc::new(OwnedKVListNode {
next_node: next_node,
kv: values.0,
}),
}
}
}
impl<T> convert::From<OwnedKV<T>> for OwnedKVList
where
T: SendSyncRefUnwindSafeKV + 'static,
{
fn from(from: OwnedKV<T>) -> Self {
OwnedKVList::root(from)
}
}
// }}}
// {{{ Error
#[derive(Debug)]
#[cfg(feature = "std")]
/// Serialization Error
pub enum Error {
/// `io::Error` (not available in ![no_std] mode)
Io(std::io::Error),
/// `fmt::Error`
Fmt(std::fmt::Error),
/// Other error
Other,
}
#[derive(Debug)]
#[cfg(not(feature = "std"))]
/// Serialization Error
pub enum Error {
/// `fmt::Error`
Fmt(core::fmt::Error),
/// Other error
Other,
}
/// Serialization `Result`
pub type Result<T = ()> = result::Result<T, Error>;
#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
Error::Io(err)
}
}
impl From<core::fmt::Error> for Error {
fn from(_: core::fmt::Error) -> Error {
Error::Other
}
}
#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
fn from(e: Error) -> std::io::Error {
match e {
Error::Io(e) => e,
Error::Fmt(_) => std::io::Error::new(
std::io::ErrorKind::Other,
"formatting error",
),
Error::Other => {
std::io::Error::new(std::io::ErrorKind::Other, "other error")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Io(ref e) => e.description(),
Error::Fmt(_) => "formatting error",
Error::Other => "serialization error",
}
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
Error::Io(ref e) => Some(e),
Error::Fmt(ref e) => Some(e),
Error::Other => None,
}
}
}
#[cfg(feature = "std")]
impl core::fmt::Display for Error {
fn fmt(&self, fmt: &mut core::fmt::Formatter) -> std::fmt::Result {
match *self {
Error::Io(ref e) => e.fmt(fmt),
Error::Fmt(ref e) => e.fmt(fmt),
Error::Other => fmt.write_str("Other serialization error"),
}
}
}
// }}}
// {{{ Misc
/// This type is here just to abstract away lack of `!` type support in stable
/// rust during time of the release. It will be switched to `!` at some point
/// and `Never` should not be considered "stable" API.
#[doc(hidden)]
pub type Never = private::NeverStruct;
mod private {
#[doc(hidden)]
#[derive(Debug)]
pub struct NeverStruct(());
}
/// This is not part of "stable" API
#[doc(hidden)]
pub static STATIC_TERMINATOR_UNIT: () = ();
#[allow(unknown_lints)]
#[allow(inline_always)]
#[inline(always)]
#[doc(hidden)]
/// Not an API
///
/// Generally it's a bad idea to depend on static logging level
/// in your code. Use closures to perform operations lazily
/// only when logging actually takes place.
pub fn __slog_static_max_level() -> FilterLevel {
if !cfg!(debug_assertions) {
if cfg!(feature = "release_max_level_off") {
return FilterLevel::Off;
} else if cfg!(feature = "release_max_level_error") {
return FilterLevel::Error;
} else if cfg!(feature = "release_max_level_warn") {
return FilterLevel::Warning;
} else if cfg!(feature = "release_max_level_info") {
return FilterLevel::Info;
} else if cfg!(feature = "release_max_level_debug") {
return FilterLevel::Debug;
} else if cfg!(feature = "release_max_level_trace") {
return FilterLevel::Trace;
}
}
if cfg!(feature = "max_level_off") {
FilterLevel::Off
} else if cfg!(feature = "max_level_error") {
FilterLevel::Error
} else if cfg!(feature = "max_level_warn") {
FilterLevel::Warning
} else if cfg!(feature = "max_level_info") {
FilterLevel::Info
} else if cfg!(feature = "max_level_debug") {
FilterLevel::Debug
} else if cfg!(feature = "max_level_trace") {
FilterLevel::Trace
} else {
if !cfg!(debug_assertions) {
FilterLevel::Info
} else {
FilterLevel::Debug
}
}
}
// }}}
// {{{ Slog v1 Compat
#[deprecated(note = "Renamed to `Value`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type Serialize = Value;
#[deprecated(note = "Renamed to `PushFnValue`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type PushLazy<T> = PushFnValue<T>;
#[deprecated(note = "Renamed to `PushFnValueSerializer`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type ValueSerializer<'a> = PushFnValueSerializer<'a>;
#[deprecated(note = "Renamed to `OwnedKVList`")]
/// Compatibility name to ease upgrading from `slog v1`
pub type OwnedKeyValueList = OwnedKVList;
#[deprecated(note = "Content of ser module moved to main namespace")]
/// Compatibility name to ease upgrading from `slog v1`
pub mod ser {
#[allow(deprecated)]
pub use super::{OwnedKeyValueList, PushLazy, Serialize, Serializer,
ValueSerializer};
}
// }}}
// {{{ Test
#[cfg(test)]
mod tests;
// }}}
// vim: foldmethod=marker foldmarker={{{,}}}
|
pub fn xor(source: &[u8], key: &[u8]) -> Vec<u8> {
if source.len() == 0 {
return Vec::new();
}
if key.len() == 0 {
return source.to_vec();
}
let key_iter = InfiniteByteIterator::new(key);
source.iter().zip(key_iter).map(|(&a, b)| a ^ b).collect()
}
struct InfiniteByteIterator {
bytes: Vec<u8>,
index: uint
}
impl InfiniteByteIterator {
pub fn new(bytes: &[u8]) -> InfiniteByteIterator {
InfiniteByteIterator {
bytes: bytes.to_vec(),
index: 0
}
}
}
impl Iterator<u8> for InfiniteByteIterator {
fn next(&mut self) -> Option<u8> {
let byte = self.bytes[self.index];
self.index = next_index(self.index, self.bytes.len());
Some(byte)
}
}
fn next_index(current: uint, count: uint) -> uint {
let index = current + 1;
if index < count {
index
} else {
0
}
}
#[cfg(test)]
mod test {
use super::xor;
#[test]
fn test_len() {
let source = [0, 1, 2, 3];
let key = [34, 52];
assert!(xor(source, key).len() == source.len());
}
#[test]
fn test_result() {
let source = [0, 1, 2, 3];
let key = [34, 52];
assert!(xor(source, key) == vec![34, 53, 32, 55]);
}
#[test]
fn test_with_empty_key() {
let source = [0, 1, 2, 3];
let key = [];
assert!(xor(source, key) == vec![0, 1, 2, 3]);
}
#[test]
fn test_with_empty_source() {
let source = [];
let key = [45, 32, 56];
assert!(xor(source, key) == vec![]);
}
}
Removed unneeded test.
pub fn xor(source: &[u8], key: &[u8]) -> Vec<u8> {
if source.len() == 0 {
return Vec::new();
}
if key.len() == 0 {
return source.to_vec();
}
let key_iter = InfiniteByteIterator::new(key);
source.iter().zip(key_iter).map(|(&a, b)| a ^ b).collect()
}
struct InfiniteByteIterator {
bytes: Vec<u8>,
index: uint
}
impl InfiniteByteIterator {
pub fn new(bytes: &[u8]) -> InfiniteByteIterator {
InfiniteByteIterator {
bytes: bytes.to_vec(),
index: 0
}
}
}
impl Iterator<u8> for InfiniteByteIterator {
fn next(&mut self) -> Option<u8> {
let byte = self.bytes[self.index];
self.index = next_index(self.index, self.bytes.len());
Some(byte)
}
}
fn next_index(current: uint, count: uint) -> uint {
let index = current + 1;
if index < count {
index
} else {
0
}
}
#[cfg(test)]
mod test {
use super::xor;
#[test]
fn test_result() {
let source = [0, 1, 2, 3];
let key = [34, 52];
assert!(xor(source, key) == vec![34, 53, 32, 55]);
}
#[test]
fn test_with_empty_key() {
let source = [0, 1, 2, 3];
let key = [];
assert!(xor(source, key) == vec![0, 1, 2, 3]);
}
#[test]
fn test_with_empty_source() {
let source = [];
let key = [45, 32, 56];
assert!(xor(source, key) == vec![]);
}
}
|
//! **cobalt** is a networking library which provides [virtual connections
//! over UDP](http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/)
//! along with a messaging layer for sending both unreliable, reliable as well
//! as ordered messages.
//!
//! It is primarily designed to be used as the basis for real-time, latency
//! bound, multi client systems.
//!
//! The library provides the underlying architecture required for handling and
//! maintaining virtual connections over UDP sockets and takes care of sending
//! reliable, raw messages over the established client-server connections with
//! minimal overhead.
//!
//! cobalt is also fully configurable and can be plugged in a variety of ways,
//! so that library users have the largest possible degree of control over
//! the behavior of their connections.
//!
//! ## Getting started
//!
//! When working with **cobalt** the most important part is implementing the so
//! called handlers. A `Handler` is a trait which acts as a event proxy for
//! both server and client events that are emitted from the underlying tick
//! loop.
//!
//! Below follows a very basic example implementation of a custom game server.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, ConnectionID, Handler, Server};
//!
//! struct GameServer;
//! impl Handler<Server> for GameServer {
//!
//! fn bind(&mut self, server: &mut Server) {
//! // Since this is a runnable doc, we'll just exit right away
//! server.shutdown();
//! }
//!
//! fn tick_connections(
//! &mut self, _: &mut Server,
//! connections: &mut HashMap<ConnectionID, Connection>
//! ) {
//!
//! for (_, conn) in connections.iter_mut() {
//! // Receive player input
//! }
//!
//! // Advance game state
//!
//! for (_, conn) in connections.iter_mut() {
//! // Send state to players
//! }
//!
//! }
//!
//! fn shutdown(&mut self, _: &mut Server) {
//! // Logging and things
//! }
//!
//! fn connection(&mut self, _: &mut Server, _: &mut Connection) {
//! // Create Player, send MOTD etc.
//! }
//!
//! fn connection_lost(&mut self, _: &mut Server, _: &mut Connection) {
//! // Remove Player
//! }
//!
//! }
//!
//! let mut handler = GameServer;
//! let mut server = Server::new(Config::default());
//! server.bind(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! And the client version would look almost identical except for a few methods
//! having different names.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, Handler, Client};
//!
//! struct GameClient;
//! impl Handler<Client> for GameClient {
//!
//! fn connect(&mut self, client: &mut Client) {
//! // Since this is a runnable doc, we'll just exit right away
//! client.close();
//! }
//!
//! fn tick_connection(&mut self, _: &mut Client, conn: &mut Connection) {
//!
//! for msg in conn.received() {
//! // Receive state from server
//! }
//!
//! // Advance game state
//!
//! // Send input to server
//!
//! }
//!
//! fn close(&mut self, _: &mut Client) {
//! // Exit game
//! }
//!
//! fn connection(&mut self, _: &mut Client, _: &mut Connection) {
//! // Request map list and settings from server
//! }
//!
//! fn connection_failed(&mut self, client: &mut Client, _: &mut Connection) {
//! // Failed to connect to the server
//! }
//!
//! fn connection_lost(&mut self, client: &mut Client, _: &mut Connection) {
//! // Inform the user
//! }
//!
//! }
//!
//! let mut handler = GameClient;
//! let mut client = Client::new(Config::default());
//! client.connect(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
#![deny(
missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications
)]
mod client;
mod server;
mod shared {
pub mod binary_rate_limiter;
pub mod config;
pub mod connection;
pub mod message_queue;
pub mod udp_socket;
pub mod stats;
}
mod traits {
pub mod handler;
pub mod rate_limiter;
pub mod socket;
}
#[doc(inline)]
pub use shared::config::Config;
#[doc(inline)]
pub use shared::connection::{Connection, ConnectionID, ConnectionState};
#[doc(inline)]
pub use shared::message_queue::MessageKind;
#[doc(inline)]
pub use shared::binary_rate_limiter::BinaryRateLimiter;
#[doc(inline)]
pub use shared::udp_socket::UdpSocket;
#[doc(inline)]
pub use shared::stats::Stats;
#[doc(inline)]
pub use traits::handler::Handler;
#[doc(inline)]
pub use traits::rate_limiter::RateLimiter;
#[doc(inline)]
pub use traits::socket::Socket;
#[doc(inline)]
pub use client::Client;
#[doc(inline)]
pub use client::ClientState;
#[doc(inline)]
pub use server::Server;
#[cfg(test)]
mod tests {
mod client;
mod connection;
mod message_queue;
mod server;
}
Add initial top level documentation on synchronized client apis.
//! **cobalt** is a networking library which provides [virtual connections
//! over UDP](http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/)
//! along with a messaging layer for sending both unreliable, reliable as well
//! as ordered messages.
//!
//! It is primarily designed to be used as the basis for real-time, latency
//! bound, multi client systems.
//!
//! The library provides the underlying architecture required for handling and
//! maintaining virtual connections over UDP sockets and takes care of sending
//! reliable, raw messages over the established client-server connections with
//! minimal overhead.
//!
//! cobalt is also fully configurable and can be plugged in a variety of ways,
//! so that library users have the largest possible degree of control over
//! the behavior of their connections.
//!
//! ## Getting started
//!
//! When working with **cobalt** the most important part is implementing the so
//! called handlers. A `Handler` is a trait which acts as a event proxy for
//! both server and client events that are emitted from the underlying tick
//! loop.
//!
//! Below follows a very basic example implementation of a custom game server.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, ConnectionID, Handler, Server};
//!
//! struct GameServer;
//! impl Handler<Server> for GameServer {
//!
//! fn bind(&mut self, server: &mut Server) {
//! // Since this is a runnable doc, we'll just exit right away
//! server.shutdown();
//! }
//!
//! fn tick_connections(
//! &mut self, _: &mut Server,
//! connections: &mut HashMap<ConnectionID, Connection>
//! ) {
//!
//! for (_, conn) in connections.iter_mut() {
//! // Receive player input
//! }
//!
//! // Advance game state
//!
//! for (_, conn) in connections.iter_mut() {
//! // Send state to players
//! }
//!
//! }
//!
//! fn shutdown(&mut self, _: &mut Server) {
//! // Logging and things
//! }
//!
//! fn connection(&mut self, _: &mut Server, _: &mut Connection) {
//! // Create Player, send MOTD etc.
//! }
//!
//! fn connection_lost(&mut self, _: &mut Server, _: &mut Connection) {
//! // Remove Player
//! }
//!
//! }
//!
//! let mut handler = GameServer;
//! let mut server = Server::new(Config::default());
//! server.bind(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! And the client version would look almost identical except for a few methods
//! having different names.
//!
//! ```
//! use std::collections::HashMap;
//! use cobalt::{Config, Connection, Handler, Client};
//!
//! struct GameClient;
//! impl Handler<Client> for GameClient {
//!
//! fn connect(&mut self, client: &mut Client) {
//! // Since this is a runnable doc, we'll just exit right away
//! client.close();
//! }
//!
//! fn tick_connection(&mut self, _: &mut Client, conn: &mut Connection) {
//!
//! for msg in conn.received() {
//! // Receive state from server
//! }
//!
//! // Advance game state
//!
//! // Send input to server
//!
//! }
//!
//! fn close(&mut self, _: &mut Client) {
//! // Exit game
//! }
//!
//! fn connection(&mut self, _: &mut Client, _: &mut Connection) {
//! // Request map list and settings from server
//! }
//!
//! fn connection_failed(&mut self, client: &mut Client, _: &mut Connection) {
//! // Failed to connect to the server
//! }
//!
//! fn connection_lost(&mut self, client: &mut Client, _: &mut Connection) {
//! // Inform the user
//! }
//!
//! }
//!
//! let mut handler = GameClient;
//! let mut client = Client::new(Config::default());
//! client.connect(&mut handler, "127.0.0.1:7156").unwrap();
//! ```
//!
//! ## Integration with existing event loops
//!
//! When a client already provides its own event loop via a rendering framework
//! or game engine, a **synchronous** version of the `Client` interface is also
//! available in order to ease integration in such cases.
//!
//! In these cases it can also make sense to use a `EventQueue` like
//! implementation of the `Handler` trait.
//!
//! ```
//! use cobalt::{Client, Config, Connection, ConnectionID, Handler};
//!
//! struct SyncHandler;
//! impl Handler<Client> for SyncHandler {}
//!
//! let mut handler = SyncHandler;
//! let mut client = Client::new(Config::default());
//! let mut state = client.connect_sync(&mut handler, "127.0.0.1:7156").unwrap();
//!
//! // Receive from and tick the client connection
//! client.receive_sync(&mut handler, &mut state);
//! client.tick_sync(&mut handler, &mut state);
//!
//! // Handle received message and send new ones here
//!
//! // Send any pending messages via the connection
//! client.send_sync(&mut handler, &mut state);
//! ```
#![deny(
missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications
)]
mod client;
mod server;
mod shared {
pub mod binary_rate_limiter;
pub mod config;
pub mod connection;
pub mod message_queue;
pub mod udp_socket;
pub mod stats;
}
mod traits {
pub mod handler;
pub mod rate_limiter;
pub mod socket;
}
#[doc(inline)]
pub use shared::config::Config;
#[doc(inline)]
pub use shared::connection::{Connection, ConnectionID, ConnectionState};
#[doc(inline)]
pub use shared::message_queue::MessageKind;
#[doc(inline)]
pub use shared::binary_rate_limiter::BinaryRateLimiter;
#[doc(inline)]
pub use shared::udp_socket::UdpSocket;
#[doc(inline)]
pub use shared::stats::Stats;
#[doc(inline)]
pub use traits::handler::Handler;
#[doc(inline)]
pub use traits::rate_limiter::RateLimiter;
#[doc(inline)]
pub use traits::socket::Socket;
#[doc(inline)]
pub use client::Client;
#[doc(inline)]
pub use client::ClientState;
#[doc(inline)]
pub use server::Server;
#[cfg(test)]
mod tests {
mod client;
mod connection;
mod message_queue;
mod server;
}
|
#![warn(missing_docs)]
#![feature(slice_patterns)]
//! rebind
//! =========
//!
//! A library for binding input keys to actions, and modifying mouse behaviour. Keys can be
//! bound to actions, and then translated during runtime. `Keys` are mapped to `Actions` using
//! a `HashMap`, so lookup time is constant.
extern crate input;
extern crate itertools;
extern crate window;
extern crate rustc_serialize;
extern crate viewport;
mod builder;
#[cfg(test)]
mod test;
use input::{Input, Button, Motion};
use itertools::Itertools;
use window::Size;
use std::collections::HashMap;
use std::default::Default;
use std::cmp::{PartialEq, Eq, Ord};
use std::fmt::{Debug, Formatter, Result};
use std::hash::Hash;
use viewport::Viewport;
pub use builder::RebindBuilder;
/// Represents a logical action to be bound to a particular button press, e.g.
/// jump, attack, or move forward. Needs to be hashable, as it is used as a
/// lookup key when rebinding an action to a different button.
pub trait Action: Copy + Eq + Hash + Ord { }
/// A translated action.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Translated<A: Action> {
/// A keypress event which was bound to an action
Press(A),
/// A key release event which was bound to an action
Release(A),
/// A translated mouse motion. The logical origin of a translated MouseCursor event
/// is in the top left corner of the window, and the logical scroll is non-natural.
/// Relative events are unchanged for now.
Move(Motion)
}
/// A three-element tuple of Option<Button>. For simplicity, a maximum number of 3
/// buttons can be bound to each action, and this is exposed through the `InputRebind`
/// struct.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ButtonTuple(pub Option<Button>, pub Option<Button>, pub Option<Button>);
impl ButtonTuple {
/// Creates a new tuple with no buttons in it (equivalent to `Default::default()`).
pub fn new() -> Self { Default::default() }
/// Check if the button is in the tuple.
pub fn contains(&self, button: Button) -> bool {
let sbtn = Some(button);
self.0 == sbtn || self.1 == sbtn || self.2 == sbtn
}
/// Insert a button into the tuple if there is room, searching from left to right.
/// If the button is inserted, returns true. Otherwise, if the button is not inserted,
/// this function returns false.
pub fn insert_inplace(&mut self, button: Button) -> bool {
let sbtn = Some(button);
match self {
&mut ButtonTuple(a, b, c) if a.is_none() => {*self = ButtonTuple(sbtn, b, c); true},
&mut ButtonTuple(a, b, c) if b.is_none() => {*self = ButtonTuple(a, sbtn, c); true},
&mut ButtonTuple(a, b, c) if c.is_none() => {*self = ButtonTuple(a, b, sbtn); true}
_ => false
}
}
/// Returns an iterator over this tuple.
pub fn iter(&self) -> ButtonTupleIter { (*self).into_iter() }
}
impl Default for ButtonTuple {
/// Creates a new tuple with no buttons in it.
fn default() -> Self { ButtonTuple(None, None, None) }
}
impl IntoIterator for ButtonTuple {
type Item = Option<Button>;
type IntoIter = ButtonTupleIter;
fn into_iter(self) -> Self::IntoIter {
ButtonTupleIter {
button_tuple: self,
i: 0
}
}
}
/// An iterator over a ButtonTuple.
pub struct ButtonTupleIter {
button_tuple: ButtonTuple,
i: usize
}
impl Iterator for ButtonTupleIter {
type Item = Option<Button>;
fn next(&mut self) -> Option<Self::Item> {
let i = self.i;
self.i += 1;
match i {
0 => Some(self.button_tuple.0),
1 => Some(self.button_tuple.1),
2 => Some(self.button_tuple.2),
_ => None
}
}
}
/// An object which translates piston::input::Input events into input_map::Translated<A> events
#[derive(Clone, Debug, PartialEq)]
pub struct InputTranslator<A: Action> {
keymap: HashMap<Button, A>,
mouse_translator: MouseTranslator
}
impl<A: Action> InputTranslator<A> {
/// Creates an empty InputTranslator.
pub fn new(size: Size) -> Self {
InputTranslator {
keymap: HashMap::new(),
mouse_translator: MouseTranslator::new(size)
}
}
/// Translate an Input into a Translated<A> event. Returns `None` if there is no
/// action associated with the `Input` variant.
pub fn translate(&self, input: &Input) -> Option<Translated<A>> {
macro_rules! translate_button(($but_state:ident, $but_var:ident) => (
match self.keymap.get(&$but_var).cloned() {
Some(act) => Some(Translated::$but_state(act)),
None => None
});
);
match input {
&Input::Press(button) => translate_button!(Press, button),
&Input::Release(button) => translate_button!(Release, button),
&Input::Move(motion) =>
Some(Translated::Move(self.mouse_translator.translate(motion))),
_ => None
}
}
/// Re-set the mouse bounds size used for calculating mouse events
pub fn set_size(&mut self, size: Size) {
self.mouse_translator.data.viewport_size = size
}
/// Re-set the mouse bounds size from a viewport
pub fn set_size_from_viewport(&mut self, vp: Viewport) {
self.set_size(Size::from(vp.draw_size));
}
}
#[derive(Clone)]
struct MouseTranslationData {
x_axis_motion_inverted: bool,
y_axis_motion_inverted: bool,
x_axis_scroll_inverted: bool,
y_axis_scroll_inverted: bool,
_sensitivity: f64,
viewport_size: Size
}
impl MouseTranslationData {
fn new(size: Size) -> Self {
MouseTranslationData {
x_axis_motion_inverted: false,
y_axis_motion_inverted: false,
x_axis_scroll_inverted: false,
y_axis_scroll_inverted: false,
_sensitivity: 0.0,
viewport_size: size
}
}
}
impl Debug for MouseTranslationData {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}, {}, {}, {}, {}, ({}, {})",
self.x_axis_motion_inverted,
self.y_axis_motion_inverted,
self.x_axis_scroll_inverted,
self.y_axis_scroll_inverted,
self._sensitivity,
self.viewport_size.width,
self.viewport_size.height)
}
}
impl PartialEq for MouseTranslationData {
fn eq(&self, other: &Self) -> bool {
self.x_axis_motion_inverted == other.x_axis_motion_inverted &&
self.y_axis_motion_inverted == other.y_axis_motion_inverted &&
self.x_axis_scroll_inverted == other.x_axis_scroll_inverted &&
self.y_axis_scroll_inverted == other.y_axis_scroll_inverted &&
self._sensitivity == other._sensitivity &&
self.viewport_size.width == other.viewport_size.width &&
self.viewport_size.height == other.viewport_size.height
}
}
#[derive(Clone, Debug, PartialEq)]
struct MouseTranslator {
data: MouseTranslationData
}
impl MouseTranslator {
fn new(size: Size) -> Self {
MouseTranslator {
data: MouseTranslationData::new(size)
}
}
fn translate(&self, motion: Motion) -> Motion {
match motion {
Motion::MouseCursor(x, y) => {
let (sw, sh) = {
let Size {width, height} = self.data.viewport_size;
(width as f64, height as f64)
};
let cx = if self.data.x_axis_motion_inverted { sw - x } else { x };
let cy = if self.data.y_axis_motion_inverted { sh - y } else { y };
Motion::MouseCursor(cx, cy)
},
Motion::MouseScroll(x, y) => {
let mx = if self.data.x_axis_scroll_inverted { -1.0f64 } else { 1.0 };
let my = if self.data.y_axis_scroll_inverted { -1.0f64 } else { 1.0 };
Motion::MouseScroll(x * mx, y * my)
},
relative => relative
}
}
}
/// An interface for rebinding keys to actions. This is freely convertable to and
/// from an InputTranslator.
#[derive(Clone, Debug, PartialEq)]
pub struct InputRebind<A: Action> {
keymap: HashMap<A, ButtonTuple>,
mouse_data: MouseTranslationData
}
impl<A: Action> InputRebind<A> {
/// Creates a new InputRebind with no stored Action/ButtonTuple pairs.
pub fn new(size: Size) -> Self {
InputRebind {
keymap: HashMap::new(),
mouse_data: MouseTranslationData::new(size)
}
}
/// Insert an Action into this InputRebind. If the Action is already in the
/// InputRebind, then its ButtonTuple will be reset to (None, None, None), and
/// the old ButtonTuple will be returned.
pub fn insert_action(&mut self, action: A) -> Option<ButtonTuple> {
self.keymap.insert(action, ButtonTuple::new())
}
/// Insert an Action into this InputRebind, and assign it to the ButtonTuple.
/// If the Action is already in the InputRebind, the old ButtonTuple will be
/// returned.
pub fn insert_action_with_buttons(&mut self, action: A, buttons: ButtonTuple) -> Option<ButtonTuple> {
self.keymap.insert(action, buttons)
}
/// Return a reference to the current ButtonTuple stored for an action. If the action
/// is not stored in this InputRebind, then `None` will be returned.
pub fn get_bindings(&self, action: &A) -> Option<&ButtonTuple> {
self.keymap.get(action)
}
/// Returns a mutable reference to the current ButtonTuple stored for an action. If the
/// action is not stored in this InputRebind, then `None` will be returned.
pub fn get_bindings_mut(&mut self, action: &mut A) -> Option<&mut ButtonTuple> {
self.keymap.get_mut(action)
}
/// Returns a reference to the boolean which represents whether x axis scrolling is inverted.
pub fn get_x_scroll_inverted(&self) -> &bool {
&self.mouse_data.x_axis_scroll_inverted
}
/// Returns a mutable reference to the boolean which represents whether x axis scrolling is inverted.
pub fn get_x_scroll_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.x_axis_scroll_inverted
}
/// Returns a reference to the boolean which represents whether y axis scrolling is inverted.
pub fn get_y_scroll_inverted(&self) -> &bool {
&self.mouse_data.y_axis_scroll_inverted
}
/// Returns a mutable reference to the boolean which represents whether y axis scrolling is inverted.
pub fn get_y_scroll_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.y_axis_scroll_inverted
}
/// Returns a reference to the boolean which represents whether mouse movement along the x axis is
/// inverted.
pub fn get_x_motion_inverted(&self) -> &bool {
&self.mouse_data.x_axis_motion_inverted
}
/// Returns a mutable reference to the boolean which represents whether mouse movement along the
/// x axis is inverted.
pub fn get_x_motion_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.x_axis_motion_inverted
}
/// Returns a reference to the boolean which represents whether mouse movement along the y axis is
/// inverted.
pub fn get_y_motion_inverted(&self) -> &bool {
&self.mouse_data.y_axis_motion_inverted
}
/// Returns a mutable reference to the boolean which represents whether mouse movement along the
/// y axis is inverted.
pub fn get_y_motion_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.y_axis_motion_inverted
}
/// Returns a reference to the currently stored viewport size used for calculating the imaginary mouse
/// position.
pub fn get_viewport_size(&self) -> &Size {
&self.mouse_data.viewport_size
}
/// Returns a mutable reference to the currently stored viewport size used for calculating the imaginary
/// mouse position.
pub fn get_viewport_size_mut(&mut self) -> &mut Size {
&mut self.mouse_data.viewport_size
}
}
impl<A: Action> Default for InputRebind<A> {
/// Creates an `InputRebind` with no pairs. In addition, the viewport size is set to [800, 600].
fn default() -> Self {
InputRebind::new((800, 600).into())
}
}
impl<A: Action> Into<InputTranslator<A>> for InputRebind<A> {
fn into(self) -> InputTranslator<A> {
let mut input_translator = InputTranslator::new(self.mouse_data.viewport_size);
input_translator.mouse_translator.data = self.mouse_data;
let key_vec = self.keymap.values()
.flat_map(|bt| bt.into_iter().filter_map(|x| x))
.collect::<Vec<_>>();
input_translator.keymap.reserve(key_vec.len());
for &k in &key_vec {
for (&a, bt) in self.keymap.iter() {
if bt.contains(k) {
input_translator.keymap.insert(k, a);
}
}
}
input_translator
}
}
impl<A: Action> Into<InputRebind<A>> for InputTranslator<A> {
fn into(self) -> InputRebind<A> {
let mut input_rebind = InputRebind::new(self.mouse_translator.data.viewport_size);
input_rebind.mouse_data = self.mouse_translator.data;
input_rebind.keymap = self.keymap.iter()
.map(|(k, v)| (*v, vec![Some(*k)]))
.sorted_by(|&(v0, _), &(v1, _)| Ord::cmp(&v0, &v1))
.into_iter()
.coalesce(|(k0, v0), (k1, v1)| if k0 == k1 {
Ok((k0, v0.into_iter().chain(v1).collect()))
} else {
Err(((k0, v0), (k1, v1)))
})
.map(|(k, v)| if let [b0, b1, b2] = &v.iter()
.cloned()
.pad_using(3, |_| None)
.take(3)
.collect::<Vec<_>>()[..] {
(k, ButtonTuple(b0, b1, b2))
} else {
unreachable!();
})
.collect();
input_rebind
}
}
Alphebetise imports
#![warn(missing_docs)]
#![feature(slice_patterns)]
//! rebind
//! =========
//!
//! A library for binding input keys to actions, and modifying mouse behaviour. Keys can be
//! bound to actions, and then translated during runtime. `Keys` are mapped to `Actions` using
//! a `HashMap`, so lookup time is constant.
extern crate input;
extern crate itertools;
extern crate rustc_serialize;
extern crate viewport;
extern crate window;
mod builder;
#[cfg(test)]
mod test;
use input::{Input, Button, Motion};
use itertools::Itertools;
use std::cmp::{PartialEq, Eq, Ord};
use std::collections::HashMap;
use std::default::Default;
use std::fmt::{Debug, Formatter, Result};
use std::hash::Hash;
use viewport::Viewport;
use window::Size;
pub use builder::RebindBuilder;
/// Represents a logical action to be bound to a particular button press, e.g.
/// jump, attack, or move forward. Needs to be hashable, as it is used as a
/// lookup key when rebinding an action to a different button.
pub trait Action: Copy + Eq + Hash + Ord { }
/// A translated action.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Translated<A: Action> {
/// A keypress event which was bound to an action
Press(A),
/// A key release event which was bound to an action
Release(A),
/// A translated mouse motion. The logical origin of a translated MouseCursor event
/// is in the top left corner of the window, and the logical scroll is non-natural.
/// Relative events are unchanged for now.
Move(Motion)
}
/// A three-element tuple of Option<Button>. For simplicity, a maximum number of 3
/// buttons can be bound to each action, and this is exposed through the `InputRebind`
/// struct.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ButtonTuple(pub Option<Button>, pub Option<Button>, pub Option<Button>);
impl ButtonTuple {
/// Creates a new tuple with no buttons in it (equivalent to `Default::default()`).
pub fn new() -> Self { Default::default() }
/// Check if the button is in the tuple.
pub fn contains(&self, button: Button) -> bool {
let sbtn = Some(button);
self.0 == sbtn || self.1 == sbtn || self.2 == sbtn
}
/// Insert a button into the tuple if there is room, searching from left to right.
/// If the button is inserted, returns true. Otherwise, if the button is not inserted,
/// this function returns false.
pub fn insert_inplace(&mut self, button: Button) -> bool {
let sbtn = Some(button);
match self {
&mut ButtonTuple(a, b, c) if a.is_none() => {*self = ButtonTuple(sbtn, b, c); true},
&mut ButtonTuple(a, b, c) if b.is_none() => {*self = ButtonTuple(a, sbtn, c); true},
&mut ButtonTuple(a, b, c) if c.is_none() => {*self = ButtonTuple(a, b, sbtn); true}
_ => false
}
}
/// Returns an iterator over this tuple.
pub fn iter(&self) -> ButtonTupleIter { (*self).into_iter() }
}
impl Default for ButtonTuple {
/// Creates a new tuple with no buttons in it.
fn default() -> Self { ButtonTuple(None, None, None) }
}
impl IntoIterator for ButtonTuple {
type Item = Option<Button>;
type IntoIter = ButtonTupleIter;
fn into_iter(self) -> Self::IntoIter {
ButtonTupleIter {
button_tuple: self,
i: 0
}
}
}
/// An iterator over a ButtonTuple.
pub struct ButtonTupleIter {
button_tuple: ButtonTuple,
i: usize
}
impl Iterator for ButtonTupleIter {
type Item = Option<Button>;
fn next(&mut self) -> Option<Self::Item> {
let i = self.i;
self.i += 1;
match i {
0 => Some(self.button_tuple.0),
1 => Some(self.button_tuple.1),
2 => Some(self.button_tuple.2),
_ => None
}
}
}
/// An object which translates piston::input::Input events into input_map::Translated<A> events
#[derive(Clone, Debug, PartialEq)]
pub struct InputTranslator<A: Action> {
keymap: HashMap<Button, A>,
mouse_translator: MouseTranslator
}
impl<A: Action> InputTranslator<A> {
/// Creates an empty InputTranslator.
pub fn new(size: Size) -> Self {
InputTranslator {
keymap: HashMap::new(),
mouse_translator: MouseTranslator::new(size)
}
}
/// Translate an Input into a Translated<A> event. Returns `None` if there is no
/// action associated with the `Input` variant.
pub fn translate(&self, input: &Input) -> Option<Translated<A>> {
macro_rules! translate_button(($but_state:ident, $but_var:ident) => (
match self.keymap.get(&$but_var).cloned() {
Some(act) => Some(Translated::$but_state(act)),
None => None
});
);
match input {
&Input::Press(button) => translate_button!(Press, button),
&Input::Release(button) => translate_button!(Release, button),
&Input::Move(motion) =>
Some(Translated::Move(self.mouse_translator.translate(motion))),
_ => None
}
}
/// Re-set the mouse bounds size used for calculating mouse events
pub fn set_size(&mut self, size: Size) {
self.mouse_translator.data.viewport_size = size
}
/// Re-set the mouse bounds size from a viewport
pub fn set_size_from_viewport(&mut self, vp: Viewport) {
self.set_size(Size::from(vp.draw_size));
}
}
#[derive(Clone)]
struct MouseTranslationData {
x_axis_motion_inverted: bool,
y_axis_motion_inverted: bool,
x_axis_scroll_inverted: bool,
y_axis_scroll_inverted: bool,
_sensitivity: f64,
viewport_size: Size
}
impl MouseTranslationData {
fn new(size: Size) -> Self {
MouseTranslationData {
x_axis_motion_inverted: false,
y_axis_motion_inverted: false,
x_axis_scroll_inverted: false,
y_axis_scroll_inverted: false,
_sensitivity: 0.0,
viewport_size: size
}
}
}
impl Debug for MouseTranslationData {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}, {}, {}, {}, {}, ({}, {})",
self.x_axis_motion_inverted,
self.y_axis_motion_inverted,
self.x_axis_scroll_inverted,
self.y_axis_scroll_inverted,
self._sensitivity,
self.viewport_size.width,
self.viewport_size.height)
}
}
impl PartialEq for MouseTranslationData {
fn eq(&self, other: &Self) -> bool {
self.x_axis_motion_inverted == other.x_axis_motion_inverted &&
self.y_axis_motion_inverted == other.y_axis_motion_inverted &&
self.x_axis_scroll_inverted == other.x_axis_scroll_inverted &&
self.y_axis_scroll_inverted == other.y_axis_scroll_inverted &&
self._sensitivity == other._sensitivity &&
self.viewport_size.width == other.viewport_size.width &&
self.viewport_size.height == other.viewport_size.height
}
}
#[derive(Clone, Debug, PartialEq)]
struct MouseTranslator {
data: MouseTranslationData
}
impl MouseTranslator {
fn new(size: Size) -> Self {
MouseTranslator {
data: MouseTranslationData::new(size)
}
}
fn translate(&self, motion: Motion) -> Motion {
match motion {
Motion::MouseCursor(x, y) => {
let (sw, sh) = {
let Size {width, height} = self.data.viewport_size;
(width as f64, height as f64)
};
let cx = if self.data.x_axis_motion_inverted { sw - x } else { x };
let cy = if self.data.y_axis_motion_inverted { sh - y } else { y };
Motion::MouseCursor(cx, cy)
},
Motion::MouseScroll(x, y) => {
let mx = if self.data.x_axis_scroll_inverted { -1.0f64 } else { 1.0 };
let my = if self.data.y_axis_scroll_inverted { -1.0f64 } else { 1.0 };
Motion::MouseScroll(x * mx, y * my)
},
relative => relative
}
}
}
/// An interface for rebinding keys to actions. This is freely convertable to and
/// from an InputTranslator.
#[derive(Clone, Debug, PartialEq)]
pub struct InputRebind<A: Action> {
keymap: HashMap<A, ButtonTuple>,
mouse_data: MouseTranslationData
}
impl<A: Action> InputRebind<A> {
/// Creates a new InputRebind with no stored Action/ButtonTuple pairs.
pub fn new(size: Size) -> Self {
InputRebind {
keymap: HashMap::new(),
mouse_data: MouseTranslationData::new(size)
}
}
/// Insert an Action into this InputRebind. If the Action is already in the
/// InputRebind, then its ButtonTuple will be reset to (None, None, None), and
/// the old ButtonTuple will be returned.
pub fn insert_action(&mut self, action: A) -> Option<ButtonTuple> {
self.keymap.insert(action, ButtonTuple::new())
}
/// Insert an Action into this InputRebind, and assign it to the ButtonTuple.
/// If the Action is already in the InputRebind, the old ButtonTuple will be
/// returned.
pub fn insert_action_with_buttons(&mut self, action: A, buttons: ButtonTuple) -> Option<ButtonTuple> {
self.keymap.insert(action, buttons)
}
/// Return a reference to the current ButtonTuple stored for an action. If the action
/// is not stored in this InputRebind, then `None` will be returned.
pub fn get_bindings(&self, action: &A) -> Option<&ButtonTuple> {
self.keymap.get(action)
}
/// Returns a mutable reference to the current ButtonTuple stored for an action. If the
/// action is not stored in this InputRebind, then `None` will be returned.
pub fn get_bindings_mut(&mut self, action: &mut A) -> Option<&mut ButtonTuple> {
self.keymap.get_mut(action)
}
/// Returns a reference to the boolean which represents whether x axis scrolling is inverted.
pub fn get_x_scroll_inverted(&self) -> &bool {
&self.mouse_data.x_axis_scroll_inverted
}
/// Returns a mutable reference to the boolean which represents whether x axis scrolling is inverted.
pub fn get_x_scroll_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.x_axis_scroll_inverted
}
/// Returns a reference to the boolean which represents whether y axis scrolling is inverted.
pub fn get_y_scroll_inverted(&self) -> &bool {
&self.mouse_data.y_axis_scroll_inverted
}
/// Returns a mutable reference to the boolean which represents whether y axis scrolling is inverted.
pub fn get_y_scroll_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.y_axis_scroll_inverted
}
/// Returns a reference to the boolean which represents whether mouse movement along the x axis is
/// inverted.
pub fn get_x_motion_inverted(&self) -> &bool {
&self.mouse_data.x_axis_motion_inverted
}
/// Returns a mutable reference to the boolean which represents whether mouse movement along the
/// x axis is inverted.
pub fn get_x_motion_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.x_axis_motion_inverted
}
/// Returns a reference to the boolean which represents whether mouse movement along the y axis is
/// inverted.
pub fn get_y_motion_inverted(&self) -> &bool {
&self.mouse_data.y_axis_motion_inverted
}
/// Returns a mutable reference to the boolean which represents whether mouse movement along the
/// y axis is inverted.
pub fn get_y_motion_inverted_mut(&mut self) -> &mut bool {
&mut self.mouse_data.y_axis_motion_inverted
}
/// Returns a reference to the currently stored viewport size used for calculating the imaginary mouse
/// position.
pub fn get_viewport_size(&self) -> &Size {
&self.mouse_data.viewport_size
}
/// Returns a mutable reference to the currently stored viewport size used for calculating the imaginary
/// mouse position.
pub fn get_viewport_size_mut(&mut self) -> &mut Size {
&mut self.mouse_data.viewport_size
}
}
impl<A: Action> Default for InputRebind<A> {
/// Creates an `InputRebind` with no pairs. In addition, the viewport size is set to [800, 600].
fn default() -> Self {
InputRebind::new((800, 600).into())
}
}
impl<A: Action> Into<InputTranslator<A>> for InputRebind<A> {
fn into(self) -> InputTranslator<A> {
let mut input_translator = InputTranslator::new(self.mouse_data.viewport_size);
input_translator.mouse_translator.data = self.mouse_data;
let key_vec = self.keymap.values()
.flat_map(|bt| bt.into_iter().filter_map(|x| x))
.collect::<Vec<_>>();
input_translator.keymap.reserve(key_vec.len());
for &k in &key_vec {
for (&a, bt) in self.keymap.iter() {
if bt.contains(k) {
input_translator.keymap.insert(k, a);
}
}
}
input_translator
}
}
impl<A: Action> Into<InputRebind<A>> for InputTranslator<A> {
fn into(self) -> InputRebind<A> {
let mut input_rebind = InputRebind::new(self.mouse_translator.data.viewport_size);
input_rebind.mouse_data = self.mouse_translator.data;
input_rebind.keymap = self.keymap.iter()
.map(|(k, v)| (*v, vec![Some(*k)]))
.sorted_by(|&(v0, _), &(v1, _)| Ord::cmp(&v0, &v1))
.into_iter()
.coalesce(|(k0, v0), (k1, v1)| if k0 == k1 {
Ok((k0, v0.into_iter().chain(v1).collect()))
} else {
Err(((k0, v0), (k1, v1)))
})
.map(|(k, v)| if let [b0, b1, b2] = &v.iter()
.cloned()
.pad_using(3, |_| None)
.take(3)
.collect::<Vec<_>>()[..] {
(k, ButtonTuple(b0, b1, b2))
} else {
unreachable!();
})
.collect();
input_rebind
}
}
|
#![feature(rust_2018_preview)]
use std::cmp;
use std::collections as col;
use std::ops;
use std::rc;
const OVERFLOW_COST: f32 = 100.0;
const NEWLINE_COST: f32 = 1.0;
#[derive(Clone, Debug)]
pub struct Layout(rc::Rc<LayoutContents>);
impl Layout {
fn with_contents(contents: LayoutContents) -> Layout {
Layout(rc::Rc::new(contents))
}
fn contents(&self) -> &LayoutContents {
&*self.0
}
pub fn text(lit_text: String) -> Layout {
Layout::with_contents(LayoutContents::Text(lit_text))
}
pub fn choice(first: &Layout, second: &Layout) -> Layout {
// We should canonicalize this so that the choices are always in the same order.
Layout::with_contents(LayoutContents::Choice(first.clone(), second.clone()))
}
pub fn stack(top: &Layout, bottom: &Layout) -> Layout {
Layout::with_contents(LayoutContents::Stack(top.clone(), bottom.clone()))
}
pub fn juxtapose(left: &Layout, right: &Layout) -> Layout {
let mut builder = JuxtaposeBuilder::new(right);
builder.juxtapose(left)
}
pub fn choices(items: &[&Layout]) -> Layout {
assert!(items.len() > 0);
let mut curr_layout = items[0].clone();
for i in 1..items.len() {
curr_layout = Layout::choice(&curr_layout, &items[i]);
}
curr_layout
}
pub fn layout(&self, margin: u16) -> String {
let builder = KnotSetBuilder {
margin: margin,
overflow_cost: OVERFLOW_COST,
newline_cost: NEWLINE_COST,
memo: std::cell::RefCell::new(col::BTreeMap::new()),
};
let final_knot_set = builder.get_knot_set(self);
println!("Final memo size: {}", builder.memo.borrow().len());
let final_layout = final_knot_set.knot_data_at(KnotColumn::new(0)).resolved_layout.clone();
println!("Number of knots in final: {}", final_knot_set.knot_values().len());
return final_layout.to_text(0);
}
}
#[derive(Debug)]
enum LayoutContents {
Text(String),
Choice(Layout, Layout),
Stack(Layout, Layout),
Juxtapose(String, Layout),
}
struct JuxtaposeBuilder {
right: Layout,
memo: col::BTreeMap<*const LayoutContents, Layout>,
}
impl JuxtaposeBuilder {
fn new(right: &Layout) -> Self {
JuxtaposeBuilder {
right: right.clone(),
memo: col::BTreeMap::new(),
}
}
fn juxtapose(&mut self, left: &Layout) -> Layout {
if let Some(v) = self.memo.get(&(left.contents() as *const LayoutContents)) {
return v.clone();
}
let new_layout = match left.contents() {
LayoutContents::Text(t) => {
Layout::with_contents(LayoutContents::Juxtapose(t.clone(), self.right.clone()))
}
LayoutContents::Choice(first, second) => Layout::with_contents(LayoutContents::Choice(
self.juxtapose(first),
self.juxtapose(second),
)),
LayoutContents::Stack(top, bottom) => {
Layout::with_contents(LayoutContents::Stack(top.clone(), self.juxtapose(bottom)))
}
LayoutContents::Juxtapose(text, jux_right) => Layout::with_contents(
LayoutContents::Juxtapose(text.clone(), self.juxtapose(jux_right)),
),
};
self.memo
.insert(left.contents() as *const LayoutContents, new_layout.clone());
new_layout
}
}
#[derive(Clone, Debug)]
enum ResolvedLayout {
Text(String),
Horiz(ResolvedLayoutRef, ResolvedLayoutRef),
Vert(ResolvedLayoutRef, ResolvedLayoutRef),
}
#[derive(Clone, Debug)]
struct ResolvedLayoutRef(std::rc::Rc<ResolvedLayout>);
impl ResolvedLayoutRef {
fn new(inner: ResolvedLayout) -> ResolvedLayoutRef {
ResolvedLayoutRef(rc::Rc::new(inner))
}
pub fn new_text(text: impl Into<String>) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Text(text.into()))
}
pub fn new_horiz(left: ResolvedLayoutRef, right: ResolvedLayoutRef) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Horiz(left, right))
}
pub fn new_vert(top: ResolvedLayoutRef, bottom: ResolvedLayoutRef) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Vert(top, bottom))
}
pub fn to_text(&self, curr_indent: u16) -> String {
use self::ResolvedLayout::*;
match &*self.0 {
Text(text) => text.clone(),
Horiz(left_ref, right_ref) => {
left_ref.to_text(curr_indent) + &right_ref.to_text(curr_indent + left_ref.size())
}
Vert(top, bottom) => {
top.to_text(curr_indent)
+ "\n"
+ &(" ".repeat(curr_indent as usize))
+ &bottom.to_text(curr_indent)
}
}
}
pub fn size(&self) -> u16 {
use self::ResolvedLayout::*;
match &*self.0 {
Text(text) => text.len() as u16,
Horiz(left, right) => left.size() + right.size(),
Vert(_, bottom) => bottom.size(),
}
}
}
mod knot_column {
use std::ops;
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct KnotColumn(u16);
impl KnotColumn {
pub fn new(col: u16) -> KnotColumn {
KnotColumn(col)
}
pub fn col(self) -> u16 {
self.0
}
}
impl ops::Add for KnotColumn {
type Output = KnotColumn;
fn add(self, other: Self) -> KnotColumn {
KnotColumn(self.0.checked_add(other.0).expect("Must not overflow"))
}
}
impl ops::Sub for KnotColumn {
type Output = KnotColumn;
fn sub(self, other: Self) -> KnotColumn {
KnotColumn(self.0.checked_sub(other.0).expect("Must not overflow"))
}
}
}
use knot_column::KnotColumn;
mod linear_value {
use std::ops;
#[derive(Copy, Clone, Debug)]
pub struct LinearValue {
intercept: f32,
rise: f32,
}
#[derive(Copy, Clone, Debug)]
pub enum BinaryResult {
Left,
Right,
}
impl LinearValue {
pub fn new(intercept: f32, rise: f32) -> LinearValue {
LinearValue { intercept, rise }
}
pub fn new_flat(intercept: f32) -> LinearValue {
LinearValue {
intercept,
rise: 0.0,
}
}
pub fn identity() -> LinearValue {
LinearValue {
intercept: 0.0,
rise: 0.0,
}
}
pub fn value_at(self, offset: u16) -> f32 {
self.intercept + self.rise * (offset as f32)
}
pub fn advance(self, steps: u16) -> LinearValue {
LinearValue {
intercept: self.value_at(steps),
..self
}
}
// Finds the next time the two lines cross in the positive direction.
// Returns None if the lines do not intersect, or the intersection point is
// out of range.
pub fn forward_intersection(self, other: LinearValue) -> Option<u16> {
let numerator = other.intercept - self.intercept;
let denominator = self.intercept - other.intercept;
if denominator == 0.0 {
if numerator == 0.0 {
// The lines are the same. Thus they intersect everywhere, including
// at 0. That's the next value, so we use that.
Some(0)
} else {
// The lines are parallel. It intersects nowhere.
None
}
} else {
let intersection = numerator / denominator;
if intersection.is_infinite() {
return None;
}
if intersection < 0.0 {
return None;
}
if intersection > std::u16::MAX as f32 {
return None;
}
Some(intersection.ceil() as u16)
}
}
pub fn max_initial_value(self, other: LinearValue) -> BinaryResult {
use self::BinaryResult::*;
use std::cmp::Ordering::*;
match self
.intercept
.partial_cmp(&other.intercept)
.expect("Intercept should never be edge values.")
{
Less => Right,
Greater => Left,
Eq => if self.rise > other.rise {
Left
} else {
Right
},
}
}
}
impl ops::Add for LinearValue {
type Output = LinearValue;
fn add(self, other: Self) -> LinearValue {
LinearValue {
intercept: self.intercept + other.intercept,
rise: self.rise + other.rise,
}
}
}
impl ops::Sub for LinearValue {
type Output = LinearValue;
fn sub(self, other: Self) -> LinearValue {
LinearValue {
intercept: self.intercept - other.intercept,
rise: self.rise - other.rise,
}
}
}
}
use linear_value::{BinaryResult, LinearValue};
#[derive(Clone, Debug)]
struct KnotData {
// The layout as resolved.
resolved_layout: ResolvedLayoutRef,
/// The number of characters in the last line
span: u16,
/// The cost value at knot start
value: LinearValue,
}
#[derive(Copy, Clone, Debug)]
enum SearchDirection {
Less,
LessEq,
Greater,
GreaterEq,
}
fn search_map<'a, T, K, V>(
map: &'a col::BTreeMap<K, V>,
search_key: &T,
direction: SearchDirection,
) -> Option<(&'a K, &'a V)>
where
K: std::borrow::Borrow<T> + cmp::Ord,
T: cmp::Ord,
{
match direction {
SearchDirection::Less => {
let mut range = map.range((ops::Bound::Unbounded, ops::Bound::Excluded(search_key)));
range.next_back()
}
SearchDirection::LessEq => {
let mut range = map.range((ops::Bound::Unbounded, ops::Bound::Included(search_key)));
range.next_back()
}
SearchDirection::Greater => {
let mut range = map.range((ops::Bound::Excluded(search_key), ops::Bound::Unbounded));
range.next()
}
SearchDirection::GreaterEq => {
let mut range = map.range((ops::Bound::Included(search_key), ops::Bound::Unbounded));
range.next()
}
}
}
#[derive(Clone, Debug)]
struct KnotSet {
knots: col::BTreeMap<KnotColumn, KnotData>,
}
impl KnotSet {
fn new_knot_set(
knot_cols: &col::BTreeSet<KnotColumn>,
func: impl Fn(KnotColumn) -> KnotData,
) -> KnotSet {
let mut new_knots = col::BTreeMap::new();
for &col in knot_cols {
new_knots.insert(col, func(col));
}
KnotSet { knots: new_knots }
}
fn knot_data_at(&self, col: KnotColumn) -> KnotData {
let (&knot_col, knot_value) = search_map(&self.knots, &col, SearchDirection::LessEq)
.expect("There should always be a knot at 0");
let column_distance = (col - knot_col).col();
KnotData {
resolved_layout: knot_value.resolved_layout.clone(),
span: knot_value.span,
value: knot_value.value.advance(column_distance),
}
}
fn knot_values(&self) -> col::BTreeSet<KnotColumn> {
self.knots.keys().cloned().collect()
}
fn knot_values_between(
&self,
begin: KnotColumn,
end: Option<KnotColumn>,
) -> col::BTreeSet<KnotColumn> {
let right_bound = match end {
Some(c) => ops::Bound::Excluded(c),
None => ops::Bound::Unbounded,
};
self.knots
.range((ops::Bound::Included(begin), right_bound))
.map(|(k, _)| *k)
.collect()
}
}
fn column_intervals(columns: &col::BTreeSet<KnotColumn>) -> Vec<(KnotColumn, Option<KnotColumn>)> {
let mut iter = columns.iter();
let first = iter.next().expect("Always at least a knot at 0");
let mut curr_start = *first;
let mut result = Vec::new();
for &col in iter {
result.push((curr_start, Some(col)));
curr_start = col;
}
result.push((curr_start, None));
result
}
struct KnotSetBuilder {
margin: u16,
overflow_cost: f32,
newline_cost: f32,
memo: std::cell::RefCell<col::BTreeMap<*const LayoutContents, rc::Rc<KnotSet>>>,
}
impl KnotSetBuilder {
pub fn new_text_impl(&self, text: impl Into<String>) -> KnotSet {
let text_str = text.into();
let text_len = text_str.len() as u16;
let layout = ResolvedLayoutRef::new_text(text_str);
let mut knots = col::BTreeMap::new();
if text_len < self.margin {
let flat_data = KnotData {
resolved_layout: layout.clone(),
span: text_len,
value: LinearValue::new(0.0, 0.0),
};
knots.insert(KnotColumn::new(0), flat_data);
let rise_data = KnotData {
resolved_layout: layout,
span: text_len,
value: LinearValue::new(0.0, self.overflow_cost),
};
knots.insert(KnotColumn::new(self.margin - text_len), rise_data);
} else {
let rise_data = KnotData {
resolved_layout: layout,
span: text_len,
value: LinearValue::new(
self.overflow_cost * ((text_len - self.margin) as f32),
self.overflow_cost,
),
};
knots.insert(KnotColumn::new(0), rise_data);
}
KnotSet { knots: knots }
}
pub fn new_vert_impl(&self, top: &KnotSet, bottom: &KnotSet) -> KnotSet {
let new_knot_values = top
.knot_values()
.union(&bottom.knot_values())
.cloned()
.collect();
KnotSet::new_knot_set(&new_knot_values, |col| {
let top_data = top.knot_data_at(col);
let bottom_data = bottom.knot_data_at(col);
KnotData {
resolved_layout: ResolvedLayoutRef::new_vert(
top_data.resolved_layout.clone(),
bottom_data.resolved_layout.clone(),
),
span: bottom_data.span,
value: top_data.value
+ bottom_data.value
+ LinearValue::new_flat(self.newline_cost),
}
})
}
pub fn new_horiz_impl(&self, left: impl Into<String>, right: &KnotSet) -> KnotSet {
let left = left.into();
let left_width = left.len() as u16;
let shifted_left_knot_values = right
.knot_values_between(KnotColumn::new(left_width), None)
.into_iter()
.map(|col| col - KnotColumn::new(left_width))
.collect();
let text_knot_set = self.new_text_impl(left);
let new_knot_values: col::BTreeSet<_> = text_knot_set
.knot_values()
.union(&shifted_left_knot_values)
.cloned()
.collect();
KnotSet::new_knot_set(&new_knot_values, |col| {
let right_knot_col = col + KnotColumn::new(left_width);
let left_data = text_knot_set.knot_data_at(col);
let right_data = right.knot_data_at(right_knot_col);
let sub_factor;
if col > KnotColumn::new(self.margin) {
sub_factor = LinearValue::new(0.0, self.overflow_cost)
.advance((col - KnotColumn::new(self.margin)).col());
} else {
sub_factor = LinearValue::identity();
}
KnotData {
resolved_layout: ResolvedLayoutRef::new_horiz(
left_data.resolved_layout.clone(),
right_data.resolved_layout.clone(),
),
span: left_data.span + right_data.span,
value: left_data.value + right_data.value - sub_factor,
}
})
}
pub fn new_choice_impl(&self, choice1: &KnotSet, choice2: &KnotSet) -> KnotSet {
// Set "L" in the paper
let base_knots: col::BTreeSet<_> = choice1
.knot_values()
.union(&choice2.knot_values())
.cloned()
.collect();
let mut extra_knots = col::BTreeSet::new();
for (start, end_opt) in column_intervals(&base_knots) {
// Find the Chi_K value for this range.
let choice1_data = choice1.knot_data_at(start);
let choice2_data = choice2.knot_data_at(start);
let intersect = choice1_data.value.forward_intersection(choice2_data.value);
if let Some(intersect) = intersect {
let intersect_delta = KnotColumn::new(intersect);
let in_range = match end_opt {
Some(k) => start + intersect_delta < k,
None => false,
};
if in_range {
extra_knots.insert(start + intersect_delta);
}
}
}
let all_knots: col::BTreeSet<_> = base_knots.union(&extra_knots).cloned().collect();
KnotSet::new_knot_set(&all_knots, |col| {
let choice1_data = choice1.knot_data_at(col);
let choice2_data = choice2.knot_data_at(col);
match choice1_data.value.max_initial_value(choice2_data.value) {
BinaryResult::Left => choice2_data,
BinaryResult::Right => choice1_data,
}
})
}
fn get_knot_set(&self, layout: &Layout) -> rc::Rc<KnotSet> {
use self::LayoutContents::*;
let contents = layout.contents();
let memo_key = contents as *const LayoutContents;
{
let borrow = self.memo.borrow();
if let Some(memoized) = borrow.get(&memo_key) {
return memoized.clone();
}
}
let new_knot_set = match contents {
Text(text) => self.new_text_impl(text.clone()),
Stack(top, bottom) => {
self.new_vert_impl(&*self.get_knot_set(top), &*self.get_knot_set(bottom))
}
Juxtapose(left, right) => self.new_horiz_impl(left.clone(), &*self.get_knot_set(right)),
Choice(left, right) => {
self.new_choice_impl(&*self.get_knot_set(left), &*self.get_knot_set(right))
}
};
{
let mut borrow = self.memo.borrow_mut();
borrow.insert(memo_key, rc::Rc::new(new_knot_set));
borrow.get(&memo_key).unwrap().clone()
}
}
}
#[macro_export]
macro_rules! pp_stack {
() => { Layout::text("".to_owned()) };
($only:expr) => { $only };
($first:expr, $($rest:expr),*) => { Layout::stack($first, pp_stack!($($rest),*)) };
}
#[cfg(test)]
mod test {
use super::Layout;
#[test]
fn test_simple_set() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::juxtapose(&foo, &foo);
assert_eq!(pair.layout(10), "foofoo");
}
#[test]
fn test_simple_stack() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::stack(&foo, &foo);
assert_eq!(pair.layout(10), "foo\nfoo");
}
#[test]
fn text_simple_choice() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::choice(&Layout::juxtapose(&foo, &foo), &Layout::stack(&foo, &foo));
assert_eq!(pair.layout(10), "foofoo");
assert_eq!(pair.layout(4), "foo\nfoo");
}
#[test]
fn text_large_stack() {
let foo = Layout::text("foo".to_owned());
let bar = Layout::text("bar".to_owned());
let foo_stack = Layout::stack(&foo, &bar);
let foo_jux = Layout::juxtapose(&foo, &bar);
let foo_choice = Layout::choice(&foo_stack, &foo_jux);
let mut curr_choice = foo_choice.clone();
for _ in 0..1000 {
curr_choice = Layout::juxtapose(&foo_choice, &curr_choice);
}
println!("Done creating layout.");
curr_choice.layout(500);
assert!(false);
}
}
Fix some warnings
#![feature(rust_2018_preview)]
use std::cmp;
use std::collections as col;
use std::ops;
use std::rc;
const OVERFLOW_COST: f32 = 100.0;
const NEWLINE_COST: f32 = 1.0;
#[derive(Clone, Debug)]
pub struct Layout(rc::Rc<LayoutContents>);
impl Layout {
fn with_contents(contents: LayoutContents) -> Layout {
Layout(rc::Rc::new(contents))
}
fn contents(&self) -> &LayoutContents {
&*self.0
}
pub fn text(lit_text: String) -> Layout {
Layout::with_contents(LayoutContents::Text(lit_text))
}
pub fn choice(first: &Layout, second: &Layout) -> Layout {
// We should canonicalize this so that the choices are always in the same order.
Layout::with_contents(LayoutContents::Choice(first.clone(), second.clone()))
}
pub fn stack(top: &Layout, bottom: &Layout) -> Layout {
Layout::with_contents(LayoutContents::Stack(top.clone(), bottom.clone()))
}
pub fn juxtapose(left: &Layout, right: &Layout) -> Layout {
let mut builder = JuxtaposeBuilder::new(right);
builder.juxtapose(left)
}
pub fn choices(items: &[&Layout]) -> Layout {
assert!(items.len() > 0);
let mut curr_layout = items[0].clone();
for i in 1..items.len() {
curr_layout = Layout::choice(&curr_layout, &items[i]);
}
curr_layout
}
pub fn layout(&self, margin: u16) -> String {
let builder = KnotSetBuilder {
margin: margin,
overflow_cost: OVERFLOW_COST,
newline_cost: NEWLINE_COST,
memo: std::cell::RefCell::new(col::BTreeMap::new()),
};
let final_knot_set = builder.get_knot_set(self);
println!("Final memo size: {}", builder.memo.borrow().len());
let final_layout = final_knot_set.knot_data_at(KnotColumn::new(0)).resolved_layout.clone();
println!("Number of knots in final: {}", final_knot_set.knot_values().len());
return final_layout.to_text(0);
}
}
#[derive(Debug)]
enum LayoutContents {
Text(String),
Choice(Layout, Layout),
Stack(Layout, Layout),
Juxtapose(String, Layout),
}
struct JuxtaposeBuilder {
right: Layout,
memo: col::BTreeMap<*const LayoutContents, Layout>,
}
impl JuxtaposeBuilder {
fn new(right: &Layout) -> Self {
JuxtaposeBuilder {
right: right.clone(),
memo: col::BTreeMap::new(),
}
}
fn juxtapose(&mut self, left: &Layout) -> Layout {
if let Some(v) = self.memo.get(&(left.contents() as *const LayoutContents)) {
return v.clone();
}
let new_layout = match left.contents() {
LayoutContents::Text(t) => {
Layout::with_contents(LayoutContents::Juxtapose(t.clone(), self.right.clone()))
}
LayoutContents::Choice(first, second) => Layout::with_contents(LayoutContents::Choice(
self.juxtapose(first),
self.juxtapose(second),
)),
LayoutContents::Stack(top, bottom) => {
Layout::with_contents(LayoutContents::Stack(top.clone(), self.juxtapose(bottom)))
}
LayoutContents::Juxtapose(text, jux_right) => Layout::with_contents(
LayoutContents::Juxtapose(text.clone(), self.juxtapose(jux_right)),
),
};
self.memo
.insert(left.contents() as *const LayoutContents, new_layout.clone());
new_layout
}
}
#[derive(Clone, Debug)]
enum ResolvedLayout {
Text(String),
Horiz(ResolvedLayoutRef, ResolvedLayoutRef),
Vert(ResolvedLayoutRef, ResolvedLayoutRef),
}
#[derive(Clone, Debug)]
struct ResolvedLayoutRef(std::rc::Rc<ResolvedLayout>);
impl ResolvedLayoutRef {
fn new(inner: ResolvedLayout) -> ResolvedLayoutRef {
ResolvedLayoutRef(rc::Rc::new(inner))
}
pub fn new_text(text: impl Into<String>) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Text(text.into()))
}
pub fn new_horiz(left: ResolvedLayoutRef, right: ResolvedLayoutRef) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Horiz(left, right))
}
pub fn new_vert(top: ResolvedLayoutRef, bottom: ResolvedLayoutRef) -> ResolvedLayoutRef {
ResolvedLayoutRef::new(ResolvedLayout::Vert(top, bottom))
}
pub fn to_text(&self, curr_indent: u16) -> String {
use self::ResolvedLayout::*;
match &*self.0 {
Text(text) => text.clone(),
Horiz(left_ref, right_ref) => {
left_ref.to_text(curr_indent) + &right_ref.to_text(curr_indent + left_ref.size())
}
Vert(top, bottom) => {
top.to_text(curr_indent)
+ "\n"
+ &(" ".repeat(curr_indent as usize))
+ &bottom.to_text(curr_indent)
}
}
}
pub fn size(&self) -> u16 {
use self::ResolvedLayout::*;
match &*self.0 {
Text(text) => text.len() as u16,
Horiz(left, right) => left.size() + right.size(),
Vert(_, bottom) => bottom.size(),
}
}
}
mod knot_column {
use std::ops;
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct KnotColumn(u16);
impl KnotColumn {
pub fn new(col: u16) -> KnotColumn {
KnotColumn(col)
}
pub fn col(self) -> u16 {
self.0
}
}
impl ops::Add for KnotColumn {
type Output = KnotColumn;
fn add(self, other: Self) -> KnotColumn {
KnotColumn(self.0.checked_add(other.0).expect("Must not overflow"))
}
}
impl ops::Sub for KnotColumn {
type Output = KnotColumn;
fn sub(self, other: Self) -> KnotColumn {
KnotColumn(self.0.checked_sub(other.0).expect("Must not overflow"))
}
}
}
use knot_column::KnotColumn;
mod linear_value {
use std::ops;
#[derive(Copy, Clone, Debug)]
pub struct LinearValue {
intercept: f32,
rise: f32,
}
#[derive(Copy, Clone, Debug)]
pub enum BinaryResult {
Left,
Right,
}
impl LinearValue {
pub fn new(intercept: f32, rise: f32) -> LinearValue {
LinearValue { intercept, rise }
}
pub fn new_flat(intercept: f32) -> LinearValue {
LinearValue {
intercept,
rise: 0.0,
}
}
pub fn identity() -> LinearValue {
LinearValue {
intercept: 0.0,
rise: 0.0,
}
}
pub fn value_at(self, offset: u16) -> f32 {
self.intercept + self.rise * (offset as f32)
}
pub fn advance(self, steps: u16) -> LinearValue {
LinearValue {
intercept: self.value_at(steps),
..self
}
}
// Finds the next time the two lines cross in the positive direction.
// Returns None if the lines do not intersect, or the intersection point is
// out of range.
pub fn forward_intersection(self, other: LinearValue) -> Option<u16> {
let numerator = other.intercept - self.intercept;
let denominator = self.intercept - other.intercept;
if denominator == 0.0 {
if numerator == 0.0 {
// The lines are the same. Thus they intersect everywhere, including
// at 0. That's the next value, so we use that.
Some(0)
} else {
// The lines are parallel. It intersects nowhere.
None
}
} else {
let intersection = numerator / denominator;
if intersection.is_infinite() {
return None;
}
if intersection < 0.0 {
return None;
}
if intersection > std::u16::MAX as f32 {
return None;
}
Some(intersection.ceil() as u16)
}
}
pub fn max_initial_value(self, other: LinearValue) -> BinaryResult {
use self::BinaryResult::*;
use std::cmp::Ordering::*;
match self
.intercept
.partial_cmp(&other.intercept)
.expect("Intercept should never be edge values.")
{
Less => Right,
Greater => Left,
Equal => if self.rise > other.rise {
Left
} else {
Right
},
}
}
}
impl ops::Add for LinearValue {
type Output = LinearValue;
fn add(self, other: Self) -> LinearValue {
LinearValue {
intercept: self.intercept + other.intercept,
rise: self.rise + other.rise,
}
}
}
impl ops::Sub for LinearValue {
type Output = LinearValue;
fn sub(self, other: Self) -> LinearValue {
LinearValue {
intercept: self.intercept - other.intercept,
rise: self.rise - other.rise,
}
}
}
}
use linear_value::{BinaryResult, LinearValue};
#[derive(Clone, Debug)]
struct KnotData {
// The layout as resolved.
resolved_layout: ResolvedLayoutRef,
/// The number of characters in the last line
span: u16,
/// The cost value at knot start
value: LinearValue,
}
#[derive(Copy, Clone, Debug)]
enum SearchDirection {
LessEq,
}
fn search_map<'a, T, K, V>(
map: &'a col::BTreeMap<K, V>,
search_key: &T,
direction: SearchDirection,
) -> Option<(&'a K, &'a V)>
where
K: std::borrow::Borrow<T> + cmp::Ord,
T: cmp::Ord,
{
match direction {
SearchDirection::LessEq => {
let mut range = map.range((ops::Bound::Unbounded, ops::Bound::Included(search_key)));
range.next_back()
}
}
}
#[derive(Clone, Debug)]
struct KnotSet {
knots: col::BTreeMap<KnotColumn, KnotData>,
}
impl KnotSet {
fn new_knot_set(
knot_cols: &col::BTreeSet<KnotColumn>,
func: impl Fn(KnotColumn) -> KnotData,
) -> KnotSet {
let mut new_knots = col::BTreeMap::new();
for &col in knot_cols {
new_knots.insert(col, func(col));
}
KnotSet { knots: new_knots }
}
fn knot_data_at(&self, col: KnotColumn) -> KnotData {
let (&knot_col, knot_value) = search_map(&self.knots, &col, SearchDirection::LessEq)
.expect("There should always be a knot at 0");
let column_distance = (col - knot_col).col();
KnotData {
resolved_layout: knot_value.resolved_layout.clone(),
span: knot_value.span,
value: knot_value.value.advance(column_distance),
}
}
fn knot_values(&self) -> col::BTreeSet<KnotColumn> {
self.knots.keys().cloned().collect()
}
fn knot_values_between(
&self,
begin: KnotColumn,
end: Option<KnotColumn>,
) -> col::BTreeSet<KnotColumn> {
let right_bound = match end {
Some(c) => ops::Bound::Excluded(c),
None => ops::Bound::Unbounded,
};
self.knots
.range((ops::Bound::Included(begin), right_bound))
.map(|(k, _)| *k)
.collect()
}
}
fn column_intervals(columns: &col::BTreeSet<KnotColumn>) -> Vec<(KnotColumn, Option<KnotColumn>)> {
let mut iter = columns.iter();
let first = iter.next().expect("Always at least a knot at 0");
let mut curr_start = *first;
let mut result = Vec::new();
for &col in iter {
result.push((curr_start, Some(col)));
curr_start = col;
}
result.push((curr_start, None));
result
}
struct KnotSetBuilder {
margin: u16,
overflow_cost: f32,
newline_cost: f32,
memo: std::cell::RefCell<col::BTreeMap<*const LayoutContents, rc::Rc<KnotSet>>>,
}
impl KnotSetBuilder {
pub fn new_text_impl(&self, text: impl Into<String>) -> KnotSet {
let text_str = text.into();
let text_len = text_str.len() as u16;
let layout = ResolvedLayoutRef::new_text(text_str);
let mut knots = col::BTreeMap::new();
if text_len < self.margin {
let flat_data = KnotData {
resolved_layout: layout.clone(),
span: text_len,
value: LinearValue::new(0.0, 0.0),
};
knots.insert(KnotColumn::new(0), flat_data);
let rise_data = KnotData {
resolved_layout: layout,
span: text_len,
value: LinearValue::new(0.0, self.overflow_cost),
};
knots.insert(KnotColumn::new(self.margin - text_len), rise_data);
} else {
let rise_data = KnotData {
resolved_layout: layout,
span: text_len,
value: LinearValue::new(
self.overflow_cost * ((text_len - self.margin) as f32),
self.overflow_cost,
),
};
knots.insert(KnotColumn::new(0), rise_data);
}
KnotSet { knots: knots }
}
pub fn new_vert_impl(&self, top: &KnotSet, bottom: &KnotSet) -> KnotSet {
let new_knot_values = top
.knot_values()
.union(&bottom.knot_values())
.cloned()
.collect();
KnotSet::new_knot_set(&new_knot_values, |col| {
let top_data = top.knot_data_at(col);
let bottom_data = bottom.knot_data_at(col);
KnotData {
resolved_layout: ResolvedLayoutRef::new_vert(
top_data.resolved_layout.clone(),
bottom_data.resolved_layout.clone(),
),
span: bottom_data.span,
value: top_data.value
+ bottom_data.value
+ LinearValue::new_flat(self.newline_cost),
}
})
}
pub fn new_horiz_impl(&self, left: impl Into<String>, right: &KnotSet) -> KnotSet {
let left = left.into();
let left_width = left.len() as u16;
let shifted_left_knot_values = right
.knot_values_between(KnotColumn::new(left_width), None)
.into_iter()
.map(|col| col - KnotColumn::new(left_width))
.collect();
let text_knot_set = self.new_text_impl(left);
let new_knot_values: col::BTreeSet<_> = text_knot_set
.knot_values()
.union(&shifted_left_knot_values)
.cloned()
.collect();
KnotSet::new_knot_set(&new_knot_values, |col| {
let right_knot_col = col + KnotColumn::new(left_width);
let left_data = text_knot_set.knot_data_at(col);
let right_data = right.knot_data_at(right_knot_col);
let sub_factor;
if col > KnotColumn::new(self.margin) {
sub_factor = LinearValue::new(0.0, self.overflow_cost)
.advance((col - KnotColumn::new(self.margin)).col());
} else {
sub_factor = LinearValue::identity();
}
KnotData {
resolved_layout: ResolvedLayoutRef::new_horiz(
left_data.resolved_layout.clone(),
right_data.resolved_layout.clone(),
),
span: left_data.span + right_data.span,
value: left_data.value + right_data.value - sub_factor,
}
})
}
pub fn new_choice_impl(&self, choice1: &KnotSet, choice2: &KnotSet) -> KnotSet {
// Set "L" in the paper
let base_knots: col::BTreeSet<_> = choice1
.knot_values()
.union(&choice2.knot_values())
.cloned()
.collect();
let mut extra_knots = col::BTreeSet::new();
for (start, end_opt) in column_intervals(&base_knots) {
// Find the Chi_K value for this range.
let choice1_data = choice1.knot_data_at(start);
let choice2_data = choice2.knot_data_at(start);
let intersect = choice1_data.value.forward_intersection(choice2_data.value);
if let Some(intersect) = intersect {
let intersect_delta = KnotColumn::new(intersect);
let in_range = match end_opt {
Some(k) => start + intersect_delta < k,
None => false,
};
if in_range {
extra_knots.insert(start + intersect_delta);
}
}
}
let all_knots: col::BTreeSet<_> = base_knots.union(&extra_knots).cloned().collect();
KnotSet::new_knot_set(&all_knots, |col| {
let choice1_data = choice1.knot_data_at(col);
let choice2_data = choice2.knot_data_at(col);
match choice1_data.value.max_initial_value(choice2_data.value) {
BinaryResult::Left => choice2_data,
BinaryResult::Right => choice1_data,
}
})
}
fn get_knot_set(&self, layout: &Layout) -> rc::Rc<KnotSet> {
use self::LayoutContents::*;
let contents = layout.contents();
let memo_key = contents as *const LayoutContents;
{
let borrow = self.memo.borrow();
if let Some(memoized) = borrow.get(&memo_key) {
return memoized.clone();
}
}
let new_knot_set = match contents {
Text(text) => self.new_text_impl(text.clone()),
Stack(top, bottom) => {
self.new_vert_impl(&*self.get_knot_set(top), &*self.get_knot_set(bottom))
}
Juxtapose(left, right) => self.new_horiz_impl(left.clone(), &*self.get_knot_set(right)),
Choice(left, right) => {
self.new_choice_impl(&*self.get_knot_set(left), &*self.get_knot_set(right))
}
};
{
let mut borrow = self.memo.borrow_mut();
borrow.insert(memo_key, rc::Rc::new(new_knot_set));
borrow.get(&memo_key).unwrap().clone()
}
}
}
#[macro_export]
macro_rules! pp_stack {
() => { Layout::text("".to_owned()) };
($only:expr) => { $only };
($first:expr, $($rest:expr),*) => { Layout::stack($first, pp_stack!($($rest),*)) };
}
#[cfg(test)]
mod test {
use super::Layout;
#[test]
fn test_simple_set() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::juxtapose(&foo, &foo);
assert_eq!(pair.layout(10), "foofoo");
}
#[test]
fn test_simple_stack() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::stack(&foo, &foo);
assert_eq!(pair.layout(10), "foo\nfoo");
}
#[test]
fn text_simple_choice() {
let foo = Layout::text("foo".to_owned());
let pair = Layout::choice(&Layout::juxtapose(&foo, &foo), &Layout::stack(&foo, &foo));
assert_eq!(pair.layout(10), "foofoo");
assert_eq!(pair.layout(4), "foo\nfoo");
}
#[test]
fn text_large_stack() {
let foo = Layout::text("foo".to_owned());
let bar = Layout::text("bar".to_owned());
let foo_stack = Layout::stack(&foo, &bar);
let foo_jux = Layout::juxtapose(&foo, &bar);
let foo_choice = Layout::choice(&foo_stack, &foo_jux);
let mut curr_choice = foo_choice.clone();
for _ in 0..1000 {
curr_choice = Layout::juxtapose(&foo_choice, &curr_choice);
}
println!("Done creating layout.");
curr_choice.layout(500);
assert!(false);
}
}
|
// Copyright 2016 Jason Lingle
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(missing_docs)]
//! `Supercow` is `Cow` on steroids.
//!
//! `Supercow` provides a mechanism for making APIs that accept very general
//! references while maintaining very low overhead for usages not involving
//! heavy-weight references (eg, `Arc`). Though nominally similar to `Cow` in
//! structure (and being named after it), `Supercow` does not require the
//! containee to be `Clone` or `ToOwned` unless operations inherently depending
//! on either are invoked.
//!
//! # Quick Start
//!
//! ## Simple Types
//!
//! In many cases, you can think of a `Supercow` as having only one lifetime
//! parameter and one type parameter, corresponding to the lifetime and type of
//! an immutable reference.
//!
//! ```
//! extern crate supercow;
//!
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! # fn main() {
//! // Declare some data we want to reference.
//! let fourty_two = 42u32;
//! // Make a Supercow referencing the above.
//! // N.B. Type inference doesn't work reliably if there is nothing explicitly
//! // typed to which the Supercow is passed, so we declare the type of this
//! // variable explicitly.
//! let mut a: Supercow<u32> = Supercow::borrowed(&fourty_two);
//! // We can deref `a` to a `u32`, and also see that it does
//! // indeed reference `fourty_two`.
//! assert_eq!(42, *a);
//! assert_eq!(&fourty_two as *const u32, &*a as *const u32);
//!
//! // Clone `a` so that it also points to `fourty_two`.
//! let mut b = a.clone();
//! assert_eq!(42, *b);
//! assert_eq!(&fourty_two as *const u32, &*b as *const u32);
//!
//! // `to_mut()` can be used to mutate `a` and `b` independently, taking
//! // ownership as needed.
//! *a.to_mut() += 2;
//! assert_eq!(42, fourty_two);
//! assert_eq!(44, *a);
//! assert_eq!(42, *b);
//! assert_eq!(&fourty_two as *const u32, &*b as *const u32);
//!
//! *b.to_mut() = 56;
//! assert_eq!(44, *a);
//! assert_eq!(56, *b);
//! assert_eq!(42, fourty_two);
//!
//! // We can also use `Arc` transparently.
//! let mut c: Supercow<u32> = Supercow::shared(Arc::new(99));
//! assert_eq!(99, *c);
//! *c.to_mut() += 1;
//! assert_eq!(100, *c);
//! # }
//! ```
//!
//! ## Owned/Borrowed Types
//!
//! `Supercow` can have different owned and borrowed types, for example
//! `String` and `str`. In this case, the two are separate type parameters,
//! with the owned one written first. (Both need to be listed explicitly since
//! `Supercow` does not require the contained value to be `ToOwned`.)
//!
//! ```
//! extern crate supercow;
//!
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! # fn main() {
//! let hello: Supercow<String, str> = Supercow::borrowed("hello");
//! let mut hello_world = hello.clone();
//! hello_world.to_mut().push_str(" world");
//!
//! assert_eq!(hello, "hello");
//! assert_eq!(hello_world, "hello world");
//! # }
//! ```
//!
//! ## Accepting `Supercow` in an API
//!
//! If you want to make an API taking `Supercow` values, the recommended
//! approach is to accept anything that is `Into<Supercow<YourType>>`, which
//! allows bare owned types and references to owned values to be accepted as
//! well.
//!
//! ```
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! fn some_api_function<'a, T : Into<Supercow<'a,u32>>>
//! (t: T) -> Supercow<'a,u32>
//! {
//! let mut x = t.into();
//! *x.to_mut() *= 2;
//! x
//! }
//!
//! fn main() {
//! assert_eq!(42, *some_api_function(21));
//! let twenty_one = 21;
//! assert_eq!(42, *some_api_function(&twenty_one));
//! assert_eq!(42, *some_api_function(Arc::new(21)));
//! }
//! ```
//!
//! ## Chosing the right variant
//!
//! `Supercow` is extremely flexible as to how it internally stores and manages
//! data. There are four variants provided by default: `Supercow`,
//! `NonSyncSupercow`, `InlineSupercow`, and `InlineNonSyncSupercow`. Here is a
//! quick reference on the trade-offs:
//!
//! | Variant | Send+Sync? | `Rc`? | Size | Init | Deref |
//! |-------------------|---------------|-------|-------|-------|------------|
//! | (Default) | Yes | No | Small | Slow | Very Fast |
//! | `NonSync` | No | Yes | Small | Slow | Very Fast |
//! | `Inline` | Yes | No | Big | Fast | Fast |
//! | `InlineNonSync` | No | Yes | Big | Fast | Fast |
//!
//! "Init" above specifically refers to initialisation with an owned value or
//! shared reference. Supercows constructed with mundane references always
//! construct extremely quickly.
//!
//! The only difference between the `NonSync` variant and the default is that
//! the default is to require the shared pointer type (eg, `Arc`) to be `Send`
//! and `Sync` (which thus prohibits using `Rc`), whereas `NonSync` does not
//! and so allows `Rc`. Note that a side-effect of the default `Send + Sync`
//! requirement is that the type of `BORROWED` also needs to be `Send` and
//! `Sync` when using `Arc` as the shared reference type; if it is not `Send`
//! and `Sync`, use `NonSyncSupercow` instead.
//!
//! By default, `Supercow` boxes any owned value or shared reference. This
//! makes the `Deref` implementation faster since it does not need to account
//! for internal pointers, but more importantly, means that the `Supercow` does
//! not need to reserve space for the owned and shared values, so the default
//! `Supercow` is only one pointer wider than a bare reference.
//!
//! The obvious problem with boxing values is that it makes construction of the
//! `Supercow` slower, as one must pay for an allocation. If you want to avoid
//! the allocation, you can use the `Inline` variants instead, which store the
//! values inline inside the `Supercow`. (Note that if you are looking to
//! eliminate allocation entirely, you will also need to tinker with the
//! `SHARED` type, which by default has its own `Box` as well.) Note that this
//! of course makes the `Supercow` much bigger; be particularly careful if you
//! create a hierarchy of things containing `InlineSupercow`s referencing each
//! other, as each would effectively have space for the entire tree above it
//! inline.
//!
//! The default to box values was chosen on the grounds that it is generally
//! easier to use, less likely to cause confusing problems, and in many cases
//! the allocation doesn't affect performance:
//!
//! - In either choice, creating a `Supercow` with a borrowed reference incurs
//! no allocation. The boxed option will actually be slightly faster since it
//! does not need to initialise as much memory and results in better locality
//! due to being smaller.
//!
//! - The value contained usually is reasonably expensive to construct anyway,
//! or else there would be less incentive to pass it around as a reference when
//! possible. In these cases, the extra allocation likely is a minor impact on
//! performance.
//!
//! - Overuse of boxed values results in a "uniform slowness" that can be
//! identified reasonably easily, and results in a linear performance
//! degradation relative to overuse. Overuse of `InlineSupercow`s at best
//! results in linear memory bloat, but if `InlineSupercow`s reference
//! structures containing other `InlineSupercow`s, the result can even be
//! exponential bloat to the structures. At best, this is a harder problem to
//! track down; at worst, it can result in entirely non-obvious stack
//! overflows.
//!
//! # Use Cases
//!
//! ## More flexible Copy-on-Write
//!
//! `std::borrow::Cow` only supports two modes of ownership: You either fully
//! own the value, or only borrow it. `Rc` and `Arc` have the `make_mut()`
//! method, which allows either total ownership or shared ownership. `Supercow`
//! supports all three: owned, shared, and borrowed.
//!
//! ## More flexible Copy-if-Needed
//!
//! A major use of `Cow` in `std` is found on functions like
//! `OsStr::to_string_lossy()`, which returns a borrowed view into itself if
//! possible, or an owned string if it needed to change something. If the
//! caller does not intend to do its own writing, this is more a "copy if
//! needed" structure, and the fact that it requires the contained value to be
//! `ToOwned` limits it to things that can be cloned.
//!
//! `Supercow` only requires `ToOwned` if the caller actually intends to invoke
//! functionality which requires cloning a borrowed value, so it can fit this
//! use-case even for non-cloneable types.
//!
//! ## Working around awkward lifetimes
//!
//! This is the original case for which `Supercow` was designed.
//!
//! Say you have an API with a sort of hierarchical structure of heavyweight
//! resources, for example handles to a local database and tables within it. A
//! natural representation may be to make the table handle hold a reference to
//! the database handle.
//!
//! ```no_run
//! struct Database;
//! impl Database {
//! fn new() -> Self {
//! // Computation...
//! Database
//! }
//! fn close(self) -> bool {
//! // Eg, it returns an error on failure or something
//! true
//! }
//! }
//! impl Drop for Database {
//! fn drop(&mut self) {
//! println!("Dropping database");
//! }
//! }
//! struct Table<'a>(&'a Database);
//! impl<'a> Table<'a> {
//! fn new(db: &'a Database) -> Self {
//! // Computation...
//! Table(db)
//! }
//! }
//! impl<'a> Drop for Table<'a> {
//! fn drop(&mut self) {
//! println!("Dropping table");
//! // Notify `self.db` about this
//! }
//! }
//! ```
//!
//! We can use this quite easily:
//!
//! ```
//! # struct Database;
//! # impl Database {
//! # fn new() -> Self {
//! # // Computation...
//! # Database
//! # }
//! # fn close(self) -> bool {
//! # // Eg, it returns an error on failure or something
//! # true
//! # }
//! # }
//! # impl Drop for Database {
//! # fn drop(&mut self) {
//! # println!("Dropping database");
//! # }
//! # }
//! # struct Table<'a>(&'a Database);
//! # impl<'a> Table<'a> {
//! # fn new(db: &'a Database) -> Self {
//! # // Computation...
//! # Table(db)
//! # }
//! # }
//! # impl<'a> Drop for Table<'a> {
//! # fn drop(&mut self) {
//! # println!("Dropping table");
//! # // Notify `self.db` about this
//! # }
//! # }
//!
//! # #[allow(unused_variables)]
//! fn main() {
//! let db = Database::new();
//! {
//! let table1 = Table::new(&db);
//! let table2 = Table::new(&db);
//! do_stuff(&table1);
//! // Etc
//! }
//! assert!(db.close());
//! }
//!
//! # #[allow(unused_variables)]
//! fn do_stuff(table: &Table) {
//! // Stuff
//! }
//! ```
//!
//! That is, until we want to hold the database and the tables in a struct.
//!
//! ```ignore
//! struct Resources {
//! db: Database,
//! table: Table<'uhhh>, // Uh, what is the lifetime here?
//! }
//! ```
//!
//! There are several options here:
//!
//! - Change the API to use `Arc`s or similar. This works, but adds overhead
//! for clients that don't need it, and additionally removes from everybody the
//! ability to statically know whether `db.close()` can be called.
//!
//! - Force clients to resort to unsafety, such as
//! [`OwningHandle`](http://kimundi.github.io/owning-ref-rs/owning_ref/struct.OwningHandle.html).
//! This sacrifices no performance and allows the stack-based client usage to
//! be able to call `db.close()` easily, but makes things much more difficult
//! for other clients.
//!
//! - Take a `Borrow` type parameter. This works and is zero-overhead, but
//! results in a proliferation of generics throughout the API and client code,
//! and becomes especially problematic when the hierarchy is multiple such
//! levels deep.
//!
//! - Use `Supercow` to get the best of both worlds.
//!
//! We can adapt and use the API like so:
//!
//! ```
//! use std::sync::Arc;
//!
//! use supercow::Supercow;
//!
//! struct Database;
//! impl Database {
//! fn new() -> Self {
//! // Computation...
//! Database
//! }
//! fn close(self) -> bool {
//! // Eg, it returns an error on failure or something
//! true
//! }
//! }
//! impl Drop for Database {
//! fn drop(&mut self) {
//! println!("Dropping database");
//! }
//! }
//! struct Table<'a>(Supercow<'a, Database>);
//! impl<'a> Table<'a> {
//! fn new<T : Into<Supercow<'a, Database>>>(db: T) -> Self {
//! // Computation...
//! Table(db.into())
//! }
//! }
//! impl<'a> Drop for Table<'a> {
//! fn drop(&mut self) {
//! println!("Dropping table");
//! // Notify `self.db` about this
//! }
//! }
//!
//! // The original stack-based code, unmodified
//!
//! # #[allow(unused_variables)]
//! fn on_stack() {
//! let db = Database::new();
//! {
//! let table1 = Table::new(&db);
//! let table2 = Table::new(&db);
//! do_stuff(&table1);
//! // Etc
//! }
//! assert!(db.close());
//! }
//!
//! // If we only wanted one Table and didn't care about ever getting the
//! // Database back, we don't even need a reference.
//! fn by_value() {
//! let db = Database::new();
//! let table = Table::new(db);
//! do_stuff(&table);
//! }
//!
//! // And we can declare our holds-everything struct by using `Arc`s to deal
//! // with ownership.
//! struct Resources {
//! db: Arc<Database>,
//! table: Table<'static>,
//! }
//! impl Resources {
//! fn new() -> Self {
//! let db = Arc::new(Database::new());
//! let table = Table::new(db.clone());
//! Resources { db: db, table: table }
//! }
//!
//! fn close(self) -> bool {
//! drop(self.table);
//! Arc::try_unwrap(self.db).ok().unwrap().close()
//! }
//! }
//!
//! fn with_struct() {
//! let res = Resources::new();
//! do_stuff(&res.table);
//! assert!(res.close());
//! }
//!
//! # #[allow(unused_variables)]
//! fn do_stuff(table: &Table) {
//! // Stuff
//! }
//!
//! ```
//!
//! # Shared Reference Type
//!
//! The third type parameter type to `Supercow` specifies the shared reference
//! type.
//!
//! The default is `Box<DefaultFeatures<'static>>`, which is a boxed trait
//! object describing the features a shared reference type must have while
//! allowing any such reference to be used without needing a generic type
//! argument.
//!
//! An alternate feature set can be found in `NonSyncFeatures`, which is also
//! usable through the `NonSyncSupercow` typedef (which also makes it
//! `'static`). You can create custom feature traits in this style with
//! `supercow_features!`.
//!
//! It is perfectly legal to use a non-`'static` shared reference type. In
//! fact, the original design for `Supercow<'a>` used `DefaultFeatures<'a>`.
//! However, a non-`'static` lifetime makes the system harder to use, and if
//! entangled with `'a` on `Supercow`, makes the structure lifetime-invariant,
//! which makes it much harder to treat as a reference.
//!
//! Boxing the shared reference and putting it behind a trait object both add
//! overhead, of course. If you wish, you can use a real reference type in the
//! third parameter as long as you are OK with losing the flexibility the
//! boxing would provide. For example,
//!
//! ```
//! use std::rc::Rc;
//!
//! use supercow::Supercow;
//!
//! # fn main() {
//! let x: Supercow<u32, u32, Rc<u32>> = Supercow::shared(Rc::new(42u32));
//! println!("{}", *x);
//! # }
//! ```
//!
//! Note that you may need to provide an identity `supercow::aux::SharedFrom`
//! implementation if you have a custom reference type.
//!
//! # Conversions
//!
//! To facilitate client API designs, `Supercow` converts (via `From`/`Into`)
//! from a number of things. Unfortunately, due to trait coherence rules, this
//! does not yet apply in all cases where one might hope. The currently
//! available conversions are:
//!
//! - The `OWNED` type into an owned `Supercow`. This applies without
//! restriction.
//!
//! - A reference to the `OWNED` type. References to a different `BORROWED`
//! type are currently not convertable; `Supercow::borrowed()` will be needed
//! to construct the `Supercow` explicitly.
//!
//! - `Rc<OWNED>` and `Arc<OWNED>` for `Supercow`s where `OWNED` and `BORROWED`
//! are the exact same type, and where the `Rc` or `Arc` can be converted into
//! `SHARED` via `supercow::aux::SharedFrom`. If `OWNED` and `BORROWED` are
//! different types, `Supercow::shared()` will be needed to construct the
//! `Supercow` explicitly.
//!
//! # Storage Type
//!
//! When in owned or shared mode, a `Supercow` needs someplace to store the
//! `OWNED` or `SHARED` value itself. This can be customised with the fourth
//! type parameter and the `OwnedStorage` trait. Two strategies are provided by
//! this crate:
//!
//! - `BoxedStorage` puts everything behind `Box`es. This has the advantage
//! that the `Supercow` structure is only one pointer wider than a basic
//! reference, and results in a faster `Deref`. The obvious drawback is that
//! you pay for allocations on construction. This is the default with
//! `Supercow` and `NonSyncSupercow`.
//!
//! - `InlineStorage` uses an `enum` to store the values inline in the
//! `Supercow`, thus incurring no allocation, but making the `Supercow` itself
//! bigger. This is easily available via the `InlineSupercow` and
//! `InlineNonSyncSupercow` types.
//!
//! If you find some need, you can define custom storage types, though note
//! that the trait is quite unsafe and somewhat subtle.
//!
//! # Advanced
//!
//! ## Variance
//!
//! `Supercow` is covariant on its lifetime and all its type parameters, except
//! for `SHARED` which is invariant. The default `SHARED` type for both
//! `Supercow` and `NonSyncSupercow` uses the `'static` lifetime, so simple
//! `Supercow`s are in general covariant.
//!
//! ```
//! use std::rc::Rc;
//!
//! use supercow::Supercow;
//!
//! fn assert_covariance<'a, 'b: 'a>(
//! imm: Supercow<'b, u32>,
//! bor: &'b Supercow<'b, u32>)
//! {
//! let _imm_a: Supercow<'a, u32> = imm;
//! let _bor_aa: &'a Supercow<'a, u32> = bor;
//! let _bor_ab: &'a Supercow<'b, u32> = bor;
//! // Invalid, since the external `&'b` reference is declared to live longer
//! // than the internal `&'a` reference.
//! // let _bor_ba: &'b Supercow<'a, u32> = bor;
//! }
//!
//! # fn main() { }
//! ```
//!
//! ## `Sync` and `Send`
//!
//! A `Supercow` is `Sync` and `Send` iff the types it contains, including the
//! shared reference type, are.
//!
//! ```
//! use supercow::Supercow;
//!
//! fn assert_sync_and_send<T : Sync + Send>(_: T) { }
//! fn main() {
//! let s: Supercow<u32> = Supercow::owned(42);
//! assert_sync_and_send(s);
//! }
//! ```
//!
//! # Performance Considerations
//!
//! ## Construction Cost
//!
//! Since it inherently moves certain decisions about ownership from
//! compile-time to run-time, `Supercow` is obviously not as fast as using an
//! owned value directly or a reference directly.
//!
//! Constructing any kind of `Supercow` with a normal reference is very fast,
//! only requiring a bit of internal memory initialisation besides setting the
//! reference itself.
//!
//! The defual `Supercow` type boxes the owned type and double-boxes the shared
//! type. This obviously dominates construction cost in those cases.
//!
//! `InlineSupercow` eliminates one box layer. This means that constructing an
//! owned instance is simply a move of the owned structure plus the common
//! reference initialisation. Shared values still by default require one boxing
//! level as well as virtual dispatch on certain operations; as described
//! above, this property too can be dealt with by using a custom `SHARED` type.
//!
//! ## Destruction Cost
//!
//! Destroying a `Supercow` is roughly the same proportional cost of creating
//! it.
//!
//! ## `Deref` Cost
//!
//! For the default `Supercow` type, the `Deref` is exactly equivalent to
//! dereferencing an `&&BORROWED`.
//!
//! For `InlineSupercow`, the implementation is a bit slower, comparable to
//! `std::borrow::Cow` but with fewer memory accesses..
//!
//! In all cases, the `Deref` implementation is not dependent on the ownership
//! mode of the `Supercow`, and so is not affected by the shared reference
//! type, most importantly, making no virtual function calls even under the
//! default boxed shared reference type. However, the way it works colud
//! prevent LLVM optimisations from applying in particular circumstances.
//!
//! For those wanting specifics, the function
//!
//! ```ignore
//! // Substitute Cow with InlineSupercow for the other case.
//! // This takes references so that the destructor code is not intermingled.
//! fn add_two(a: &Cow<u32>, b: &Cow<u32>) -> u32 {
//! **a + **b
//! }
//! ```
//!
//! results in the following on AMD64 with Rust 1.13.0:
//!
//! ```text
//! Cow Supercow
//! cmp DWORD PTR [rdi],0x1 mov rcx,QWORD PTR [rdi]
//! lea rcx,[rdi+0x4] xor eax,eax
//! cmovne rcx,QWORD PTR [rdi+0x8] cmp rcx,0x800
//! cmp DWORD PTR [rsi],0x1 cmovae rdi,rax
//! lea rax,[rsi+0x4] mov rdx,QWORD PTR [rsi]
//! cmovne rax,QWORD PTR [rsi+0x8] cmp rdx,0x800
//! mov eax,DWORD PTR [rax] cmovb rax,rsi
//! add eax,DWORD PTR [rcx] mov eax,DWORD PTR [rax+rdx]
//! ret add eax,DWORD PTR [rdi+rcx]
//! ret
//! ```
//!
//! The same code on ARM v7l and Rust 1.12.1:
//!
//! ```text
//! Cow Supercow
//! push {fp, lr} ldr r2, [r0]
//! mov r2, r0 ldr r3, [r1]
//! ldr r3, [r2, #4]! cmp r2, #2048
//! ldr ip, [r0] addcc r2, r2, r0
//! mov r0, r1 cmp r3, #2048
//! ldr lr, [r0, #4]! addcc r3, r3, r1
//! ldr r1, [r1] ldr r0, [r2]
//! cmp ip, #1 ldr r1, [r3]
//! moveq r3, r2 add r0, r1, r0
//! cmp r1, #1 bx lr
//! ldr r2, [r3]
//! moveq lr, r0
//! ldr r0, [lr]
//! add r0, r0, r2
//! pop {fp, pc}
//! ```
//!
//! If the default `Supercow` is used above instead of `InlineSupercow`, the
//! function actually compiles to the same thing as one taking two `&u32`
//! arguments. (This is partially due to optimisations eliminating one level of
//! indirection; if the optimiser did not do as much, it would be equivalent to
//! taking two `&&u32` arguments.)
//!
//! ## `to_mut` Cost
//!
//! Obtaining a `Ref` is substantially more expensive than `Deref`, as it must
//! inspect the ownership mode of the `Supercow` and possibly move it into the
//! owned mode. This will include a virtual call to the boxed shared reference
//! if in shared mode when using the default `Supercow` shared reference type.
//!
//! There is also cost in releasing the mutable reference, though
//! insubstantial in comparison.
//!
//! ## Memory Usage
//!
//! The default `Supercow` is only one pointer wider than a mundane reference
//! on Rust 1.13.0 and later. Earlier Rust versions have an extra word due to
//! the drop flag.
//!
//! ```
//! use std::mem::size_of;
//!
//! use supercow::Supercow;
//!
//! // Determine the size of the drop flag including alignment padding.
//! // On Rust 0.13.0+, `dflag` will be zero.
//! struct DropFlag(*const ());
//! impl Drop for DropFlag { fn drop(&mut self) { } }
//! let dflag = size_of::<DropFlag>() - size_of::<*const ()>();
//!
//! assert_eq!(size_of::<&'static u32>() + size_of::<*const ()>() + dflag,
//! size_of::<Supercow<'static, u32>>());
//!
//! assert_eq!(size_of::<&'static str>() + size_of::<*const ()>() + dflag,
//! size_of::<Supercow<'static, String, str>>());
//! ```
//!
//! Of course, you also pay for heap space in this case when using owned or
//! shared `Supercow`s.
//!
//! `InlineSupercow` can be quite large in comparison to a normal reference.
//! You need to be particularly careful that structures you reference don't
//! themselves contain `InlineSupercow`s or you can end up with
//! quadratically-sized or even exponentially-sized structures.
//!
//! ```
//! use std::mem;
//!
//! use supercow::InlineSupercow;
//!
//! // Define our structures
//! // (The extra lifetimes are needed for intra-function lifetime inference to
//! // succeed.)
//! struct Big([u8;1024]);
//! struct A<'a>(InlineSupercow<'a, Big>);
//! struct B<'b,'a:'b>(InlineSupercow<'b, A<'a>>);
//! struct C<'b,'a:'b>(InlineSupercow<'b, B<'a,'a>>);
//!
//! // Now say an API consumer, etc, decides to use references
//! let big = Big([0u8;1024]);
//! let a = A((&big).into());
//! let b = B((&a).into());
//! let c = C((&b).into());
//!
//! // Well, we've now allocated space for four `Big`s on the stack, despite
//! // only really needing one.
//! assert!(mem::size_of_val(&big) + mem::size_of_val(&a) +
//! mem::size_of_val(&b) + mem::size_of_val(&c) >
//! 4 * mem::size_of::<Big>());
//! ```
//!
//! # Other Notes
//!
//! Using `Supercow` will not give your application `apt-get`-style Super Cow
//! Powers.
pub mod ext;
use std::borrow::Borrow;
use std::cmp;
use std::convert::AsRef;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
use self::ext::*;
/// Defines a "feature set" for a custom `Supercow` type.
///
/// ## Syntax
///
/// ```
/// #[macro_use] extern crate supercow;
///
/// # pub trait SomeTrait { }
/// # pub trait AnotherTrait { }
///
/// supercow_features!(
/// /// Some documentation, etc, if desired.
/// pub trait FeatureName: SomeTrait, AnotherTrait);
/// supercow_features!(
/// pub trait FeatureName2: SomeTrait, Clone, AnotherTrait);
///
/// # fn main() { }
/// ```
///
/// ## Semantics
///
/// A public trait named `FeatureName` is defined which extends all the listed
/// traits, minus special cases below, and in addition to `ConstDeref`.
///
/// If `Clone` is listed, the trait gains a `clone_boxed()` method and
/// `Box<FeatureName>` is `Clone`.
///
/// All types which implement all the listed traits (including special cases)
/// and `ConstDeref` implement `FeatureName`.
#[macro_export]
macro_rules! supercow_features {
($(#[$meta:meta])* pub trait $feature_name:ident: $($stuff:ident),*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
[] [] $($stuff),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:tt),*] Clone $(, $more:ident)*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
[Clone clone_boxed] [$($others)*]
$($more),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:ident),*] $other:ident $(, $more:tt)*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
$clone [$($others, )* $other]
$($more),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:ident),*]) => {
supercow_features!(@_DEFINE $(#[$meta])* pub trait $feature_name:
$clone [$($others),*]);
};
(@_DEFINE $(#[$meta:meta])*
pub trait $feature_name:ident:
[$($clone:ident $clone_boxed:ident)*] [$($req:ident),*]) => {
$(#[$meta])*
pub trait $feature_name<'a>: $($req +)* $crate::ext::ConstDeref + 'a {
$(
/// Clone this value, and then immediately put it into a `Box`
/// behind a trait object of this trait.
fn $clone_boxed
(&self)
-> Box<$feature_name<'a, Target = Self::Target> + 'a>;
)*
}
impl<'a, T : 'a + $($req +)* $($clone +)* $crate::ext::ConstDeref>
$feature_name<'a> for T {
$(
fn $clone_boxed
(&self)
-> Box<$feature_name<'a, Target = Self::Target> + 'a>
{
let cloned: T = self.clone();
Box::new(cloned)
}
)*
}
impl<'a, T : $feature_name<'a>> $crate::ext::SharedFrom<T>
for Box<$feature_name<'a, Target = T::Target> + 'a> {
fn shared_from(t: T) -> Self {
Box::new(t)
}
}
$(
impl<'a, S : 'a + ?Sized> $clone for Box<$feature_name<'a, Target = S> + 'a> {
fn clone(&self) -> Self {
$feature_name::clone_boxed(&**self)
}
}
)*
};
}
supercow_features!(
/// The default shared reference type for `Supercow`.
///
/// This requires the shared reference type to be `Clone`, `Send`, and
/// `Sync`, which thus disqualifies using `Rc`. This was chosen as the
/// default since the inability to use `Rc` is generally a less subtle
/// issue than the `Supercow` not being `Send` or `Sync`.
///
/// See also `NonSyncFeatures`.
pub trait DefaultFeatures: Clone, Send, Sync);
supercow_features!(
/// The shared reference type for `NonSyncSupercow`.
///
/// Unlike `DefaultFeatures`, this only requires the shared reference type
/// to be `Clone`, thus permitting `Rc`.
pub trait NonSyncFeatures: Clone);
/// `Supercow` with the default `SHARED` changed to `NonSyncFeatures`, enabling
/// the use of `Rc` as a shared reference type as well as making it possible to
/// use non-`Send` or non-`Sync` `BORROWED` types easily.
///
/// Note that the `SHARED` type must have `'static` lifetime, since this is
/// generally more convenient and makes the `Supercow` as a whole covariant.
///
/// ## Example
///
/// ```
/// use supercow::{NonSyncSupercow, Supercow};
///
/// # fn main() {
/// let x: NonSyncSupercow<u32> = Supercow::owned(42u32);
/// println!("{}", *x);
/// # }
/// ```
pub type NonSyncSupercow<'a, OWNED, BORROWED = OWNED> =
Supercow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
BoxedStorage>;
/// `Supercow` with the default `STORAGE` changed to `InlineStorage`.
///
/// This reduces the number of allocations needed to construct an owned or
/// shared `Superow` (down to zero for owned, but note that the default
/// `SHARED` still has its own `Box`) at the cost of bloating the `Supercow`
/// itself, as it now needs to be able to fit a whole `OWNED` instance.
pub type InlineSupercow<'a, OWNED, BORROWED = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>> =
Supercow<'a, OWNED, BORROWED, SHARED, InlineStorage<OWNED, SHARED>>;
/// `NonSyncSupercow` with the `STORAGE` changed to `InlineStorage`.
///
/// This combines both properties of `NonSyncSupercow` and `InlineSupercow`.
pub type InlineNonSyncSupercow<'a, OWNED, BORROWED = OWNED> =
Supercow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
InlineStorage<OWNED, Box<
NonSyncFeatures<'static, Target = BORROWED> + 'static>>>;
/// The actual generic reference type.
///
/// See the module documentation for most of the details.
///
/// The generics here may look somewhat frightening at first; try not to be too
/// alarmed, and remember that in most use-cases all you need to worry about is
/// the stuff concerning `OWNED`.
pub struct Supercow<'a, OWNED, BORROWED : ?Sized = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>,
STORAGE = BoxedStorage>
where BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
STORAGE : OwnedStorage<OWNED, SHARED> {
// This stores the precalculated `Deref` target, and is the only thing the
// `Deref` implementation needs to inspect.
//
// Note that there are three cases with references:
//
// - A reference to an external value. In this case, we know that the
// reference will not be invalidated by movement or for the lifetime of
// `'a` and simply store the reference here as an absolute address.
//
// - A reference to a ZST at an "external" location, often address 1. We
// don't need to handle this in any particular manner as long as we don't
// accidentally make a null reference, since the only thing safe rust can
// do with a ZST reference is inspect its address, and if we do "move" it
// around, there's nothing unsafe from this fact being leaked.
//
// - A reference into this `Supercow`. In this case, the absolute address
// will change whenever this `Supercow` is relocated. To handle this, we
// instead store the offset from `&self` here, and adjust it at `Deref`
// time. We differentiate between the two cases by inspecting the absolute
// value of the address: If it is less than
// `MAX_INTERNAL_BORROW_DISPLACEMENT*2`, we assume it is an internal
// reference, since no modern system ever has virtual memory mapped between
// 0 and 4kB (and any code elsewhere involving this region is presumably
// too low-level to be using `Supercow`).
//
// One pecularity is that this is declared as a reference even though it
// does not necessarily reference anything. This is so that it works with
// DSTs, which have references larger than pointers. We assume the first
// pointer-sized value is the actual address (see `PointerFirstRef`).
//
// We do need to take care that we still don't create a null reference
// here; there is code to check for Rust putting the internal storage first
// in the struct and adding 1 if this happens.
//
// If `STORAGE` does not use internal pointers, we can skip all the
// arithmetic and return this value unmodified.
ptr: &'a BORROWED,
// The current ownership mode of this `Supercow`.
//
// This has three states:
//
// - Null. The `Supercow` holds a `&'a BORROWED`.
//
// - Even alignment. The `Supercow` holds an `OWNED` accessible via
// `STORAGE`, and this value is what is passed into the `STORAGE` methods.
//
// - Odd alignment. The `Supercow` holds a `SHARED`, behind a `Box` at the
// address one less than this value. Note that since the default `SHARED`
// is a `Box<DefaultFeatures>`, we actually end up with two levels of
// boxing here. This is actually necessary so that the whole thing only
// takes one immediate pointer.
mode: *mut (),
storage: STORAGE,
_owned: PhantomData<OWNED>,
_shared: PhantomData<SHARED>,
}
/// `Phantomcow<'a, Type>` is to `Supercow<'a, Type>` as
/// `PhantomData<&'a Type>` is to `&'a Type`.
///
/// That is, `Phantomcow` effects a lifetime dependency on the borrowed value,
/// while still permitting the owned and shared modes of `Supercow`, and
/// keeping the underlying objects alive as necessary.
///
/// There is not much one can do with a `Phantomcow`; it can be moved around,
/// and in some cases cloned. Its main use is in FFI wrappers, where `BORROWED`
/// maintains some external state or resource that will be destroyed when it
/// is, and which the owner of the `Phantomcow` depends on to function.
///
/// The size of a `Phantomcow` is generally equal to the size of the
/// corresponding `Supercow` type minus the size of `&'a BORROWED`, though this
/// may not be exact depending on `STORAGE` alignment, etc.
pub struct Phantomcow<'a, OWNED, BORROWED : ?Sized = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>,
STORAGE = BoxedStorage>
where BORROWED : 'a,
STORAGE : OwnedStorage<OWNED, SHARED> {
mode: *mut (),
storage: STORAGE,
_owned: PhantomData<OWNED>,
_borrowed: PhantomData<&'a BORROWED>,
_shared: PhantomData<SHARED>
}
/// The `Phantomcow` variant corresponding to `NonSyncSupercow`.
pub type NonSyncPhantomcow<'a, OWNED, BORROWED = OWNED> =
Phantomcow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
BoxedStorage>;
/// The `Phantomcow` variant corresponding to `InlineStorage`.
pub type InlinePhantomcow<'a, OWNED, BORROWED = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>> =
Phantomcow<'a, OWNED, BORROWED, SHARED, InlineStorage<OWNED, SHARED>>;
/// The `Phantomcow` variant corresponding to `InlineNonSyncSupercow`.
pub type InlineNonSyncPhantomcow<'a, OWNED, BORROWED = OWNED> =
Phantomcow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
InlineStorage<OWNED, Box<
NonSyncFeatures<'static, Target = BORROWED> + 'static>>>;
enum SupercowMode {
Owned(*mut ()),
Borrowed,
Shared(*mut ()),
}
impl SupercowMode {
fn from_ptr(mode: *mut ()) -> Self {
if mode.is_null() {
Borrowed
} else if 0 == (mode as usize & 1) {
Owned(mode)
} else {
Shared((mode as usize & !1usize) as *mut ())
}
}
}
use self::SupercowMode::*;
macro_rules! defimpl {
($(@$us:tt)* [$($tparm:ident $(: ?$tparmsized:ident)*),*] ($($spec:tt)*)
where { $($wo:tt)* } $body:tt) => {
$($us)* impl<'a, $($tparm $(: ?$tparmsized)*,)* OWNED,
BORROWED : ?Sized, SHARED, STORAGE>
$($spec)* Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>
where BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
STORAGE : OwnedStorage<OWNED, SHARED>,
$($wo)*
$body
}
}
macro_rules! defphantomimpl {
($(@$us:tt)* [$($tparm:ident $(: ?$tparmsized:ident)*),*] ($($spec:tt)*)
where { $($wo:tt)* } $body:tt) => {
$($us)* impl<'a, $($tparm $(: ?$tparmsized)*,)* OWNED,
BORROWED : ?Sized, SHARED, STORAGE>
$($spec)* Phantomcow<'a, OWNED, BORROWED, SHARED, STORAGE>
where BORROWED : 'a,
STORAGE : OwnedStorage<OWNED, SHARED>,
$($wo)*
$body
}
}
defimpl! {[] (Drop for) where { } {
fn drop(&mut self) {
match self.mode() {
Owned(ptr) => unsafe { self.storage.deallocate_a(ptr) },
Shared(ptr) => unsafe { self.storage.deallocate_b(ptr) },
Borrowed => (),
}
}
} }
defphantomimpl! {[] (Drop for) where { } {
fn drop(&mut self) {
match SupercowMode::from_ptr(self.mode) {
Owned(ptr) => unsafe { self.storage.deallocate_a(ptr) },
Shared(ptr) => unsafe { self.storage.deallocate_b(ptr) },
Borrowed => (),
}
}
} }
defimpl! {@unsafe [] (Send for) where {
OWNED : Send,
&'a BORROWED : Send,
SHARED : Send,
STORAGE : Send,
} { } }
defphantomimpl! {@unsafe [] (Send for) where {
OWNED : Send,
SHARED : Send,
STORAGE : Send,
} { } }
defimpl! {@unsafe [] (Sync for) where {
OWNED : Sync,
&'a BORROWED : Sync,
SHARED : Sync,
STORAGE : Sync,
} { } }
defphantomimpl! {@unsafe [] (Sync for) where {
OWNED : Sync,
SHARED : Sync,
STORAGE : Sync,
} { } }
defimpl! {[] () where { } {
/// Creates a new `Supercow` which owns the given value.
///
/// This can create a `Supercow` with a `'static` lifetime.
pub fn owned(inner: OWNED) -> Self
where OWNED : SafeBorrow<BORROWED> {
let mut this = unsafe { Self::empty() };
this.mode = this.storage.allocate_a(inner);
// This line could panic, but `this` doesn't have anything that would
// run destructors at this point other than `storage`, which was
// initialised in an ordinary way.
unsafe { this.borrow_owned(); }
this
}
/// Creates a new `Supercow` which borrows the given value.
pub fn borrowed<T : Borrow<BORROWED> + ?Sized>(inner: &'a T) -> Self {
let mut this = unsafe { Self::empty() };
this.ptr = inner.borrow();
this
}
/// Creates a new `Supercow` using the given shared reference.
///
/// The reference must be convertable to `SHARED` via `SharedFrom`.
pub fn shared<T>(inner: T) -> Self
where SHARED : SharedFrom<T> + ConstDeref<Target = BORROWED> {
Self::shared_nocvt(SHARED::shared_from(inner))
}
fn shared_nocvt(shared: SHARED) -> Self
where SHARED : ConstDeref<Target = BORROWED> {
let mut this = unsafe { Self::empty() };
this.ptr = unsafe {
&*(shared.const_deref() as *const BORROWED)
};
let nominal_mode = this.storage.allocate_b(shared);
this.mode = (1usize | (nominal_mode as usize)) as *mut ();
this
}
/// If `this` is non-owned, clone `this` and return it.
///
/// Otherwise, return `None`.
///
/// ## Example
///
/// ```
/// use supercow::Supercow;
///
/// struct SomeNonCloneThing;
///
/// let owned: Supercow<SomeNonCloneThing> = SomeNonCloneThing.into();
/// assert!(Supercow::clone_non_owned(&owned).is_none());
///
/// let the_thing = SomeNonCloneThing;
/// let borrowed: Supercow<SomeNonCloneThing> = (&the_thing).into();
/// let also_borrowed = Supercow::clone_non_owned(&borrowed).unwrap();
/// ```
pub fn clone_non_owned(this: &Self) -> Option<Self>
where SHARED : Clone + ConstDeref<Target = BORROWED> {
match this.mode() {
Owned(_) => None,
Borrowed => Some(Supercow {
ptr: this.ptr,
mode: this.mode,
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
}),
Shared(s) => Some(Self::shared_nocvt(unsafe {
this.storage.get_ptr_b(s)
}.clone())),
}
}
/// If `this` is borrowed, return the underlying reference with the
/// original lifetime. Otherwise, return `None`.
///
/// The returned reference has a lifetime independent of `this`.
///
/// This can be used to bridge between `Supercow` APIs and mundane
/// reference APIs without needing to restrict the lifetime to the
/// `Supercow`, but as a result is only available if the contained
/// reference is actually independent.
///
/// ## Example
///
/// ```
/// use std::sync::Arc;
///
/// use supercow::Supercow;
///
/// let fourty_two: u32 = 42;
///
/// let borrowed: Supercow<u32> = (&fourty_two).into();
/// assert_eq!(Some(&fourty_two), Supercow::extract_ref(&borrowed));
///
/// let owned: Supercow<u32> = fourty_two.into();
/// assert_eq!(None, Supercow::extract_ref(&owned));
///
/// let shared: Supercow<u32> = Arc::new(fourty_two).into();
/// assert_eq!(None, Supercow::extract_ref(&shared));
/// ```
pub fn extract_ref(this: &Self) -> Option<&'a BORROWED> {
match this.mode() {
Borrowed => Some(this.ptr),
_ => None,
}
}
/// Takes ownership of the underling value if needed, then returns it,
/// consuming `self`.
pub fn into_inner(mut this: Self) -> OWNED
where OWNED : Borrow<BORROWED>,
BORROWED : ToOwned<Owned = OWNED> {
match this.mode() {
Owned(ptr) => {
unsafe { this.storage.deallocate_into_a(ptr) }
},
_ => (*this).to_owned(),
}
}
/// Returns a (indirect) mutable reference to an underlying owned value.
///
/// If this `Supercow` does not currently own the value, it takes
/// ownership. A `Ref` is then returned which allows accessing the mutable
/// owned value directly.
///
/// ## Leak Safety
///
/// If the returned `Ref` is released without its destructor being run, the
/// behaviour of the `Supercow` is unspecified (but does not result in
/// memory unsafety).
pub fn to_mut<'b>
(&'b mut self)
-> Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where OWNED : SafeBorrow<BORROWED>,
BORROWED : ToOwned<Owned = OWNED>,
{
// Become owned if not already.
match self.mode() {
Owned(_) => (),
_ => *self = Self::owned((*self).to_owned()),
}
// Clear out `ptr` if it points somewhere unstable
self.ptr = OWNED::borrow_replacement(self.ptr);
Ref {
r: unsafe { self.storage.get_mut_a(self.mode) } as *mut OWNED,
parent: self,
}
}
/// Converts this `Supercow` into a `Phantomcow`.
pub fn phantom(mut this: Self)
-> Phantomcow<'a, OWNED, BORROWED, SHARED, STORAGE> {
let ret = Phantomcow {
mode: this.mode,
storage: mem::replace(&mut this.storage, Default::default()),
_owned: PhantomData,
_borrowed: PhantomData,
_shared: PhantomData,
};
this.mode = ptr::null_mut();
ret
}
unsafe fn borrow_owned(&mut self)
where OWNED : SafeBorrow<BORROWED> {
// There's no safe way to propagate `borrowed_ptr` into
// `ptr` since the former has a borrow scoped to this
// function.
{
let borrowed_ptr = self.storage.get_ptr_a(self.mode).borrow();
self.ptr = &*(borrowed_ptr as *const BORROWED);
}
// Adjust the pointer if needed
if STORAGE::is_internal_storage() {
let self_start = self as *mut Self as usize;
let self_end = self_start + mem::size_of::<Self>();
let bias = self.relative_pointer_bias();
let ptr_address: &mut usize = mem::transmute(&mut self.ptr);
if *ptr_address >= self_start && *ptr_address < self_end {
debug_assert!(*ptr_address - self_start <
MAX_INTERNAL_BORROW_DISPLACEMENT * 3/2,
"Borrowed pointer displaced too far from \
base address (supercow at {:x}, self at {:x}, \
borrowed to {:x}", self_start,
&self.storage as *const STORAGE as usize,
*ptr_address);
*ptr_address -= self_start - bias;
}
}
}
unsafe fn empty() -> Self {
Supercow {
ptr: mem::uninitialized(),
mode: ptr::null_mut(),
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
}
}
fn mode(&self) -> SupercowMode {
SupercowMode::from_ptr(self.mode)
}
/// Returns the bias to use for relative pointers to avoid creating null
/// references.
///
/// If rust lays this structure out such that `storage_address` is at the
/// base of `self`, returns 1. Otherwise, no bias is needed and it returns
/// 0.
#[inline(always)]
fn relative_pointer_bias(&self) -> usize {
let self_address = self as *const Self as usize;
let storage_address = &self.storage as *const STORAGE as usize;
if self_address == storage_address {
1
} else {
0
}
}
} }
// Separate `impl` as rustc doesn't seem to like having multiple `&'x Type`
// constraints in one place.
impl<'a, OWNED, BORROWED : ?Sized, SHARED, STORAGE>
Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>
where OWNED : SafeBorrow<BORROWED>,
BORROWED : 'a + ToOwned<Owned = OWNED>,
for<'l> &'l BORROWED : PointerFirstRef,
SHARED : ConstDeref<Target = BORROWED>,
STORAGE : OwnedStorage<OWNED, SHARED> {
/// Takes ownership of the underlying value, so that this `Supercow` has a
/// `'static` lifetime.
///
/// This may also change the `SHARED` type parameter arbitrarily (which
/// happens, eg, when converting from `Supercow<'a,u32>` to
/// `Supercow<'static,u32>`).
///
/// ## Example
///
/// ```
/// use supercow::Supercow;
///
/// let s = {
/// let fourty_two = 42u32;
/// let by_ref: Supercow<u32> = Supercow::borrowed(&fourty_two);
/// // We can't return `by_ref` because it holds a reference to
/// // `fourty_two`. However, we can change that lifetime parameter
/// // to `'static` and then move that out of the block.
/// let by_val: Supercow<'static, u32> =
/// Supercow::take_ownership(by_ref);
/// by_val
/// };
/// assert_eq!(42, *s);
/// ```
pub fn take_ownership<NS : ConstDeref<Target = BORROWED>>
(mut this: Self) -> Supercow<'static, OWNED, BORROWED, NS, STORAGE>
where STORAGE : OwnedStorage<OWNED, NS> {
let static_ptr: &'static BORROWED =
unsafe { &*(this.ptr as *const BORROWED) };
match this.mode() {
Owned(_) => Supercow {
ptr: static_ptr,
mode: this.mode,
storage: mem::replace(&mut this.storage, Default::default()),
_owned: PhantomData,
_shared: PhantomData,
},
_ => Supercow::owned((*this).to_owned()),
}
}
}
/// Provides mutable access to an owned value within a `Supercow`.
///
/// This is similar to the `Ref` used with `RefCell`.
pub struct Ref<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
r: *mut OWNED,
parent: &'b mut Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>,
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> Deref
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
type Target = OWNED;
#[inline]
fn deref(&self) -> &OWNED {
unsafe { &*self.r }
}
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> DerefMut
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
#[inline]
fn deref_mut(&mut self) -> &mut OWNED {
unsafe { &mut*self.r }
}
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> Drop
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
#[inline]
fn drop(&mut self) {
// The value of `OWNED::borrow()` may have changed, so recompute
// everything instead of backing the old values up.
unsafe { self.parent.borrow_owned() }
}
}
defimpl! {[] (Deref for) where { } {
type Target = BORROWED;
#[inline]
fn deref(&self) -> &BORROWED {
let self_address = self as *const Self as usize;
let mut target_ref = self.ptr;
unsafe {
let target_address: &mut usize = mem::transmute(&mut target_ref);
let nominal_address = *target_address;
if STORAGE::is_internal_storage() &&
nominal_address < MAX_INTERNAL_BORROW_DISPLACEMENT
{
*target_address = nominal_address + self_address -
self.relative_pointer_bias();
}
}
target_ref
}
} }
defimpl! {[] (Borrow<BORROWED> for) where { } {
fn borrow(&self) -> &BORROWED {
self.deref()
}
} }
defimpl! {[] (AsRef<BORROWED> for) where { } {
fn as_ref(&self) -> &BORROWED {
self.deref()
}
} }
defimpl! {[] (Clone for) where {
OWNED : Clone + SafeBorrow<BORROWED>,
SHARED : Clone + ConstDeref<Target = BORROWED>,
} {
fn clone(&self) -> Self {
match self.mode() {
Owned(ptr) => Self::owned(unsafe {
self.storage.get_ptr_a(ptr)
}.clone()),
Borrowed => Supercow {
ptr: self.ptr,
mode: self.mode,
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
},
Shared(s) => Self::shared_nocvt(unsafe {
self.storage.get_ptr_b(s)
}.clone()),
}
}
} }
defphantomimpl! {[] (Clone for) where {
OWNED : Clone,
SHARED : Clone,
} {
fn clone(&self) -> Self {
let mut clone: Self = Phantomcow {
mode: ptr::null_mut(),
storage: Default::default(),
_owned: PhantomData,
_borrowed: PhantomData,
_shared: PhantomData,
};
match SupercowMode::from_ptr(self.mode) {
Owned(ptr) => clone.mode = clone.storage.allocate_a(
unsafe { self.storage.get_ptr_a(ptr) }.clone()),
Borrowed => (),
Shared(ptr) => {
let m = clone.storage.allocate_b(
unsafe { self.storage.get_ptr_b(ptr) }.clone());
clone.mode = (1usize | (m as usize)) as *mut ();
},
}
clone
}
} }
defimpl! {[] (From<OWNED> for) where {
OWNED : SafeBorrow<BORROWED>,
} {
fn from(inner: OWNED) -> Self {
Self::owned(inner)
}
} }
// For now, we can't accept `&BORROWED` because it's theoretically possible for
// someone to make `<BORROWED as ToOwned>::Owned = &BORROWED`, in which case
// the `OWNED` version above would apply.
//
// Maybe once specialisation lands in stable, we can make `From` do what we
// want everywhere.
defimpl! {[] (From<&'a OWNED> for) where {
// Does not need to be `SafeBorrow` since it's not embedded inside us.
OWNED : Borrow<BORROWED>,
} {
fn from(inner: &'a OWNED) -> Self {
Self::borrowed(inner.borrow())
}
} }
// Similarly, we can't support arbitrary types here, and need to require
// `BORROWED == OWNED` for `Rc` and `Arc`. Ideally, we'd support anything that
// coerces into `SHARED`. Again, maybe one day after specialisation..
impl<'a, OWNED, SHARED, STORAGE> From<Rc<OWNED>>
for Supercow<'a, OWNED, OWNED, SHARED, STORAGE>
where SHARED : ConstDeref<Target = OWNED> + SharedFrom<Rc<OWNED>>,
STORAGE : OwnedStorage<OWNED, SHARED>,
OWNED : 'a,
&'a OWNED : PointerFirstRef {
fn from(rc: Rc<OWNED>) -> Self {
Self::shared(rc)
}
}
impl<'a, OWNED, SHARED, STORAGE> From<Arc<OWNED>>
for Supercow<'a, OWNED, OWNED, SHARED, STORAGE>
where SHARED : ConstDeref<Target = OWNED> + SharedFrom<Arc<OWNED>>,
STORAGE : OwnedStorage<OWNED, SHARED>,
OWNED : 'a,
&'a OWNED : PointerFirstRef {
fn from(rc: Arc<OWNED>) -> Self {
Self::shared(rc)
}
}
macro_rules! deleg_fmt { ($tr:ident) => {
defimpl! {[] (fmt::$tr for) where {
BORROWED : fmt::$tr
} {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
} }
} }
deleg_fmt!(Binary);
deleg_fmt!(Debug);
deleg_fmt!(Display);
deleg_fmt!(LowerExp);
deleg_fmt!(LowerHex);
deleg_fmt!(Octal);
deleg_fmt!(Pointer);
deleg_fmt!(UpperExp);
deleg_fmt!(UpperHex);
defimpl! {[T] (cmp::PartialEq<T> for) where {
T : Borrow<BORROWED>,
BORROWED : PartialEq<BORROWED>,
} {
fn eq(&self, other: &T) -> bool {
**self == *other.borrow()
}
fn ne(&self, other: &T) -> bool {
**self != *other.borrow()
}
} }
defimpl! {[] (cmp::Eq for) where {
BORROWED : Eq
} { } }
defimpl! {[T] (cmp::PartialOrd<T> for) where {
T : Borrow<BORROWED>,
BORROWED : cmp::PartialOrd<BORROWED>,
} {
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
(**self).partial_cmp(other.borrow())
}
fn lt(&self, other: &T) -> bool {
**self < *other.borrow()
}
fn le(&self, other: &T) -> bool {
**self <= *other.borrow()
}
fn gt(&self, other: &T) -> bool {
**self > *other.borrow()
}
fn ge(&self, other: &T) -> bool {
**self >= *other.borrow()
}
} }
defimpl! {[] (cmp::Ord for) where {
BORROWED : cmp::Ord
} {
fn cmp(&self, other: &Self) -> cmp::Ordering {
(**self).cmp(other)
}
} }
defimpl! {[] (Hash for) where {
BORROWED : Hash
} {
fn hash<H : Hasher>(&self, h: &mut H) {
(**self).hash(h)
}
} }
#[cfg(test)]
mod misc_tests {
use std::borrow::Cow;
use super::*;
// This is where the asm in the Performance Notes section comes from.
#[inline(never)]
fn add_two_cow(a: &Cow<u32>, b: &Cow<u32>) -> u32 {
**a + **b
}
#[inline(never)]
fn add_two_supercow(a: &InlineSupercow<u32>,
b: &InlineSupercow<u32>) -> u32 {
**a + **b
}
#[test]
fn do_add_two() {
// Need to call `add_two_cow` twice to prevent LLVM from specialising
// it.
assert_eq!(42, add_two_cow(&Cow::Owned(40), &Cow::Owned(2)));
assert_eq!(44, add_two_cow(&Cow::Borrowed(&38), &Cow::Borrowed(&6)));
assert_eq!(42, add_two_supercow(&Supercow::owned(40),
&Supercow::owned(2)));
}
}
macro_rules! tests { ($modname:ident, $stype:ident, $ptype:ident) => {
#[cfg(test)]
mod $modname {
use std::sync::Arc;
use super::*;
#[test]
fn ref_to_owned() {
let x = 42u32;
let a: $stype<u32> = Supercow::borrowed(&x);
assert_eq!(x, *a);
assert_eq!(&x as *const u32 as usize,
(&*a) as *const u32 as usize);
let mut b = a.clone();
assert_eq!(x, *b);
assert_eq!(&x as *const u32 as usize,
(&*b) as *const u32 as usize);
*b.to_mut() = 56;
assert_eq!(42, *a);
assert_eq!(x, *a);
assert_eq!(&x as *const u32 as usize,
(&*a) as *const u32 as usize);
assert_eq!(56, *b);
}
#[test]
fn supports_dst() {
let a: $stype<String, str> = Supercow::borrowed("hello");
let b: $stype<String, str> = Supercow::owned("hello".to_owned());
assert_eq!(a, b);
let mut c = a.clone();
c.to_mut().push_str(" world");
assert_eq!(a, b);
assert_eq!(c, "hello world");
}
#[test]
fn default_accepts_arc() {
let x: $stype<u32> = Supercow::shared(Arc::new(42u32));
assert_eq!(42, *x);
}
#[test]
fn ref_safe_even_if_forgotten() {
let mut x: $stype<String, str> = Supercow::owned("foo".to_owned());
{
let mut m = x.to_mut();
// Add a bunch of characters to invalidate the allocation
for _ in 0..65536 {
m.push('x');
}
// Prevent the dtor from running but allow us to release the borrow
::std::mem::forget(m);
}
// While the value has been corrupted, we have been left with a *safe*
// deref result nonetheless.
assert_eq!("", &*x);
// The actual String has not been lost so no memory has been leaked
assert_eq!(65539, x.to_mut().len());
}
#[test]
// `SipHasher` is deprecated, but its replacement `DefaultHasher` doesn't
// exist in Rust 1.12.1.
#[allow(deprecated)]
fn general_trait_delegs_work() {
use std::borrow::Borrow;
use std::convert::AsRef;
use std::cmp::*;
use std::hash::*;
macro_rules! test_fmt {
($fmt:expr, $x:expr) => {
assert_eq!(format!($fmt, 42u32), format!($fmt, $x));
}
}
let x: $stype<u32> = Supercow::owned(42u32);
test_fmt!("{}", x);
test_fmt!("{:?}", x);
test_fmt!("{:o}", x);
test_fmt!("{:x}", x);
test_fmt!("{:X}", x);
test_fmt!("{:b}", x);
assert!(x == 42);
assert!(x != 43);
assert!(x < 43);
assert!(x <= 43);
assert!(x > 41);
assert!(x >= 41);
assert_eq!(42.partial_cmp(&43), x.partial_cmp(&43));
assert_eq!(42.cmp(&43), x.cmp(&Supercow::owned(43)));
let mut expected_hash = SipHasher::new();
42u32.hash(&mut expected_hash);
let mut actual_hash = SipHasher::new();
x.hash(&mut actual_hash);
assert_eq!(expected_hash.finish(), actual_hash.finish());
assert_eq!(42u32, *x.borrow());
assert_eq!(42u32, *x.as_ref());
}
#[test]
fn owned_mode_survives_moving() {
// Using a `HashMap` here because it means the optimiser can't reason
// about which one will eventually be chosen, and so one of the values
// is guaranteed to eventually be moved off the heap onto the stack.
#[inline(never)]
fn pick_one() -> $stype<'static, String> {
use std::collections::HashMap;
let mut hm = HashMap::new();
hm.insert("hello", Supercow::owned("hello".to_owned()));
hm.insert("world", Supercow::owned("world".to_owned()));
hm.into_iter().map(|(_, v)| v).next().unwrap()
}
let s = pick_one();
assert!("hello".to_owned() == *s ||
"world".to_owned() == *s);
}
#[test]
fn dst_string_str() {
let mut s: $stype<'static, String, str> = String::new().into();
let mut expected = String::new();
for i in 0..1024 {
assert_eq!(expected.as_str(), &*s);
expected.push_str(&format!("{}", i));
s.to_mut().push_str(&format!("{}", i));
assert_eq!(expected.as_str(), &*s);
}
}
#[test]
fn dst_vec_u8s() {
let mut s: $stype<'static, Vec<u8>, [u8]> = Vec::new().into();
let mut expected = Vec::<u8>::new();
for i in 0..1024 {
assert_eq!(&expected[..], &*s);
expected.push((i & 0xFF) as u8);
s.to_mut().push((i & 0xFF) as u8);
assert_eq!(&expected[..], &*s);
}
}
#[test]
fn dst_osstring_osstr() {
use std::ffi::{OsStr, OsString};
let mut s: $stype<'static, OsString, OsStr> = OsString::new().into();
let mut expected = OsString::new();
for i in 0..1024 {
assert_eq!(expected.as_os_str(), &*s);
expected.push(&format!("{}", i));
s.to_mut().push(&format!("{}", i));
assert_eq!(expected.as_os_str(), &*s);
}
}
#[test]
fn dst_cstring_cstr() {
use std::ffi::{CStr, CString};
use std::mem;
use std::ops::Deref;
let mut s: $stype<'static, CString, CStr> =
CString::new("").unwrap().into();
let mut expected = CString::new("").unwrap();
for i in 0..1024 {
assert_eq!(expected.deref(), &*s);
{
let mut ve = expected.into_bytes_with_nul();
ve.pop();
ve.push(((i & 0xFF) | 1) as u8);
ve.push(0);
expected = unsafe {
CString::from_vec_unchecked(ve)
};
}
{
let mut m = s.to_mut();
let mut vs = mem::replace(&mut *m, CString::new("").unwrap())
.into_bytes_with_nul();
vs.pop();
vs.push(((i & 0xFF) | 1) as u8);
vs.push(0);
*m = unsafe {
CString::from_vec_unchecked(vs)
};
}
assert_eq!(expected.deref(), &*s);
}
}
#[test]
fn dst_pathbuf_path() {
use std::path::{Path, PathBuf};
let mut s: $stype<'static, PathBuf, Path> = PathBuf::new().into();
let mut expected = PathBuf::new();
for i in 0..1024 {
assert_eq!(expected.as_path(), &*s);
expected.push(format!("{}", i));
s.to_mut().push(format!("{}", i));
assert_eq!(expected.as_path(), &*s);
}
}
struct MockNativeResource(*mut u32);
impl Drop for MockNativeResource {
fn drop(&mut self) {
unsafe { *self.0 = 0 };
}
}
// Not truly safe, but we're not crossing threads here and we need
// something for the Sync tests either way.
unsafe impl Send for MockNativeResource { }
unsafe impl Sync for MockNativeResource { }
struct MockDependentResource<'a> {
ptr: *mut u32,
_handle: $ptype<'a, MockNativeResource>,
}
fn check_dependent_ok(mdr: MockDependentResource) {
assert_eq!(42, unsafe { *mdr.ptr });
}
#[test]
fn borrowed_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> = Supercow::borrowed(&native);
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn owned_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> = Supercow::owned(native);
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn shared_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> =
Supercow::shared(Arc::new(native));
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn clone_owned_phantomcow() {
let sc: $stype<String> = Supercow::owned("hello world".to_owned());
let p1 = Supercow::phantom(sc);
let _p2 = p1.clone();
}
#[test]
fn clone_borrowed_phantomcow() {
let sc: $stype<String, str> = Supercow::borrowed("hello world");
let p1 = Supercow::phantom(sc);
let _p2 = p1.clone();
}
#[test]
fn clone_shared_phantomcow() {
let sc: $stype<String> = Supercow::shared(
Arc::new("hello world".to_owned()));
let p1 = Supercow::phantom(sc);
let _p2 = p1.clone();
}
} } }
tests!(inline_sync_tests, InlineSupercow, InlinePhantomcow);
tests!(inline_nonsync_tests, InlineNonSyncSupercow, InlineNonSyncPhantomcow);
tests!(boxed_sync_tests, Supercow, Phantomcow);
tests!(boxed_nonsync_tests, NonSyncSupercow, NonSyncPhantomcow);
Add `Phantomcow::clone_non_owned()`.
// Copyright 2016 Jason Lingle
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(missing_docs)]
//! `Supercow` is `Cow` on steroids.
//!
//! `Supercow` provides a mechanism for making APIs that accept very general
//! references while maintaining very low overhead for usages not involving
//! heavy-weight references (eg, `Arc`). Though nominally similar to `Cow` in
//! structure (and being named after it), `Supercow` does not require the
//! containee to be `Clone` or `ToOwned` unless operations inherently depending
//! on either are invoked.
//!
//! # Quick Start
//!
//! ## Simple Types
//!
//! In many cases, you can think of a `Supercow` as having only one lifetime
//! parameter and one type parameter, corresponding to the lifetime and type of
//! an immutable reference.
//!
//! ```
//! extern crate supercow;
//!
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! # fn main() {
//! // Declare some data we want to reference.
//! let fourty_two = 42u32;
//! // Make a Supercow referencing the above.
//! // N.B. Type inference doesn't work reliably if there is nothing explicitly
//! // typed to which the Supercow is passed, so we declare the type of this
//! // variable explicitly.
//! let mut a: Supercow<u32> = Supercow::borrowed(&fourty_two);
//! // We can deref `a` to a `u32`, and also see that it does
//! // indeed reference `fourty_two`.
//! assert_eq!(42, *a);
//! assert_eq!(&fourty_two as *const u32, &*a as *const u32);
//!
//! // Clone `a` so that it also points to `fourty_two`.
//! let mut b = a.clone();
//! assert_eq!(42, *b);
//! assert_eq!(&fourty_two as *const u32, &*b as *const u32);
//!
//! // `to_mut()` can be used to mutate `a` and `b` independently, taking
//! // ownership as needed.
//! *a.to_mut() += 2;
//! assert_eq!(42, fourty_two);
//! assert_eq!(44, *a);
//! assert_eq!(42, *b);
//! assert_eq!(&fourty_two as *const u32, &*b as *const u32);
//!
//! *b.to_mut() = 56;
//! assert_eq!(44, *a);
//! assert_eq!(56, *b);
//! assert_eq!(42, fourty_two);
//!
//! // We can also use `Arc` transparently.
//! let mut c: Supercow<u32> = Supercow::shared(Arc::new(99));
//! assert_eq!(99, *c);
//! *c.to_mut() += 1;
//! assert_eq!(100, *c);
//! # }
//! ```
//!
//! ## Owned/Borrowed Types
//!
//! `Supercow` can have different owned and borrowed types, for example
//! `String` and `str`. In this case, the two are separate type parameters,
//! with the owned one written first. (Both need to be listed explicitly since
//! `Supercow` does not require the contained value to be `ToOwned`.)
//!
//! ```
//! extern crate supercow;
//!
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! # fn main() {
//! let hello: Supercow<String, str> = Supercow::borrowed("hello");
//! let mut hello_world = hello.clone();
//! hello_world.to_mut().push_str(" world");
//!
//! assert_eq!(hello, "hello");
//! assert_eq!(hello_world, "hello world");
//! # }
//! ```
//!
//! ## Accepting `Supercow` in an API
//!
//! If you want to make an API taking `Supercow` values, the recommended
//! approach is to accept anything that is `Into<Supercow<YourType>>`, which
//! allows bare owned types and references to owned values to be accepted as
//! well.
//!
//! ```
//! use std::sync::Arc;
//! use supercow::Supercow;
//!
//! fn some_api_function<'a, T : Into<Supercow<'a,u32>>>
//! (t: T) -> Supercow<'a,u32>
//! {
//! let mut x = t.into();
//! *x.to_mut() *= 2;
//! x
//! }
//!
//! fn main() {
//! assert_eq!(42, *some_api_function(21));
//! let twenty_one = 21;
//! assert_eq!(42, *some_api_function(&twenty_one));
//! assert_eq!(42, *some_api_function(Arc::new(21)));
//! }
//! ```
//!
//! ## Chosing the right variant
//!
//! `Supercow` is extremely flexible as to how it internally stores and manages
//! data. There are four variants provided by default: `Supercow`,
//! `NonSyncSupercow`, `InlineSupercow`, and `InlineNonSyncSupercow`. Here is a
//! quick reference on the trade-offs:
//!
//! | Variant | Send+Sync? | `Rc`? | Size | Init | Deref |
//! |-------------------|---------------|-------|-------|-------|------------|
//! | (Default) | Yes | No | Small | Slow | Very Fast |
//! | `NonSync` | No | Yes | Small | Slow | Very Fast |
//! | `Inline` | Yes | No | Big | Fast | Fast |
//! | `InlineNonSync` | No | Yes | Big | Fast | Fast |
//!
//! "Init" above specifically refers to initialisation with an owned value or
//! shared reference. Supercows constructed with mundane references always
//! construct extremely quickly.
//!
//! The only difference between the `NonSync` variant and the default is that
//! the default is to require the shared pointer type (eg, `Arc`) to be `Send`
//! and `Sync` (which thus prohibits using `Rc`), whereas `NonSync` does not
//! and so allows `Rc`. Note that a side-effect of the default `Send + Sync`
//! requirement is that the type of `BORROWED` also needs to be `Send` and
//! `Sync` when using `Arc` as the shared reference type; if it is not `Send`
//! and `Sync`, use `NonSyncSupercow` instead.
//!
//! By default, `Supercow` boxes any owned value or shared reference. This
//! makes the `Deref` implementation faster since it does not need to account
//! for internal pointers, but more importantly, means that the `Supercow` does
//! not need to reserve space for the owned and shared values, so the default
//! `Supercow` is only one pointer wider than a bare reference.
//!
//! The obvious problem with boxing values is that it makes construction of the
//! `Supercow` slower, as one must pay for an allocation. If you want to avoid
//! the allocation, you can use the `Inline` variants instead, which store the
//! values inline inside the `Supercow`. (Note that if you are looking to
//! eliminate allocation entirely, you will also need to tinker with the
//! `SHARED` type, which by default has its own `Box` as well.) Note that this
//! of course makes the `Supercow` much bigger; be particularly careful if you
//! create a hierarchy of things containing `InlineSupercow`s referencing each
//! other, as each would effectively have space for the entire tree above it
//! inline.
//!
//! The default to box values was chosen on the grounds that it is generally
//! easier to use, less likely to cause confusing problems, and in many cases
//! the allocation doesn't affect performance:
//!
//! - In either choice, creating a `Supercow` with a borrowed reference incurs
//! no allocation. The boxed option will actually be slightly faster since it
//! does not need to initialise as much memory and results in better locality
//! due to being smaller.
//!
//! - The value contained usually is reasonably expensive to construct anyway,
//! or else there would be less incentive to pass it around as a reference when
//! possible. In these cases, the extra allocation likely is a minor impact on
//! performance.
//!
//! - Overuse of boxed values results in a "uniform slowness" that can be
//! identified reasonably easily, and results in a linear performance
//! degradation relative to overuse. Overuse of `InlineSupercow`s at best
//! results in linear memory bloat, but if `InlineSupercow`s reference
//! structures containing other `InlineSupercow`s, the result can even be
//! exponential bloat to the structures. At best, this is a harder problem to
//! track down; at worst, it can result in entirely non-obvious stack
//! overflows.
//!
//! # Use Cases
//!
//! ## More flexible Copy-on-Write
//!
//! `std::borrow::Cow` only supports two modes of ownership: You either fully
//! own the value, or only borrow it. `Rc` and `Arc` have the `make_mut()`
//! method, which allows either total ownership or shared ownership. `Supercow`
//! supports all three: owned, shared, and borrowed.
//!
//! ## More flexible Copy-if-Needed
//!
//! A major use of `Cow` in `std` is found on functions like
//! `OsStr::to_string_lossy()`, which returns a borrowed view into itself if
//! possible, or an owned string if it needed to change something. If the
//! caller does not intend to do its own writing, this is more a "copy if
//! needed" structure, and the fact that it requires the contained value to be
//! `ToOwned` limits it to things that can be cloned.
//!
//! `Supercow` only requires `ToOwned` if the caller actually intends to invoke
//! functionality which requires cloning a borrowed value, so it can fit this
//! use-case even for non-cloneable types.
//!
//! ## Working around awkward lifetimes
//!
//! This is the original case for which `Supercow` was designed.
//!
//! Say you have an API with a sort of hierarchical structure of heavyweight
//! resources, for example handles to a local database and tables within it. A
//! natural representation may be to make the table handle hold a reference to
//! the database handle.
//!
//! ```no_run
//! struct Database;
//! impl Database {
//! fn new() -> Self {
//! // Computation...
//! Database
//! }
//! fn close(self) -> bool {
//! // Eg, it returns an error on failure or something
//! true
//! }
//! }
//! impl Drop for Database {
//! fn drop(&mut self) {
//! println!("Dropping database");
//! }
//! }
//! struct Table<'a>(&'a Database);
//! impl<'a> Table<'a> {
//! fn new(db: &'a Database) -> Self {
//! // Computation...
//! Table(db)
//! }
//! }
//! impl<'a> Drop for Table<'a> {
//! fn drop(&mut self) {
//! println!("Dropping table");
//! // Notify `self.db` about this
//! }
//! }
//! ```
//!
//! We can use this quite easily:
//!
//! ```
//! # struct Database;
//! # impl Database {
//! # fn new() -> Self {
//! # // Computation...
//! # Database
//! # }
//! # fn close(self) -> bool {
//! # // Eg, it returns an error on failure or something
//! # true
//! # }
//! # }
//! # impl Drop for Database {
//! # fn drop(&mut self) {
//! # println!("Dropping database");
//! # }
//! # }
//! # struct Table<'a>(&'a Database);
//! # impl<'a> Table<'a> {
//! # fn new(db: &'a Database) -> Self {
//! # // Computation...
//! # Table(db)
//! # }
//! # }
//! # impl<'a> Drop for Table<'a> {
//! # fn drop(&mut self) {
//! # println!("Dropping table");
//! # // Notify `self.db` about this
//! # }
//! # }
//!
//! # #[allow(unused_variables)]
//! fn main() {
//! let db = Database::new();
//! {
//! let table1 = Table::new(&db);
//! let table2 = Table::new(&db);
//! do_stuff(&table1);
//! // Etc
//! }
//! assert!(db.close());
//! }
//!
//! # #[allow(unused_variables)]
//! fn do_stuff(table: &Table) {
//! // Stuff
//! }
//! ```
//!
//! That is, until we want to hold the database and the tables in a struct.
//!
//! ```ignore
//! struct Resources {
//! db: Database,
//! table: Table<'uhhh>, // Uh, what is the lifetime here?
//! }
//! ```
//!
//! There are several options here:
//!
//! - Change the API to use `Arc`s or similar. This works, but adds overhead
//! for clients that don't need it, and additionally removes from everybody the
//! ability to statically know whether `db.close()` can be called.
//!
//! - Force clients to resort to unsafety, such as
//! [`OwningHandle`](http://kimundi.github.io/owning-ref-rs/owning_ref/struct.OwningHandle.html).
//! This sacrifices no performance and allows the stack-based client usage to
//! be able to call `db.close()` easily, but makes things much more difficult
//! for other clients.
//!
//! - Take a `Borrow` type parameter. This works and is zero-overhead, but
//! results in a proliferation of generics throughout the API and client code,
//! and becomes especially problematic when the hierarchy is multiple such
//! levels deep.
//!
//! - Use `Supercow` to get the best of both worlds.
//!
//! We can adapt and use the API like so:
//!
//! ```
//! use std::sync::Arc;
//!
//! use supercow::Supercow;
//!
//! struct Database;
//! impl Database {
//! fn new() -> Self {
//! // Computation...
//! Database
//! }
//! fn close(self) -> bool {
//! // Eg, it returns an error on failure or something
//! true
//! }
//! }
//! impl Drop for Database {
//! fn drop(&mut self) {
//! println!("Dropping database");
//! }
//! }
//! struct Table<'a>(Supercow<'a, Database>);
//! impl<'a> Table<'a> {
//! fn new<T : Into<Supercow<'a, Database>>>(db: T) -> Self {
//! // Computation...
//! Table(db.into())
//! }
//! }
//! impl<'a> Drop for Table<'a> {
//! fn drop(&mut self) {
//! println!("Dropping table");
//! // Notify `self.db` about this
//! }
//! }
//!
//! // The original stack-based code, unmodified
//!
//! # #[allow(unused_variables)]
//! fn on_stack() {
//! let db = Database::new();
//! {
//! let table1 = Table::new(&db);
//! let table2 = Table::new(&db);
//! do_stuff(&table1);
//! // Etc
//! }
//! assert!(db.close());
//! }
//!
//! // If we only wanted one Table and didn't care about ever getting the
//! // Database back, we don't even need a reference.
//! fn by_value() {
//! let db = Database::new();
//! let table = Table::new(db);
//! do_stuff(&table);
//! }
//!
//! // And we can declare our holds-everything struct by using `Arc`s to deal
//! // with ownership.
//! struct Resources {
//! db: Arc<Database>,
//! table: Table<'static>,
//! }
//! impl Resources {
//! fn new() -> Self {
//! let db = Arc::new(Database::new());
//! let table = Table::new(db.clone());
//! Resources { db: db, table: table }
//! }
//!
//! fn close(self) -> bool {
//! drop(self.table);
//! Arc::try_unwrap(self.db).ok().unwrap().close()
//! }
//! }
//!
//! fn with_struct() {
//! let res = Resources::new();
//! do_stuff(&res.table);
//! assert!(res.close());
//! }
//!
//! # #[allow(unused_variables)]
//! fn do_stuff(table: &Table) {
//! // Stuff
//! }
//!
//! ```
//!
//! # Shared Reference Type
//!
//! The third type parameter type to `Supercow` specifies the shared reference
//! type.
//!
//! The default is `Box<DefaultFeatures<'static>>`, which is a boxed trait
//! object describing the features a shared reference type must have while
//! allowing any such reference to be used without needing a generic type
//! argument.
//!
//! An alternate feature set can be found in `NonSyncFeatures`, which is also
//! usable through the `NonSyncSupercow` typedef (which also makes it
//! `'static`). You can create custom feature traits in this style with
//! `supercow_features!`.
//!
//! It is perfectly legal to use a non-`'static` shared reference type. In
//! fact, the original design for `Supercow<'a>` used `DefaultFeatures<'a>`.
//! However, a non-`'static` lifetime makes the system harder to use, and if
//! entangled with `'a` on `Supercow`, makes the structure lifetime-invariant,
//! which makes it much harder to treat as a reference.
//!
//! Boxing the shared reference and putting it behind a trait object both add
//! overhead, of course. If you wish, you can use a real reference type in the
//! third parameter as long as you are OK with losing the flexibility the
//! boxing would provide. For example,
//!
//! ```
//! use std::rc::Rc;
//!
//! use supercow::Supercow;
//!
//! # fn main() {
//! let x: Supercow<u32, u32, Rc<u32>> = Supercow::shared(Rc::new(42u32));
//! println!("{}", *x);
//! # }
//! ```
//!
//! Note that you may need to provide an identity `supercow::aux::SharedFrom`
//! implementation if you have a custom reference type.
//!
//! # Conversions
//!
//! To facilitate client API designs, `Supercow` converts (via `From`/`Into`)
//! from a number of things. Unfortunately, due to trait coherence rules, this
//! does not yet apply in all cases where one might hope. The currently
//! available conversions are:
//!
//! - The `OWNED` type into an owned `Supercow`. This applies without
//! restriction.
//!
//! - A reference to the `OWNED` type. References to a different `BORROWED`
//! type are currently not convertable; `Supercow::borrowed()` will be needed
//! to construct the `Supercow` explicitly.
//!
//! - `Rc<OWNED>` and `Arc<OWNED>` for `Supercow`s where `OWNED` and `BORROWED`
//! are the exact same type, and where the `Rc` or `Arc` can be converted into
//! `SHARED` via `supercow::aux::SharedFrom`. If `OWNED` and `BORROWED` are
//! different types, `Supercow::shared()` will be needed to construct the
//! `Supercow` explicitly.
//!
//! # Storage Type
//!
//! When in owned or shared mode, a `Supercow` needs someplace to store the
//! `OWNED` or `SHARED` value itself. This can be customised with the fourth
//! type parameter and the `OwnedStorage` trait. Two strategies are provided by
//! this crate:
//!
//! - `BoxedStorage` puts everything behind `Box`es. This has the advantage
//! that the `Supercow` structure is only one pointer wider than a basic
//! reference, and results in a faster `Deref`. The obvious drawback is that
//! you pay for allocations on construction. This is the default with
//! `Supercow` and `NonSyncSupercow`.
//!
//! - `InlineStorage` uses an `enum` to store the values inline in the
//! `Supercow`, thus incurring no allocation, but making the `Supercow` itself
//! bigger. This is easily available via the `InlineSupercow` and
//! `InlineNonSyncSupercow` types.
//!
//! If you find some need, you can define custom storage types, though note
//! that the trait is quite unsafe and somewhat subtle.
//!
//! # Advanced
//!
//! ## Variance
//!
//! `Supercow` is covariant on its lifetime and all its type parameters, except
//! for `SHARED` which is invariant. The default `SHARED` type for both
//! `Supercow` and `NonSyncSupercow` uses the `'static` lifetime, so simple
//! `Supercow`s are in general covariant.
//!
//! ```
//! use std::rc::Rc;
//!
//! use supercow::Supercow;
//!
//! fn assert_covariance<'a, 'b: 'a>(
//! imm: Supercow<'b, u32>,
//! bor: &'b Supercow<'b, u32>)
//! {
//! let _imm_a: Supercow<'a, u32> = imm;
//! let _bor_aa: &'a Supercow<'a, u32> = bor;
//! let _bor_ab: &'a Supercow<'b, u32> = bor;
//! // Invalid, since the external `&'b` reference is declared to live longer
//! // than the internal `&'a` reference.
//! // let _bor_ba: &'b Supercow<'a, u32> = bor;
//! }
//!
//! # fn main() { }
//! ```
//!
//! ## `Sync` and `Send`
//!
//! A `Supercow` is `Sync` and `Send` iff the types it contains, including the
//! shared reference type, are.
//!
//! ```
//! use supercow::Supercow;
//!
//! fn assert_sync_and_send<T : Sync + Send>(_: T) { }
//! fn main() {
//! let s: Supercow<u32> = Supercow::owned(42);
//! assert_sync_and_send(s);
//! }
//! ```
//!
//! # Performance Considerations
//!
//! ## Construction Cost
//!
//! Since it inherently moves certain decisions about ownership from
//! compile-time to run-time, `Supercow` is obviously not as fast as using an
//! owned value directly or a reference directly.
//!
//! Constructing any kind of `Supercow` with a normal reference is very fast,
//! only requiring a bit of internal memory initialisation besides setting the
//! reference itself.
//!
//! The defual `Supercow` type boxes the owned type and double-boxes the shared
//! type. This obviously dominates construction cost in those cases.
//!
//! `InlineSupercow` eliminates one box layer. This means that constructing an
//! owned instance is simply a move of the owned structure plus the common
//! reference initialisation. Shared values still by default require one boxing
//! level as well as virtual dispatch on certain operations; as described
//! above, this property too can be dealt with by using a custom `SHARED` type.
//!
//! ## Destruction Cost
//!
//! Destroying a `Supercow` is roughly the same proportional cost of creating
//! it.
//!
//! ## `Deref` Cost
//!
//! For the default `Supercow` type, the `Deref` is exactly equivalent to
//! dereferencing an `&&BORROWED`.
//!
//! For `InlineSupercow`, the implementation is a bit slower, comparable to
//! `std::borrow::Cow` but with fewer memory accesses..
//!
//! In all cases, the `Deref` implementation is not dependent on the ownership
//! mode of the `Supercow`, and so is not affected by the shared reference
//! type, most importantly, making no virtual function calls even under the
//! default boxed shared reference type. However, the way it works colud
//! prevent LLVM optimisations from applying in particular circumstances.
//!
//! For those wanting specifics, the function
//!
//! ```ignore
//! // Substitute Cow with InlineSupercow for the other case.
//! // This takes references so that the destructor code is not intermingled.
//! fn add_two(a: &Cow<u32>, b: &Cow<u32>) -> u32 {
//! **a + **b
//! }
//! ```
//!
//! results in the following on AMD64 with Rust 1.13.0:
//!
//! ```text
//! Cow Supercow
//! cmp DWORD PTR [rdi],0x1 mov rcx,QWORD PTR [rdi]
//! lea rcx,[rdi+0x4] xor eax,eax
//! cmovne rcx,QWORD PTR [rdi+0x8] cmp rcx,0x800
//! cmp DWORD PTR [rsi],0x1 cmovae rdi,rax
//! lea rax,[rsi+0x4] mov rdx,QWORD PTR [rsi]
//! cmovne rax,QWORD PTR [rsi+0x8] cmp rdx,0x800
//! mov eax,DWORD PTR [rax] cmovb rax,rsi
//! add eax,DWORD PTR [rcx] mov eax,DWORD PTR [rax+rdx]
//! ret add eax,DWORD PTR [rdi+rcx]
//! ret
//! ```
//!
//! The same code on ARM v7l and Rust 1.12.1:
//!
//! ```text
//! Cow Supercow
//! push {fp, lr} ldr r2, [r0]
//! mov r2, r0 ldr r3, [r1]
//! ldr r3, [r2, #4]! cmp r2, #2048
//! ldr ip, [r0] addcc r2, r2, r0
//! mov r0, r1 cmp r3, #2048
//! ldr lr, [r0, #4]! addcc r3, r3, r1
//! ldr r1, [r1] ldr r0, [r2]
//! cmp ip, #1 ldr r1, [r3]
//! moveq r3, r2 add r0, r1, r0
//! cmp r1, #1 bx lr
//! ldr r2, [r3]
//! moveq lr, r0
//! ldr r0, [lr]
//! add r0, r0, r2
//! pop {fp, pc}
//! ```
//!
//! If the default `Supercow` is used above instead of `InlineSupercow`, the
//! function actually compiles to the same thing as one taking two `&u32`
//! arguments. (This is partially due to optimisations eliminating one level of
//! indirection; if the optimiser did not do as much, it would be equivalent to
//! taking two `&&u32` arguments.)
//!
//! ## `to_mut` Cost
//!
//! Obtaining a `Ref` is substantially more expensive than `Deref`, as it must
//! inspect the ownership mode of the `Supercow` and possibly move it into the
//! owned mode. This will include a virtual call to the boxed shared reference
//! if in shared mode when using the default `Supercow` shared reference type.
//!
//! There is also cost in releasing the mutable reference, though
//! insubstantial in comparison.
//!
//! ## Memory Usage
//!
//! The default `Supercow` is only one pointer wider than a mundane reference
//! on Rust 1.13.0 and later. Earlier Rust versions have an extra word due to
//! the drop flag.
//!
//! ```
//! use std::mem::size_of;
//!
//! use supercow::Supercow;
//!
//! // Determine the size of the drop flag including alignment padding.
//! // On Rust 0.13.0+, `dflag` will be zero.
//! struct DropFlag(*const ());
//! impl Drop for DropFlag { fn drop(&mut self) { } }
//! let dflag = size_of::<DropFlag>() - size_of::<*const ()>();
//!
//! assert_eq!(size_of::<&'static u32>() + size_of::<*const ()>() + dflag,
//! size_of::<Supercow<'static, u32>>());
//!
//! assert_eq!(size_of::<&'static str>() + size_of::<*const ()>() + dflag,
//! size_of::<Supercow<'static, String, str>>());
//! ```
//!
//! Of course, you also pay for heap space in this case when using owned or
//! shared `Supercow`s.
//!
//! `InlineSupercow` can be quite large in comparison to a normal reference.
//! You need to be particularly careful that structures you reference don't
//! themselves contain `InlineSupercow`s or you can end up with
//! quadratically-sized or even exponentially-sized structures.
//!
//! ```
//! use std::mem;
//!
//! use supercow::InlineSupercow;
//!
//! // Define our structures
//! // (The extra lifetimes are needed for intra-function lifetime inference to
//! // succeed.)
//! struct Big([u8;1024]);
//! struct A<'a>(InlineSupercow<'a, Big>);
//! struct B<'b,'a:'b>(InlineSupercow<'b, A<'a>>);
//! struct C<'b,'a:'b>(InlineSupercow<'b, B<'a,'a>>);
//!
//! // Now say an API consumer, etc, decides to use references
//! let big = Big([0u8;1024]);
//! let a = A((&big).into());
//! let b = B((&a).into());
//! let c = C((&b).into());
//!
//! // Well, we've now allocated space for four `Big`s on the stack, despite
//! // only really needing one.
//! assert!(mem::size_of_val(&big) + mem::size_of_val(&a) +
//! mem::size_of_val(&b) + mem::size_of_val(&c) >
//! 4 * mem::size_of::<Big>());
//! ```
//!
//! # Other Notes
//!
//! Using `Supercow` will not give your application `apt-get`-style Super Cow
//! Powers.
pub mod ext;
use std::borrow::Borrow;
use std::cmp;
use std::convert::AsRef;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
use self::ext::*;
/// Defines a "feature set" for a custom `Supercow` type.
///
/// ## Syntax
///
/// ```
/// #[macro_use] extern crate supercow;
///
/// # pub trait SomeTrait { }
/// # pub trait AnotherTrait { }
///
/// supercow_features!(
/// /// Some documentation, etc, if desired.
/// pub trait FeatureName: SomeTrait, AnotherTrait);
/// supercow_features!(
/// pub trait FeatureName2: SomeTrait, Clone, AnotherTrait);
///
/// # fn main() { }
/// ```
///
/// ## Semantics
///
/// A public trait named `FeatureName` is defined which extends all the listed
/// traits, minus special cases below, and in addition to `ConstDeref`.
///
/// If `Clone` is listed, the trait gains a `clone_boxed()` method and
/// `Box<FeatureName>` is `Clone`.
///
/// All types which implement all the listed traits (including special cases)
/// and `ConstDeref` implement `FeatureName`.
#[macro_export]
macro_rules! supercow_features {
($(#[$meta:meta])* pub trait $feature_name:ident: $($stuff:ident),*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
[] [] $($stuff),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:tt),*] Clone $(, $more:ident)*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
[Clone clone_boxed] [$($others)*]
$($more),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:ident),*] $other:ident $(, $more:tt)*) => {
supercow_features!(@_ACCUM $(#[$meta])* pub trait $feature_name:
$clone [$($others, )* $other]
$($more),*);
};
(@_ACCUM $(#[$meta:meta])* pub trait $feature_name:ident:
$clone:tt [$($others:ident),*]) => {
supercow_features!(@_DEFINE $(#[$meta])* pub trait $feature_name:
$clone [$($others),*]);
};
(@_DEFINE $(#[$meta:meta])*
pub trait $feature_name:ident:
[$($clone:ident $clone_boxed:ident)*] [$($req:ident),*]) => {
$(#[$meta])*
pub trait $feature_name<'a>: $($req +)* $crate::ext::ConstDeref + 'a {
$(
/// Clone this value, and then immediately put it into a `Box`
/// behind a trait object of this trait.
fn $clone_boxed
(&self)
-> Box<$feature_name<'a, Target = Self::Target> + 'a>;
)*
}
impl<'a, T : 'a + $($req +)* $($clone +)* $crate::ext::ConstDeref>
$feature_name<'a> for T {
$(
fn $clone_boxed
(&self)
-> Box<$feature_name<'a, Target = Self::Target> + 'a>
{
let cloned: T = self.clone();
Box::new(cloned)
}
)*
}
impl<'a, T : $feature_name<'a>> $crate::ext::SharedFrom<T>
for Box<$feature_name<'a, Target = T::Target> + 'a> {
fn shared_from(t: T) -> Self {
Box::new(t)
}
}
$(
impl<'a, S : 'a + ?Sized> $clone for Box<$feature_name<'a, Target = S> + 'a> {
fn clone(&self) -> Self {
$feature_name::clone_boxed(&**self)
}
}
)*
};
}
supercow_features!(
/// The default shared reference type for `Supercow`.
///
/// This requires the shared reference type to be `Clone`, `Send`, and
/// `Sync`, which thus disqualifies using `Rc`. This was chosen as the
/// default since the inability to use `Rc` is generally a less subtle
/// issue than the `Supercow` not being `Send` or `Sync`.
///
/// See also `NonSyncFeatures`.
pub trait DefaultFeatures: Clone, Send, Sync);
supercow_features!(
/// The shared reference type for `NonSyncSupercow`.
///
/// Unlike `DefaultFeatures`, this only requires the shared reference type
/// to be `Clone`, thus permitting `Rc`.
pub trait NonSyncFeatures: Clone);
/// `Supercow` with the default `SHARED` changed to `NonSyncFeatures`, enabling
/// the use of `Rc` as a shared reference type as well as making it possible to
/// use non-`Send` or non-`Sync` `BORROWED` types easily.
///
/// Note that the `SHARED` type must have `'static` lifetime, since this is
/// generally more convenient and makes the `Supercow` as a whole covariant.
///
/// ## Example
///
/// ```
/// use supercow::{NonSyncSupercow, Supercow};
///
/// # fn main() {
/// let x: NonSyncSupercow<u32> = Supercow::owned(42u32);
/// println!("{}", *x);
/// # }
/// ```
pub type NonSyncSupercow<'a, OWNED, BORROWED = OWNED> =
Supercow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
BoxedStorage>;
/// `Supercow` with the default `STORAGE` changed to `InlineStorage`.
///
/// This reduces the number of allocations needed to construct an owned or
/// shared `Superow` (down to zero for owned, but note that the default
/// `SHARED` still has its own `Box`) at the cost of bloating the `Supercow`
/// itself, as it now needs to be able to fit a whole `OWNED` instance.
pub type InlineSupercow<'a, OWNED, BORROWED = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>> =
Supercow<'a, OWNED, BORROWED, SHARED, InlineStorage<OWNED, SHARED>>;
/// `NonSyncSupercow` with the `STORAGE` changed to `InlineStorage`.
///
/// This combines both properties of `NonSyncSupercow` and `InlineSupercow`.
pub type InlineNonSyncSupercow<'a, OWNED, BORROWED = OWNED> =
Supercow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
InlineStorage<OWNED, Box<
NonSyncFeatures<'static, Target = BORROWED> + 'static>>>;
/// The actual generic reference type.
///
/// See the module documentation for most of the details.
///
/// The generics here may look somewhat frightening at first; try not to be too
/// alarmed, and remember that in most use-cases all you need to worry about is
/// the stuff concerning `OWNED`.
pub struct Supercow<'a, OWNED, BORROWED : ?Sized = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>,
STORAGE = BoxedStorage>
where BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
STORAGE : OwnedStorage<OWNED, SHARED> {
// This stores the precalculated `Deref` target, and is the only thing the
// `Deref` implementation needs to inspect.
//
// Note that there are three cases with references:
//
// - A reference to an external value. In this case, we know that the
// reference will not be invalidated by movement or for the lifetime of
// `'a` and simply store the reference here as an absolute address.
//
// - A reference to a ZST at an "external" location, often address 1. We
// don't need to handle this in any particular manner as long as we don't
// accidentally make a null reference, since the only thing safe rust can
// do with a ZST reference is inspect its address, and if we do "move" it
// around, there's nothing unsafe from this fact being leaked.
//
// - A reference into this `Supercow`. In this case, the absolute address
// will change whenever this `Supercow` is relocated. To handle this, we
// instead store the offset from `&self` here, and adjust it at `Deref`
// time. We differentiate between the two cases by inspecting the absolute
// value of the address: If it is less than
// `MAX_INTERNAL_BORROW_DISPLACEMENT*2`, we assume it is an internal
// reference, since no modern system ever has virtual memory mapped between
// 0 and 4kB (and any code elsewhere involving this region is presumably
// too low-level to be using `Supercow`).
//
// One pecularity is that this is declared as a reference even though it
// does not necessarily reference anything. This is so that it works with
// DSTs, which have references larger than pointers. We assume the first
// pointer-sized value is the actual address (see `PointerFirstRef`).
//
// We do need to take care that we still don't create a null reference
// here; there is code to check for Rust putting the internal storage first
// in the struct and adding 1 if this happens.
//
// If `STORAGE` does not use internal pointers, we can skip all the
// arithmetic and return this value unmodified.
ptr: &'a BORROWED,
// The current ownership mode of this `Supercow`.
//
// This has three states:
//
// - Null. The `Supercow` holds a `&'a BORROWED`.
//
// - Even alignment. The `Supercow` holds an `OWNED` accessible via
// `STORAGE`, and this value is what is passed into the `STORAGE` methods.
//
// - Odd alignment. The `Supercow` holds a `SHARED`, behind a `Box` at the
// address one less than this value. Note that since the default `SHARED`
// is a `Box<DefaultFeatures>`, we actually end up with two levels of
// boxing here. This is actually necessary so that the whole thing only
// takes one immediate pointer.
mode: *mut (),
storage: STORAGE,
_owned: PhantomData<OWNED>,
_shared: PhantomData<SHARED>,
}
/// `Phantomcow<'a, Type>` is to `Supercow<'a, Type>` as
/// `PhantomData<&'a Type>` is to `&'a Type`.
///
/// That is, `Phantomcow` effects a lifetime dependency on the borrowed value,
/// while still permitting the owned and shared modes of `Supercow`, and
/// keeping the underlying objects alive as necessary.
///
/// There is not much one can do with a `Phantomcow`; it can be moved around,
/// and in some cases cloned. Its main use is in FFI wrappers, where `BORROWED`
/// maintains some external state or resource that will be destroyed when it
/// is, and which the owner of the `Phantomcow` depends on to function.
///
/// The size of a `Phantomcow` is generally equal to the size of the
/// corresponding `Supercow` type minus the size of `&'a BORROWED`, though this
/// may not be exact depending on `STORAGE` alignment, etc.
pub struct Phantomcow<'a, OWNED, BORROWED : ?Sized = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>,
STORAGE = BoxedStorage>
where BORROWED : 'a,
STORAGE : OwnedStorage<OWNED, SHARED> {
mode: *mut (),
storage: STORAGE,
_owned: PhantomData<OWNED>,
_borrowed: PhantomData<&'a BORROWED>,
_shared: PhantomData<SHARED>
}
/// The `Phantomcow` variant corresponding to `NonSyncSupercow`.
pub type NonSyncPhantomcow<'a, OWNED, BORROWED = OWNED> =
Phantomcow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
BoxedStorage>;
/// The `Phantomcow` variant corresponding to `InlineStorage`.
pub type InlinePhantomcow<'a, OWNED, BORROWED = OWNED,
SHARED = Box<DefaultFeatures<
'static, Target = BORROWED> + 'static>> =
Phantomcow<'a, OWNED, BORROWED, SHARED, InlineStorage<OWNED, SHARED>>;
/// The `Phantomcow` variant corresponding to `InlineNonSyncSupercow`.
pub type InlineNonSyncPhantomcow<'a, OWNED, BORROWED = OWNED> =
Phantomcow<'a, OWNED, BORROWED,
Box<NonSyncFeatures<'static, Target = BORROWED> + 'static>,
InlineStorage<OWNED, Box<
NonSyncFeatures<'static, Target = BORROWED> + 'static>>>;
enum SupercowMode {
Owned(*mut ()),
Borrowed,
Shared(*mut ()),
}
impl SupercowMode {
fn from_ptr(mode: *mut ()) -> Self {
if mode.is_null() {
Borrowed
} else if 0 == (mode as usize & 1) {
Owned(mode)
} else {
Shared((mode as usize & !1usize) as *mut ())
}
}
}
use self::SupercowMode::*;
macro_rules! defimpl {
($(@$us:tt)* [$($tparm:ident $(: ?$tparmsized:ident)*),*] ($($spec:tt)*)
where { $($wo:tt)* } $body:tt) => {
$($us)* impl<'a, $($tparm $(: ?$tparmsized)*,)* OWNED,
BORROWED : ?Sized, SHARED, STORAGE>
$($spec)* Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>
where BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
STORAGE : OwnedStorage<OWNED, SHARED>,
$($wo)*
$body
}
}
macro_rules! defphantomimpl {
($(@$us:tt)* [$($tparm:ident $(: ?$tparmsized:ident)*),*] ($($spec:tt)*)
where { $($wo:tt)* } $body:tt) => {
$($us)* impl<'a, $($tparm $(: ?$tparmsized)*,)* OWNED,
BORROWED : ?Sized, SHARED, STORAGE>
$($spec)* Phantomcow<'a, OWNED, BORROWED, SHARED, STORAGE>
where BORROWED : 'a,
STORAGE : OwnedStorage<OWNED, SHARED>,
$($wo)*
$body
}
}
defimpl! {[] (Drop for) where { } {
fn drop(&mut self) {
match self.mode() {
Owned(ptr) => unsafe { self.storage.deallocate_a(ptr) },
Shared(ptr) => unsafe { self.storage.deallocate_b(ptr) },
Borrowed => (),
}
}
} }
defphantomimpl! {[] (Drop for) where { } {
fn drop(&mut self) {
match SupercowMode::from_ptr(self.mode) {
Owned(ptr) => unsafe { self.storage.deallocate_a(ptr) },
Shared(ptr) => unsafe { self.storage.deallocate_b(ptr) },
Borrowed => (),
}
}
} }
defimpl! {@unsafe [] (Send for) where {
OWNED : Send,
&'a BORROWED : Send,
SHARED : Send,
STORAGE : Send,
} { } }
defphantomimpl! {@unsafe [] (Send for) where {
OWNED : Send,
SHARED : Send,
STORAGE : Send,
} { } }
defimpl! {@unsafe [] (Sync for) where {
OWNED : Sync,
&'a BORROWED : Sync,
SHARED : Sync,
STORAGE : Sync,
} { } }
defphantomimpl! {@unsafe [] (Sync for) where {
OWNED : Sync,
SHARED : Sync,
STORAGE : Sync,
} { } }
defimpl! {[] () where { } {
/// Creates a new `Supercow` which owns the given value.
///
/// This can create a `Supercow` with a `'static` lifetime.
pub fn owned(inner: OWNED) -> Self
where OWNED : SafeBorrow<BORROWED> {
let mut this = unsafe { Self::empty() };
this.mode = this.storage.allocate_a(inner);
// This line could panic, but `this` doesn't have anything that would
// run destructors at this point other than `storage`, which was
// initialised in an ordinary way.
unsafe { this.borrow_owned(); }
this
}
/// Creates a new `Supercow` which borrows the given value.
pub fn borrowed<T : Borrow<BORROWED> + ?Sized>(inner: &'a T) -> Self {
let mut this = unsafe { Self::empty() };
this.ptr = inner.borrow();
this
}
/// Creates a new `Supercow` using the given shared reference.
///
/// The reference must be convertable to `SHARED` via `SharedFrom`.
pub fn shared<T>(inner: T) -> Self
where SHARED : SharedFrom<T> + ConstDeref<Target = BORROWED> {
Self::shared_nocvt(SHARED::shared_from(inner))
}
fn shared_nocvt(shared: SHARED) -> Self
where SHARED : ConstDeref<Target = BORROWED> {
let mut this = unsafe { Self::empty() };
this.ptr = unsafe {
&*(shared.const_deref() as *const BORROWED)
};
let nominal_mode = this.storage.allocate_b(shared);
this.mode = (1usize | (nominal_mode as usize)) as *mut ();
this
}
/// If `this` is non-owned, clone `this` and return it.
///
/// Otherwise, return `None`.
///
/// ## Example
///
/// ```
/// use supercow::Supercow;
///
/// struct SomeNonCloneThing;
///
/// let owned: Supercow<SomeNonCloneThing> = SomeNonCloneThing.into();
/// assert!(Supercow::clone_non_owned(&owned).is_none());
///
/// let the_thing = SomeNonCloneThing;
/// let borrowed: Supercow<SomeNonCloneThing> = (&the_thing).into();
/// let also_borrowed = Supercow::clone_non_owned(&borrowed).unwrap();
/// ```
pub fn clone_non_owned(this: &Self) -> Option<Self>
where SHARED : Clone + ConstDeref<Target = BORROWED> {
match this.mode() {
Owned(_) => None,
Borrowed => Some(Supercow {
ptr: this.ptr,
mode: this.mode,
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
}),
Shared(s) => Some(Self::shared_nocvt(unsafe {
this.storage.get_ptr_b(s)
}.clone())),
}
}
/// If `this` is borrowed, return the underlying reference with the
/// original lifetime. Otherwise, return `None`.
///
/// The returned reference has a lifetime independent of `this`.
///
/// This can be used to bridge between `Supercow` APIs and mundane
/// reference APIs without needing to restrict the lifetime to the
/// `Supercow`, but as a result is only available if the contained
/// reference is actually independent.
///
/// ## Example
///
/// ```
/// use std::sync::Arc;
///
/// use supercow::Supercow;
///
/// let fourty_two: u32 = 42;
///
/// let borrowed: Supercow<u32> = (&fourty_two).into();
/// assert_eq!(Some(&fourty_two), Supercow::extract_ref(&borrowed));
///
/// let owned: Supercow<u32> = fourty_two.into();
/// assert_eq!(None, Supercow::extract_ref(&owned));
///
/// let shared: Supercow<u32> = Arc::new(fourty_two).into();
/// assert_eq!(None, Supercow::extract_ref(&shared));
/// ```
pub fn extract_ref(this: &Self) -> Option<&'a BORROWED> {
match this.mode() {
Borrowed => Some(this.ptr),
_ => None,
}
}
/// Takes ownership of the underling value if needed, then returns it,
/// consuming `self`.
pub fn into_inner(mut this: Self) -> OWNED
where OWNED : Borrow<BORROWED>,
BORROWED : ToOwned<Owned = OWNED> {
match this.mode() {
Owned(ptr) => {
unsafe { this.storage.deallocate_into_a(ptr) }
},
_ => (*this).to_owned(),
}
}
/// Returns a (indirect) mutable reference to an underlying owned value.
///
/// If this `Supercow` does not currently own the value, it takes
/// ownership. A `Ref` is then returned which allows accessing the mutable
/// owned value directly.
///
/// ## Leak Safety
///
/// If the returned `Ref` is released without its destructor being run, the
/// behaviour of the `Supercow` is unspecified (but does not result in
/// memory unsafety).
pub fn to_mut<'b>
(&'b mut self)
-> Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where OWNED : SafeBorrow<BORROWED>,
BORROWED : ToOwned<Owned = OWNED>,
{
// Become owned if not already.
match self.mode() {
Owned(_) => (),
_ => *self = Self::owned((*self).to_owned()),
}
// Clear out `ptr` if it points somewhere unstable
self.ptr = OWNED::borrow_replacement(self.ptr);
Ref {
r: unsafe { self.storage.get_mut_a(self.mode) } as *mut OWNED,
parent: self,
}
}
/// Converts this `Supercow` into a `Phantomcow`.
pub fn phantom(mut this: Self)
-> Phantomcow<'a, OWNED, BORROWED, SHARED, STORAGE> {
let ret = Phantomcow {
mode: this.mode,
storage: mem::replace(&mut this.storage, Default::default()),
_owned: PhantomData,
_borrowed: PhantomData,
_shared: PhantomData,
};
this.mode = ptr::null_mut();
ret
}
unsafe fn borrow_owned(&mut self)
where OWNED : SafeBorrow<BORROWED> {
// There's no safe way to propagate `borrowed_ptr` into
// `ptr` since the former has a borrow scoped to this
// function.
{
let borrowed_ptr = self.storage.get_ptr_a(self.mode).borrow();
self.ptr = &*(borrowed_ptr as *const BORROWED);
}
// Adjust the pointer if needed
if STORAGE::is_internal_storage() {
let self_start = self as *mut Self as usize;
let self_end = self_start + mem::size_of::<Self>();
let bias = self.relative_pointer_bias();
let ptr_address: &mut usize = mem::transmute(&mut self.ptr);
if *ptr_address >= self_start && *ptr_address < self_end {
debug_assert!(*ptr_address - self_start <
MAX_INTERNAL_BORROW_DISPLACEMENT * 3/2,
"Borrowed pointer displaced too far from \
base address (supercow at {:x}, self at {:x}, \
borrowed to {:x}", self_start,
&self.storage as *const STORAGE as usize,
*ptr_address);
*ptr_address -= self_start - bias;
}
}
}
unsafe fn empty() -> Self {
Supercow {
ptr: mem::uninitialized(),
mode: ptr::null_mut(),
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
}
}
fn mode(&self) -> SupercowMode {
SupercowMode::from_ptr(self.mode)
}
/// Returns the bias to use for relative pointers to avoid creating null
/// references.
///
/// If rust lays this structure out such that `storage_address` is at the
/// base of `self`, returns 1. Otherwise, no bias is needed and it returns
/// 0.
#[inline(always)]
fn relative_pointer_bias(&self) -> usize {
let self_address = self as *const Self as usize;
let storage_address = &self.storage as *const STORAGE as usize;
if self_address == storage_address {
1
} else {
0
}
}
} }
// Separate `impl` as rustc doesn't seem to like having multiple `&'x Type`
// constraints in one place.
impl<'a, OWNED, BORROWED : ?Sized, SHARED, STORAGE>
Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>
where OWNED : SafeBorrow<BORROWED>,
BORROWED : 'a + ToOwned<Owned = OWNED>,
for<'l> &'l BORROWED : PointerFirstRef,
SHARED : ConstDeref<Target = BORROWED>,
STORAGE : OwnedStorage<OWNED, SHARED> {
/// Takes ownership of the underlying value, so that this `Supercow` has a
/// `'static` lifetime.
///
/// This may also change the `SHARED` type parameter arbitrarily (which
/// happens, eg, when converting from `Supercow<'a,u32>` to
/// `Supercow<'static,u32>`).
///
/// ## Example
///
/// ```
/// use supercow::Supercow;
///
/// let s = {
/// let fourty_two = 42u32;
/// let by_ref: Supercow<u32> = Supercow::borrowed(&fourty_two);
/// // We can't return `by_ref` because it holds a reference to
/// // `fourty_two`. However, we can change that lifetime parameter
/// // to `'static` and then move that out of the block.
/// let by_val: Supercow<'static, u32> =
/// Supercow::take_ownership(by_ref);
/// by_val
/// };
/// assert_eq!(42, *s);
/// ```
pub fn take_ownership<NS : ConstDeref<Target = BORROWED>>
(mut this: Self) -> Supercow<'static, OWNED, BORROWED, NS, STORAGE>
where STORAGE : OwnedStorage<OWNED, NS> {
let static_ptr: &'static BORROWED =
unsafe { &*(this.ptr as *const BORROWED) };
match this.mode() {
Owned(_) => Supercow {
ptr: static_ptr,
mode: this.mode,
storage: mem::replace(&mut this.storage, Default::default()),
_owned: PhantomData,
_shared: PhantomData,
},
_ => Supercow::owned((*this).to_owned()),
}
}
}
/// Provides mutable access to an owned value within a `Supercow`.
///
/// This is similar to the `Ref` used with `RefCell`.
pub struct Ref<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
r: *mut OWNED,
parent: &'b mut Supercow<'a, OWNED, BORROWED, SHARED, STORAGE>,
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> Deref
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
type Target = OWNED;
#[inline]
fn deref(&self) -> &OWNED {
unsafe { &*self.r }
}
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> DerefMut
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
#[inline]
fn deref_mut(&mut self) -> &mut OWNED {
unsafe { &mut*self.r }
}
}
impl<'a, 'b, OWNED, BORROWED : ?Sized, SHARED, STORAGE> Drop
for Ref<'a, 'b, OWNED, BORROWED, SHARED, STORAGE>
where 'a: 'b,
OWNED : SafeBorrow<BORROWED> + 'b,
BORROWED : 'a,
&'a BORROWED : PointerFirstRef,
SHARED : 'b,
STORAGE : OwnedStorage<OWNED, SHARED> + 'b {
#[inline]
fn drop(&mut self) {
// The value of `OWNED::borrow()` may have changed, so recompute
// everything instead of backing the old values up.
unsafe { self.parent.borrow_owned() }
}
}
defimpl! {[] (Deref for) where { } {
type Target = BORROWED;
#[inline]
fn deref(&self) -> &BORROWED {
let self_address = self as *const Self as usize;
let mut target_ref = self.ptr;
unsafe {
let target_address: &mut usize = mem::transmute(&mut target_ref);
let nominal_address = *target_address;
if STORAGE::is_internal_storage() &&
nominal_address < MAX_INTERNAL_BORROW_DISPLACEMENT
{
*target_address = nominal_address + self_address -
self.relative_pointer_bias();
}
}
target_ref
}
} }
defimpl! {[] (Borrow<BORROWED> for) where { } {
fn borrow(&self) -> &BORROWED {
self.deref()
}
} }
defimpl! {[] (AsRef<BORROWED> for) where { } {
fn as_ref(&self) -> &BORROWED {
self.deref()
}
} }
defimpl! {[] (Clone for) where {
OWNED : Clone + SafeBorrow<BORROWED>,
SHARED : Clone + ConstDeref<Target = BORROWED>,
} {
fn clone(&self) -> Self {
match self.mode() {
Owned(ptr) => Self::owned(unsafe {
self.storage.get_ptr_a(ptr)
}.clone()),
Borrowed => Supercow {
ptr: self.ptr,
mode: self.mode,
storage: Default::default(),
_owned: PhantomData,
_shared: PhantomData,
},
Shared(s) => Self::shared_nocvt(unsafe {
self.storage.get_ptr_b(s)
}.clone()),
}
}
} }
defphantomimpl! {[] (Clone for) where {
OWNED : Clone,
SHARED : Clone,
} {
fn clone(&self) -> Self {
let mut clone: Self = Phantomcow {
mode: ptr::null_mut(),
storage: Default::default(),
_owned: PhantomData,
_borrowed: PhantomData,
_shared: PhantomData,
};
match SupercowMode::from_ptr(self.mode) {
Owned(ptr) => clone.mode = clone.storage.allocate_a(
unsafe { self.storage.get_ptr_a(ptr) }.clone()),
Borrowed => (),
Shared(ptr) => {
let m = clone.storage.allocate_b(
unsafe { self.storage.get_ptr_b(ptr) }.clone());
clone.mode = (1usize | (m as usize)) as *mut ();
},
}
clone
}
} }
defphantomimpl! {[] () where { } {
/// If this `Phantomcow` is owned, return `None`. Else, clone and return
/// `self`.
pub fn clone_non_owned(&self) -> Option<Self>
where SHARED : Clone {
let mut clone: Self = Phantomcow {
mode: ptr::null_mut(),
storage: Default::default(),
_owned: PhantomData,
_borrowed: PhantomData,
_shared: PhantomData,
};
match SupercowMode::from_ptr(self.mode) {
Owned(_) => return None,
Borrowed => (),
Shared(ptr) => {
let m = clone.storage.allocate_b(
unsafe { self.storage.get_ptr_b(ptr) }.clone());
clone.mode = (1usize | (m as usize)) as *mut ();
},
}
Some(clone)
}
} }
defimpl! {[] (From<OWNED> for) where {
OWNED : SafeBorrow<BORROWED>,
} {
fn from(inner: OWNED) -> Self {
Self::owned(inner)
}
} }
// For now, we can't accept `&BORROWED` because it's theoretically possible for
// someone to make `<BORROWED as ToOwned>::Owned = &BORROWED`, in which case
// the `OWNED` version above would apply.
//
// Maybe once specialisation lands in stable, we can make `From` do what we
// want everywhere.
defimpl! {[] (From<&'a OWNED> for) where {
// Does not need to be `SafeBorrow` since it's not embedded inside us.
OWNED : Borrow<BORROWED>,
} {
fn from(inner: &'a OWNED) -> Self {
Self::borrowed(inner.borrow())
}
} }
// Similarly, we can't support arbitrary types here, and need to require
// `BORROWED == OWNED` for `Rc` and `Arc`. Ideally, we'd support anything that
// coerces into `SHARED`. Again, maybe one day after specialisation..
impl<'a, OWNED, SHARED, STORAGE> From<Rc<OWNED>>
for Supercow<'a, OWNED, OWNED, SHARED, STORAGE>
where SHARED : ConstDeref<Target = OWNED> + SharedFrom<Rc<OWNED>>,
STORAGE : OwnedStorage<OWNED, SHARED>,
OWNED : 'a,
&'a OWNED : PointerFirstRef {
fn from(rc: Rc<OWNED>) -> Self {
Self::shared(rc)
}
}
impl<'a, OWNED, SHARED, STORAGE> From<Arc<OWNED>>
for Supercow<'a, OWNED, OWNED, SHARED, STORAGE>
where SHARED : ConstDeref<Target = OWNED> + SharedFrom<Arc<OWNED>>,
STORAGE : OwnedStorage<OWNED, SHARED>,
OWNED : 'a,
&'a OWNED : PointerFirstRef {
fn from(rc: Arc<OWNED>) -> Self {
Self::shared(rc)
}
}
macro_rules! deleg_fmt { ($tr:ident) => {
defimpl! {[] (fmt::$tr for) where {
BORROWED : fmt::$tr
} {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
} }
} }
deleg_fmt!(Binary);
deleg_fmt!(Debug);
deleg_fmt!(Display);
deleg_fmt!(LowerExp);
deleg_fmt!(LowerHex);
deleg_fmt!(Octal);
deleg_fmt!(Pointer);
deleg_fmt!(UpperExp);
deleg_fmt!(UpperHex);
defimpl! {[T] (cmp::PartialEq<T> for) where {
T : Borrow<BORROWED>,
BORROWED : PartialEq<BORROWED>,
} {
fn eq(&self, other: &T) -> bool {
**self == *other.borrow()
}
fn ne(&self, other: &T) -> bool {
**self != *other.borrow()
}
} }
defimpl! {[] (cmp::Eq for) where {
BORROWED : Eq
} { } }
defimpl! {[T] (cmp::PartialOrd<T> for) where {
T : Borrow<BORROWED>,
BORROWED : cmp::PartialOrd<BORROWED>,
} {
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
(**self).partial_cmp(other.borrow())
}
fn lt(&self, other: &T) -> bool {
**self < *other.borrow()
}
fn le(&self, other: &T) -> bool {
**self <= *other.borrow()
}
fn gt(&self, other: &T) -> bool {
**self > *other.borrow()
}
fn ge(&self, other: &T) -> bool {
**self >= *other.borrow()
}
} }
defimpl! {[] (cmp::Ord for) where {
BORROWED : cmp::Ord
} {
fn cmp(&self, other: &Self) -> cmp::Ordering {
(**self).cmp(other)
}
} }
defimpl! {[] (Hash for) where {
BORROWED : Hash
} {
fn hash<H : Hasher>(&self, h: &mut H) {
(**self).hash(h)
}
} }
#[cfg(test)]
mod misc_tests {
use std::borrow::Cow;
use super::*;
// This is where the asm in the Performance Notes section comes from.
#[inline(never)]
fn add_two_cow(a: &Cow<u32>, b: &Cow<u32>) -> u32 {
**a + **b
}
#[inline(never)]
fn add_two_supercow(a: &InlineSupercow<u32>,
b: &InlineSupercow<u32>) -> u32 {
**a + **b
}
#[test]
fn do_add_two() {
// Need to call `add_two_cow` twice to prevent LLVM from specialising
// it.
assert_eq!(42, add_two_cow(&Cow::Owned(40), &Cow::Owned(2)));
assert_eq!(44, add_two_cow(&Cow::Borrowed(&38), &Cow::Borrowed(&6)));
assert_eq!(42, add_two_supercow(&Supercow::owned(40),
&Supercow::owned(2)));
}
}
macro_rules! tests { ($modname:ident, $stype:ident, $ptype:ident) => {
#[cfg(test)]
mod $modname {
use std::sync::Arc;
use super::*;
#[test]
fn ref_to_owned() {
let x = 42u32;
let a: $stype<u32> = Supercow::borrowed(&x);
assert_eq!(x, *a);
assert_eq!(&x as *const u32 as usize,
(&*a) as *const u32 as usize);
let mut b = a.clone();
assert_eq!(x, *b);
assert_eq!(&x as *const u32 as usize,
(&*b) as *const u32 as usize);
*b.to_mut() = 56;
assert_eq!(42, *a);
assert_eq!(x, *a);
assert_eq!(&x as *const u32 as usize,
(&*a) as *const u32 as usize);
assert_eq!(56, *b);
}
#[test]
fn supports_dst() {
let a: $stype<String, str> = Supercow::borrowed("hello");
let b: $stype<String, str> = Supercow::owned("hello".to_owned());
assert_eq!(a, b);
let mut c = a.clone();
c.to_mut().push_str(" world");
assert_eq!(a, b);
assert_eq!(c, "hello world");
}
#[test]
fn default_accepts_arc() {
let x: $stype<u32> = Supercow::shared(Arc::new(42u32));
assert_eq!(42, *x);
}
#[test]
fn ref_safe_even_if_forgotten() {
let mut x: $stype<String, str> = Supercow::owned("foo".to_owned());
{
let mut m = x.to_mut();
// Add a bunch of characters to invalidate the allocation
for _ in 0..65536 {
m.push('x');
}
// Prevent the dtor from running but allow us to release the borrow
::std::mem::forget(m);
}
// While the value has been corrupted, we have been left with a *safe*
// deref result nonetheless.
assert_eq!("", &*x);
// The actual String has not been lost so no memory has been leaked
assert_eq!(65539, x.to_mut().len());
}
#[test]
// `SipHasher` is deprecated, but its replacement `DefaultHasher` doesn't
// exist in Rust 1.12.1.
#[allow(deprecated)]
fn general_trait_delegs_work() {
use std::borrow::Borrow;
use std::convert::AsRef;
use std::cmp::*;
use std::hash::*;
macro_rules! test_fmt {
($fmt:expr, $x:expr) => {
assert_eq!(format!($fmt, 42u32), format!($fmt, $x));
}
}
let x: $stype<u32> = Supercow::owned(42u32);
test_fmt!("{}", x);
test_fmt!("{:?}", x);
test_fmt!("{:o}", x);
test_fmt!("{:x}", x);
test_fmt!("{:X}", x);
test_fmt!("{:b}", x);
assert!(x == 42);
assert!(x != 43);
assert!(x < 43);
assert!(x <= 43);
assert!(x > 41);
assert!(x >= 41);
assert_eq!(42.partial_cmp(&43), x.partial_cmp(&43));
assert_eq!(42.cmp(&43), x.cmp(&Supercow::owned(43)));
let mut expected_hash = SipHasher::new();
42u32.hash(&mut expected_hash);
let mut actual_hash = SipHasher::new();
x.hash(&mut actual_hash);
assert_eq!(expected_hash.finish(), actual_hash.finish());
assert_eq!(42u32, *x.borrow());
assert_eq!(42u32, *x.as_ref());
}
#[test]
fn owned_mode_survives_moving() {
// Using a `HashMap` here because it means the optimiser can't reason
// about which one will eventually be chosen, and so one of the values
// is guaranteed to eventually be moved off the heap onto the stack.
#[inline(never)]
fn pick_one() -> $stype<'static, String> {
use std::collections::HashMap;
let mut hm = HashMap::new();
hm.insert("hello", Supercow::owned("hello".to_owned()));
hm.insert("world", Supercow::owned("world".to_owned()));
hm.into_iter().map(|(_, v)| v).next().unwrap()
}
let s = pick_one();
assert!("hello".to_owned() == *s ||
"world".to_owned() == *s);
}
#[test]
fn dst_string_str() {
let mut s: $stype<'static, String, str> = String::new().into();
let mut expected = String::new();
for i in 0..1024 {
assert_eq!(expected.as_str(), &*s);
expected.push_str(&format!("{}", i));
s.to_mut().push_str(&format!("{}", i));
assert_eq!(expected.as_str(), &*s);
}
}
#[test]
fn dst_vec_u8s() {
let mut s: $stype<'static, Vec<u8>, [u8]> = Vec::new().into();
let mut expected = Vec::<u8>::new();
for i in 0..1024 {
assert_eq!(&expected[..], &*s);
expected.push((i & 0xFF) as u8);
s.to_mut().push((i & 0xFF) as u8);
assert_eq!(&expected[..], &*s);
}
}
#[test]
fn dst_osstring_osstr() {
use std::ffi::{OsStr, OsString};
let mut s: $stype<'static, OsString, OsStr> = OsString::new().into();
let mut expected = OsString::new();
for i in 0..1024 {
assert_eq!(expected.as_os_str(), &*s);
expected.push(&format!("{}", i));
s.to_mut().push(&format!("{}", i));
assert_eq!(expected.as_os_str(), &*s);
}
}
#[test]
fn dst_cstring_cstr() {
use std::ffi::{CStr, CString};
use std::mem;
use std::ops::Deref;
let mut s: $stype<'static, CString, CStr> =
CString::new("").unwrap().into();
let mut expected = CString::new("").unwrap();
for i in 0..1024 {
assert_eq!(expected.deref(), &*s);
{
let mut ve = expected.into_bytes_with_nul();
ve.pop();
ve.push(((i & 0xFF) | 1) as u8);
ve.push(0);
expected = unsafe {
CString::from_vec_unchecked(ve)
};
}
{
let mut m = s.to_mut();
let mut vs = mem::replace(&mut *m, CString::new("").unwrap())
.into_bytes_with_nul();
vs.pop();
vs.push(((i & 0xFF) | 1) as u8);
vs.push(0);
*m = unsafe {
CString::from_vec_unchecked(vs)
};
}
assert_eq!(expected.deref(), &*s);
}
}
#[test]
fn dst_pathbuf_path() {
use std::path::{Path, PathBuf};
let mut s: $stype<'static, PathBuf, Path> = PathBuf::new().into();
let mut expected = PathBuf::new();
for i in 0..1024 {
assert_eq!(expected.as_path(), &*s);
expected.push(format!("{}", i));
s.to_mut().push(format!("{}", i));
assert_eq!(expected.as_path(), &*s);
}
}
struct MockNativeResource(*mut u32);
impl Drop for MockNativeResource {
fn drop(&mut self) {
unsafe { *self.0 = 0 };
}
}
// Not truly safe, but we're not crossing threads here and we need
// something for the Sync tests either way.
unsafe impl Send for MockNativeResource { }
unsafe impl Sync for MockNativeResource { }
struct MockDependentResource<'a> {
ptr: *mut u32,
_handle: $ptype<'a, MockNativeResource>,
}
fn check_dependent_ok(mdr: MockDependentResource) {
assert_eq!(42, unsafe { *mdr.ptr });
}
#[test]
fn borrowed_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> = Supercow::borrowed(&native);
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn owned_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> = Supercow::owned(native);
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn shared_phantomcow() {
let mut fourty_two = 42u32;
let native = MockNativeResource(&mut fourty_two);
let sc: $stype<MockNativeResource> =
Supercow::shared(Arc::new(native));
check_dependent_ok(MockDependentResource {
ptr: &mut fourty_two,
_handle: Supercow::phantom(sc),
});
}
#[test]
fn clone_owned_phantomcow() {
let sc: $stype<String> = Supercow::owned("hello world".to_owned());
let p1 = Supercow::phantom(sc);
assert!(p1.clone_non_owned().is_none());
let _p2 = p1.clone();
}
#[test]
fn clone_borrowed_phantomcow() {
let sc: $stype<String, str> = Supercow::borrowed("hello world");
let p1 = Supercow::phantom(sc);
assert!(p1.clone_non_owned().is_some());
let _p2 = p1.clone();
}
#[test]
fn clone_shared_phantomcow() {
let sc: $stype<String> = Supercow::shared(
Arc::new("hello world".to_owned()));
let p1 = Supercow::phantom(sc);
assert!(p1.clone_non_owned().is_some());
let _p2 = p1.clone();
}
} } }
tests!(inline_sync_tests, InlineSupercow, InlinePhantomcow);
tests!(inline_nonsync_tests, InlineNonSyncSupercow, InlineNonSyncPhantomcow);
tests!(boxed_sync_tests, Supercow, Phantomcow);
tests!(boxed_nonsync_tests, NonSyncSupercow, NonSyncPhantomcow);
|
#![allow(unused_features)]
#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(missing_docs, warnings)]
#![feature(convert)]
#![feature(custom_attribute)]
#![feature(fs)]
#![feature(io)]
#![feature(io_ext)]
#![feature(path)]
#![feature(plugin)]
#![feature(std_misc)]
//! A library for serial port communication
extern crate termios;
#[cfg(test)]
extern crate quickcheck;
use std::fmt;
use std::fs::{File, self};
use std::io::{Read, Write, self};
use std::os::unix::io::AsRawFd;
use std::path::Path;
pub use termios::BaudRate;
use termios::prelude::*;
#[cfg(test)]
mod socat;
#[cfg(test)]
mod test;
/// For how long to block `read()` calls
#[derive(Copy, PartialEq)]
pub struct BlockingMode {
/// The device will block until *at least* `bytes` are received
pub bytes: u8,
/// The device will block for at least `deciseconds` after each `read()` call
pub deciseconds: u8,
}
/// Options and flags which can be used to configure how a serial port is opened.
pub struct OpenOptions(fs::OpenOptions);
impl OpenOptions {
/// Creates a blank net set of options ready for configuration.
///
/// All options are initially set to false.
pub fn new() -> OpenOptions {
OpenOptions(fs::OpenOptions::new())
}
/// Set the option for read access.
///
/// This option, when true, will indicate that the serial port should be read-able when opened.
pub fn read(&mut self, read: bool) -> &mut OpenOptions {
self.0.read(read);
self
}
/// Set the option for write access.
///
/// This option, when true, will indicate that the serial port should be write-able when
/// opened.
pub fn write(&mut self, write: bool) -> &mut OpenOptions {
self.0.write(write);
self
}
/// Opens a serial port in "raw" mode with the specified read/write permissions.
///
/// If no permission was specified, the port will be opened in read only mode.
pub fn open<P: ?Sized>(&self, port: &P) -> io::Result<SerialPort> where
P: AsRef<Path>,
{
self.open_(port.as_ref())
}
fn open_(&self, path: &Path) -> io::Result<SerialPort> {
let file = try!(self.0.open(path));
let mut termios = try!(Termios::fetch(file.as_raw_fd()));
termios.make_raw();
let sp = SerialPort(file);
try!(sp.update(termios));
Ok(sp)
}
}
/// A serial device
pub struct SerialPort(File);
impl SerialPort {
/// Opens a serial port in "raw" mode with read-only permission
pub fn open(port: &Path) -> io::Result<SerialPort> {
OpenOptions::new().open(port)
}
/// Returns the input and output baud rates
pub fn baud_rate(&self) -> io::Result<(BaudRate, BaudRate)> {
self.fetch().map(|termios| {
(termios.ispeed(), termios.ospeed())
})
}
/// Returns the blocking mode used by the device
pub fn blocking_mode(&self) -> io::Result<BlockingMode> {
self.fetch().map(|termios| {
BlockingMode {
bytes: termios.cc[control::Char::VMIN],
deciseconds: termios.cc[control::Char::VTIME],
}
})
}
/// Returns the number of data bits used per character
pub fn data_bits(&self) -> io::Result<DataBits> {
self.fetch().map(|termios| {
match termios.get::<control::CSIZE>() {
control::CSIZE::CS5 => DataBits::Five,
control::CSIZE::CS6 => DataBits::Six,
control::CSIZE::CS7 => DataBits::Seven,
control::CSIZE::CS8 => DataBits::Eight,
}
})
}
/// Returns the flow control used by the device
pub fn flow_control(&self) -> io::Result<FlowControl> {
self.fetch().map(|termios| {
if termios.contains(control::Flag::CRTSCTS) {
FlowControl::Hardware
} else if termios.contains(input::Flag::IXANY) &&
termios.contains(input::Flag::IXOFF) &&
termios.contains(input::Flag::IXON)
{
FlowControl::Software
} else {
FlowControl::None
}
})
}
/// Returns the bit parity used by the device
pub fn parity(&self) -> io::Result<Parity> {
self.fetch().map(|termios| {
match (
termios.contains(control::Flag::PARENB),
termios.contains(control::Flag::PARODD),
) {
(true, true) => Parity::Odd,
(true, false) => Parity::Even,
(false, _) => Parity::None,
}
})
}
/// Changes the baud rate of the input/output or both directions
pub fn set_baud_rate(&mut self, direction: Direction, rate: BaudRate) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match direction {
Direction::Both => termios.set_speed(rate),
Direction::Input => termios.set_ispeed(rate),
Direction::Output => termios.set_ospeed(rate),
}
self.update(termios)
})
}
/// Changes the blocking mode used by the device
pub fn set_blocking_mode(&mut self, mode: BlockingMode) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
termios.cc[control::Char::VMIN] = mode.bytes;
termios.cc[control::Char::VTIME] = mode.deciseconds;
self.update(termios)
})
}
/// Changes the number of data bits per character
pub fn set_data_bits(&mut self, bits: DataBits) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
termios.set(match bits {
DataBits::Five => control::CSIZE::CS5,
DataBits::Six => control::CSIZE::CS6,
DataBits::Seven => control::CSIZE::CS7,
DataBits::Eight => control::CSIZE::CS8,
});
self.update(termios)
})
}
/// Changes the flow control used by the device
pub fn set_flow_control(&mut self, flow: FlowControl) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match flow {
FlowControl::Hardware => {
termios.clear(input::Flag::IXANY);
termios.clear(input::Flag::IXOFF);
termios.clear(input::Flag::IXON);
termios.set(control::Flag::CRTSCTS);
},
FlowControl::None => {
termios.clear(control::Flag::CRTSCTS);
termios.clear(input::Flag::IXANY);
termios.clear(input::Flag::IXOFF);
termios.clear(input::Flag::IXON);
},
FlowControl::Software => {
termios.clear(control::Flag::CRTSCTS);
termios.set(input::Flag::IXANY);
termios.set(input::Flag::IXOFF);
termios.set(input::Flag::IXON);
},
}
self.update(termios)
})
}
/// Changes the bit parity used by the device
pub fn set_parity(&mut self, parity: Parity) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match parity {
Parity::Even => {
termios.clear(control::Flag::PARODD);
termios.set(control::Flag::PARENB);
},
Parity::None => termios.clear(control::Flag::PARENB),
Parity::Odd => {
termios.set(control::Flag::PARENB);
termios.set(control::Flag::PARODD);
},
}
self.update(termios)
})
}
/// Changes the number of stop bits per character
pub fn set_stop_bits(&mut self, bits: StopBits) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match bits {
StopBits::One => termios.clear(control::Flag::CSTOPB),
StopBits::Two => termios.set(control::Flag::CSTOPB),
}
self.update(termios)
})
}
/// Returns the number of stop bits per character
pub fn stop_bits(&self) -> io::Result<StopBits> {
self.fetch().map(|termios| {
if termios.contains(control::Flag::CSTOPB) {
StopBits::Two
} else {
StopBits::One
}
})
}
/// Fetches the current state of the termios structure
fn fetch(&self) -> io::Result<Termios> {
Termios::fetch(self.0.as_raw_fd())
}
/// Updates the underlying termios structure
fn update(&self, termios: Termios) -> io::Result<()> {
termios.update(self.0.as_raw_fd(), When::Now)
}
}
impl Read for SerialPort {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.0.read_to_end(buf)
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
self.0.read_to_string(buf)
}
}
impl Write for SerialPort {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
self.0.write_fmt(fmt)
}
}
#[allow(missing_docs)]
/// Number of data bits
#[derive(Copy, Debug, PartialEq)]
pub enum DataBits {
Five,
Six,
Seven,
Eight,
}
#[allow(missing_docs)]
#[derive(Copy)]
pub enum Direction {
Both,
Input,
Output,
}
#[allow(missing_docs)]
/// Flow control
#[derive(Copy, Debug, PartialEq)]
pub enum FlowControl {
Hardware,
None,
Software,
}
#[allow(missing_docs)]
/// Parity checking
#[derive(Copy, Debug, PartialEq)]
pub enum Parity {
Even,
None,
Odd,
}
#[allow(missing_docs)]
/// Number of stop bits
#[derive(Copy, Debug, PartialEq)]
pub enum StopBits {
One,
Two,
}
fix: deriving `Copy` now needs deriving `Clone` as well
#![allow(unused_features)]
#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(missing_docs, warnings)]
#![feature(convert)]
#![feature(custom_attribute)]
#![feature(fs)]
#![feature(io)]
#![feature(io_ext)]
#![feature(path)]
#![feature(plugin)]
#![feature(std_misc)]
//! A library for serial port communication
extern crate termios;
#[cfg(test)]
extern crate quickcheck;
use std::fmt;
use std::fs::{File, self};
use std::io::{Read, Write, self};
use std::os::unix::io::AsRawFd;
use std::path::Path;
pub use termios::BaudRate;
use termios::prelude::*;
#[cfg(test)]
mod socat;
#[cfg(test)]
mod test;
/// For how long to block `read()` calls
#[derive(Clone, Copy, PartialEq)]
pub struct BlockingMode {
/// The device will block until *at least* `bytes` are received
pub bytes: u8,
/// The device will block for at least `deciseconds` after each `read()` call
pub deciseconds: u8,
}
/// Options and flags which can be used to configure how a serial port is opened.
pub struct OpenOptions(fs::OpenOptions);
impl OpenOptions {
/// Creates a blank net set of options ready for configuration.
///
/// All options are initially set to false.
pub fn new() -> OpenOptions {
OpenOptions(fs::OpenOptions::new())
}
/// Set the option for read access.
///
/// This option, when true, will indicate that the serial port should be read-able when opened.
pub fn read(&mut self, read: bool) -> &mut OpenOptions {
self.0.read(read);
self
}
/// Set the option for write access.
///
/// This option, when true, will indicate that the serial port should be write-able when
/// opened.
pub fn write(&mut self, write: bool) -> &mut OpenOptions {
self.0.write(write);
self
}
/// Opens a serial port in "raw" mode with the specified read/write permissions.
///
/// If no permission was specified, the port will be opened in read only mode.
pub fn open<P: ?Sized>(&self, port: &P) -> io::Result<SerialPort> where
P: AsRef<Path>,
{
self.open_(port.as_ref())
}
fn open_(&self, path: &Path) -> io::Result<SerialPort> {
let file = try!(self.0.open(path));
let mut termios = try!(Termios::fetch(file.as_raw_fd()));
termios.make_raw();
let sp = SerialPort(file);
try!(sp.update(termios));
Ok(sp)
}
}
/// A serial device
pub struct SerialPort(File);
impl SerialPort {
/// Opens a serial port in "raw" mode with read-only permission
pub fn open(port: &Path) -> io::Result<SerialPort> {
OpenOptions::new().open(port)
}
/// Returns the input and output baud rates
pub fn baud_rate(&self) -> io::Result<(BaudRate, BaudRate)> {
self.fetch().map(|termios| {
(termios.ispeed(), termios.ospeed())
})
}
/// Returns the blocking mode used by the device
pub fn blocking_mode(&self) -> io::Result<BlockingMode> {
self.fetch().map(|termios| {
BlockingMode {
bytes: termios.cc[control::Char::VMIN],
deciseconds: termios.cc[control::Char::VTIME],
}
})
}
/// Returns the number of data bits used per character
pub fn data_bits(&self) -> io::Result<DataBits> {
self.fetch().map(|termios| {
match termios.get::<control::CSIZE>() {
control::CSIZE::CS5 => DataBits::Five,
control::CSIZE::CS6 => DataBits::Six,
control::CSIZE::CS7 => DataBits::Seven,
control::CSIZE::CS8 => DataBits::Eight,
}
})
}
/// Returns the flow control used by the device
pub fn flow_control(&self) -> io::Result<FlowControl> {
self.fetch().map(|termios| {
if termios.contains(control::Flag::CRTSCTS) {
FlowControl::Hardware
} else if termios.contains(input::Flag::IXANY) &&
termios.contains(input::Flag::IXOFF) &&
termios.contains(input::Flag::IXON)
{
FlowControl::Software
} else {
FlowControl::None
}
})
}
/// Returns the bit parity used by the device
pub fn parity(&self) -> io::Result<Parity> {
self.fetch().map(|termios| {
match (
termios.contains(control::Flag::PARENB),
termios.contains(control::Flag::PARODD),
) {
(true, true) => Parity::Odd,
(true, false) => Parity::Even,
(false, _) => Parity::None,
}
})
}
/// Changes the baud rate of the input/output or both directions
pub fn set_baud_rate(&mut self, direction: Direction, rate: BaudRate) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match direction {
Direction::Both => termios.set_speed(rate),
Direction::Input => termios.set_ispeed(rate),
Direction::Output => termios.set_ospeed(rate),
}
self.update(termios)
})
}
/// Changes the blocking mode used by the device
pub fn set_blocking_mode(&mut self, mode: BlockingMode) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
termios.cc[control::Char::VMIN] = mode.bytes;
termios.cc[control::Char::VTIME] = mode.deciseconds;
self.update(termios)
})
}
/// Changes the number of data bits per character
pub fn set_data_bits(&mut self, bits: DataBits) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
termios.set(match bits {
DataBits::Five => control::CSIZE::CS5,
DataBits::Six => control::CSIZE::CS6,
DataBits::Seven => control::CSIZE::CS7,
DataBits::Eight => control::CSIZE::CS8,
});
self.update(termios)
})
}
/// Changes the flow control used by the device
pub fn set_flow_control(&mut self, flow: FlowControl) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match flow {
FlowControl::Hardware => {
termios.clear(input::Flag::IXANY);
termios.clear(input::Flag::IXOFF);
termios.clear(input::Flag::IXON);
termios.set(control::Flag::CRTSCTS);
},
FlowControl::None => {
termios.clear(control::Flag::CRTSCTS);
termios.clear(input::Flag::IXANY);
termios.clear(input::Flag::IXOFF);
termios.clear(input::Flag::IXON);
},
FlowControl::Software => {
termios.clear(control::Flag::CRTSCTS);
termios.set(input::Flag::IXANY);
termios.set(input::Flag::IXOFF);
termios.set(input::Flag::IXON);
},
}
self.update(termios)
})
}
/// Changes the bit parity used by the device
pub fn set_parity(&mut self, parity: Parity) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match parity {
Parity::Even => {
termios.clear(control::Flag::PARODD);
termios.set(control::Flag::PARENB);
},
Parity::None => termios.clear(control::Flag::PARENB),
Parity::Odd => {
termios.set(control::Flag::PARENB);
termios.set(control::Flag::PARODD);
},
}
self.update(termios)
})
}
/// Changes the number of stop bits per character
pub fn set_stop_bits(&mut self, bits: StopBits) -> io::Result<()> {
self.fetch().and_then(|mut termios| {
match bits {
StopBits::One => termios.clear(control::Flag::CSTOPB),
StopBits::Two => termios.set(control::Flag::CSTOPB),
}
self.update(termios)
})
}
/// Returns the number of stop bits per character
pub fn stop_bits(&self) -> io::Result<StopBits> {
self.fetch().map(|termios| {
if termios.contains(control::Flag::CSTOPB) {
StopBits::Two
} else {
StopBits::One
}
})
}
/// Fetches the current state of the termios structure
fn fetch(&self) -> io::Result<Termios> {
Termios::fetch(self.0.as_raw_fd())
}
/// Updates the underlying termios structure
fn update(&self, termios: Termios) -> io::Result<()> {
termios.update(self.0.as_raw_fd(), When::Now)
}
}
impl Read for SerialPort {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.0.read_to_end(buf)
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
self.0.read_to_string(buf)
}
}
impl Write for SerialPort {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.0.write_all(buf)
}
fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
self.0.write_fmt(fmt)
}
}
#[allow(missing_docs)]
/// Number of data bits
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DataBits {
Five,
Six,
Seven,
Eight,
}
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum Direction {
Both,
Input,
Output,
}
#[allow(missing_docs)]
/// Flow control
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FlowControl {
Hardware,
None,
Software,
}
#[allow(missing_docs)]
/// Parity checking
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Parity {
Even,
None,
Odd,
}
#[allow(missing_docs)]
/// Number of stop bits
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum StopBits {
One,
Two,
}
|
//! This crate is a reimplementation
//! of GNU gettext translation framework in Rust.
//! It allows your Rust programs to parse out GNU MO files
//! containing translations and use them in your user interface.
//!
//! It contains several differences from the official C implementation.
//! Notably, this crate does not in any way depend on a global locale
//! ([2.2](https://www.gnu.org/software/gettext/manual/gettext.html#Setting-the-GUI-Locale))
//! and does not enforce a directory structure
//! for storing your translation catalogs
//! ([11.2.3](https://www.gnu.org/software/gettext/manual/gettext.html#Locating-Catalogs)).
//! Instead, the choice of translation catalog to use is explicitly made by the user.
//!
//! This crate is still in-progress
//! and may not be on par with the original implementation feature-wise.
//!
//! For the exact feature parity see the roadmap in the
//! [README](https://github.com/justinas/gettext#readme).
//!
//! # Example
//!
//! ```ignore
//! extern crate gettext;
//!
//! use std::fs::File;
//! use gettext::Catalog;
//!
//! fn main() {
//! let f = File::open("french.mo").expect("could not open the catalog");
//! let catalog = Catalog::parse(f).expect("could not parse the catalog");
//!
//! // Will print out the French translation
//! // if it is found in the parsed file
//! // or "Name" otherwise.
//! println!("{}", catalog.gettext("Name"));
//! }
//! ```
// https://pascalhertleif.de/artikel/good-practices-for-writing-rust-libraries/
#![deny(
missing_docs,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_import_braces
)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
mod metadata;
mod parser;
mod plurals;
use std::collections::HashMap;
use std::io::Read;
use std::ops::Deref;
pub use parser::{default_resolver, Error, ParseOptions};
use plurals::*;
fn key_with_context(context: &str, key: &str) -> String {
let mut result = context.to_owned();
result.push('\x04');
result.push_str(key);
result
}
/// Catalog represents a set of translation strings
/// parsed out of one MO file.
#[derive(Clone, Debug)]
pub struct Catalog {
strings: HashMap<String, Message>,
resolver: Resolver,
}
impl Catalog {
/// Creates a new, empty gettext catalog.
fn new() -> Self {
Catalog {
strings: HashMap::new(),
resolver: Resolver::Function(default_resolver),
}
}
/// Parses a gettext catalog from the given binary MO file.
/// Returns the `Err` variant upon encountering an invalid file format
/// or invalid byte sequence in strings.
///
/// Calling this method is equivalent to calling
/// `ParseOptions::new().parse(reader)`.
///
/// # Examples
///
/// ```ignore
/// use gettext::Catalog;
/// use std::fs::File;
///
/// let file = File::open("french.mo").unwrap();
/// let catalog = Catalog::parse(file).unwrap();
/// ```
pub fn parse<R: Read>(reader: R) -> Result<Self, parser::Error> {
ParseOptions::new().parse(reader)
}
fn insert(&mut self, msg: Message) {
let key = match msg.context {
Some(ref ctxt) => key_with_context(ctxt, &msg.id),
None => msg.id.clone(),
};
self.strings.insert(key, msg);
}
/// Returns the singular translation of `msg_id` from the given catalog
/// or `msg_id` itself if a translation does not exist.
pub fn gettext<'a>(&'a self, msg_id: &'a str) -> &'a str {
self.strings
.get(msg_id)
.and_then(|msg| msg.get_translated(0))
.unwrap_or(msg_id)
}
/// Returns the plural translation of `msg_id` from the given catalog
/// with the correct plural form for the number `n` of objects.
/// Returns msg_id if a translation does not exist and `n == 1`,
/// msg_id_plural otherwise.
///
/// Currently, the only supported plural formula is `n != 1`.
pub fn ngettext<'a>(&'a self, msg_id: &'a str, msg_id_plural: &'a str, n: u64) -> &'a str {
let form_no = self.resolver.resolve(n);
match self.strings.get(msg_id) {
Some(msg) => msg
.get_translated(form_no)
.unwrap_or_else(|| [msg_id, msg_id_plural][form_no]),
None if n == 1 => msg_id,
None if n != 1 => msg_id_plural,
_ => unreachable!(),
}
}
/// Returns the singular translation of `msg_id`
/// in the context `msg_context`
/// or `msg_id` itself if a translation does not exist.
// TODO: DRY gettext/pgettext
pub fn pgettext<'a>(&'a self, msg_context: &'a str, msg_id: &'a str) -> &'a str {
let key = key_with_context(msg_context, &msg_id);
self.strings
.get(&key)
.and_then(|msg| msg.get_translated(0))
.unwrap_or(msg_id)
}
/// Returns the plural translation of `msg_id`
/// in the context `msg_context`
/// with the correct plural form for the number `n` of objects.
/// Returns msg_id if a translation does not exist and `n == 1`,
/// msg_id_plural otherwise.
///
/// Currently, the only supported plural formula is `n != 1`.
// TODO: DRY ngettext/npgettext
pub fn npgettext<'a>(
&'a self,
msg_context: &'a str,
msg_id: &'a str,
msg_id_plural: &'a str,
n: u64,
) -> &'a str {
let key = key_with_context(msg_context, &msg_id);
let form_no = self.resolver.resolve(n);
match self.strings.get(&key) {
Some(msg) => msg
.get_translated(form_no)
.unwrap_or_else(|| [msg_id, msg_id_plural][form_no]),
None if n == 1 => msg_id,
None if n != 1 => msg_id_plural,
_ => unreachable!(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct Message {
id: String,
context: Option<String>,
translated: Vec<String>,
}
impl Message {
fn new<T: Into<String>>(id: T, context: Option<T>, translated: Vec<T>) -> Self {
Message {
id: id.into(),
context: context.map(Into::into),
translated: translated.into_iter().map(Into::into).collect(),
}
}
fn get_translated(&self, form_no: usize) -> Option<&str> {
self.translated.get(form_no).map(|s| s.deref())
}
}
#[test]
fn catalog_insert() {
let mut cat = Catalog::new();
cat.insert(Message::new("thisisid", None, vec![]));
cat.insert(Message::new("anotherid", Some("context"), vec![]));
let mut keys = cat.strings.keys().collect::<Vec<_>>();
keys.sort();
assert_eq!(keys, &["context\x04anotherid", "thisisid"])
}
#[test]
fn catalog_gettext() {
let mut cat = Catalog::new();
cat.insert(Message::new("Text", None, vec!["Tekstas"]));
cat.insert(Message::new("Image", Some("context"), vec!["Paveikslelis"]));
assert_eq!(cat.gettext("Text"), "Tekstas");
assert_eq!(cat.gettext("Image"), "Image");
}
#[test]
fn catalog_ngettext() {
let mut cat = Catalog::new();
{
// n == 1, no translation
assert_eq!(cat.ngettext("Text", "Texts", 1), "Text");
// n != 1, no translation
assert_eq!(cat.ngettext("Text", "Texts", 0), "Texts");
assert_eq!(cat.ngettext("Text", "Texts", 2), "Texts");
}
{
cat.insert(Message::new("Text", None, vec!["Tekstas", "Tekstai"]));
// n == 1, translation available
assert_eq!(cat.ngettext("Text", "Texts", 1), "Tekstas");
// n != 1, translation available
assert_eq!(cat.ngettext("Text", "Texts", 0), "Tekstai");
assert_eq!(cat.ngettext("Text", "Texts", 2), "Tekstai");
}
}
#[test]
fn catalog_pgettext() {
let mut cat = Catalog::new();
cat.insert(Message::new("Text", Some("unit test"), vec!["Tekstas"]));
assert_eq!(cat.pgettext("unit test", "Text"), "Tekstas");
assert_eq!(cat.pgettext("integration test", "Text"), "Text");
}
#[test]
fn catalog_npgettext() {
let mut cat = Catalog::new();
cat.insert(Message::new(
"Text",
Some("unit test"),
vec!["Tekstas", "Tekstai"],
));
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 1), "Tekstas");
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 0), "Tekstai");
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 2), "Tekstai");
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 1),
"Text"
);
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 0),
"Texts"
);
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 2),
"Texts"
);
}
#[test]
fn test_complex_plural() {
let reader: &[u8] = include_bytes!("../test_cases/complex_plural.mo");
let cat = parser::parse_catalog(reader, ParseOptions::new()).unwrap();
assert_eq!(cat.ngettext("Test", "Tests", 0), "Plural 2");
assert_eq!(cat.ngettext("Test", "Tests", 1), "Singular");
assert_eq!(cat.ngettext("Test", "Tests", 2), "Plural 1");
for i in 3..20 {
assert_eq!(cat.ngettext("Test", "Tests", i), "Plural 2");
}
}
Add a check for Catalog being Send/Sync
Test will not compile if traits are not implemented
//! This crate is a reimplementation
//! of GNU gettext translation framework in Rust.
//! It allows your Rust programs to parse out GNU MO files
//! containing translations and use them in your user interface.
//!
//! It contains several differences from the official C implementation.
//! Notably, this crate does not in any way depend on a global locale
//! ([2.2](https://www.gnu.org/software/gettext/manual/gettext.html#Setting-the-GUI-Locale))
//! and does not enforce a directory structure
//! for storing your translation catalogs
//! ([11.2.3](https://www.gnu.org/software/gettext/manual/gettext.html#Locating-Catalogs)).
//! Instead, the choice of translation catalog to use is explicitly made by the user.
//!
//! This crate is still in-progress
//! and may not be on par with the original implementation feature-wise.
//!
//! For the exact feature parity see the roadmap in the
//! [README](https://github.com/justinas/gettext#readme).
//!
//! # Example
//!
//! ```ignore
//! extern crate gettext;
//!
//! use std::fs::File;
//! use gettext::Catalog;
//!
//! fn main() {
//! let f = File::open("french.mo").expect("could not open the catalog");
//! let catalog = Catalog::parse(f).expect("could not parse the catalog");
//!
//! // Will print out the French translation
//! // if it is found in the parsed file
//! // or "Name" otherwise.
//! println!("{}", catalog.gettext("Name"));
//! }
//! ```
// https://pascalhertleif.de/artikel/good-practices-for-writing-rust-libraries/
#![deny(
missing_docs,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_import_braces
)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
mod metadata;
mod parser;
mod plurals;
use std::collections::HashMap;
use std::io::Read;
use std::ops::Deref;
pub use parser::{default_resolver, Error, ParseOptions};
use plurals::*;
fn key_with_context(context: &str, key: &str) -> String {
let mut result = context.to_owned();
result.push('\x04');
result.push_str(key);
result
}
/// Catalog represents a set of translation strings
/// parsed out of one MO file.
#[derive(Clone, Debug)]
pub struct Catalog {
strings: HashMap<String, Message>,
resolver: Resolver,
}
impl Catalog {
/// Creates a new, empty gettext catalog.
fn new() -> Self {
Catalog {
strings: HashMap::new(),
resolver: Resolver::Function(default_resolver),
}
}
/// Parses a gettext catalog from the given binary MO file.
/// Returns the `Err` variant upon encountering an invalid file format
/// or invalid byte sequence in strings.
///
/// Calling this method is equivalent to calling
/// `ParseOptions::new().parse(reader)`.
///
/// # Examples
///
/// ```ignore
/// use gettext::Catalog;
/// use std::fs::File;
///
/// let file = File::open("french.mo").unwrap();
/// let catalog = Catalog::parse(file).unwrap();
/// ```
pub fn parse<R: Read>(reader: R) -> Result<Self, parser::Error> {
ParseOptions::new().parse(reader)
}
fn insert(&mut self, msg: Message) {
let key = match msg.context {
Some(ref ctxt) => key_with_context(ctxt, &msg.id),
None => msg.id.clone(),
};
self.strings.insert(key, msg);
}
/// Returns the singular translation of `msg_id` from the given catalog
/// or `msg_id` itself if a translation does not exist.
pub fn gettext<'a>(&'a self, msg_id: &'a str) -> &'a str {
self.strings
.get(msg_id)
.and_then(|msg| msg.get_translated(0))
.unwrap_or(msg_id)
}
/// Returns the plural translation of `msg_id` from the given catalog
/// with the correct plural form for the number `n` of objects.
/// Returns msg_id if a translation does not exist and `n == 1`,
/// msg_id_plural otherwise.
///
/// Currently, the only supported plural formula is `n != 1`.
pub fn ngettext<'a>(&'a self, msg_id: &'a str, msg_id_plural: &'a str, n: u64) -> &'a str {
let form_no = self.resolver.resolve(n);
match self.strings.get(msg_id) {
Some(msg) => msg
.get_translated(form_no)
.unwrap_or_else(|| [msg_id, msg_id_plural][form_no]),
None if n == 1 => msg_id,
None if n != 1 => msg_id_plural,
_ => unreachable!(),
}
}
/// Returns the singular translation of `msg_id`
/// in the context `msg_context`
/// or `msg_id` itself if a translation does not exist.
// TODO: DRY gettext/pgettext
pub fn pgettext<'a>(&'a self, msg_context: &'a str, msg_id: &'a str) -> &'a str {
let key = key_with_context(msg_context, &msg_id);
self.strings
.get(&key)
.and_then(|msg| msg.get_translated(0))
.unwrap_or(msg_id)
}
/// Returns the plural translation of `msg_id`
/// in the context `msg_context`
/// with the correct plural form for the number `n` of objects.
/// Returns msg_id if a translation does not exist and `n == 1`,
/// msg_id_plural otherwise.
///
/// Currently, the only supported plural formula is `n != 1`.
// TODO: DRY ngettext/npgettext
pub fn npgettext<'a>(
&'a self,
msg_context: &'a str,
msg_id: &'a str,
msg_id_plural: &'a str,
n: u64,
) -> &'a str {
let key = key_with_context(msg_context, &msg_id);
let form_no = self.resolver.resolve(n);
match self.strings.get(&key) {
Some(msg) => msg
.get_translated(form_no)
.unwrap_or_else(|| [msg_id, msg_id_plural][form_no]),
None if n == 1 => msg_id,
None if n != 1 => msg_id_plural,
_ => unreachable!(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct Message {
id: String,
context: Option<String>,
translated: Vec<String>,
}
impl Message {
fn new<T: Into<String>>(id: T, context: Option<T>, translated: Vec<T>) -> Self {
Message {
id: id.into(),
context: context.map(Into::into),
translated: translated.into_iter().map(Into::into).collect(),
}
}
fn get_translated(&self, form_no: usize) -> Option<&str> {
self.translated.get(form_no).map(|s| s.deref())
}
}
#[test]
fn catalog_impls_send_sync() {
fn check<T: Send + Sync>(_: T) { };
check(Catalog::new());
}
#[test]
fn catalog_insert() {
let mut cat = Catalog::new();
cat.insert(Message::new("thisisid", None, vec![]));
cat.insert(Message::new("anotherid", Some("context"), vec![]));
let mut keys = cat.strings.keys().collect::<Vec<_>>();
keys.sort();
assert_eq!(keys, &["context\x04anotherid", "thisisid"])
}
#[test]
fn catalog_gettext() {
let mut cat = Catalog::new();
cat.insert(Message::new("Text", None, vec!["Tekstas"]));
cat.insert(Message::new("Image", Some("context"), vec!["Paveikslelis"]));
assert_eq!(cat.gettext("Text"), "Tekstas");
assert_eq!(cat.gettext("Image"), "Image");
}
#[test]
fn catalog_ngettext() {
let mut cat = Catalog::new();
{
// n == 1, no translation
assert_eq!(cat.ngettext("Text", "Texts", 1), "Text");
// n != 1, no translation
assert_eq!(cat.ngettext("Text", "Texts", 0), "Texts");
assert_eq!(cat.ngettext("Text", "Texts", 2), "Texts");
}
{
cat.insert(Message::new("Text", None, vec!["Tekstas", "Tekstai"]));
// n == 1, translation available
assert_eq!(cat.ngettext("Text", "Texts", 1), "Tekstas");
// n != 1, translation available
assert_eq!(cat.ngettext("Text", "Texts", 0), "Tekstai");
assert_eq!(cat.ngettext("Text", "Texts", 2), "Tekstai");
}
}
#[test]
fn catalog_pgettext() {
let mut cat = Catalog::new();
cat.insert(Message::new("Text", Some("unit test"), vec!["Tekstas"]));
assert_eq!(cat.pgettext("unit test", "Text"), "Tekstas");
assert_eq!(cat.pgettext("integration test", "Text"), "Text");
}
#[test]
fn catalog_npgettext() {
let mut cat = Catalog::new();
cat.insert(Message::new(
"Text",
Some("unit test"),
vec!["Tekstas", "Tekstai"],
));
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 1), "Tekstas");
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 0), "Tekstai");
assert_eq!(cat.npgettext("unit test", "Text", "Texts", 2), "Tekstai");
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 1),
"Text"
);
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 0),
"Texts"
);
assert_eq!(
cat.npgettext("integration test", "Text", "Texts", 2),
"Texts"
);
}
#[test]
fn test_complex_plural() {
let reader: &[u8] = include_bytes!("../test_cases/complex_plural.mo");
let cat = parser::parse_catalog(reader, ParseOptions::new()).unwrap();
assert_eq!(cat.ngettext("Test", "Tests", 0), "Plural 2");
assert_eq!(cat.ngettext("Test", "Tests", 1), "Singular");
assert_eq!(cat.ngettext("Test", "Tests", 2), "Plural 1");
for i in 3..20 {
assert_eq!(cat.ngettext("Test", "Tests", i), "Plural 2");
}
}
|
/*!
<a href="https://github.com/Nercury/di-rs">
<img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png" alt="Fork me on GitHub">
</a>
<style>.sidebar { margin-top: 53px }</style>
*/
/*!
*/
#![feature(specialization)]
mod deps;
pub mod extension;
use std::any::Any;
use std::fmt;
use std::slice;
use std::convert;
use std::result;
use std::error;
pub use deps::{ Deps, Features, Scope };
pub struct Collection<T> {
items: Vec<T>,
}
impl<T> fmt::Debug for Collection<T> where T: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.items.iter()).finish()
}
}
impl<T> Collection<T> {
pub fn new() -> Collection<T> {
Collection {
items: Vec::new()
}
}
pub fn push(&mut self, item: T) {
self.items.push(item)
}
}
impl<T> convert::AsRef<[T]> for Collection<T> {
fn as_ref(&self) -> &[T] {
&self.items
}
}
pub struct CollectionIter<'a, T: 'a> {
inner: slice::Iter<'a, T>,
}
impl<'a, T: 'a> Iterator for CollectionIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
self.inner.next()
}
}
impl<'a, T> IntoIterator for &'a Collection<T> {
type IntoIter = CollectionIter<'a, T>;
type Item = &'a T;
fn into_iter(self) -> CollectionIter<'a, T> {
CollectionIter { inner: self.items.iter() }
}
}
impl<T> Into<Vec<T>> for Collection<T> {
fn into(self) -> Vec<T> {
self.items
}
}
pub struct Expect<T: Any> {
response: Option<T>,
}
impl<T: Any> Expect<T> {
pub fn load(deps: &Deps) -> Result<T> {
let expectation = Expect::<T> {
response: None,
};
let maybe_fullfilled = try!(deps.create_for(expectation)).explode();
match maybe_fullfilled.response {
Some(value) => Ok(value),
None => Err(Box::new(Error::ExpectedDependencyNotFound)),
}
}
pub fn replace(&mut self, value: T) -> Result<()> {
if let Some(_) = self.response {
return Err(Box::new(Error::ExpectedDependencyWasAlreadyFullfilled));
}
self.response = Some(value);
Ok(())
}
}
pub fn load_from<T: Any>(deps: &Deps) -> Result<T> {
Expect::load(deps)
}
#[derive(Debug)]
pub enum Error {
ExpectedDependencyNotFound,
ExpectedDependencyWasAlreadyFullfilled,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ExpectedDependencyNotFound => "Expected dependency not found".fmt(f),
Error::ExpectedDependencyWasAlreadyFullfilled => "Expected dependency was already fullfilled".fmt(f),
}
}
}
impl error::Error for Error {
fn description(&self) -> &'static str {
match *self {
Error::ExpectedDependencyNotFound => "expected dependency not found",
Error::ExpectedDependencyWasAlreadyFullfilled => "expected dependency was already fullfilled",
}
}
}
pub type Result<T> = result::Result<T, Box<error::Error>>;
Consuming iterator for collection.
/*!
<a href="https://github.com/Nercury/di-rs">
<img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_darkblue_121621.png" alt="Fork me on GitHub">
</a>
<style>.sidebar { margin-top: 53px }</style>
*/
/*!
*/
#![feature(specialization)]
mod deps;
pub mod extension;
use std::any::Any;
use std::fmt;
use std::slice;
use std::convert;
use std::result;
use std::error;
use std::vec;
pub use deps::{ Deps, Features, Scope };
pub struct Collection<T> {
items: Vec<T>,
}
impl<T> fmt::Debug for Collection<T> where T: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.items.iter()).finish()
}
}
impl<T> Collection<T> {
pub fn new() -> Collection<T> {
Collection {
items: Vec::new()
}
}
pub fn push(&mut self, item: T) {
self.items.push(item)
}
}
impl<T> convert::AsRef<[T]> for Collection<T> {
fn as_ref(&self) -> &[T] {
&self.items
}
}
pub struct CollectionIter<'a, T: 'a> {
inner: slice::Iter<'a, T>,
}
impl<'a, T: 'a> Iterator for CollectionIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
self.inner.next()
}
}
impl<'a, T> IntoIterator for &'a Collection<T> {
type IntoIter = CollectionIter<'a, T>;
type Item = &'a T;
fn into_iter(self) -> CollectionIter<'a, T> {
CollectionIter { inner: self.items.iter() }
}
}
impl<T> IntoIterator for Collection<T> {
type IntoIter = vec::IntoIter<T>;
type Item = T;
fn into_iter(self) -> vec::IntoIter<T> {
self.items.into_iter()
}
}
impl<T> Into<Vec<T>> for Collection<T> {
fn into(self) -> Vec<T> {
self.items
}
}
pub struct Expect<T: Any> {
response: Option<T>,
}
impl<T: Any> Expect<T> {
pub fn load(deps: &Deps) -> Result<T> {
let expectation = Expect::<T> {
response: None,
};
let maybe_fullfilled = try!(deps.create_for(expectation)).explode();
match maybe_fullfilled.response {
Some(value) => Ok(value),
None => Err(Box::new(Error::ExpectedDependencyNotFound)),
}
}
pub fn replace(&mut self, value: T) -> Result<()> {
if let Some(_) = self.response {
return Err(Box::new(Error::ExpectedDependencyWasAlreadyFullfilled));
}
self.response = Some(value);
Ok(())
}
}
pub fn load_from<T: Any>(deps: &Deps) -> Result<T> {
Expect::load(deps)
}
#[derive(Debug)]
pub enum Error {
ExpectedDependencyNotFound,
ExpectedDependencyWasAlreadyFullfilled,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ExpectedDependencyNotFound => "Expected dependency not found".fmt(f),
Error::ExpectedDependencyWasAlreadyFullfilled => "Expected dependency was already fullfilled".fmt(f),
}
}
}
impl error::Error for Error {
fn description(&self) -> &'static str {
match *self {
Error::ExpectedDependencyNotFound => "expected dependency not found",
Error::ExpectedDependencyWasAlreadyFullfilled => "expected dependency was already fullfilled",
}
}
}
pub type Result<T> = result::Result<T, Box<error::Error>>;
|
use std::collections::HashMap;
use std::cmp::Ordering;
extern crate regex;
use regex::Regex;
pub fn puzzle(input: &str) -> u32 {
0
}
pub struct Room {
name: String,
sector_id: u32,
checksum: String,
}
impl Room {
fn new(description: &str) -> Room {
let regex = Regex::new(r"(?x)
(?P<name>[a-z-]+)
-
(?P<sector_id>[0-9]+)
\[(?P<checksum>[a-z]{5})\]").expect("Regex is invalid");
let caps = regex.captures(description).expect("Can't capture");
Room {
name: caps.name("name").expect("No name").to_string(),
sector_id: caps.name("sector_id").expect("No sector id").parse().expect("Can't parse"),
checksum: caps.name("checksum").expect("No checksum").to_string(),
}
}
fn is_real(&self) -> bool {
self.checksum == self.computed_checksum()
}
fn computed_checksum(&self) -> String {
let mut most_common = self.five_most_common_chars();
most_common.sort();
let mut s = String::new();
for &c in most_common.iter() {
s.push(c);
}
s
}
fn five_most_common_chars(&self) -> Vec<char> {
self.chars_by_frequency_desc().into_iter().take(5).collect()
}
fn chars_by_frequency_desc(&self) -> Vec<char> {
let mut tuples: Vec<(char, u32)> = self.chars_by_frequency()
.into_iter()
.collect();
tuples.sort_by(|a, b| {
match b.1.cmp(&a.1) {
Ordering::Equal => a.0.cmp(&b.0),
other => other,
}
});
tuples.iter().map( |&(k, _)| k ).collect()
}
fn chars_by_frequency(&self) -> HashMap<char, u32> {
let mut freqs = HashMap::new();
for c in self.name.chars() {
if c != '-' {
let count = freqs.entry(c).or_insert(0);
*count += 1;
}
}
freqs
}
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashMap;
#[test]
fn test_extraction() {
let description = "aaaaa-bbb-z-y-x-123[abxyz]";
let room = Room::new(description);
assert_eq!(room.name, "aaaaa-bbb-z-y-x");
assert_eq!(room.sector_id, 123);
assert_eq!(room.checksum, "abxyz");
}
#[test]
fn test_chars_by_freq() {
let room = Room::new("aaaaa-bbb-z-y-x-123[abxyz]");
let mut expected = HashMap::new();
expected.insert('a', 5);
expected.insert('b', 3);
expected.insert('z', 1);
expected.insert('y', 1);
expected.insert('x', 1);
assert_eq!(room.chars_by_frequency(), expected);
}
#[test]
fn test_chars_by_freq_desc() {
let room = Room::new("aaaaa-bbb-z-y-x-123[abxyz]");
assert_eq!(
room.chars_by_frequency_desc(),
vec!['a', 'b', 'x', 'y', 'z']
);
}
#[test]
fn test_five_most_common_chars() {
let room = Room::new("not-a-real-room-404[oarel]");
assert_eq!(
room.five_most_common_chars(),
vec!['o', 'a', 'r', 'e', 'l']
);
}
#[test]
fn real_rooms() {
assert!(Room::new("aaaaa-bbb-z-y-x-123[abxyz]").is_real());
assert!(Room::new("a-b-c-d-e-f-g-h-987[abcde]").is_real());
assert!(Room::new("not-a-real-room-404[oarel]").is_real());
}
#[test]
fn decoy_rooms() {
assert!( ! Room::new("totally-real-room-200[decoy]").is_real() );
}
}
Oops. Final sort isn't alphabetical, it's freq then alpha.
Which I totally had but I was overwriting because I thought the spec
said "sorted" meaning alphabetical.
use std::collections::HashMap;
use std::cmp::Ordering;
extern crate regex;
use regex::Regex;
pub fn puzzle(input: &str) -> u32 {
0
}
pub struct Room {
name: String,
sector_id: u32,
checksum: String,
}
impl Room {
fn new(description: &str) -> Room {
let regex = Regex::new(r"(?x)
(?P<name>[a-z-]+)
-
(?P<sector_id>[0-9]+)
\[(?P<checksum>[a-z]{5})\]").expect("Regex is invalid");
let caps = regex.captures(description).expect("Can't capture");
Room {
name: caps.name("name").expect("No name").to_string(),
sector_id: caps.name("sector_id").expect("No sector id").parse().expect("Can't parse"),
checksum: caps.name("checksum").expect("No checksum").to_string(),
}
}
fn is_real(&self) -> bool {
self.checksum == self.computed_checksum()
}
fn computed_checksum(&self) -> String {
let mut most_common = self.five_most_common_chars();
let mut s = String::new();
for &c in most_common.iter() {
s.push(c);
}
s
}
fn five_most_common_chars(&self) -> Vec<char> {
self.chars_by_frequency_desc().into_iter().take(5).collect()
}
fn chars_by_frequency_desc(&self) -> Vec<char> {
let mut tuples: Vec<(char, u32)> = self.chars_by_frequency()
.into_iter()
.collect();
tuples.sort_by(|a, b| {
match b.1.cmp(&a.1) {
Ordering::Equal => a.0.cmp(&b.0),
other => other,
}
});
tuples.iter().map( |&(k, _)| k ).collect()
}
fn chars_by_frequency(&self) -> HashMap<char, u32> {
let mut freqs = HashMap::new();
for c in self.name.chars() {
if c != '-' {
let count = freqs.entry(c).or_insert(0);
*count += 1;
}
}
freqs
}
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashMap;
#[test]
fn test_extraction() {
let description = "aaaaa-bbb-z-y-x-123[abxyz]";
let room = Room::new(description);
assert_eq!(room.name, "aaaaa-bbb-z-y-x");
assert_eq!(room.sector_id, 123);
assert_eq!(room.checksum, "abxyz");
}
#[test]
fn test_chars_by_freq() {
let room = Room::new("aaaaa-bbb-z-y-x-123[abxyz]");
let mut expected = HashMap::new();
expected.insert('a', 5);
expected.insert('b', 3);
expected.insert('z', 1);
expected.insert('y', 1);
expected.insert('x', 1);
assert_eq!(room.chars_by_frequency(), expected);
}
#[test]
fn test_chars_by_freq_desc() {
let room = Room::new("aaaaa-bbb-z-y-x-123[abxyz]");
assert_eq!(
room.chars_by_frequency_desc(),
vec!['a', 'b', 'x', 'y', 'z']
);
}
#[test]
fn test_five_most_common_chars() {
let room = Room::new("not-a-real-room-404[oarel]");
assert_eq!(
room.five_most_common_chars(),
vec!['o', 'a', 'r', 'e', 'l']
);
}
#[test]
fn real_rooms() {
assert!(Room::new("aaaaa-bbb-z-y-x-123[abxyz]").is_real());
assert!(Room::new("a-b-c-d-e-f-g-h-987[abcde]").is_real());
assert!(Room::new("not-a-real-room-404[oarel]").is_real());
}
#[test]
fn decoy_rooms() {
assert!( ! Room::new("totally-real-room-200[decoy]").is_real() );
}
}
|
extern crate json_schema;
extern crate serde_json;
#[macro_use]
extern crate quote;
use std::borrow::Cow;
use std::error::Error;
use json_schema::{Schema, Type};
use quote::{Tokens, ToTokens};
struct Ident<S>(S);
impl<S: AsRef<str>> ToTokens for Ident<S> {
fn to_tokens(&self, tokens: &mut Tokens) {
tokens.append(self.0.as_ref())
}
}
const ONE_OR_MANY: &'static str = r#"
use std::ops::{Deref, DerefMut};
#[derive(Clone, Debug, PartialEq)]
pub enum OneOrMany<T> {
One(Box<T>),
Many(Vec<T>),
}
impl<T> Deref for OneOrMany<T> {
type Target = [T];
fn deref(&self) -> &[T] {
match *self {
OneOrMany::One(ref v) => unsafe { ::std::slice::from_raw_parts(&**v, 1) },
OneOrMany::Many(ref v) => v,
}
}
}
impl<T> DerefMut for OneOrMany<T> {
fn deref_mut(&mut self) -> &mut [T] {
match *self {
OneOrMany::One(ref mut v) => unsafe { ::std::slice::from_raw_parts_mut(&mut **v, 1) },
OneOrMany::Many(ref mut v) => v,
}
}
}
impl<T> Default for OneOrMany<T> {
fn default() -> OneOrMany<T> {
OneOrMany::Many(Vec::new())
}
}
impl<T> serde::Deserialize for OneOrMany<T>
where T: serde::Deserialize
{
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
T::deserialize(deserializer)
.map(|one| OneOrMany::One(Box::new(one)))
.or_else(|_| Vec::<T>::deserialize(deserializer).map(OneOrMany::Many))
}
}
impl<T> serde::Serialize for OneOrMany<T>
where T: serde::Serialize
{
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
match *self {
OneOrMany::One(ref one) => one.serialize(serializer),
OneOrMany::Many(ref many) => many.serialize(serializer),
}
}
}
"#;
fn rename_keyword(prefix: &str, s: &str) -> Option<Tokens> {
if ["type", "struct", "enum"].iter().any(|&keyword| keyword == s) {
let n = Ident(format!("{}_", s));
let prefix = Ident(prefix);
Some(quote!{
#[serde(rename = #s)]
#prefix #n
})
} else {
None
}
}
fn field(s: &str) -> Tokens {
if let Some(t) = rename_keyword("pub", s) {
t
} else {
let mut snake = String::new();
let mut chars = s.chars();
let mut prev_was_upper = false;
while let Some(c) = chars.next() {
if c.is_uppercase() {
if !prev_was_upper {
snake.push('_');
}
snake.extend(c.to_lowercase());
prev_was_upper = true;
} else {
snake.push(c);
prev_was_upper = false;
}
}
if snake != s || snake.contains(|c: char| c == '$' || c == '#') {
let field = Ident(snake.replace('$', "").replace('#', ""));
quote!{
#[serde(rename = #s)]
pub #field
}
} else {
let field = Ident(s);
quote!( pub #field )
}
}
}
fn merge(result: &mut Schema, r: &Schema) {
use std::collections::hash_map::Entry;
for (k, v) in &r.properties {
match result.properties.entry(k.clone()) {
Entry::Vacant(entry) => {
entry.insert(v.clone());
}
Entry::Occupied(mut entry) => merge(entry.get_mut(), v),
}
}
}
struct FieldExpander<'a, 'r: 'a> {
default: bool,
expander: &'a mut Expander<'r>,
}
impl<'a, 'r> FieldExpander<'a, 'r> {
fn expand_fields(&mut self, type_name: &str, schema: &Schema) -> Vec<Tokens> {
let schema = self.expander.schema(schema);
schema.properties
.iter()
.map(|(field_name, value)| {
let key = field(field_name);
let required = schema.required.iter().any(|req| req == field_name);
let typ = Ident(self.expander.expand_type(type_name, required, value));
if !typ.0.starts_with("Option<") {
self.default = false;
}
quote!( #key : #typ )
})
.collect()
}
}
struct Expander<'r> {
root_name: Option<&'r str>,
root: &'r Schema,
needs_one_or_many: bool,
}
impl<'r> Expander<'r> {
fn new(root_name: Option<&'r str>, root: &'r Schema) -> Expander<'r> {
Expander {
root_name: root_name,
root: root,
needs_one_or_many: false,
}
}
fn type_ref(&self, s: &str) -> String {
if s == "#" {
self.root_name.expect("Root name").into()
} else {
s.split('/').last().expect("Component").into()
}
}
fn schema(&self, schema: &'r Schema) -> Cow<'r, Schema> {
let result = match schema.allOf.first() {
Some(result) => {
schema.allOf
.iter()
.skip(1)
.fold(Cow::Borrowed(result), |mut result, def| {
merge(result.to_mut(), &self.schema(def));
result
})
}
None => Cow::Borrowed(schema),
};
if let Some(ref ref_) = result.ref_ {
return Cow::Borrowed(self.schema_ref(ref_));
}
result
}
fn schema_ref(&self, s: &str) -> &'r Schema {
s.split('/').fold(self.root, |schema, comp| {
if comp == "#" {
self.root
} else if comp == "definitions" {
schema
} else {
schema.definitions
.get(comp)
.unwrap_or_else(|| panic!("Expected definition: `{}` {}", s, comp))
}
})
}
fn expand_type(&mut self, type_name: &str, required: bool, typ: &Schema) -> String {
let result = self.expand_type_(typ);
let result = if type_name == result {
format!("Box<{}>", result)
} else {
result
};
if required {
result
} else {
format!("Option<{}>", result)
}
}
fn expand_type_(&mut self, typ: &Schema) -> String {
if let Some(ref ref_) = typ.ref_ {
self.type_ref(ref_)
} else if typ.anyOf.len() == 2 {
let simple = self.schema(&typ.anyOf[0]);
let array = self.schema(&typ.anyOf[1]);
match array.items {
Some(ref item_schema) => {
if array.type_[0] == Type::Array && simple == self.schema(item_schema) {
self.needs_one_or_many = true;
return format!("OneOrMany<{}>", self.expand_type_(&typ.anyOf[0]));
}
}
_ => (),
}
return "serde_json::Value".into();
} else if typ.type_.len() == 1 {
match typ.type_[0] {
Type::String => {
if !typ.enum_.is_empty() {
"serde_json::Value".into()
} else {
"String".into()
}
}
Type::Integer => "i64".into(),
Type::Boolean => "bool".into(),
Type::Number => "f64".into(),
Type::Object => "serde_json::Value".into(),
Type::Array => {
let item_type =
typ.items.as_ref().map_or("serde_json::Value".into(),
|item_schema| self.expand_type_(item_schema));
format!("Vec<{}>", item_type)
}
_ => panic!("Type"),
}
} else {
"serde_json::Value".into()
}
}
pub fn expand_definitions(&mut self, schema: &Schema) -> Vec<Tokens> {
let mut types = Vec::new();
for (name, def) in &schema.definitions {
types.push(self.expand_schema(name, def));
}
types
}
pub fn expand_schema(&mut self, name: &str, schema: &Schema) -> Tokens {
let (fields, default) = {
let mut field_expander = FieldExpander {
default: true,
expander: self,
};
let fields = field_expander.expand_fields(name, schema);
(fields, field_expander.default)
};
let name = Ident(name);
if !fields.is_empty() {
if default {
quote! {
#[derive(Default, Deserialize, Serialize)]
pub struct #name {
#(#fields),*
}
}
} else {
quote! {
#[derive(Deserialize, Serialize)]
pub struct #name {
#(#fields),*
}
}
}
} else if !schema.enum_.is_empty() {
let variants = schema.enum_.iter().map(|v| {
rename_keyword("", v).unwrap_or_else(|| {
let v = Ident(v);
quote!(#v)
})
});
quote! {
#[derive(Deserialize, Serialize)]
pub enum #name {
#(#variants),*
}
}
} else {
let typ = Ident(self.expand_type("", true, schema));
quote! {
pub type #name = #typ;
}
}
}
pub fn expand(&mut self, schema: &Schema) -> Tokens {
let mut types = self.expand_definitions(schema);
if let Some(name) = self.root_name {
types.push(self.expand_schema(name, schema));
}
let one_or_many = Ident(if self.needs_one_or_many {
ONE_OR_MANY
} else {
""
});
quote! {
#one_or_many
#( #types )*
}
}
}
pub fn generate(root_name: Option<&str>, s: &str) -> Result<String, Box<Error>> {
use std::process::{Command, Stdio};
use std::io::Write;
let schema = serde_json::from_str(s).unwrap();
let mut expander = Expander::new(root_name, &schema);
let output = expander.expand(&schema).to_string();
let mut child =
try!(Command::new("rustfmt").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
try!(child.stdin.as_mut().expect("stdin").write_all(output.as_bytes()));
let output = try!(child.wait_with_output());
assert!(output.status.success());
Ok(try!(String::from_utf8(output.stdout)))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
#[test]
fn generate_schema() {
let s = include_str!("../../json-schema/tests/schema.json");
let s = generate(Some("Schema"), s).unwrap().to_string();
verify_compile("schema", &s);
assert!(s.contains("pub struct Schema"), "{}", s);
assert!(s.contains("pub type positiveInteger = i64"));
assert!(s.contains("pub type_: Option<OneOrMany<simpleTypes>>"));
let result = Command::new("rustc")
.args(&["-L",
"target/debug/deps/",
"-o",
"target/debug/schema-test",
"tests/support/schema-test.rs"])
.status()
.unwrap();
assert!(result.success());
let result = Command::new("./target/debug/schema-test")
.status()
.unwrap();
assert!(result.success());
}
fn verify_compile(name: &str, s: &str) {
let mut filename = PathBuf::from("target/debug");
filename.push(&format!("{}.rs", name));
{
let mut file = File::create(&filename).unwrap();
let header = r#"
#![feature(proc_macro)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
"#;
file.write_all(header.as_bytes()).unwrap();
file.write_all(s.as_bytes()).unwrap();
}
println!("{}", filename.display());
let child = Command::new("rustc")
.args(&["-L",
"target/debug/deps/",
"--crate-type=rlib",
"-o",
&format!("target/debug/deps/lib{}.rlib", name),
filename.to_str().unwrap()])
.stderr(Stdio::piped())
.spawn()
.unwrap();
let output = child.wait_with_output().unwrap();
let error = String::from_utf8(output.stderr).unwrap();
assert!(output.status.success(), "{}", error);
}
#[test]
fn builds_with_rustc() {
let s = include_str!("../../json-schema/tests/debugserver-schema.json");
let s = generate(None, s).unwrap().to_string();
verify_compile("debug-server", &s)
}
}
fix: Treat additionalProperties as a HashMap
extern crate json_schema;
extern crate serde_json;
#[macro_use]
extern crate quote;
use std::borrow::Cow;
use std::error::Error;
use json_schema::{Schema, Type};
use quote::{Tokens, ToTokens};
struct Ident<S>(S);
impl<S: AsRef<str>> ToTokens for Ident<S> {
fn to_tokens(&self, tokens: &mut Tokens) {
tokens.append(self.0.as_ref())
}
}
const ONE_OR_MANY: &'static str = r#"
use std::ops::{Deref, DerefMut};
#[derive(Clone, Debug, PartialEq)]
pub enum OneOrMany<T> {
One(Box<T>),
Many(Vec<T>),
}
impl<T> Deref for OneOrMany<T> {
type Target = [T];
fn deref(&self) -> &[T] {
match *self {
OneOrMany::One(ref v) => unsafe { ::std::slice::from_raw_parts(&**v, 1) },
OneOrMany::Many(ref v) => v,
}
}
}
impl<T> DerefMut for OneOrMany<T> {
fn deref_mut(&mut self) -> &mut [T] {
match *self {
OneOrMany::One(ref mut v) => unsafe { ::std::slice::from_raw_parts_mut(&mut **v, 1) },
OneOrMany::Many(ref mut v) => v,
}
}
}
impl<T> Default for OneOrMany<T> {
fn default() -> OneOrMany<T> {
OneOrMany::Many(Vec::new())
}
}
impl<T> serde::Deserialize for OneOrMany<T>
where T: serde::Deserialize
{
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer
{
T::deserialize(deserializer)
.map(|one| OneOrMany::One(Box::new(one)))
.or_else(|_| Vec::<T>::deserialize(deserializer).map(OneOrMany::Many))
}
}
impl<T> serde::Serialize for OneOrMany<T>
where T: serde::Serialize
{
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
match *self {
OneOrMany::One(ref one) => one.serialize(serializer),
OneOrMany::Many(ref many) => many.serialize(serializer),
}
}
}
"#;
fn rename_keyword(prefix: &str, s: &str) -> Option<Tokens> {
if ["type", "struct", "enum"].iter().any(|&keyword| keyword == s) {
let n = Ident(format!("{}_", s));
let prefix = Ident(prefix);
Some(quote!{
#[serde(rename = #s)]
#prefix #n
})
} else {
None
}
}
fn field(s: &str) -> Tokens {
if let Some(t) = rename_keyword("pub", s) {
t
} else {
let mut snake = String::new();
let mut chars = s.chars();
let mut prev_was_upper = false;
while let Some(c) = chars.next() {
if c.is_uppercase() {
if !prev_was_upper {
snake.push('_');
}
snake.extend(c.to_lowercase());
prev_was_upper = true;
} else {
snake.push(c);
prev_was_upper = false;
}
}
if snake != s || snake.contains(|c: char| c == '$' || c == '#') {
let field = Ident(snake.replace('$', "").replace('#', ""));
quote!{
#[serde(rename = #s)]
pub #field
}
} else {
let field = Ident(s);
quote!( pub #field )
}
}
}
fn merge(result: &mut Schema, r: &Schema) {
use std::collections::hash_map::Entry;
for (k, v) in &r.properties {
match result.properties.entry(k.clone()) {
Entry::Vacant(entry) => {
entry.insert(v.clone());
}
Entry::Occupied(mut entry) => merge(entry.get_mut(), v),
}
}
}
struct FieldExpander<'a, 'r: 'a> {
default: bool,
expander: &'a mut Expander<'r>,
}
impl<'a, 'r> FieldExpander<'a, 'r> {
fn expand_fields(&mut self, type_name: &str, schema: &Schema) -> Vec<Tokens> {
let schema = self.expander.schema(schema);
schema.properties
.iter()
.map(|(field_name, value)| {
let key = field(field_name);
let required = schema.required.iter().any(|req| req == field_name);
let typ = Ident(self.expander.expand_type(type_name, required, value));
if !typ.0.starts_with("Option<") {
self.default = false;
}
quote!( #key : #typ )
})
.collect()
}
}
struct Expander<'r> {
root_name: Option<&'r str>,
root: &'r Schema,
needs_one_or_many: bool,
}
impl<'r> Expander<'r> {
fn new(root_name: Option<&'r str>, root: &'r Schema) -> Expander<'r> {
Expander {
root_name: root_name,
root: root,
needs_one_or_many: false,
}
}
fn type_ref(&self, s: &str) -> String {
if s == "#" {
self.root_name.expect("Root name").into()
} else {
s.split('/').last().expect("Component").into()
}
}
fn schema(&self, schema: &'r Schema) -> Cow<'r, Schema> {
let result = match schema.allOf.first() {
Some(result) => {
schema.allOf
.iter()
.skip(1)
.fold(Cow::Borrowed(result), |mut result, def| {
merge(result.to_mut(), &self.schema(def));
result
})
}
None => Cow::Borrowed(schema),
};
if let Some(ref ref_) = result.ref_ {
return Cow::Borrowed(self.schema_ref(ref_));
}
result
}
fn schema_ref(&self, s: &str) -> &'r Schema {
s.split('/').fold(self.root, |schema, comp| {
if comp == "#" {
self.root
} else if comp == "definitions" {
schema
} else {
schema.definitions
.get(comp)
.unwrap_or_else(|| panic!("Expected definition: `{}` {}", s, comp))
}
})
}
fn expand_type(&mut self, type_name: &str, required: bool, typ: &Schema) -> String {
let result = self.expand_type_(typ);
let result = if type_name == result {
format!("Box<{}>", result)
} else {
result
};
if required {
result
} else {
format!("Option<{}>", result)
}
}
fn expand_type_(&mut self, typ: &Schema) -> String {
if let Some(ref ref_) = typ.ref_ {
self.type_ref(ref_)
} else if typ.anyOf.len() == 2 {
let simple = self.schema(&typ.anyOf[0]);
let array = self.schema(&typ.anyOf[1]);
match array.items {
Some(ref item_schema) => {
if array.type_[0] == Type::Array && simple == self.schema(item_schema) {
self.needs_one_or_many = true;
return format!("OneOrMany<{}>", self.expand_type_(&typ.anyOf[0]));
}
}
_ => (),
}
return "serde_json::Value".into();
} else if typ.type_.len() == 1 {
match typ.type_[0] {
Type::String => {
if !typ.enum_.is_empty() {
"serde_json::Value".into()
} else {
"String".into()
}
}
Type::Integer => "i64".into(),
Type::Boolean => "bool".into(),
Type::Number => "f64".into(),
Type::Object if typ.additionalProperties.is_some() => {
let prop = typ.additionalProperties.as_ref().unwrap();
format!("::std::collections::HashMap<String, {}>", self.expand_type_(prop))
}
Type::Array => {
let item_type =
typ.items.as_ref().map_or("serde_json::Value".into(),
|item_schema| self.expand_type_(item_schema));
format!("Vec<{}>", item_type)
}
_ => "serde_json::Value".into(),
}
} else {
"serde_json::Value".into()
}
}
pub fn expand_definitions(&mut self, schema: &Schema) -> Vec<Tokens> {
let mut types = Vec::new();
for (name, def) in &schema.definitions {
types.push(self.expand_schema(name, def));
}
types
}
pub fn expand_schema(&mut self, name: &str, schema: &Schema) -> Tokens {
let (fields, default) = {
let mut field_expander = FieldExpander {
default: true,
expander: self,
};
let fields = field_expander.expand_fields(name, schema);
(fields, field_expander.default)
};
let name = Ident(name);
if !fields.is_empty() {
if default {
quote! {
#[derive(Default, Deserialize, Serialize)]
pub struct #name {
#(#fields),*
}
}
} else {
quote! {
#[derive(Deserialize, Serialize)]
pub struct #name {
#(#fields),*
}
}
}
} else if !schema.enum_.is_empty() {
let variants = schema.enum_.iter().map(|v| {
rename_keyword("", v).unwrap_or_else(|| {
let v = Ident(v);
quote!(#v)
})
});
quote! {
#[derive(Deserialize, Serialize)]
pub enum #name {
#(#variants),*
}
}
} else {
let typ = Ident(self.expand_type("", true, schema));
quote! {
pub type #name = #typ;
}
}
}
pub fn expand(&mut self, schema: &Schema) -> Tokens {
let mut types = self.expand_definitions(schema);
if let Some(name) = self.root_name {
types.push(self.expand_schema(name, schema));
}
let one_or_many = Ident(if self.needs_one_or_many {
ONE_OR_MANY
} else {
""
});
quote! {
#one_or_many
#( #types )*
}
}
}
pub fn generate(root_name: Option<&str>, s: &str) -> Result<String, Box<Error>> {
use std::process::{Command, Stdio};
use std::io::Write;
let schema = serde_json::from_str(s).unwrap();
let mut expander = Expander::new(root_name, &schema);
let output = expander.expand(&schema).to_string();
let mut child =
try!(Command::new("rustfmt").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
try!(child.stdin.as_mut().expect("stdin").write_all(output.as_bytes()));
let output = try!(child.wait_with_output());
assert!(output.status.success());
Ok(try!(String::from_utf8(output.stdout)))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
#[test]
fn generate_schema() {
let s = include_str!("../../json-schema/tests/schema.json");
let s = generate(Some("Schema"), s).unwrap().to_string();
verify_compile("schema", &s);
assert!(s.contains("pub struct Schema"), "{}", s);
assert!(s.contains("pub type positiveInteger = i64"));
assert!(s.contains("pub type_: Option<OneOrMany<simpleTypes>>"));
let result = Command::new("rustc")
.args(&["-L",
"target/debug/deps/",
"-o",
"target/debug/schema-test",
"tests/support/schema-test.rs"])
.status()
.unwrap();
assert!(result.success());
let result = Command::new("./target/debug/schema-test")
.status()
.unwrap();
assert!(result.success());
}
fn verify_compile(name: &str, s: &str) {
let mut filename = PathBuf::from("target/debug");
filename.push(&format!("{}.rs", name));
{
let mut file = File::create(&filename).unwrap();
let header = r#"
#![feature(proc_macro)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
"#;
file.write_all(header.as_bytes()).unwrap();
file.write_all(s.as_bytes()).unwrap();
}
println!("{}", filename.display());
let child = Command::new("rustc")
.args(&["-L",
"target/debug/deps/",
"--crate-type=rlib",
"-o",
&format!("target/debug/deps/lib{}.rlib", name),
filename.to_str().unwrap()])
.stderr(Stdio::piped())
.spawn()
.unwrap();
let output = child.wait_with_output().unwrap();
let error = String::from_utf8(output.stderr).unwrap();
assert!(output.status.success(), "{}", error);
}
#[test]
fn builds_with_rustc() {
let s = include_str!("../../json-schema/tests/debugserver-schema.json");
let s = generate(None, s).unwrap().to_string();
verify_compile("debug-server", &s)
}
}
|
//! The textwrap library provides functions for word wrapping and
//! indenting text.
//!
//! # Wrapping Text
//!
//! Wrapping text can be very useful in command-line programs where
//! you want to format dynamic output nicely so it looks good in a
//! terminal. A quick example:
//!
//! ```
//! # #[cfg(feature = "smawk")] {
//! let text = "textwrap: a small library for wrapping text.";
//! assert_eq!(textwrap::wrap(text, 18),
//! vec!["textwrap: a",
//! "small library for",
//! "wrapping text."]);
//! # }
//! ```
//!
//! The [`wrap`] function returns the individual lines, use [`fill`]
//! is you want the lines joined with `'\n'` to form a `String`.
//!
//! If you enable the `hyphenation` Cargo feature, you can get
//! automatic hyphenation for a number of languages:
//!
//! ```
//! #[cfg(feature = "hyphenation")] {
//! use hyphenation::{Language, Load, Standard};
//! use textwrap::{wrap, Options, WordSplitter};
//!
//! let text = "textwrap: a small library for wrapping text.";
//! let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
//! let options = Options::new(18).word_splitter(WordSplitter::Hyphenation(dictionary));
//! assert_eq!(wrap(text, &options),
//! vec!["textwrap: a small",
//! "library for wrap-",
//! "ping text."]);
//! }
//! ```
//!
//! See also the [`unfill`] and [`refill`] functions which allow you to
//! manipulate already wrapped text.
//!
//! ## Wrapping Strings at Compile Time
//!
//! If your strings are known at compile time, please take a look at
//! the procedural macros from the [textwrap-macros] crate.
//!
//! ## Displayed Width vs Byte Size
//!
//! To word wrap text, one must know the width of each word so one can
//! know when to break lines. This library will by default measure the
//! width of text using the _displayed width_, not the size in bytes.
//! The `unicode-width` Cargo feature controls this.
//!
//! This is important for non-ASCII text. ASCII characters such as `a`
//! and `!` are simple and take up one column each. This means that
//! the displayed width is equal to the string length in bytes.
//! However, non-ASCII characters and symbols take up more than one
//! byte when UTF-8 encoded: `é` is `0xc3 0xa9` (two bytes) and `⚙` is
//! `0xe2 0x9a 0x99` (three bytes) in UTF-8, respectively.
//!
//! This is why we take care to use the displayed width instead of the
//! byte count when computing line lengths. All functions in this
//! library handle Unicode characters like this when the
//! `unicode-width` Cargo feature is enabled (it is enabled by
//! default).
//!
//! # Indentation and Dedentation
//!
//! The textwrap library also offers functions for adding a prefix to
//! every line of a string and to remove leading whitespace. As an
//! example, the [`indent`] function allows you to turn lines of text
//! into a bullet list:
//!
//! ```
//! let before = "\
//! foo
//! bar
//! baz
//! ";
//! let after = "\
//! * foo
//! * bar
//! * baz
//! ";
//! assert_eq!(textwrap::indent(before, "* "), after);
//! ```
//!
//! Removing leading whitespace is done with [`dedent`]:
//!
//! ```
//! let before = "
//! Some
//! indented
//! text
//! ";
//! let after = "
//! Some
//! indented
//! text
//! ";
//! assert_eq!(textwrap::dedent(before), after);
//! ```
//!
//! # Cargo Features
//!
//! The textwrap library can be slimmed down as needed via a number of
//! Cargo features. This means you only pay for the features you
//! actually use.
//!
//! The full dependency graph, where dashed lines indicate optional
//! dependencies, is shown below:
//!
//! <img src="https://raw.githubusercontent.com/mgeisler/textwrap/master/images/textwrap-0.15.0.svg">
//!
//! ## Default Features
//!
//! These features are enabled by default:
//!
//! * `unicode-linebreak`: enables finding words using the
//! [unicode-linebreak] crate, which implements the line breaking
//! algorithm described in [Unicode Standard Annex
//! #14](https://www.unicode.org/reports/tr14/).
//!
//! This feature can be disabled if you are happy to find words
//! separated by ASCII space characters only. People wrapping text
//! with emojis or East-Asian characters will want most likely want
//! to enable this feature. See [`WordSeparator`] for details.
//!
//! * `unicode-width`: enables correct width computation of non-ASCII
//! characters via the [unicode-width] crate. Without this feature,
//! every [`char`] is 1 column wide, except for emojis which are 2
//! columns wide. See the [`core::display_width`] function for
//! details.
//!
//! This feature can be disabled if you only need to wrap ASCII
//! text, or if the functions in [`core`] are used directly with
//! [`core::Fragment`]s for which the widths have been computed in
//! other ways.
//!
//! * `smawk`: enables linear-time wrapping of the whole paragraph via
//! the [smawk] crate. See the [`wrap_algorithms::wrap_optimal_fit`]
//! function for details on the optimal-fit algorithm.
//!
//! This feature can be disabled if you only ever intend to use
//! [`wrap_algorithms::wrap_first_fit`].
//!
//! With Rust 1.59.0, the size impact of the above features on your
//! binary is as follows:
//!
//! | Configuration | Binary Size | Delta |
//! | :--- | ---: | ---: |
//! | quick-and-dirty implementation | 289 KB | — KB |
//! | textwrap without default features | 301 KB | 12 KB |
//! | textwrap with smawk | 317 KB | 28 KB |
//! | textwrap with unicode-width | 313 KB | 24 KB |
//! | textwrap with unicode-linebreak | 395 KB | 106 KB |
//!
//! The above sizes are the stripped sizes and the binary is compiled
//! in release mode with this profile:
//!
//! ```toml
//! [profile.release]
//! lto = true
//! codegen-units = 1
//! ```
//!
//! See the [binary-sizes demo] if you want to reproduce these
//! results.
//!
//! ## Optional Features
//!
//! These Cargo features enable new functionality:
//!
//! * `terminal_size`: enables automatic detection of the terminal
//! width via the [terminal_size] crate. See the
//! [`Options::with_termwidth`] constructor for details.
//!
//! * `hyphenation`: enables language-sensitive hyphenation via the
//! [hyphenation] crate. See the [`word_splitters::WordSplitter`]
//! trait for details.
//!
//! [unicode-linebreak]: https://docs.rs/unicode-linebreak/
//! [unicode-width]: https://docs.rs/unicode-width/
//! [smawk]: https://docs.rs/smawk/
//! [binary-sizes demo]: https://github.com/mgeisler/textwrap/tree/master/examples/binary-sizes
//! [textwrap-macros]: https://docs.rs/textwrap-macros/
//! [terminal_size]: https://docs.rs/terminal_size/
//! [hyphenation]: https://docs.rs/hyphenation/
#![doc(html_root_url = "https://docs.rs/textwrap/0.15.0")]
#![forbid(unsafe_code)] // See https://github.com/mgeisler/textwrap/issues/210
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![allow(clippy::redundant_field_names)]
// Make `cargo test` execute the README doctests.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctest {}
use std::borrow::Cow;
mod indentation;
pub use crate::indentation::{dedent, indent};
mod word_separators;
pub use word_separators::WordSeparator;
pub mod word_splitters;
pub use word_splitters::WordSplitter;
pub mod wrap_algorithms;
pub use wrap_algorithms::WrapAlgorithm;
mod line_ending;
pub use line_ending::LineEnding;
pub mod core;
/// Holds configuration options for wrapping and filling text.
#[derive(Debug, Clone)]
pub struct Options<'a> {
/// The width in columns at which the text will be wrapped.
pub width: usize,
/// Line ending used for breaking lines.
pub line_ending: LineEnding,
/// Indentation used for the first line of output. See the
/// [`Options::initial_indent`] method.
pub initial_indent: &'a str,
/// Indentation used for subsequent lines of output. See the
/// [`Options::subsequent_indent`] method.
pub subsequent_indent: &'a str,
/// Allow long words to be broken if they cannot fit on a line.
/// When set to `false`, some lines may be longer than
/// `self.width`. See the [`Options::break_words`] method.
pub break_words: bool,
/// Wrapping algorithm to use, see the implementations of the
/// [`wrap_algorithms::WrapAlgorithm`] trait for details.
pub wrap_algorithm: WrapAlgorithm,
/// The line breaking algorithm to use, see
/// [`word_separators::WordSeparator`] trait for an overview and
/// possible implementations.
pub word_separator: WordSeparator,
/// The method for splitting words. This can be used to prohibit
/// splitting words on hyphens, or it can be used to implement
/// language-aware machine hyphenation.
pub word_splitter: WordSplitter,
}
impl<'a> From<&'a Options<'a>> for Options<'a> {
fn from(options: &'a Options<'a>) -> Self {
Self {
width: options.width,
line_ending: options.line_ending,
initial_indent: options.initial_indent,
subsequent_indent: options.subsequent_indent,
break_words: options.break_words,
word_separator: options.word_separator,
wrap_algorithm: options.wrap_algorithm,
word_splitter: options.word_splitter.clone(),
}
}
}
impl<'a> From<usize> for Options<'a> {
fn from(width: usize) -> Self {
Options::new(width)
}
}
impl<'a> Options<'a> {
/// Creates a new [`Options`] with the specified width. Equivalent to
///
/// ```
/// # use textwrap::{LineEnding, Options, WordSplitter, WordSeparator, WrapAlgorithm};
/// # let width = 80;
/// # let actual = Options::new(width);
/// # let expected =
/// Options {
/// width: width,
/// line_ending: LineEnding::LF,
/// initial_indent: "",
/// subsequent_indent: "",
/// break_words: true,
/// #[cfg(feature = "unicode-linebreak")]
/// word_separator: WordSeparator::UnicodeBreakProperties,
/// #[cfg(not(feature = "unicode-linebreak"))]
/// word_separator: WordSeparator::AsciiSpace,
/// #[cfg(feature = "smawk")]
/// wrap_algorithm: WrapAlgorithm::new_optimal_fit(),
/// #[cfg(not(feature = "smawk"))]
/// wrap_algorithm: WrapAlgorithm::FirstFit,
/// word_splitter: WordSplitter::HyphenSplitter,
/// }
/// # ;
/// # assert_eq!(actual.width, expected.width);
/// # assert_eq!(actual.line_ending, expected.line_ending);
/// # assert_eq!(actual.initial_indent, expected.initial_indent);
/// # assert_eq!(actual.subsequent_indent, expected.subsequent_indent);
/// # assert_eq!(actual.break_words, expected.break_words);
/// # assert_eq!(actual.word_splitter, expected.word_splitter);
/// ```
///
/// Note that the default word separator and wrap algorithms
/// changes based on the available Cargo features. The best
/// available algorithms are used by default.
pub const fn new(width: usize) -> Self {
Options {
width,
line_ending: LineEnding::LF,
initial_indent: "",
subsequent_indent: "",
break_words: true,
word_separator: WordSeparator::new(),
wrap_algorithm: WrapAlgorithm::new(),
word_splitter: WordSplitter::HyphenSplitter,
}
}
/// Creates a new [`Options`] with `width` set to the current
/// terminal width. If the terminal width cannot be determined
/// (typically because the standard input and output is not
/// connected to a terminal), a width of 80 characters will be
/// used. Other settings use the same defaults as
/// [`Options::new`].
///
/// Equivalent to:
///
/// ```no_run
/// use textwrap::{termwidth, Options};
///
/// let options = Options::new(termwidth());
/// ```
///
/// **Note:** Only available when the `terminal_size` feature is
/// enabled.
#[cfg(feature = "terminal_size")]
pub fn with_termwidth() -> Self {
Self::new(termwidth())
}
/// Change [`self.line_ending`]. This specifies which of the
/// supported line endings should be used to break the lines of the
/// input text.
///
/// # Examples
///
/// ```
/// use textwrap::{refill, LineEnding, Options};
///
/// let options = Options::new(15).line_ending(LineEnding::CRLF);
/// assert_eq!(refill("This is a little example.", options),
/// "This is a\r\nlittle example.");
/// ```
///
/// [`self.line_ending`]: #structfield.line_ending
pub fn line_ending(self, line_ending: LineEnding) -> Self {
Options {
line_ending,
..self
}
}
/// Change [`self.initial_indent`]. The initial indentation is
/// used on the very first line of output.
///
/// # Examples
///
/// Classic paragraph indentation can be achieved by specifying an
/// initial indentation and wrapping each paragraph by itself:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(16).initial_indent(" ");
/// assert_eq!(wrap("This is a little example.", options),
/// vec![" This is a",
/// "little example."]);
/// ```
///
/// [`self.initial_indent`]: #structfield.initial_indent
pub fn initial_indent(self, indent: &'a str) -> Self {
Options {
initial_indent: indent,
..self
}
}
/// Change [`self.subsequent_indent`]. The subsequent indentation
/// is used on lines following the first line of output.
///
/// # Examples
///
/// Combining initial and subsequent indentation lets you format a
/// single paragraph as a bullet list:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(12)
/// .initial_indent("* ")
/// .subsequent_indent(" ");
/// #[cfg(feature = "smawk")]
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["* This is",
/// " a little",
/// " example."]);
///
/// // Without the `smawk` feature, the wrapping is a little different:
/// #[cfg(not(feature = "smawk"))]
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["* This is a",
/// " little",
/// " example."]);
/// ```
///
/// [`self.subsequent_indent`]: #structfield.subsequent_indent
pub fn subsequent_indent(self, indent: &'a str) -> Self {
Options {
subsequent_indent: indent,
..self
}
}
/// Change [`self.break_words`]. This controls if words longer
/// than `self.width` can be broken, or if they will be left
/// sticking out into the right margin.
///
/// # Examples
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(4).break_words(true);
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["This",
/// "is a",
/// "litt",
/// "le",
/// "exam",
/// "ple."]);
/// ```
///
/// [`self.break_words`]: #structfield.break_words
pub fn break_words(self, setting: bool) -> Self {
Options {
break_words: setting,
..self
}
}
/// Change [`self.word_separator`].
///
/// See [`word_separators::WordSeparator`] for details on the choices.
///
/// [`self.word_separator`]: #structfield.word_separator
pub fn word_separator(self, word_separator: WordSeparator) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: word_separator,
wrap_algorithm: self.wrap_algorithm,
word_splitter: self.word_splitter,
}
}
/// Change [`self.wrap_algorithm`].
///
/// See the [`wrap_algorithms::WrapAlgorithm`] trait for details on
/// the choices.
///
/// [`self.wrap_algorithm`]: #structfield.wrap_algorithm
pub fn wrap_algorithm(self, wrap_algorithm: WrapAlgorithm) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: self.word_separator,
wrap_algorithm: wrap_algorithm,
word_splitter: self.word_splitter,
}
}
/// Change [`self.word_splitter`]. The
/// [`word_splitters::WordSplitter`] is used to fit part of a word
/// into the current line when wrapping text.
///
/// # Examples
///
/// ```
/// use textwrap::{Options, WordSplitter};
/// let opt = Options::new(80);
/// assert_eq!(opt.word_splitter, WordSplitter::HyphenSplitter);
/// let opt = opt.word_splitter(WordSplitter::NoHyphenation);
/// assert_eq!(opt.word_splitter, WordSplitter::NoHyphenation);
/// ```
///
/// [`self.word_splitter`]: #structfield.word_splitter
pub fn word_splitter(self, word_splitter: WordSplitter) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: self.word_separator,
wrap_algorithm: self.wrap_algorithm,
word_splitter,
}
}
}
/// Return the current terminal width.
///
/// If the terminal width cannot be determined (typically because the
/// standard output is not connected to a terminal), a default width
/// of 80 characters will be used.
///
/// # Examples
///
/// Create an [`Options`] for wrapping at the current terminal width
/// with a two column margin to the left and the right:
///
/// ```no_run
/// use textwrap::{termwidth, Options};
///
/// let width = termwidth() - 4; // Two columns on each side.
/// let options = Options::new(width)
/// .initial_indent(" ")
/// .subsequent_indent(" ");
/// ```
///
/// **Note:** Only available when the `terminal_size` Cargo feature is
/// enabled.
#[cfg(feature = "terminal_size")]
pub fn termwidth() -> usize {
terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into())
}
/// Fill a line of text at a given width.
///
/// The result is a [`String`], complete with newlines between each
/// line. Use the [`wrap`] function if you need access to the
/// individual lines.
///
/// The easiest way to use this function is to pass an integer for
/// `width_or_options`:
///
/// ```
/// use textwrap::fill;
///
/// assert_eq!(
/// fill("Memory safety without garbage collection.", 15),
/// "Memory safety\nwithout garbage\ncollection."
/// );
/// ```
///
/// If you need to customize the wrapping, you can pass an [`Options`]
/// instead of an `usize`:
///
/// ```
/// use textwrap::{fill, Options};
///
/// let options = Options::new(15)
/// .initial_indent("- ")
/// .subsequent_indent(" ");
/// assert_eq!(
/// fill("Memory safety without garbage collection.", &options),
/// "- Memory safety\n without\n garbage\n collection."
/// );
/// ```
pub fn fill<'a, Opt>(text: &str, width_or_options: Opt) -> String
where
Opt: Into<Options<'a>>,
{
let options = width_or_options.into();
let line_ending_str = options.line_ending.as_str();
// This will avoid reallocation in simple cases (no
// indentation, no hyphenation).
let mut result = String::with_capacity(text.len());
for (i, line) in wrap(text, options).iter().enumerate() {
if i > 0 {
result.push_str(line_ending_str);
}
result.push_str(line);
}
result
}
/// Unpack a paragraph of already-wrapped text.
///
/// This function attempts to recover the original text from a single
/// paragraph of text produced by the [`fill`] function. This means
/// that it turns
///
/// ```text
/// textwrap: a small
/// library for
/// wrapping text.
/// ```
///
/// back into
///
/// ```text
/// textwrap: a small library for wrapping text.
/// ```
///
/// In addition, it will recognize a common prefix and a common line
/// ending among the lines.
///
/// The prefix of the first line is returned in
/// [`Options::initial_indent`] and the prefix (if any) of the the
/// other lines is returned in [`Options::subsequent_indent`].
///
/// Line ending is returned in [`Options::line_ending`]. If line ending
/// can not be confidently detected (mixed or no line endings in the
/// input), [`LineEnding::LF`] will be returned.
///
/// In addition to `' '`, the prefixes can consist of characters used
/// for unordered lists (`'-'`, `'+'`, and `'*'`) and block quotes
/// (`'>'`) in Markdown as well as characters often used for inline
/// comments (`'#'` and `'/'`).
///
/// The text must come from a single wrapped paragraph. This means
/// that there can be no `"\n\n"` within the text.
///
/// # Examples
///
/// ```
/// use textwrap::{LineEnding, unfill};
///
/// let (text, options) = unfill("\
/// * This is an
/// example of
/// a list item.
/// ");
///
/// assert_eq!(text, "This is an example of a list item.\n");
/// assert_eq!(options.initial_indent, "* ");
/// assert_eq!(options.subsequent_indent, " ");
/// assert_eq!(options.line_ending, LineEnding::LF);
/// ```
pub fn unfill(text: &str) -> (String, Options<'_>) {
let line_ending_pat: &[_] = &['\r', '\n'];
let trimmed = text.trim_end_matches(line_ending_pat);
let prefix_chars: &[_] = &[' ', '-', '+', '*', '>', '#', '/'];
let mut options = Options::new(0);
for (idx, line) in trimmed.lines().enumerate() {
options.width = std::cmp::max(options.width, core::display_width(line));
let without_prefix = line.trim_start_matches(prefix_chars);
let prefix = &line[..line.len() - without_prefix.len()];
if idx == 0 {
options.initial_indent = prefix;
} else if idx == 1 {
options.subsequent_indent = prefix;
} else if idx > 1 {
for ((idx, x), y) in prefix.char_indices().zip(options.subsequent_indent.chars()) {
if x != y {
options.subsequent_indent = &prefix[..idx];
break;
}
}
if prefix.len() < options.subsequent_indent.len() {
options.subsequent_indent = prefix;
}
}
}
let mut unfilled = String::with_capacity(text.len());
let mut detected_line_ending = None;
for (line, ending) in line_ending::NonEmptyLines(text) {
if unfilled.is_empty() {
unfilled.push_str(&line[options.initial_indent.len()..]);
} else {
unfilled.push(' ');
unfilled.push_str(&line[options.subsequent_indent.len()..]);
}
match (detected_line_ending, ending) {
(None, Some(_)) => detected_line_ending = ending,
(Some(LineEnding::CRLF), Some(LineEnding::LF)) => detected_line_ending = ending,
_ => (),
}
}
unfilled.push_str(&text[trimmed.len()..]);
options.line_ending = detected_line_ending.unwrap_or(LineEnding::LF);
(unfilled, options)
}
/// Refill a paragraph of wrapped text with a new width.
///
/// This function will first use the [`unfill`] function to remove
/// newlines from the text. Afterwards the text is filled again using
/// the [`fill`] function.
///
/// The `new_width_or_options` argument specify the new width and can
/// specify other options as well — except for
/// [`Options::initial_indent`] and [`Options::subsequent_indent`],
/// which are deduced from `filled_text`.
///
/// # Examples
///
/// ```
/// use textwrap::refill;
///
/// // Some loosely wrapped text. The "> " prefix is recognized automatically.
/// let text = "\
/// > Memory
/// > safety without garbage
/// > collection.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// > Memory safety
/// > without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 40), "\
/// > Memory safety without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 60), "\
/// > Memory safety without garbage collection.
/// ");
/// ```
///
/// You can also reshape bullet points:
///
/// ```
/// use textwrap::refill;
///
/// let text = "\
/// - This is my
/// list item.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// - This is my list
/// item.
/// ");
/// ```
pub fn refill<'a, Opt>(filled_text: &str, new_width_or_options: Opt) -> String
where
Opt: Into<Options<'a>>,
{
let mut new_options = new_width_or_options.into();
let trimmed = filled_text.trim_end_matches(new_options.line_ending.as_str());
let (text, options) = unfill(trimmed);
new_options.initial_indent = options.initial_indent;
new_options.subsequent_indent = options.subsequent_indent;
let mut refilled = fill(&text, new_options);
refilled.push_str(&filled_text[trimmed.len()..]);
refilled
}
/// Wrap a line of text at a given width.
///
/// The result is a vector of lines, each line is of type [`Cow<'_,
/// str>`](Cow), which means that the line will borrow from the input
/// `&str` if possible. The lines do not have trailing whitespace,
/// including a final `'\n'`. Please use the [`fill`] function if you
/// need a [`String`] instead.
///
/// The easiest way to use this function is to pass an integer for
/// `width_or_options`:
///
/// ```
/// use textwrap::wrap;
///
/// let lines = wrap("Memory safety without garbage collection.", 15);
/// assert_eq!(lines, &[
/// "Memory safety",
/// "without garbage",
/// "collection.",
/// ]);
/// ```
///
/// If you need to customize the wrapping, you can pass an [`Options`]
/// instead of an `usize`:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(15)
/// .initial_indent("- ")
/// .subsequent_indent(" ");
/// let lines = wrap("Memory safety without garbage collection.", &options);
/// assert_eq!(lines, &[
/// "- Memory safety",
/// " without",
/// " garbage",
/// " collection.",
/// ]);
/// ```
///
/// # Optimal-Fit Wrapping
///
/// By default, `wrap` will try to ensure an even right margin by
/// finding breaks which avoid short lines. We call this an
/// “optimal-fit algorithm” since the line breaks are computed by
/// considering all possible line breaks. The alternative is a
/// “first-fit algorithm” which simply accumulates words until they no
/// longer fit on the line.
///
/// As an example, using the first-fit algorithm to wrap the famous
/// Hamlet quote “To be, or not to be: that is the question” in a
/// narrow column with room for only 10 characters looks like this:
///
/// ```
/// # use textwrap::{WrapAlgorithm::FirstFit, Options, wrap};
/// #
/// # let lines = wrap("To be, or not to be: that is the question",
/// # Options::new(10).wrap_algorithm(FirstFit));
/// # assert_eq!(lines.join("\n") + "\n", "\
/// To be, or
/// not to be:
/// that is
/// the
/// question
/// # ");
/// ```
///
/// Notice how the second to last line is quite narrow because
/// “question” was too large to fit? The greedy first-fit algorithm
/// doesn’t look ahead, so it has no other option than to put
/// “question” onto its own line.
///
/// With the optimal-fit wrapping algorithm, the previous lines are
/// shortened slightly in order to make the word “is” go into the
/// second last line:
///
/// ```
/// # #[cfg(feature = "smawk")] {
/// # use textwrap::{Options, WrapAlgorithm, wrap};
/// #
/// # let lines = wrap(
/// # "To be, or not to be: that is the question",
/// # Options::new(10).wrap_algorithm(WrapAlgorithm::new_optimal_fit())
/// # );
/// # assert_eq!(lines.join("\n") + "\n", "\
/// To be,
/// or not to
/// be: that
/// is the
/// question
/// # "); }
/// ```
///
/// Please see [`WrapAlgorithm`] for details on the choices.
///
/// # Examples
///
/// The returned iterator yields lines of type `Cow<'_, str>`. If
/// possible, the wrapped lines will borrow from the input string. As
/// an example, a hanging indentation, the first line can borrow from
/// the input, but the subsequent lines become owned strings:
///
/// ```
/// use std::borrow::Cow::{Borrowed, Owned};
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(15).subsequent_indent("....");
/// let lines = wrap("Wrapping text all day long.", &options);
/// let annotated = lines
/// .iter()
/// .map(|line| match line {
/// Borrowed(text) => format!("[Borrowed] {}", text),
/// Owned(text) => format!("[Owned] {}", text),
/// })
/// .collect::<Vec<_>>();
/// assert_eq!(
/// annotated,
/// &[
/// "[Borrowed] Wrapping text",
/// "[Owned] ....all day",
/// "[Owned] ....long.",
/// ]
/// );
/// ```
///
/// ## Leading and Trailing Whitespace
///
/// As a rule, leading whitespace (indentation) is preserved and
/// trailing whitespace is discarded.
///
/// In more details, when wrapping words into lines, words are found
/// by splitting the input text on space characters. One or more
/// spaces (shown here as “␣”) are attached to the end of each word:
///
/// ```text
/// "Foo␣␣␣bar␣baz" -> ["Foo␣␣␣", "bar␣", "baz"]
/// ```
///
/// These words are then put into lines. The interword whitespace is
/// preserved, unless the lines are wrapped so that the `"Foo␣␣␣"`
/// word falls at the end of a line:
///
/// ```
/// use textwrap::wrap;
///
/// assert_eq!(wrap("Foo bar baz", 10), vec!["Foo bar", "baz"]);
/// assert_eq!(wrap("Foo bar baz", 8), vec!["Foo", "bar baz"]);
/// ```
///
/// Notice how the trailing whitespace is removed in both case: in the
/// first example, `"bar␣"` becomes `"bar"` and in the second case
/// `"Foo␣␣␣"` becomes `"Foo"`.
///
/// Leading whitespace is preserved when the following word fits on
/// the first line. To understand this, consider how words are found
/// in a text with leading spaces:
///
/// ```text
/// "␣␣foo␣bar" -> ["␣␣", "foo␣", "bar"]
/// ```
///
/// When put into lines, the indentation is preserved if `"foo"` fits
/// on the first line, otherwise you end up with an empty line:
///
/// ```
/// use textwrap::wrap;
///
/// assert_eq!(wrap(" foo bar", 8), vec![" foo", "bar"]);
/// assert_eq!(wrap(" foo bar", 4), vec!["", "foo", "bar"]);
/// ```
pub fn wrap<'a, Opt>(text: &str, width_or_options: Opt) -> Vec<Cow<'_, str>>
where
Opt: Into<Options<'a>>,
{
let options: Options = width_or_options.into();
let line_ending_str = options.line_ending.as_str();
let initial_width = options
.width
.saturating_sub(core::display_width(options.initial_indent));
let subsequent_width = options
.width
.saturating_sub(core::display_width(options.subsequent_indent));
let mut lines = Vec::new();
for line in text.split(line_ending_str) {
let words = options.word_separator.find_words(line);
let split_words = word_splitters::split_words(words, &options.word_splitter);
let broken_words = if options.break_words {
let mut broken_words = core::break_words(split_words, subsequent_width);
if !options.initial_indent.is_empty() {
// Without this, the first word will always go into
// the first line. However, since we break words based
// on the _second_ line width, it can be wrong to
// unconditionally put the first word onto the first
// line. An empty zero-width word fixed this.
broken_words.insert(0, core::Word::from(""));
}
broken_words
} else {
split_words.collect::<Vec<_>>()
};
let line_widths = [initial_width, subsequent_width];
let wrapped_words = options.wrap_algorithm.wrap(&broken_words, &line_widths);
let mut idx = 0;
for words in wrapped_words {
let last_word = match words.last() {
None => {
lines.push(Cow::from(""));
continue;
}
Some(word) => word,
};
// We assume here that all words are contiguous in `line`.
// That is, the sum of their lengths should add up to the
// length of `line`.
let len = words
.iter()
.map(|word| word.len() + word.whitespace.len())
.sum::<usize>()
- last_word.whitespace.len();
// The result is owned if we have indentation, otherwise
// we can simply borrow an empty string.
let mut result = if lines.is_empty() && !options.initial_indent.is_empty() {
Cow::Owned(options.initial_indent.to_owned())
} else if !lines.is_empty() && !options.subsequent_indent.is_empty() {
Cow::Owned(options.subsequent_indent.to_owned())
} else {
// We can use an empty string here since string
// concatenation for `Cow` preserves a borrowed value
// when either side is empty.
Cow::from("")
};
result += &line[idx..idx + len];
if !last_word.penalty.is_empty() {
result.to_mut().push_str(last_word.penalty);
}
lines.push(result);
// Advance by the length of `result`, plus the length of
// `last_word.whitespace` -- even if we had a penalty, we
// need to skip over the whitespace.
idx += len + last_word.whitespace.len();
}
}
lines
}
/// Wrap text into columns with a given total width.
///
/// The `left_gap`, `middle_gap` and `right_gap` arguments specify the
/// strings to insert before, between, and after the columns. The
/// total width of all columns and all gaps is specified using the
/// `total_width_or_options` argument. This argument can simply be an
/// integer if you want to use default settings when wrapping, or it
/// can be a [`Options`] value if you want to customize the wrapping.
///
/// If the columns are narrow, it is recommended to set
/// [`Options::break_words`] to `true` to prevent words from
/// protruding into the margins.
///
/// The per-column width is computed like this:
///
/// ```
/// # let (left_gap, middle_gap, right_gap) = ("", "", "");
/// # let columns = 2;
/// # let options = textwrap::Options::new(80);
/// let inner_width = options.width
/// - textwrap::core::display_width(left_gap)
/// - textwrap::core::display_width(right_gap)
/// - textwrap::core::display_width(middle_gap) * (columns - 1);
/// let column_width = inner_width / columns;
/// ```
///
/// The `text` is wrapped using [`wrap`] and the given `options`
/// argument, but the width is overwritten to the computed
/// `column_width`.
///
/// # Panics
///
/// Panics if `columns` is zero.
///
/// # Examples
///
/// ```
/// use textwrap::wrap_columns;
///
/// let text = "\
/// This is an example text, which is wrapped into three columns. \
/// Notice how the final column can be shorter than the others.";
///
/// #[cfg(feature = "smawk")]
/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
/// vec!["| This is | into three | column can be |",
/// "| an example | columns. | shorter than |",
/// "| text, which | Notice how | the others. |",
/// "| is wrapped | the final | |"]);
///
/// // Without the `smawk` feature, the middle column is a little more uneven:
/// #[cfg(not(feature = "smawk"))]
/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
/// vec!["| This is an | three | column can be |",
/// "| example text, | columns. | shorter than |",
/// "| which is | Notice how | the others. |",
/// "| wrapped into | the final | |"]);
pub fn wrap_columns<'a, Opt>(
text: &str,
columns: usize,
total_width_or_options: Opt,
left_gap: &str,
middle_gap: &str,
right_gap: &str,
) -> Vec<String>
where
Opt: Into<Options<'a>>,
{
assert!(columns > 0);
let mut options: Options = total_width_or_options.into();
let inner_width = options
.width
.saturating_sub(core::display_width(left_gap))
.saturating_sub(core::display_width(right_gap))
.saturating_sub(core::display_width(middle_gap) * (columns - 1));
let column_width = std::cmp::max(inner_width / columns, 1);
options.width = column_width;
let last_column_padding = " ".repeat(inner_width % column_width);
let wrapped_lines = wrap(text, options);
let lines_per_column =
wrapped_lines.len() / columns + usize::from(wrapped_lines.len() % columns > 0);
let mut lines = Vec::new();
for line_no in 0..lines_per_column {
let mut line = String::from(left_gap);
for column_no in 0..columns {
match wrapped_lines.get(line_no + column_no * lines_per_column) {
Some(column_line) => {
line.push_str(column_line);
line.push_str(&" ".repeat(column_width - core::display_width(column_line)));
}
None => {
line.push_str(&" ".repeat(column_width));
}
}
if column_no == columns - 1 {
line.push_str(&last_column_padding);
} else {
line.push_str(middle_gap);
}
}
line.push_str(right_gap);
lines.push(line);
}
lines
}
/// Fill `text` in-place without reallocating the input string.
///
/// This function works by modifying the input string: some `' '`
/// characters will be replaced by `'\n'` characters. The rest of the
/// text remains untouched.
///
/// Since we can only replace existing whitespace in the input with
/// `'\n'`, we cannot do hyphenation nor can we split words longer
/// than the line width. We also need to use `AsciiSpace` as the word
/// separator since we need `' '` characters between words in order to
/// replace some of them with a `'\n'`. Indentation is also ruled out.
/// In other words, `fill_inplace(width)` behaves as if you had called
/// [`fill`] with these options:
///
/// ```
/// # use textwrap::{core, LineEnding, Options, WordSplitter, WordSeparator, WrapAlgorithm};
/// # let width = 80;
/// Options {
/// width: width,
/// line_ending: LineEnding::LF,
/// initial_indent: "",
/// subsequent_indent: "",
/// break_words: false,
/// word_separator: WordSeparator::AsciiSpace,
/// wrap_algorithm: WrapAlgorithm::FirstFit,
/// word_splitter: WordSplitter::NoHyphenation,
/// };
/// ```
///
/// The wrap algorithm is [`WrapAlgorithm::FirstFit`] since this
/// is the fastest algorithm — and the main reason to use
/// `fill_inplace` is to get the string broken into newlines as fast
/// as possible.
///
/// A last difference is that (unlike [`fill`]) `fill_inplace` can
/// leave trailing whitespace on lines. This is because we wrap by
/// inserting a `'\n'` at the final whitespace in the input string:
///
/// ```
/// let mut text = String::from("Hello World!");
/// textwrap::fill_inplace(&mut text, 10);
/// assert_eq!(text, "Hello \nWorld!");
/// ```
///
/// If we didn't do this, the word `World!` would end up being
/// indented. You can avoid this if you make sure that your input text
/// has no double spaces.
///
/// # Performance
///
/// In benchmarks, `fill_inplace` is about twice as fast as [`fill`].
/// Please see the [`linear`
/// benchmark](https://github.com/mgeisler/textwrap/blob/master/benches/linear.rs)
/// for details.
pub fn fill_inplace(text: &mut String, width: usize) {
let mut indices = Vec::new();
let mut offset = 0;
for line in text.split('\n') {
let words = WordSeparator::AsciiSpace
.find_words(line)
.collect::<Vec<_>>();
let wrapped_words = wrap_algorithms::wrap_first_fit(&words, &[width as f64]);
let mut line_offset = offset;
for words in &wrapped_words[..wrapped_words.len() - 1] {
let line_len = words
.iter()
.map(|word| word.len() + word.whitespace.len())
.sum::<usize>();
line_offset += line_len;
// We've advanced past all ' ' characters -- want to move
// one ' ' backwards and insert our '\n' there.
indices.push(line_offset - 1);
}
// Advance past entire line, plus the '\n' which was removed
// by the split call above.
offset += line.len() + 1;
}
let mut bytes = std::mem::take(text).into_bytes();
for idx in indices {
bytes[idx] = b'\n';
}
*text = String::from_utf8(bytes).unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
#[test]
fn options_agree_with_usize() {
let opt_usize = Options::from(42_usize);
let opt_options = Options::new(42);
assert_eq!(opt_usize.width, opt_options.width);
assert_eq!(opt_usize.initial_indent, opt_options.initial_indent);
assert_eq!(opt_usize.subsequent_indent, opt_options.subsequent_indent);
assert_eq!(opt_usize.break_words, opt_options.break_words);
assert_eq!(
opt_usize.word_splitter.split_points("hello-world"),
opt_options.word_splitter.split_points("hello-world")
);
}
#[test]
fn no_wrap() {
assert_eq!(wrap("foo", 10), vec!["foo"]);
}
#[test]
fn wrap_simple() {
assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]);
}
#[test]
fn to_be_or_not() {
assert_eq!(
wrap(
"To be, or not to be, that is the question.",
Options::new(10).wrap_algorithm(WrapAlgorithm::FirstFit)
),
vec!["To be, or", "not to be,", "that is", "the", "question."]
);
}
#[test]
fn multiple_words_on_first_line() {
assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]);
}
#[test]
fn long_word() {
assert_eq!(wrap("foo", 0), vec!["f", "o", "o"]);
}
#[test]
fn long_words() {
assert_eq!(wrap("foo bar", 0), vec!["f", "o", "o", "b", "a", "r"]);
}
#[test]
fn max_width() {
assert_eq!(wrap("foo bar", usize::MAX), vec!["foo bar"]);
let text = "Hello there! This is some English text. \
It should not be wrapped given the extents below.";
assert_eq!(wrap(text, usize::MAX), vec![text]);
}
#[test]
fn leading_whitespace() {
assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]);
}
#[test]
fn leading_whitespace_empty_first_line() {
// If there is no space for the first word, the first line
// will be empty. This is because the string is split into
// words like [" ", "foobar ", "baz"], which puts "foobar " on
// the second line. We never output trailing whitespace
assert_eq!(wrap(" foobar baz", 6), vec!["", "foobar", "baz"]);
}
#[test]
fn trailing_whitespace() {
// Whitespace is only significant inside a line. After a line
// gets too long and is broken, the first word starts in
// column zero and is not indented.
assert_eq!(wrap("foo bar baz ", 5), vec!["foo", "bar", "baz"]);
}
#[test]
fn issue_99() {
// We did not reset the in_whitespace flag correctly and did
// not handle single-character words after a line break.
assert_eq!(
wrap("aaabbbccc x yyyzzzwww", 9),
vec!["aaabbbccc", "x", "yyyzzzwww"]
);
}
#[test]
fn issue_129() {
// The dash is an em-dash which takes up four bytes. We used
// to panic since we tried to index into the character.
let options = Options::new(1).word_separator(WordSeparator::AsciiSpace);
assert_eq!(wrap("x – x", options), vec!["x", "–", "x"]);
}
#[test]
fn wide_character_handling() {
assert_eq!(wrap("Hello, World!", 15), vec!["Hello, World!"]);
assert_eq!(
wrap(
"Hello, World!",
Options::new(15).word_separator(WordSeparator::AsciiSpace)
),
vec!["Hello,", "World!"]
);
// Wide characters are allowed to break if the
// unicode-linebreak feature is enabled.
#[cfg(feature = "unicode-linebreak")]
assert_eq!(
wrap(
"Hello, World!",
Options::new(15).word_separator(WordSeparator::UnicodeBreakProperties),
),
vec!["Hello, W", "orld!"]
);
}
#[test]
fn empty_line_is_indented() {
// Previously, indentation was not applied to empty lines.
// However, this is somewhat inconsistent and undesirable if
// the indentation is something like a border ("| ") which you
// want to apply to all lines, empty or not.
let options = Options::new(10).initial_indent("!!!");
assert_eq!(fill("", &options), "!!!");
}
#[test]
fn indent_single_line() {
let options = Options::new(10).initial_indent(">>>"); // No trailing space
assert_eq!(fill("foo", &options), ">>>foo");
}
#[test]
fn indent_first_emoji() {
let options = Options::new(10).initial_indent("👉👉");
assert_eq!(
wrap("x x x x x x x x x x x x x", &options),
vec!["👉👉x x x", "x x x x x", "x x x x x"]
);
}
#[test]
fn indent_multiple_lines() {
let options = Options::new(6).initial_indent("* ").subsequent_indent(" ");
assert_eq!(
wrap("foo bar baz", &options),
vec!["* foo", " bar", " baz"]
);
}
#[test]
fn indent_break_words() {
let options = Options::new(5).initial_indent("* ").subsequent_indent(" ");
assert_eq!(wrap("foobarbaz", &options), vec!["* foo", " bar", " baz"]);
}
#[test]
fn initial_indent_break_words() {
// This is a corner-case showing how the long word is broken
// according to the width of the subsequent lines. The first
// fragment of the word no longer fits on the first line,
// which ends up being pure indentation.
let options = Options::new(5).initial_indent("-->");
assert_eq!(wrap("foobarbaz", &options), vec!["-->", "fooba", "rbaz"]);
}
#[test]
fn hyphens() {
assert_eq!(wrap("foo-bar", 5), vec!["foo-", "bar"]);
}
#[test]
fn trailing_hyphen() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foobar-", &options), vec!["foobar-"]);
}
#[test]
fn multiple_hyphens() {
assert_eq!(wrap("foo-bar-baz", 5), vec!["foo-", "bar-", "baz"]);
}
#[test]
fn hyphens_flag() {
let options = Options::new(5).break_words(false);
assert_eq!(
wrap("The --foo-bar flag.", &options),
vec!["The", "--foo-", "bar", "flag."]
);
}
#[test]
fn repeated_hyphens() {
let options = Options::new(4).break_words(false);
assert_eq!(wrap("foo--bar", &options), vec!["foo--bar"]);
}
#[test]
fn hyphens_alphanumeric() {
assert_eq!(wrap("Na2-CH4", 5), vec!["Na2-", "CH4"]);
}
#[test]
fn hyphens_non_alphanumeric() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foo(-)bar", &options), vec!["foo(-)bar"]);
}
#[test]
fn multiple_splits() {
assert_eq!(wrap("foo-bar-baz", 9), vec!["foo-bar-", "baz"]);
}
#[test]
fn forced_split() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foobar-baz", &options), vec!["foobar-", "baz"]);
}
#[test]
fn multiple_unbroken_words_issue_193() {
let options = Options::new(3).break_words(false);
assert_eq!(
wrap("small large tiny", &options),
vec!["small", "large", "tiny"]
);
assert_eq!(
wrap("small large tiny", &options),
vec!["small", "large", "tiny"]
);
}
#[test]
fn very_narrow_lines_issue_193() {
let options = Options::new(1).break_words(false);
assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]);
assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]);
}
#[test]
fn simple_hyphens() {
let options = Options::new(8).word_splitter(WordSplitter::HyphenSplitter);
assert_eq!(wrap("foo bar-baz", &options), vec!["foo bar-", "baz"]);
}
#[test]
fn no_hyphenation() {
let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation);
assert_eq!(wrap("foo bar-baz", &options), vec!["foo", "bar-baz"]);
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_double_hyphenation() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10);
assert_eq!(
wrap("Internationalization", &options),
vec!["Internatio", "nalization"]
);
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("Internationalization", &options),
vec!["Interna-", "tionaliza-", "tion"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_issue_158() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10);
assert_eq!(
wrap("participation is the key to success", &options),
vec!["participat", "ion is", "the key to", "success"]
);
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("participation is the key to success", &options),
vec!["partici-", "pation is", "the key to", "success"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn split_len_hyphenation() {
// Test that hyphenation takes the width of the whitespace
// into account.
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(15).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("garbage collection", &options),
vec!["garbage col-", "lection"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn borrowed_lines() {
// Lines that end with an extra hyphen are owned, the final
// line is borrowed.
use std::borrow::Cow::{Borrowed, Owned};
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
let lines = wrap("Internationalization", &options);
assert_eq!(lines, vec!["Interna-", "tionaliza-", "tion"]);
if let Borrowed(s) = lines[0] {
assert!(false, "should not have been borrowed: {:?}", s);
}
if let Borrowed(s) = lines[1] {
assert!(false, "should not have been borrowed: {:?}", s);
}
if let Owned(ref s) = lines[2] {
assert!(false, "should not have been owned: {:?}", s);
}
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_with_hyphen() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(8).break_words(false);
assert_eq!(
wrap("over-caffinated", &options),
vec!["over-", "caffinated"]
);
let options = options.word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("over-caffinated", &options),
vec!["over-", "caffi-", "nated"]
);
}
#[test]
fn break_words() {
assert_eq!(wrap("foobarbaz", 3), vec!["foo", "bar", "baz"]);
}
#[test]
fn break_words_wide_characters() {
// Even the poor man's version of `ch_width` counts these
// characters as wide.
let options = Options::new(5).word_separator(WordSeparator::AsciiSpace);
assert_eq!(wrap("Hello", options), vec!["He", "ll", "o"]);
}
#[test]
fn break_words_zero_width() {
assert_eq!(wrap("foobar", 0), vec!["f", "o", "o", "b", "a", "r"]);
}
#[test]
fn break_long_first_word() {
assert_eq!(wrap("testx y", 4), vec!["test", "x y"]);
}
#[test]
fn break_words_line_breaks() {
assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl");
assert_eq!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl");
}
#[test]
fn break_words_empty_lines() {
assert_eq!(
fill("foo\nbar", &Options::new(2).break_words(false)),
"foo\nbar"
);
}
#[test]
fn preserve_line_breaks() {
assert_eq!(fill("", 80), "");
assert_eq!(fill("\n", 80), "\n");
assert_eq!(fill("\n\n\n", 80), "\n\n\n");
assert_eq!(fill("test\n", 80), "test\n");
assert_eq!(fill("test\n\na\n\n", 80), "test\n\na\n\n");
assert_eq!(
fill(
"1 3 5 7\n1 3 5 7",
Options::new(7).wrap_algorithm(WrapAlgorithm::FirstFit)
),
"1 3 5 7\n1 3 5 7"
);
assert_eq!(
fill(
"1 3 5 7\n1 3 5 7",
Options::new(5).wrap_algorithm(WrapAlgorithm::FirstFit)
),
"1 3 5\n7\n1 3 5\n7"
);
}
#[test]
fn preserve_line_breaks_with_whitespace() {
assert_eq!(fill(" ", 80), "");
assert_eq!(fill(" \n ", 80), "\n");
assert_eq!(fill(" \n \n \n ", 80), "\n\n\n");
}
#[test]
fn non_breaking_space() {
let options = Options::new(5).break_words(false);
assert_eq!(fill("foo bar baz", &options), "foo bar baz");
}
#[test]
fn non_breaking_hyphen() {
let options = Options::new(5).break_words(false);
assert_eq!(fill("foo‑bar‑baz", &options), "foo‑bar‑baz");
}
#[test]
fn fill_simple() {
assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz");
}
#[test]
fn fill_colored_text() {
// The words are much longer than 6 bytes, but they remain
// intact after filling the text.
let green_hello = "\u{1b}[0m\u{1b}[32mHello\u{1b}[0m";
let blue_world = "\u{1b}[0m\u{1b}[34mWorld!\u{1b}[0m";
assert_eq!(
fill(&(String::from(green_hello) + " " + &blue_world), 6),
String::from(green_hello) + "\n" + &blue_world
);
}
#[test]
fn fill_unicode_boundary() {
// https://github.com/mgeisler/textwrap/issues/390
fill("\u{1b}!Ͽ", 10);
}
#[test]
fn fill_inplace_empty() {
let mut text = String::from("");
fill_inplace(&mut text, 80);
assert_eq!(text, "");
}
#[test]
fn fill_inplace_simple() {
let mut text = String::from("foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\nbaz");
}
#[test]
fn fill_inplace_multiple_lines() {
let mut text = String::from("Some text to wrap over multiple lines");
fill_inplace(&mut text, 12);
assert_eq!(text, "Some text to\nwrap over\nmultiple\nlines");
}
#[test]
fn fill_inplace_long_word() {
let mut text = String::from("Internationalization is hard");
fill_inplace(&mut text, 10);
assert_eq!(text, "Internationalization\nis hard");
}
#[test]
fn fill_inplace_no_hyphen_splitting() {
let mut text = String::from("A well-chosen example");
fill_inplace(&mut text, 10);
assert_eq!(text, "A\nwell-chosen\nexample");
}
#[test]
fn fill_inplace_newlines() {
let mut text = String::from("foo bar\n\nbaz\n\n\n");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\n\nbaz\n\n\n");
}
#[test]
fn fill_inplace_newlines_reset_line_width() {
let mut text = String::from("1 3 5\n1 3 5 7 9\n1 3 5 7 9 1 3");
fill_inplace(&mut text, 10);
assert_eq!(text, "1 3 5\n1 3 5 7 9\n1 3 5 7 9\n1 3");
}
#[test]
fn fill_inplace_leading_whitespace() {
let mut text = String::from(" foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, " foo bar\nbaz");
}
#[test]
fn fill_inplace_trailing_whitespace() {
let mut text = String::from("foo bar baz ");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\nbaz ");
}
#[test]
fn fill_inplace_interior_whitespace() {
// To avoid an unwanted indentation of "baz", it is important
// to replace the final ' ' with '\n'.
let mut text = String::from("foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar \nbaz");
}
#[test]
fn unfill_simple() {
let (text, options) = unfill("foo\nbar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_no_new_line() {
let (text, options) = unfill("foo bar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 7);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_simple_crlf() {
let (text, options) = unfill("foo\r\nbar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::CRLF);
}
/// If mixed new line sequence is encountered, we want to fallback to `\n`
/// 1. it is the default
/// 2. it still matches both `\n` and `\r\n` unlike `\r\n` which will not match `\n`
#[test]
fn unfill_mixed_new_lines() {
let (text, options) = unfill("foo\r\nbar\nbaz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_trailing_newlines() {
let (text, options) = unfill("foo\nbar\n\n\n");
assert_eq!(text, "foo bar\n\n\n");
assert_eq!(options.width, 3);
}
#[test]
fn unfill_mixed_trailing_newlines() {
let (text, options) = unfill("foo\r\nbar\n\r\n\n");
assert_eq!(text, "foo bar\n\r\n\n");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_trailing_crlf() {
let (text, options) = unfill("foo bar\r\n");
assert_eq!(text, "foo bar\r\n");
assert_eq!(options.width, 7);
assert_eq!(options.line_ending, LineEnding::CRLF);
}
#[test]
fn unfill_initial_indent() {
let (text, options) = unfill(" foo\nbar\nbaz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, " ");
}
#[test]
fn unfill_differing_indents() {
let (text, options) = unfill(" foo\n bar\n baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 7);
assert_eq!(options.initial_indent, " ");
assert_eq!(options.subsequent_indent, " ");
}
#[test]
fn unfill_list_item() {
let (text, options) = unfill("* foo\n bar\n baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, "* ");
assert_eq!(options.subsequent_indent, " ");
}
#[test]
fn unfill_multiple_char_prefix() {
let (text, options) = unfill(" // foo bar\n // baz\n // quux");
assert_eq!(text, "foo bar baz quux");
assert_eq!(options.width, 14);
assert_eq!(options.initial_indent, " // ");
assert_eq!(options.subsequent_indent, " // ");
}
#[test]
fn unfill_block_quote() {
let (text, options) = unfill("> foo\n> bar\n> baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, "> ");
assert_eq!(options.subsequent_indent, "> ");
}
#[test]
fn unfill_whitespace() {
assert_eq!(unfill("foo bar").0, "foo bar");
}
#[test]
fn refill_convert_crlf() {
assert_eq!(
refill("foo\nbar\n", Options::new(5).line_ending(LineEnding::CRLF)),
"foo\r\nbar\n",
);
}
#[test]
fn wrap_columns_empty_text() {
assert_eq!(wrap_columns("", 1, 10, "| ", "", " |"), vec!["| |"]);
}
#[test]
fn wrap_columns_single_column() {
assert_eq!(
wrap_columns("Foo", 3, 30, "| ", " | ", " |"),
vec!["| Foo | | |"]
);
}
#[test]
fn wrap_columns_uneven_columns() {
// The gaps take up a total of 5 columns, so the columns are
// (21 - 5)/4 = 4 columns wide:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 21, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux|"]
);
// As the total width increases, the last column absorbs the
// excess width:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 24, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux |"]
);
// Finally, when the width is 25, the columns can be resized
// to a width of (25 - 5)/4 = 5 columns:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 25, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux |"]
);
}
#[test]
#[cfg(feature = "unicode-width")]
fn wrap_columns_with_emojis() {
assert_eq!(
wrap_columns(
"Words and a few emojis 😍 wrapped in ⓶ columns",
2,
30,
"✨ ",
" ⚽ ",
" 👀"
),
vec![
"✨ Words ⚽ wrapped in 👀",
"✨ and a few ⚽ ⓶ columns 👀",
"✨ emojis 😍 ⚽ 👀"
]
);
}
#[test]
fn wrap_columns_big_gaps() {
// The column width shrinks to 1 because the gaps take up all
// the space.
assert_eq!(
wrap_columns("xyz", 2, 10, "----> ", " !!! ", " <----"),
vec![
"----> x !!! z <----", //
"----> y !!! <----"
]
);
}
#[test]
#[should_panic]
fn wrap_columns_panic_with_zero_columns() {
wrap_columns("", 0, 10, "", "", "");
}
}
Fix crash in `refill` when the first line consists of prefix chars
The crash is actually in `unfill`. After processing the first line, we
would erroneously use the `options.initial_indent` to index into the
second line. This lead to a panic when the second line is shorter than
the first line.
//! The textwrap library provides functions for word wrapping and
//! indenting text.
//!
//! # Wrapping Text
//!
//! Wrapping text can be very useful in command-line programs where
//! you want to format dynamic output nicely so it looks good in a
//! terminal. A quick example:
//!
//! ```
//! # #[cfg(feature = "smawk")] {
//! let text = "textwrap: a small library for wrapping text.";
//! assert_eq!(textwrap::wrap(text, 18),
//! vec!["textwrap: a",
//! "small library for",
//! "wrapping text."]);
//! # }
//! ```
//!
//! The [`wrap`] function returns the individual lines, use [`fill`]
//! is you want the lines joined with `'\n'` to form a `String`.
//!
//! If you enable the `hyphenation` Cargo feature, you can get
//! automatic hyphenation for a number of languages:
//!
//! ```
//! #[cfg(feature = "hyphenation")] {
//! use hyphenation::{Language, Load, Standard};
//! use textwrap::{wrap, Options, WordSplitter};
//!
//! let text = "textwrap: a small library for wrapping text.";
//! let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
//! let options = Options::new(18).word_splitter(WordSplitter::Hyphenation(dictionary));
//! assert_eq!(wrap(text, &options),
//! vec!["textwrap: a small",
//! "library for wrap-",
//! "ping text."]);
//! }
//! ```
//!
//! See also the [`unfill`] and [`refill`] functions which allow you to
//! manipulate already wrapped text.
//!
//! ## Wrapping Strings at Compile Time
//!
//! If your strings are known at compile time, please take a look at
//! the procedural macros from the [textwrap-macros] crate.
//!
//! ## Displayed Width vs Byte Size
//!
//! To word wrap text, one must know the width of each word so one can
//! know when to break lines. This library will by default measure the
//! width of text using the _displayed width_, not the size in bytes.
//! The `unicode-width` Cargo feature controls this.
//!
//! This is important for non-ASCII text. ASCII characters such as `a`
//! and `!` are simple and take up one column each. This means that
//! the displayed width is equal to the string length in bytes.
//! However, non-ASCII characters and symbols take up more than one
//! byte when UTF-8 encoded: `é` is `0xc3 0xa9` (two bytes) and `⚙` is
//! `0xe2 0x9a 0x99` (three bytes) in UTF-8, respectively.
//!
//! This is why we take care to use the displayed width instead of the
//! byte count when computing line lengths. All functions in this
//! library handle Unicode characters like this when the
//! `unicode-width` Cargo feature is enabled (it is enabled by
//! default).
//!
//! # Indentation and Dedentation
//!
//! The textwrap library also offers functions for adding a prefix to
//! every line of a string and to remove leading whitespace. As an
//! example, the [`indent`] function allows you to turn lines of text
//! into a bullet list:
//!
//! ```
//! let before = "\
//! foo
//! bar
//! baz
//! ";
//! let after = "\
//! * foo
//! * bar
//! * baz
//! ";
//! assert_eq!(textwrap::indent(before, "* "), after);
//! ```
//!
//! Removing leading whitespace is done with [`dedent`]:
//!
//! ```
//! let before = "
//! Some
//! indented
//! text
//! ";
//! let after = "
//! Some
//! indented
//! text
//! ";
//! assert_eq!(textwrap::dedent(before), after);
//! ```
//!
//! # Cargo Features
//!
//! The textwrap library can be slimmed down as needed via a number of
//! Cargo features. This means you only pay for the features you
//! actually use.
//!
//! The full dependency graph, where dashed lines indicate optional
//! dependencies, is shown below:
//!
//! <img src="https://raw.githubusercontent.com/mgeisler/textwrap/master/images/textwrap-0.15.0.svg">
//!
//! ## Default Features
//!
//! These features are enabled by default:
//!
//! * `unicode-linebreak`: enables finding words using the
//! [unicode-linebreak] crate, which implements the line breaking
//! algorithm described in [Unicode Standard Annex
//! #14](https://www.unicode.org/reports/tr14/).
//!
//! This feature can be disabled if you are happy to find words
//! separated by ASCII space characters only. People wrapping text
//! with emojis or East-Asian characters will want most likely want
//! to enable this feature. See [`WordSeparator`] for details.
//!
//! * `unicode-width`: enables correct width computation of non-ASCII
//! characters via the [unicode-width] crate. Without this feature,
//! every [`char`] is 1 column wide, except for emojis which are 2
//! columns wide. See the [`core::display_width`] function for
//! details.
//!
//! This feature can be disabled if you only need to wrap ASCII
//! text, or if the functions in [`core`] are used directly with
//! [`core::Fragment`]s for which the widths have been computed in
//! other ways.
//!
//! * `smawk`: enables linear-time wrapping of the whole paragraph via
//! the [smawk] crate. See the [`wrap_algorithms::wrap_optimal_fit`]
//! function for details on the optimal-fit algorithm.
//!
//! This feature can be disabled if you only ever intend to use
//! [`wrap_algorithms::wrap_first_fit`].
//!
//! With Rust 1.59.0, the size impact of the above features on your
//! binary is as follows:
//!
//! | Configuration | Binary Size | Delta |
//! | :--- | ---: | ---: |
//! | quick-and-dirty implementation | 289 KB | — KB |
//! | textwrap without default features | 301 KB | 12 KB |
//! | textwrap with smawk | 317 KB | 28 KB |
//! | textwrap with unicode-width | 313 KB | 24 KB |
//! | textwrap with unicode-linebreak | 395 KB | 106 KB |
//!
//! The above sizes are the stripped sizes and the binary is compiled
//! in release mode with this profile:
//!
//! ```toml
//! [profile.release]
//! lto = true
//! codegen-units = 1
//! ```
//!
//! See the [binary-sizes demo] if you want to reproduce these
//! results.
//!
//! ## Optional Features
//!
//! These Cargo features enable new functionality:
//!
//! * `terminal_size`: enables automatic detection of the terminal
//! width via the [terminal_size] crate. See the
//! [`Options::with_termwidth`] constructor for details.
//!
//! * `hyphenation`: enables language-sensitive hyphenation via the
//! [hyphenation] crate. See the [`word_splitters::WordSplitter`]
//! trait for details.
//!
//! [unicode-linebreak]: https://docs.rs/unicode-linebreak/
//! [unicode-width]: https://docs.rs/unicode-width/
//! [smawk]: https://docs.rs/smawk/
//! [binary-sizes demo]: https://github.com/mgeisler/textwrap/tree/master/examples/binary-sizes
//! [textwrap-macros]: https://docs.rs/textwrap-macros/
//! [terminal_size]: https://docs.rs/terminal_size/
//! [hyphenation]: https://docs.rs/hyphenation/
#![doc(html_root_url = "https://docs.rs/textwrap/0.15.0")]
#![forbid(unsafe_code)] // See https://github.com/mgeisler/textwrap/issues/210
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![allow(clippy::redundant_field_names)]
// Make `cargo test` execute the README doctests.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctest {}
use std::borrow::Cow;
mod indentation;
pub use crate::indentation::{dedent, indent};
mod word_separators;
pub use word_separators::WordSeparator;
pub mod word_splitters;
pub use word_splitters::WordSplitter;
pub mod wrap_algorithms;
pub use wrap_algorithms::WrapAlgorithm;
mod line_ending;
pub use line_ending::LineEnding;
pub mod core;
/// Holds configuration options for wrapping and filling text.
#[derive(Debug, Clone)]
pub struct Options<'a> {
/// The width in columns at which the text will be wrapped.
pub width: usize,
/// Line ending used for breaking lines.
pub line_ending: LineEnding,
/// Indentation used for the first line of output. See the
/// [`Options::initial_indent`] method.
pub initial_indent: &'a str,
/// Indentation used for subsequent lines of output. See the
/// [`Options::subsequent_indent`] method.
pub subsequent_indent: &'a str,
/// Allow long words to be broken if they cannot fit on a line.
/// When set to `false`, some lines may be longer than
/// `self.width`. See the [`Options::break_words`] method.
pub break_words: bool,
/// Wrapping algorithm to use, see the implementations of the
/// [`wrap_algorithms::WrapAlgorithm`] trait for details.
pub wrap_algorithm: WrapAlgorithm,
/// The line breaking algorithm to use, see
/// [`word_separators::WordSeparator`] trait for an overview and
/// possible implementations.
pub word_separator: WordSeparator,
/// The method for splitting words. This can be used to prohibit
/// splitting words on hyphens, or it can be used to implement
/// language-aware machine hyphenation.
pub word_splitter: WordSplitter,
}
impl<'a> From<&'a Options<'a>> for Options<'a> {
fn from(options: &'a Options<'a>) -> Self {
Self {
width: options.width,
line_ending: options.line_ending,
initial_indent: options.initial_indent,
subsequent_indent: options.subsequent_indent,
break_words: options.break_words,
word_separator: options.word_separator,
wrap_algorithm: options.wrap_algorithm,
word_splitter: options.word_splitter.clone(),
}
}
}
impl<'a> From<usize> for Options<'a> {
fn from(width: usize) -> Self {
Options::new(width)
}
}
impl<'a> Options<'a> {
/// Creates a new [`Options`] with the specified width. Equivalent to
///
/// ```
/// # use textwrap::{LineEnding, Options, WordSplitter, WordSeparator, WrapAlgorithm};
/// # let width = 80;
/// # let actual = Options::new(width);
/// # let expected =
/// Options {
/// width: width,
/// line_ending: LineEnding::LF,
/// initial_indent: "",
/// subsequent_indent: "",
/// break_words: true,
/// #[cfg(feature = "unicode-linebreak")]
/// word_separator: WordSeparator::UnicodeBreakProperties,
/// #[cfg(not(feature = "unicode-linebreak"))]
/// word_separator: WordSeparator::AsciiSpace,
/// #[cfg(feature = "smawk")]
/// wrap_algorithm: WrapAlgorithm::new_optimal_fit(),
/// #[cfg(not(feature = "smawk"))]
/// wrap_algorithm: WrapAlgorithm::FirstFit,
/// word_splitter: WordSplitter::HyphenSplitter,
/// }
/// # ;
/// # assert_eq!(actual.width, expected.width);
/// # assert_eq!(actual.line_ending, expected.line_ending);
/// # assert_eq!(actual.initial_indent, expected.initial_indent);
/// # assert_eq!(actual.subsequent_indent, expected.subsequent_indent);
/// # assert_eq!(actual.break_words, expected.break_words);
/// # assert_eq!(actual.word_splitter, expected.word_splitter);
/// ```
///
/// Note that the default word separator and wrap algorithms
/// changes based on the available Cargo features. The best
/// available algorithms are used by default.
pub const fn new(width: usize) -> Self {
Options {
width,
line_ending: LineEnding::LF,
initial_indent: "",
subsequent_indent: "",
break_words: true,
word_separator: WordSeparator::new(),
wrap_algorithm: WrapAlgorithm::new(),
word_splitter: WordSplitter::HyphenSplitter,
}
}
/// Creates a new [`Options`] with `width` set to the current
/// terminal width. If the terminal width cannot be determined
/// (typically because the standard input and output is not
/// connected to a terminal), a width of 80 characters will be
/// used. Other settings use the same defaults as
/// [`Options::new`].
///
/// Equivalent to:
///
/// ```no_run
/// use textwrap::{termwidth, Options};
///
/// let options = Options::new(termwidth());
/// ```
///
/// **Note:** Only available when the `terminal_size` feature is
/// enabled.
#[cfg(feature = "terminal_size")]
pub fn with_termwidth() -> Self {
Self::new(termwidth())
}
/// Change [`self.line_ending`]. This specifies which of the
/// supported line endings should be used to break the lines of the
/// input text.
///
/// # Examples
///
/// ```
/// use textwrap::{refill, LineEnding, Options};
///
/// let options = Options::new(15).line_ending(LineEnding::CRLF);
/// assert_eq!(refill("This is a little example.", options),
/// "This is a\r\nlittle example.");
/// ```
///
/// [`self.line_ending`]: #structfield.line_ending
pub fn line_ending(self, line_ending: LineEnding) -> Self {
Options {
line_ending,
..self
}
}
/// Change [`self.initial_indent`]. The initial indentation is
/// used on the very first line of output.
///
/// # Examples
///
/// Classic paragraph indentation can be achieved by specifying an
/// initial indentation and wrapping each paragraph by itself:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(16).initial_indent(" ");
/// assert_eq!(wrap("This is a little example.", options),
/// vec![" This is a",
/// "little example."]);
/// ```
///
/// [`self.initial_indent`]: #structfield.initial_indent
pub fn initial_indent(self, indent: &'a str) -> Self {
Options {
initial_indent: indent,
..self
}
}
/// Change [`self.subsequent_indent`]. The subsequent indentation
/// is used on lines following the first line of output.
///
/// # Examples
///
/// Combining initial and subsequent indentation lets you format a
/// single paragraph as a bullet list:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(12)
/// .initial_indent("* ")
/// .subsequent_indent(" ");
/// #[cfg(feature = "smawk")]
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["* This is",
/// " a little",
/// " example."]);
///
/// // Without the `smawk` feature, the wrapping is a little different:
/// #[cfg(not(feature = "smawk"))]
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["* This is a",
/// " little",
/// " example."]);
/// ```
///
/// [`self.subsequent_indent`]: #structfield.subsequent_indent
pub fn subsequent_indent(self, indent: &'a str) -> Self {
Options {
subsequent_indent: indent,
..self
}
}
/// Change [`self.break_words`]. This controls if words longer
/// than `self.width` can be broken, or if they will be left
/// sticking out into the right margin.
///
/// # Examples
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(4).break_words(true);
/// assert_eq!(wrap("This is a little example.", options),
/// vec!["This",
/// "is a",
/// "litt",
/// "le",
/// "exam",
/// "ple."]);
/// ```
///
/// [`self.break_words`]: #structfield.break_words
pub fn break_words(self, setting: bool) -> Self {
Options {
break_words: setting,
..self
}
}
/// Change [`self.word_separator`].
///
/// See [`word_separators::WordSeparator`] for details on the choices.
///
/// [`self.word_separator`]: #structfield.word_separator
pub fn word_separator(self, word_separator: WordSeparator) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: word_separator,
wrap_algorithm: self.wrap_algorithm,
word_splitter: self.word_splitter,
}
}
/// Change [`self.wrap_algorithm`].
///
/// See the [`wrap_algorithms::WrapAlgorithm`] trait for details on
/// the choices.
///
/// [`self.wrap_algorithm`]: #structfield.wrap_algorithm
pub fn wrap_algorithm(self, wrap_algorithm: WrapAlgorithm) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: self.word_separator,
wrap_algorithm: wrap_algorithm,
word_splitter: self.word_splitter,
}
}
/// Change [`self.word_splitter`]. The
/// [`word_splitters::WordSplitter`] is used to fit part of a word
/// into the current line when wrapping text.
///
/// # Examples
///
/// ```
/// use textwrap::{Options, WordSplitter};
/// let opt = Options::new(80);
/// assert_eq!(opt.word_splitter, WordSplitter::HyphenSplitter);
/// let opt = opt.word_splitter(WordSplitter::NoHyphenation);
/// assert_eq!(opt.word_splitter, WordSplitter::NoHyphenation);
/// ```
///
/// [`self.word_splitter`]: #structfield.word_splitter
pub fn word_splitter(self, word_splitter: WordSplitter) -> Options<'a> {
Options {
width: self.width,
line_ending: self.line_ending,
initial_indent: self.initial_indent,
subsequent_indent: self.subsequent_indent,
break_words: self.break_words,
word_separator: self.word_separator,
wrap_algorithm: self.wrap_algorithm,
word_splitter,
}
}
}
/// Return the current terminal width.
///
/// If the terminal width cannot be determined (typically because the
/// standard output is not connected to a terminal), a default width
/// of 80 characters will be used.
///
/// # Examples
///
/// Create an [`Options`] for wrapping at the current terminal width
/// with a two column margin to the left and the right:
///
/// ```no_run
/// use textwrap::{termwidth, Options};
///
/// let width = termwidth() - 4; // Two columns on each side.
/// let options = Options::new(width)
/// .initial_indent(" ")
/// .subsequent_indent(" ");
/// ```
///
/// **Note:** Only available when the `terminal_size` Cargo feature is
/// enabled.
#[cfg(feature = "terminal_size")]
pub fn termwidth() -> usize {
terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into())
}
/// Fill a line of text at a given width.
///
/// The result is a [`String`], complete with newlines between each
/// line. Use the [`wrap`] function if you need access to the
/// individual lines.
///
/// The easiest way to use this function is to pass an integer for
/// `width_or_options`:
///
/// ```
/// use textwrap::fill;
///
/// assert_eq!(
/// fill("Memory safety without garbage collection.", 15),
/// "Memory safety\nwithout garbage\ncollection."
/// );
/// ```
///
/// If you need to customize the wrapping, you can pass an [`Options`]
/// instead of an `usize`:
///
/// ```
/// use textwrap::{fill, Options};
///
/// let options = Options::new(15)
/// .initial_indent("- ")
/// .subsequent_indent(" ");
/// assert_eq!(
/// fill("Memory safety without garbage collection.", &options),
/// "- Memory safety\n without\n garbage\n collection."
/// );
/// ```
pub fn fill<'a, Opt>(text: &str, width_or_options: Opt) -> String
where
Opt: Into<Options<'a>>,
{
let options = width_or_options.into();
let line_ending_str = options.line_ending.as_str();
// This will avoid reallocation in simple cases (no
// indentation, no hyphenation).
let mut result = String::with_capacity(text.len());
for (i, line) in wrap(text, options).iter().enumerate() {
if i > 0 {
result.push_str(line_ending_str);
}
result.push_str(line);
}
result
}
/// Unpack a paragraph of already-wrapped text.
///
/// This function attempts to recover the original text from a single
/// paragraph of text produced by the [`fill`] function. This means
/// that it turns
///
/// ```text
/// textwrap: a small
/// library for
/// wrapping text.
/// ```
///
/// back into
///
/// ```text
/// textwrap: a small library for wrapping text.
/// ```
///
/// In addition, it will recognize a common prefix and a common line
/// ending among the lines.
///
/// The prefix of the first line is returned in
/// [`Options::initial_indent`] and the prefix (if any) of the the
/// other lines is returned in [`Options::subsequent_indent`].
///
/// Line ending is returned in [`Options::line_ending`]. If line ending
/// can not be confidently detected (mixed or no line endings in the
/// input), [`LineEnding::LF`] will be returned.
///
/// In addition to `' '`, the prefixes can consist of characters used
/// for unordered lists (`'-'`, `'+'`, and `'*'`) and block quotes
/// (`'>'`) in Markdown as well as characters often used for inline
/// comments (`'#'` and `'/'`).
///
/// The text must come from a single wrapped paragraph. This means
/// that there can be no `"\n\n"` within the text.
///
/// # Examples
///
/// ```
/// use textwrap::{LineEnding, unfill};
///
/// let (text, options) = unfill("\
/// * This is an
/// example of
/// a list item.
/// ");
///
/// assert_eq!(text, "This is an example of a list item.\n");
/// assert_eq!(options.initial_indent, "* ");
/// assert_eq!(options.subsequent_indent, " ");
/// assert_eq!(options.line_ending, LineEnding::LF);
/// ```
pub fn unfill(text: &str) -> (String, Options<'_>) {
let line_ending_pat: &[_] = &['\r', '\n'];
let trimmed = text.trim_end_matches(line_ending_pat);
let prefix_chars: &[_] = &[' ', '-', '+', '*', '>', '#', '/'];
let mut options = Options::new(0);
for (idx, line) in trimmed.lines().enumerate() {
options.width = std::cmp::max(options.width, core::display_width(line));
let without_prefix = line.trim_start_matches(prefix_chars);
let prefix = &line[..line.len() - without_prefix.len()];
if idx == 0 {
options.initial_indent = prefix;
} else if idx == 1 {
options.subsequent_indent = prefix;
} else if idx > 1 {
for ((idx, x), y) in prefix.char_indices().zip(options.subsequent_indent.chars()) {
if x != y {
options.subsequent_indent = &prefix[..idx];
break;
}
}
if prefix.len() < options.subsequent_indent.len() {
options.subsequent_indent = prefix;
}
}
}
let mut unfilled = String::with_capacity(text.len());
let mut detected_line_ending = None;
for (idx, (line, ending)) in line_ending::NonEmptyLines(text).enumerate() {
if idx == 0 {
unfilled.push_str(&line[options.initial_indent.len()..]);
} else {
unfilled.push(' ');
unfilled.push_str(&line[options.subsequent_indent.len()..]);
}
match (detected_line_ending, ending) {
(None, Some(_)) => detected_line_ending = ending,
(Some(LineEnding::CRLF), Some(LineEnding::LF)) => detected_line_ending = ending,
_ => (),
}
}
unfilled.push_str(&text[trimmed.len()..]);
options.line_ending = detected_line_ending.unwrap_or(LineEnding::LF);
(unfilled, options)
}
/// Refill a paragraph of wrapped text with a new width.
///
/// This function will first use the [`unfill`] function to remove
/// newlines from the text. Afterwards the text is filled again using
/// the [`fill`] function.
///
/// The `new_width_or_options` argument specify the new width and can
/// specify other options as well — except for
/// [`Options::initial_indent`] and [`Options::subsequent_indent`],
/// which are deduced from `filled_text`.
///
/// # Examples
///
/// ```
/// use textwrap::refill;
///
/// // Some loosely wrapped text. The "> " prefix is recognized automatically.
/// let text = "\
/// > Memory
/// > safety without garbage
/// > collection.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// > Memory safety
/// > without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 40), "\
/// > Memory safety without garbage
/// > collection.
/// ");
///
/// assert_eq!(refill(text, 60), "\
/// > Memory safety without garbage collection.
/// ");
/// ```
///
/// You can also reshape bullet points:
///
/// ```
/// use textwrap::refill;
///
/// let text = "\
/// - This is my
/// list item.
/// ";
///
/// assert_eq!(refill(text, 20), "\
/// - This is my list
/// item.
/// ");
/// ```
pub fn refill<'a, Opt>(filled_text: &str, new_width_or_options: Opt) -> String
where
Opt: Into<Options<'a>>,
{
let mut new_options = new_width_or_options.into();
let trimmed = filled_text.trim_end_matches(new_options.line_ending.as_str());
let (text, options) = unfill(trimmed);
new_options.initial_indent = options.initial_indent;
new_options.subsequent_indent = options.subsequent_indent;
let mut refilled = fill(&text, new_options);
refilled.push_str(&filled_text[trimmed.len()..]);
refilled
}
/// Wrap a line of text at a given width.
///
/// The result is a vector of lines, each line is of type [`Cow<'_,
/// str>`](Cow), which means that the line will borrow from the input
/// `&str` if possible. The lines do not have trailing whitespace,
/// including a final `'\n'`. Please use the [`fill`] function if you
/// need a [`String`] instead.
///
/// The easiest way to use this function is to pass an integer for
/// `width_or_options`:
///
/// ```
/// use textwrap::wrap;
///
/// let lines = wrap("Memory safety without garbage collection.", 15);
/// assert_eq!(lines, &[
/// "Memory safety",
/// "without garbage",
/// "collection.",
/// ]);
/// ```
///
/// If you need to customize the wrapping, you can pass an [`Options`]
/// instead of an `usize`:
///
/// ```
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(15)
/// .initial_indent("- ")
/// .subsequent_indent(" ");
/// let lines = wrap("Memory safety without garbage collection.", &options);
/// assert_eq!(lines, &[
/// "- Memory safety",
/// " without",
/// " garbage",
/// " collection.",
/// ]);
/// ```
///
/// # Optimal-Fit Wrapping
///
/// By default, `wrap` will try to ensure an even right margin by
/// finding breaks which avoid short lines. We call this an
/// “optimal-fit algorithm” since the line breaks are computed by
/// considering all possible line breaks. The alternative is a
/// “first-fit algorithm” which simply accumulates words until they no
/// longer fit on the line.
///
/// As an example, using the first-fit algorithm to wrap the famous
/// Hamlet quote “To be, or not to be: that is the question” in a
/// narrow column with room for only 10 characters looks like this:
///
/// ```
/// # use textwrap::{WrapAlgorithm::FirstFit, Options, wrap};
/// #
/// # let lines = wrap("To be, or not to be: that is the question",
/// # Options::new(10).wrap_algorithm(FirstFit));
/// # assert_eq!(lines.join("\n") + "\n", "\
/// To be, or
/// not to be:
/// that is
/// the
/// question
/// # ");
/// ```
///
/// Notice how the second to last line is quite narrow because
/// “question” was too large to fit? The greedy first-fit algorithm
/// doesn’t look ahead, so it has no other option than to put
/// “question” onto its own line.
///
/// With the optimal-fit wrapping algorithm, the previous lines are
/// shortened slightly in order to make the word “is” go into the
/// second last line:
///
/// ```
/// # #[cfg(feature = "smawk")] {
/// # use textwrap::{Options, WrapAlgorithm, wrap};
/// #
/// # let lines = wrap(
/// # "To be, or not to be: that is the question",
/// # Options::new(10).wrap_algorithm(WrapAlgorithm::new_optimal_fit())
/// # );
/// # assert_eq!(lines.join("\n") + "\n", "\
/// To be,
/// or not to
/// be: that
/// is the
/// question
/// # "); }
/// ```
///
/// Please see [`WrapAlgorithm`] for details on the choices.
///
/// # Examples
///
/// The returned iterator yields lines of type `Cow<'_, str>`. If
/// possible, the wrapped lines will borrow from the input string. As
/// an example, a hanging indentation, the first line can borrow from
/// the input, but the subsequent lines become owned strings:
///
/// ```
/// use std::borrow::Cow::{Borrowed, Owned};
/// use textwrap::{wrap, Options};
///
/// let options = Options::new(15).subsequent_indent("....");
/// let lines = wrap("Wrapping text all day long.", &options);
/// let annotated = lines
/// .iter()
/// .map(|line| match line {
/// Borrowed(text) => format!("[Borrowed] {}", text),
/// Owned(text) => format!("[Owned] {}", text),
/// })
/// .collect::<Vec<_>>();
/// assert_eq!(
/// annotated,
/// &[
/// "[Borrowed] Wrapping text",
/// "[Owned] ....all day",
/// "[Owned] ....long.",
/// ]
/// );
/// ```
///
/// ## Leading and Trailing Whitespace
///
/// As a rule, leading whitespace (indentation) is preserved and
/// trailing whitespace is discarded.
///
/// In more details, when wrapping words into lines, words are found
/// by splitting the input text on space characters. One or more
/// spaces (shown here as “␣”) are attached to the end of each word:
///
/// ```text
/// "Foo␣␣␣bar␣baz" -> ["Foo␣␣␣", "bar␣", "baz"]
/// ```
///
/// These words are then put into lines. The interword whitespace is
/// preserved, unless the lines are wrapped so that the `"Foo␣␣␣"`
/// word falls at the end of a line:
///
/// ```
/// use textwrap::wrap;
///
/// assert_eq!(wrap("Foo bar baz", 10), vec!["Foo bar", "baz"]);
/// assert_eq!(wrap("Foo bar baz", 8), vec!["Foo", "bar baz"]);
/// ```
///
/// Notice how the trailing whitespace is removed in both case: in the
/// first example, `"bar␣"` becomes `"bar"` and in the second case
/// `"Foo␣␣␣"` becomes `"Foo"`.
///
/// Leading whitespace is preserved when the following word fits on
/// the first line. To understand this, consider how words are found
/// in a text with leading spaces:
///
/// ```text
/// "␣␣foo␣bar" -> ["␣␣", "foo␣", "bar"]
/// ```
///
/// When put into lines, the indentation is preserved if `"foo"` fits
/// on the first line, otherwise you end up with an empty line:
///
/// ```
/// use textwrap::wrap;
///
/// assert_eq!(wrap(" foo bar", 8), vec![" foo", "bar"]);
/// assert_eq!(wrap(" foo bar", 4), vec!["", "foo", "bar"]);
/// ```
pub fn wrap<'a, Opt>(text: &str, width_or_options: Opt) -> Vec<Cow<'_, str>>
where
Opt: Into<Options<'a>>,
{
let options: Options = width_or_options.into();
let line_ending_str = options.line_ending.as_str();
let initial_width = options
.width
.saturating_sub(core::display_width(options.initial_indent));
let subsequent_width = options
.width
.saturating_sub(core::display_width(options.subsequent_indent));
let mut lines = Vec::new();
for line in text.split(line_ending_str) {
let words = options.word_separator.find_words(line);
let split_words = word_splitters::split_words(words, &options.word_splitter);
let broken_words = if options.break_words {
let mut broken_words = core::break_words(split_words, subsequent_width);
if !options.initial_indent.is_empty() {
// Without this, the first word will always go into
// the first line. However, since we break words based
// on the _second_ line width, it can be wrong to
// unconditionally put the first word onto the first
// line. An empty zero-width word fixed this.
broken_words.insert(0, core::Word::from(""));
}
broken_words
} else {
split_words.collect::<Vec<_>>()
};
let line_widths = [initial_width, subsequent_width];
let wrapped_words = options.wrap_algorithm.wrap(&broken_words, &line_widths);
let mut idx = 0;
for words in wrapped_words {
let last_word = match words.last() {
None => {
lines.push(Cow::from(""));
continue;
}
Some(word) => word,
};
// We assume here that all words are contiguous in `line`.
// That is, the sum of their lengths should add up to the
// length of `line`.
let len = words
.iter()
.map(|word| word.len() + word.whitespace.len())
.sum::<usize>()
- last_word.whitespace.len();
// The result is owned if we have indentation, otherwise
// we can simply borrow an empty string.
let mut result = if lines.is_empty() && !options.initial_indent.is_empty() {
Cow::Owned(options.initial_indent.to_owned())
} else if !lines.is_empty() && !options.subsequent_indent.is_empty() {
Cow::Owned(options.subsequent_indent.to_owned())
} else {
// We can use an empty string here since string
// concatenation for `Cow` preserves a borrowed value
// when either side is empty.
Cow::from("")
};
result += &line[idx..idx + len];
if !last_word.penalty.is_empty() {
result.to_mut().push_str(last_word.penalty);
}
lines.push(result);
// Advance by the length of `result`, plus the length of
// `last_word.whitespace` -- even if we had a penalty, we
// need to skip over the whitespace.
idx += len + last_word.whitespace.len();
}
}
lines
}
/// Wrap text into columns with a given total width.
///
/// The `left_gap`, `middle_gap` and `right_gap` arguments specify the
/// strings to insert before, between, and after the columns. The
/// total width of all columns and all gaps is specified using the
/// `total_width_or_options` argument. This argument can simply be an
/// integer if you want to use default settings when wrapping, or it
/// can be a [`Options`] value if you want to customize the wrapping.
///
/// If the columns are narrow, it is recommended to set
/// [`Options::break_words`] to `true` to prevent words from
/// protruding into the margins.
///
/// The per-column width is computed like this:
///
/// ```
/// # let (left_gap, middle_gap, right_gap) = ("", "", "");
/// # let columns = 2;
/// # let options = textwrap::Options::new(80);
/// let inner_width = options.width
/// - textwrap::core::display_width(left_gap)
/// - textwrap::core::display_width(right_gap)
/// - textwrap::core::display_width(middle_gap) * (columns - 1);
/// let column_width = inner_width / columns;
/// ```
///
/// The `text` is wrapped using [`wrap`] and the given `options`
/// argument, but the width is overwritten to the computed
/// `column_width`.
///
/// # Panics
///
/// Panics if `columns` is zero.
///
/// # Examples
///
/// ```
/// use textwrap::wrap_columns;
///
/// let text = "\
/// This is an example text, which is wrapped into three columns. \
/// Notice how the final column can be shorter than the others.";
///
/// #[cfg(feature = "smawk")]
/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
/// vec!["| This is | into three | column can be |",
/// "| an example | columns. | shorter than |",
/// "| text, which | Notice how | the others. |",
/// "| is wrapped | the final | |"]);
///
/// // Without the `smawk` feature, the middle column is a little more uneven:
/// #[cfg(not(feature = "smawk"))]
/// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
/// vec!["| This is an | three | column can be |",
/// "| example text, | columns. | shorter than |",
/// "| which is | Notice how | the others. |",
/// "| wrapped into | the final | |"]);
pub fn wrap_columns<'a, Opt>(
text: &str,
columns: usize,
total_width_or_options: Opt,
left_gap: &str,
middle_gap: &str,
right_gap: &str,
) -> Vec<String>
where
Opt: Into<Options<'a>>,
{
assert!(columns > 0);
let mut options: Options = total_width_or_options.into();
let inner_width = options
.width
.saturating_sub(core::display_width(left_gap))
.saturating_sub(core::display_width(right_gap))
.saturating_sub(core::display_width(middle_gap) * (columns - 1));
let column_width = std::cmp::max(inner_width / columns, 1);
options.width = column_width;
let last_column_padding = " ".repeat(inner_width % column_width);
let wrapped_lines = wrap(text, options);
let lines_per_column =
wrapped_lines.len() / columns + usize::from(wrapped_lines.len() % columns > 0);
let mut lines = Vec::new();
for line_no in 0..lines_per_column {
let mut line = String::from(left_gap);
for column_no in 0..columns {
match wrapped_lines.get(line_no + column_no * lines_per_column) {
Some(column_line) => {
line.push_str(column_line);
line.push_str(&" ".repeat(column_width - core::display_width(column_line)));
}
None => {
line.push_str(&" ".repeat(column_width));
}
}
if column_no == columns - 1 {
line.push_str(&last_column_padding);
} else {
line.push_str(middle_gap);
}
}
line.push_str(right_gap);
lines.push(line);
}
lines
}
/// Fill `text` in-place without reallocating the input string.
///
/// This function works by modifying the input string: some `' '`
/// characters will be replaced by `'\n'` characters. The rest of the
/// text remains untouched.
///
/// Since we can only replace existing whitespace in the input with
/// `'\n'`, we cannot do hyphenation nor can we split words longer
/// than the line width. We also need to use `AsciiSpace` as the word
/// separator since we need `' '` characters between words in order to
/// replace some of them with a `'\n'`. Indentation is also ruled out.
/// In other words, `fill_inplace(width)` behaves as if you had called
/// [`fill`] with these options:
///
/// ```
/// # use textwrap::{core, LineEnding, Options, WordSplitter, WordSeparator, WrapAlgorithm};
/// # let width = 80;
/// Options {
/// width: width,
/// line_ending: LineEnding::LF,
/// initial_indent: "",
/// subsequent_indent: "",
/// break_words: false,
/// word_separator: WordSeparator::AsciiSpace,
/// wrap_algorithm: WrapAlgorithm::FirstFit,
/// word_splitter: WordSplitter::NoHyphenation,
/// };
/// ```
///
/// The wrap algorithm is [`WrapAlgorithm::FirstFit`] since this
/// is the fastest algorithm — and the main reason to use
/// `fill_inplace` is to get the string broken into newlines as fast
/// as possible.
///
/// A last difference is that (unlike [`fill`]) `fill_inplace` can
/// leave trailing whitespace on lines. This is because we wrap by
/// inserting a `'\n'` at the final whitespace in the input string:
///
/// ```
/// let mut text = String::from("Hello World!");
/// textwrap::fill_inplace(&mut text, 10);
/// assert_eq!(text, "Hello \nWorld!");
/// ```
///
/// If we didn't do this, the word `World!` would end up being
/// indented. You can avoid this if you make sure that your input text
/// has no double spaces.
///
/// # Performance
///
/// In benchmarks, `fill_inplace` is about twice as fast as [`fill`].
/// Please see the [`linear`
/// benchmark](https://github.com/mgeisler/textwrap/blob/master/benches/linear.rs)
/// for details.
pub fn fill_inplace(text: &mut String, width: usize) {
let mut indices = Vec::new();
let mut offset = 0;
for line in text.split('\n') {
let words = WordSeparator::AsciiSpace
.find_words(line)
.collect::<Vec<_>>();
let wrapped_words = wrap_algorithms::wrap_first_fit(&words, &[width as f64]);
let mut line_offset = offset;
for words in &wrapped_words[..wrapped_words.len() - 1] {
let line_len = words
.iter()
.map(|word| word.len() + word.whitespace.len())
.sum::<usize>();
line_offset += line_len;
// We've advanced past all ' ' characters -- want to move
// one ' ' backwards and insert our '\n' there.
indices.push(line_offset - 1);
}
// Advance past entire line, plus the '\n' which was removed
// by the split call above.
offset += line.len() + 1;
}
let mut bytes = std::mem::take(text).into_bytes();
for idx in indices {
bytes[idx] = b'\n';
}
*text = String::from_utf8(bytes).unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
#[test]
fn options_agree_with_usize() {
let opt_usize = Options::from(42_usize);
let opt_options = Options::new(42);
assert_eq!(opt_usize.width, opt_options.width);
assert_eq!(opt_usize.initial_indent, opt_options.initial_indent);
assert_eq!(opt_usize.subsequent_indent, opt_options.subsequent_indent);
assert_eq!(opt_usize.break_words, opt_options.break_words);
assert_eq!(
opt_usize.word_splitter.split_points("hello-world"),
opt_options.word_splitter.split_points("hello-world")
);
}
#[test]
fn no_wrap() {
assert_eq!(wrap("foo", 10), vec!["foo"]);
}
#[test]
fn wrap_simple() {
assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]);
}
#[test]
fn to_be_or_not() {
assert_eq!(
wrap(
"To be, or not to be, that is the question.",
Options::new(10).wrap_algorithm(WrapAlgorithm::FirstFit)
),
vec!["To be, or", "not to be,", "that is", "the", "question."]
);
}
#[test]
fn multiple_words_on_first_line() {
assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]);
}
#[test]
fn long_word() {
assert_eq!(wrap("foo", 0), vec!["f", "o", "o"]);
}
#[test]
fn long_words() {
assert_eq!(wrap("foo bar", 0), vec!["f", "o", "o", "b", "a", "r"]);
}
#[test]
fn max_width() {
assert_eq!(wrap("foo bar", usize::MAX), vec!["foo bar"]);
let text = "Hello there! This is some English text. \
It should not be wrapped given the extents below.";
assert_eq!(wrap(text, usize::MAX), vec![text]);
}
#[test]
fn leading_whitespace() {
assert_eq!(wrap(" foo bar", 6), vec![" foo", "bar"]);
}
#[test]
fn leading_whitespace_empty_first_line() {
// If there is no space for the first word, the first line
// will be empty. This is because the string is split into
// words like [" ", "foobar ", "baz"], which puts "foobar " on
// the second line. We never output trailing whitespace
assert_eq!(wrap(" foobar baz", 6), vec!["", "foobar", "baz"]);
}
#[test]
fn trailing_whitespace() {
// Whitespace is only significant inside a line. After a line
// gets too long and is broken, the first word starts in
// column zero and is not indented.
assert_eq!(wrap("foo bar baz ", 5), vec!["foo", "bar", "baz"]);
}
#[test]
fn issue_99() {
// We did not reset the in_whitespace flag correctly and did
// not handle single-character words after a line break.
assert_eq!(
wrap("aaabbbccc x yyyzzzwww", 9),
vec!["aaabbbccc", "x", "yyyzzzwww"]
);
}
#[test]
fn issue_129() {
// The dash is an em-dash which takes up four bytes. We used
// to panic since we tried to index into the character.
let options = Options::new(1).word_separator(WordSeparator::AsciiSpace);
assert_eq!(wrap("x – x", options), vec!["x", "–", "x"]);
}
#[test]
fn wide_character_handling() {
assert_eq!(wrap("Hello, World!", 15), vec!["Hello, World!"]);
assert_eq!(
wrap(
"Hello, World!",
Options::new(15).word_separator(WordSeparator::AsciiSpace)
),
vec!["Hello,", "World!"]
);
// Wide characters are allowed to break if the
// unicode-linebreak feature is enabled.
#[cfg(feature = "unicode-linebreak")]
assert_eq!(
wrap(
"Hello, World!",
Options::new(15).word_separator(WordSeparator::UnicodeBreakProperties),
),
vec!["Hello, W", "orld!"]
);
}
#[test]
fn empty_line_is_indented() {
// Previously, indentation was not applied to empty lines.
// However, this is somewhat inconsistent and undesirable if
// the indentation is something like a border ("| ") which you
// want to apply to all lines, empty or not.
let options = Options::new(10).initial_indent("!!!");
assert_eq!(fill("", &options), "!!!");
}
#[test]
fn indent_single_line() {
let options = Options::new(10).initial_indent(">>>"); // No trailing space
assert_eq!(fill("foo", &options), ">>>foo");
}
#[test]
fn indent_first_emoji() {
let options = Options::new(10).initial_indent("👉👉");
assert_eq!(
wrap("x x x x x x x x x x x x x", &options),
vec!["👉👉x x x", "x x x x x", "x x x x x"]
);
}
#[test]
fn indent_multiple_lines() {
let options = Options::new(6).initial_indent("* ").subsequent_indent(" ");
assert_eq!(
wrap("foo bar baz", &options),
vec!["* foo", " bar", " baz"]
);
}
#[test]
fn indent_break_words() {
let options = Options::new(5).initial_indent("* ").subsequent_indent(" ");
assert_eq!(wrap("foobarbaz", &options), vec!["* foo", " bar", " baz"]);
}
#[test]
fn initial_indent_break_words() {
// This is a corner-case showing how the long word is broken
// according to the width of the subsequent lines. The first
// fragment of the word no longer fits on the first line,
// which ends up being pure indentation.
let options = Options::new(5).initial_indent("-->");
assert_eq!(wrap("foobarbaz", &options), vec!["-->", "fooba", "rbaz"]);
}
#[test]
fn hyphens() {
assert_eq!(wrap("foo-bar", 5), vec!["foo-", "bar"]);
}
#[test]
fn trailing_hyphen() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foobar-", &options), vec!["foobar-"]);
}
#[test]
fn multiple_hyphens() {
assert_eq!(wrap("foo-bar-baz", 5), vec!["foo-", "bar-", "baz"]);
}
#[test]
fn hyphens_flag() {
let options = Options::new(5).break_words(false);
assert_eq!(
wrap("The --foo-bar flag.", &options),
vec!["The", "--foo-", "bar", "flag."]
);
}
#[test]
fn repeated_hyphens() {
let options = Options::new(4).break_words(false);
assert_eq!(wrap("foo--bar", &options), vec!["foo--bar"]);
}
#[test]
fn hyphens_alphanumeric() {
assert_eq!(wrap("Na2-CH4", 5), vec!["Na2-", "CH4"]);
}
#[test]
fn hyphens_non_alphanumeric() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foo(-)bar", &options), vec!["foo(-)bar"]);
}
#[test]
fn multiple_splits() {
assert_eq!(wrap("foo-bar-baz", 9), vec!["foo-bar-", "baz"]);
}
#[test]
fn forced_split() {
let options = Options::new(5).break_words(false);
assert_eq!(wrap("foobar-baz", &options), vec!["foobar-", "baz"]);
}
#[test]
fn multiple_unbroken_words_issue_193() {
let options = Options::new(3).break_words(false);
assert_eq!(
wrap("small large tiny", &options),
vec!["small", "large", "tiny"]
);
assert_eq!(
wrap("small large tiny", &options),
vec!["small", "large", "tiny"]
);
}
#[test]
fn very_narrow_lines_issue_193() {
let options = Options::new(1).break_words(false);
assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]);
assert_eq!(wrap("fooo x y", &options), vec!["fooo", "x", "y"]);
}
#[test]
fn simple_hyphens() {
let options = Options::new(8).word_splitter(WordSplitter::HyphenSplitter);
assert_eq!(wrap("foo bar-baz", &options), vec!["foo bar-", "baz"]);
}
#[test]
fn no_hyphenation() {
let options = Options::new(8).word_splitter(WordSplitter::NoHyphenation);
assert_eq!(wrap("foo bar-baz", &options), vec!["foo", "bar-baz"]);
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_double_hyphenation() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10);
assert_eq!(
wrap("Internationalization", &options),
vec!["Internatio", "nalization"]
);
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("Internationalization", &options),
vec!["Interna-", "tionaliza-", "tion"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_issue_158() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10);
assert_eq!(
wrap("participation is the key to success", &options),
vec!["participat", "ion is", "the key to", "success"]
);
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("participation is the key to success", &options),
vec!["partici-", "pation is", "the key to", "success"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn split_len_hyphenation() {
// Test that hyphenation takes the width of the whitespace
// into account.
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(15).word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("garbage collection", &options),
vec!["garbage col-", "lection"]
);
}
#[test]
#[cfg(feature = "hyphenation")]
fn borrowed_lines() {
// Lines that end with an extra hyphen are owned, the final
// line is borrowed.
use std::borrow::Cow::{Borrowed, Owned};
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(10).word_splitter(WordSplitter::Hyphenation(dictionary));
let lines = wrap("Internationalization", &options);
assert_eq!(lines, vec!["Interna-", "tionaliza-", "tion"]);
if let Borrowed(s) = lines[0] {
assert!(false, "should not have been borrowed: {:?}", s);
}
if let Borrowed(s) = lines[1] {
assert!(false, "should not have been borrowed: {:?}", s);
}
if let Owned(ref s) = lines[2] {
assert!(false, "should not have been owned: {:?}", s);
}
}
#[test]
#[cfg(feature = "hyphenation")]
fn auto_hyphenation_with_hyphen() {
let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
let options = Options::new(8).break_words(false);
assert_eq!(
wrap("over-caffinated", &options),
vec!["over-", "caffinated"]
);
let options = options.word_splitter(WordSplitter::Hyphenation(dictionary));
assert_eq!(
wrap("over-caffinated", &options),
vec!["over-", "caffi-", "nated"]
);
}
#[test]
fn break_words() {
assert_eq!(wrap("foobarbaz", 3), vec!["foo", "bar", "baz"]);
}
#[test]
fn break_words_wide_characters() {
// Even the poor man's version of `ch_width` counts these
// characters as wide.
let options = Options::new(5).word_separator(WordSeparator::AsciiSpace);
assert_eq!(wrap("Hello", options), vec!["He", "ll", "o"]);
}
#[test]
fn break_words_zero_width() {
assert_eq!(wrap("foobar", 0), vec!["f", "o", "o", "b", "a", "r"]);
}
#[test]
fn break_long_first_word() {
assert_eq!(wrap("testx y", 4), vec!["test", "x y"]);
}
#[test]
fn break_words_line_breaks() {
assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl");
assert_eq!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl");
}
#[test]
fn break_words_empty_lines() {
assert_eq!(
fill("foo\nbar", &Options::new(2).break_words(false)),
"foo\nbar"
);
}
#[test]
fn preserve_line_breaks() {
assert_eq!(fill("", 80), "");
assert_eq!(fill("\n", 80), "\n");
assert_eq!(fill("\n\n\n", 80), "\n\n\n");
assert_eq!(fill("test\n", 80), "test\n");
assert_eq!(fill("test\n\na\n\n", 80), "test\n\na\n\n");
assert_eq!(
fill(
"1 3 5 7\n1 3 5 7",
Options::new(7).wrap_algorithm(WrapAlgorithm::FirstFit)
),
"1 3 5 7\n1 3 5 7"
);
assert_eq!(
fill(
"1 3 5 7\n1 3 5 7",
Options::new(5).wrap_algorithm(WrapAlgorithm::FirstFit)
),
"1 3 5\n7\n1 3 5\n7"
);
}
#[test]
fn preserve_line_breaks_with_whitespace() {
assert_eq!(fill(" ", 80), "");
assert_eq!(fill(" \n ", 80), "\n");
assert_eq!(fill(" \n \n \n ", 80), "\n\n\n");
}
#[test]
fn non_breaking_space() {
let options = Options::new(5).break_words(false);
assert_eq!(fill("foo bar baz", &options), "foo bar baz");
}
#[test]
fn non_breaking_hyphen() {
let options = Options::new(5).break_words(false);
assert_eq!(fill("foo‑bar‑baz", &options), "foo‑bar‑baz");
}
#[test]
fn fill_simple() {
assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz");
}
#[test]
fn fill_colored_text() {
// The words are much longer than 6 bytes, but they remain
// intact after filling the text.
let green_hello = "\u{1b}[0m\u{1b}[32mHello\u{1b}[0m";
let blue_world = "\u{1b}[0m\u{1b}[34mWorld!\u{1b}[0m";
assert_eq!(
fill(&(String::from(green_hello) + " " + &blue_world), 6),
String::from(green_hello) + "\n" + &blue_world
);
}
#[test]
fn fill_unicode_boundary() {
// https://github.com/mgeisler/textwrap/issues/390
fill("\u{1b}!Ͽ", 10);
}
#[test]
fn fill_inplace_empty() {
let mut text = String::from("");
fill_inplace(&mut text, 80);
assert_eq!(text, "");
}
#[test]
fn fill_inplace_simple() {
let mut text = String::from("foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\nbaz");
}
#[test]
fn fill_inplace_multiple_lines() {
let mut text = String::from("Some text to wrap over multiple lines");
fill_inplace(&mut text, 12);
assert_eq!(text, "Some text to\nwrap over\nmultiple\nlines");
}
#[test]
fn fill_inplace_long_word() {
let mut text = String::from("Internationalization is hard");
fill_inplace(&mut text, 10);
assert_eq!(text, "Internationalization\nis hard");
}
#[test]
fn fill_inplace_no_hyphen_splitting() {
let mut text = String::from("A well-chosen example");
fill_inplace(&mut text, 10);
assert_eq!(text, "A\nwell-chosen\nexample");
}
#[test]
fn fill_inplace_newlines() {
let mut text = String::from("foo bar\n\nbaz\n\n\n");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\n\nbaz\n\n\n");
}
#[test]
fn fill_inplace_newlines_reset_line_width() {
let mut text = String::from("1 3 5\n1 3 5 7 9\n1 3 5 7 9 1 3");
fill_inplace(&mut text, 10);
assert_eq!(text, "1 3 5\n1 3 5 7 9\n1 3 5 7 9\n1 3");
}
#[test]
fn fill_inplace_leading_whitespace() {
let mut text = String::from(" foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, " foo bar\nbaz");
}
#[test]
fn fill_inplace_trailing_whitespace() {
let mut text = String::from("foo bar baz ");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar\nbaz ");
}
#[test]
fn fill_inplace_interior_whitespace() {
// To avoid an unwanted indentation of "baz", it is important
// to replace the final ' ' with '\n'.
let mut text = String::from("foo bar baz");
fill_inplace(&mut text, 10);
assert_eq!(text, "foo bar \nbaz");
}
#[test]
fn unfill_simple() {
let (text, options) = unfill("foo\nbar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_no_new_line() {
let (text, options) = unfill("foo bar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 7);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_simple_crlf() {
let (text, options) = unfill("foo\r\nbar");
assert_eq!(text, "foo bar");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::CRLF);
}
/// If mixed new line sequence is encountered, we want to fallback to `\n`
/// 1. it is the default
/// 2. it still matches both `\n` and `\r\n` unlike `\r\n` which will not match `\n`
#[test]
fn unfill_mixed_new_lines() {
let (text, options) = unfill("foo\r\nbar\nbaz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_trailing_newlines() {
let (text, options) = unfill("foo\nbar\n\n\n");
assert_eq!(text, "foo bar\n\n\n");
assert_eq!(options.width, 3);
}
#[test]
fn unfill_mixed_trailing_newlines() {
let (text, options) = unfill("foo\r\nbar\n\r\n\n");
assert_eq!(text, "foo bar\n\r\n\n");
assert_eq!(options.width, 3);
assert_eq!(options.line_ending, LineEnding::LF);
}
#[test]
fn unfill_trailing_crlf() {
let (text, options) = unfill("foo bar\r\n");
assert_eq!(text, "foo bar\r\n");
assert_eq!(options.width, 7);
assert_eq!(options.line_ending, LineEnding::CRLF);
}
#[test]
fn unfill_initial_indent() {
let (text, options) = unfill(" foo\nbar\nbaz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, " ");
}
#[test]
fn unfill_differing_indents() {
let (text, options) = unfill(" foo\n bar\n baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 7);
assert_eq!(options.initial_indent, " ");
assert_eq!(options.subsequent_indent, " ");
}
#[test]
fn unfill_list_item() {
let (text, options) = unfill("* foo\n bar\n baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, "* ");
assert_eq!(options.subsequent_indent, " ");
}
#[test]
fn unfill_multiple_char_prefix() {
let (text, options) = unfill(" // foo bar\n // baz\n // quux");
assert_eq!(text, "foo bar baz quux");
assert_eq!(options.width, 14);
assert_eq!(options.initial_indent, " // ");
assert_eq!(options.subsequent_indent, " // ");
}
#[test]
fn unfill_block_quote() {
let (text, options) = unfill("> foo\n> bar\n> baz");
assert_eq!(text, "foo bar baz");
assert_eq!(options.width, 5);
assert_eq!(options.initial_indent, "> ");
assert_eq!(options.subsequent_indent, "> ");
}
#[test]
fn unfill_only_prefixes_issue_466() {
// Test that we don't crash if the first line has only prefix
// chars *and* the second line is shorter than the first line.
let (text, options) = unfill("######\nfoo");
assert_eq!(text, " foo");
assert_eq!(options.width, 6);
assert_eq!(options.initial_indent, "######");
assert_eq!(options.subsequent_indent, "");
}
#[test]
fn unfill_whitespace() {
assert_eq!(unfill("foo bar").0, "foo bar");
}
#[test]
fn refill_convert_crlf() {
assert_eq!(
refill("foo\nbar\n", Options::new(5).line_ending(LineEnding::CRLF)),
"foo\r\nbar\n",
);
}
#[test]
fn wrap_columns_empty_text() {
assert_eq!(wrap_columns("", 1, 10, "| ", "", " |"), vec!["| |"]);
}
#[test]
fn wrap_columns_single_column() {
assert_eq!(
wrap_columns("Foo", 3, 30, "| ", " | ", " |"),
vec!["| Foo | | |"]
);
}
#[test]
fn wrap_columns_uneven_columns() {
// The gaps take up a total of 5 columns, so the columns are
// (21 - 5)/4 = 4 columns wide:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 21, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux|"]
);
// As the total width increases, the last column absorbs the
// excess width:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 24, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux |"]
);
// Finally, when the width is 25, the columns can be resized
// to a width of (25 - 5)/4 = 5 columns:
assert_eq!(
wrap_columns("Foo Bar Baz Quux", 4, 25, "|", "|", "|"),
vec!["|Foo |Bar |Baz |Quux |"]
);
}
#[test]
#[cfg(feature = "unicode-width")]
fn wrap_columns_with_emojis() {
assert_eq!(
wrap_columns(
"Words and a few emojis 😍 wrapped in ⓶ columns",
2,
30,
"✨ ",
" ⚽ ",
" 👀"
),
vec![
"✨ Words ⚽ wrapped in 👀",
"✨ and a few ⚽ ⓶ columns 👀",
"✨ emojis 😍 ⚽ 👀"
]
);
}
#[test]
fn wrap_columns_big_gaps() {
// The column width shrinks to 1 because the gaps take up all
// the space.
assert_eq!(
wrap_columns("xyz", 2, 10, "----> ", " !!! ", " <----"),
vec![
"----> x !!! z <----", //
"----> y !!! <----"
]
);
}
#[test]
#[should_panic]
fn wrap_columns_panic_with_zero_columns() {
wrap_columns("", 0, 10, "", "", "");
}
}
|
//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
extern crate libc;
/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
get_num_cpus()
}
#[cfg(windows)]
fn get_num_cpus() -> usize {
unsafe {
let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
libc::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
}
}
#[cfg(
any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd"
)
)]
fn get_num_cpus() -> usize {
use libc::{c_int, c_uint};
use libc::funcs::bsd44::sysctl;
use std::ptr;
//XXX: uplift to libc?
const CTL_HW: c_int = 6;
const HW_AVAILCPU: c_int = 25;
const HW_NCPU: c_int = 3;
let mut cpus: c_uint = 0;
let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];
unsafe {
sysctl(mib.as_mut_ptr(), 2,
&mut cpus as *mut _ as *mut _, &mut CPUS_SIZE as *mut _ as *mut _,
ptr::null_mut(), 0);
}
if cpus < 1 {
mib[1] = HW_NCPU;
unsafe {
sysctl(mib.as_mut_ptr(), 2,
&mut cpus as *mut _ as *mut _, &mut CPUS_SIZE as *mut _ as *mut _,
ptr::null_mut(), 0);
}
if cpus < 1 {
cpus = 1;
}
}
cpus as usize
}
#[cfg(
any(
target_os = "linux",
target_os = "nacl",
target_os = "macos",
target_os = "ios"
)
)]
fn get_num_cpus() -> usize {
unsafe {
libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as usize
}
}
#[cfg(target_os= "android")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(97) as usize
}
}
#[test]
fn lower_bound() {
assert!(get() > 0);
}
#[test]
fn upper_bound() {
assert!(get() < 236_451);
}
Fix the build on rumprun
//! Replaces the deprecated functionality of std::os::num_cpus.
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
extern crate libc;
/// Returns the number of CPUs of the current machine.
#[inline]
pub fn get() -> usize {
get_num_cpus()
}
#[cfg(windows)]
fn get_num_cpus() -> usize {
unsafe {
let mut sysinfo: libc::SYSTEM_INFO = ::std::mem::uninitialized();
libc::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
}
}
#[cfg(
any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "bitrig",
target_os = "openbsd",
target_os = "netbsd"
)
)]
fn get_num_cpus() -> usize {
use libc::{c_int, c_uint};
use libc::funcs::bsd44::sysctl;
use std::ptr;
//XXX: uplift to libc?
const CTL_HW: c_int = 6;
const HW_AVAILCPU: c_int = 25;
const HW_NCPU: c_int = 3;
let mut cpus: c_uint = 0;
let mut CPUS_SIZE = ::std::mem::size_of::<c_uint>();
let mut mib: [c_int; 4] = [CTL_HW, HW_AVAILCPU, 0, 0];
unsafe {
sysctl(mib.as_mut_ptr(), 2,
&mut cpus as *mut _ as *mut _, &mut CPUS_SIZE as *mut _ as *mut _,
ptr::null_mut(), 0);
}
if cpus < 1 {
mib[1] = HW_NCPU;
unsafe {
sysctl(mib.as_mut_ptr(), 2,
&mut cpus as *mut _ as *mut _, &mut CPUS_SIZE as *mut _ as *mut _,
ptr::null_mut(), 0);
}
if cpus < 1 {
cpus = 1;
}
}
cpus as usize
}
#[cfg(
any(
target_os = "linux",
target_os = "nacl",
target_os = "macos",
target_os = "ios"
)
)]
fn get_num_cpus() -> usize {
unsafe {
libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as usize
}
}
#[cfg(target_os= "android")]
fn get_num_cpus() -> usize {
//to-do: replace with libc::_SC_NPROCESSORS_ONLN once available
unsafe {
libc::sysconf(97) as usize
}
}
#[test]
fn lower_bound() {
assert!(get() > 0);
}
#[test]
fn upper_bound() {
assert!(get() < 236_451);
}
|
//! A library to read and write FLAC metadata tags.
#![crate_name = "metaflac"]
#![crate_type = "rlib"]
#![feature(macro_rules)]
#![warn(missing_docs)]
#![feature(phase)]
#[phase(plugin, link)] extern crate log;
extern crate audiotag;
pub use self::audiotag::{AudioTag, TagResult, TagError, ErrorKind};
pub use tag::FlacTag;
pub use block::{
Block, BlockType,
StreamInfo,
Application,
CueSheet, CueSheetTrack, CueSheetTrackIndex,
Picture, PictureType,
SeekTable, SeekPoint,
VorbisComment,
};
macro_rules! try_string {
($data:expr) => {
try!(String::from_utf8($data))
};
}
mod util;
mod tag;
mod block;
Respond to macro changes
//! A library to read and write FLAC metadata tags.
#![crate_name = "metaflac"]
#![crate_type = "rlib"]
#![warn(missing_docs)]
#[macro_use]
extern crate log;
extern crate audiotag;
pub use self::audiotag::{AudioTag, TagResult, TagError, ErrorKind};
pub use tag::FlacTag;
pub use block::{
Block, BlockType,
StreamInfo,
Application,
CueSheet, CueSheetTrack, CueSheetTrackIndex,
Picture, PictureType,
SeekTable, SeekPoint,
VorbisComment,
};
macro_rules! try_string {
($data:expr) => {
try!(String::from_utf8($data))
};
}
mod util;
mod tag;
mod block;
|
mod alias_dist;
use alias_dist::AliasDistribution;
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug)]
pub struct MarkovNode<T: Hash + Eq + Clone> {
pub value: T,
dist: AliasDistribution<T>,
}
impl<T: Hash + Eq + Clone> MarkovNode<T> {
pub fn new(value: T, counts: HashMap<T, usize>) -> MarkovNode<T> {
MarkovNode {
value: value.clone(),
dist: AliasDistribution::new(counts),
}
}
pub fn next(&self) -> &T {
self.dist.choice().unwrap()
}
pub fn entropy(&self) -> f64 {
self.dist.entropy
}
}
#[derive(Debug)]
pub struct PassphraseMarkovChain {
nodes: HashMap<String, MarkovNode<String>>,
starting_dist: AliasDistribution<String>,
}
impl PassphraseMarkovChain {
pub fn new<U: Iterator<Item=String> + Clone>(ngrams: U)
-> Result<PassphraseMarkovChain, &'static str> {
let mut transition_map = HashMap::new();
let mut starting_counts = HashMap::new();
let mut ngrams_copy = ngrams.clone().cycle();
ngrams_copy.next();
for (a, b) in ngrams.zip(ngrams_copy) {
if b.starts_with(" ") {
let count = starting_counts.entry(b.clone()).or_insert(0);
*count += 1
}
let transitions = transition_map.entry(a).or_insert(HashMap::new());
let count = transitions.entry(b).or_insert(0);
*count += 1;
};
let mut total_entropy: f64 = 0.0;
let mut nodes = HashMap::new();
for (ngram, transition_counts) in transition_map.into_iter() {
let node = MarkovNode::new(ngram.clone(), transition_counts);
total_entropy += node.entropy();
nodes.insert(ngram, node);
};
let starting_dist = AliasDistribution::new(starting_counts);
if total_entropy == 0.0 {
return Err("No entropy found in input.");
} else if starting_dist.entropy == 0.0 {
return Err("No start of word entropy found in input.");
};
Ok(PassphraseMarkovChain {
nodes: nodes,
starting_dist: starting_dist,
})
}
pub fn get_node(&self) -> &MarkovNode<String> {
self.nodes.get(self.starting_dist.choice().unwrap()).unwrap()
}
pub fn passphrase(&self, min_entropy: f64) -> (String, f64) {
let mut node = self.get_node();
let mut entropy = self.starting_dist.entropy;
let mut nodes = Vec::new();
loop {
nodes.push(node);
entropy += node.entropy();
if entropy >= min_entropy && node.value.ends_with(" ") { break };
node = self.nodes.get(node.next()).unwrap();
}
let tail = nodes.last().unwrap().value.chars().skip(1);
let chars = nodes.iter().map(|n| n.value.chars().next().unwrap()).chain(tail);
let passphrase = chars.collect::<String>().trim().to_string();
(passphrase, entropy)
}
}
Remove another unnecessary clone
mod alias_dist;
use alias_dist::AliasDistribution;
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug)]
pub struct MarkovNode<T: Hash + Eq> {
pub value: T,
dist: AliasDistribution<T>,
}
impl<T: Hash + Eq> MarkovNode<T> {
pub fn new(value: T, counts: HashMap<T, usize>) -> MarkovNode<T> {
MarkovNode {
value: value,
dist: AliasDistribution::new(counts),
}
}
pub fn next(&self) -> &T {
self.dist.choice().unwrap()
}
pub fn entropy(&self) -> f64 {
self.dist.entropy
}
}
#[derive(Debug)]
pub struct PassphraseMarkovChain {
nodes: HashMap<String, MarkovNode<String>>,
starting_dist: AliasDistribution<String>,
}
impl PassphraseMarkovChain {
pub fn new<U: Iterator<Item=String> + Clone>(ngrams: U)
-> Result<PassphraseMarkovChain, &'static str> {
let mut transition_map = HashMap::new();
let mut starting_counts = HashMap::new();
let mut ngrams_copy = ngrams.clone().cycle();
ngrams_copy.next();
for (a, b) in ngrams.zip(ngrams_copy) {
if b.starts_with(" ") {
let count = starting_counts.entry(b.clone()).or_insert(0);
*count += 1
}
let transitions = transition_map.entry(a).or_insert(HashMap::new());
let count = transitions.entry(b).or_insert(0);
*count += 1;
};
let mut total_entropy: f64 = 0.0;
let mut nodes = HashMap::new();
for (ngram, transition_counts) in transition_map.into_iter() {
let node = MarkovNode::new(ngram.clone(), transition_counts);
total_entropy += node.entropy();
nodes.insert(ngram, node);
};
let starting_dist = AliasDistribution::new(starting_counts);
if total_entropy == 0.0 {
return Err("No entropy found in input.");
} else if starting_dist.entropy == 0.0 {
return Err("No start of word entropy found in input.");
};
Ok(PassphraseMarkovChain {
nodes: nodes,
starting_dist: starting_dist,
})
}
pub fn get_node(&self) -> &MarkovNode<String> {
self.nodes.get(self.starting_dist.choice().unwrap()).unwrap()
}
pub fn passphrase(&self, min_entropy: f64) -> (String, f64) {
let mut node = self.get_node();
let mut entropy = self.starting_dist.entropy;
let mut nodes = Vec::new();
loop {
nodes.push(node);
entropy += node.entropy();
if entropy >= min_entropy && node.value.ends_with(" ") { break };
node = self.nodes.get(node.next()).unwrap();
}
let tail = nodes.last().unwrap().value.chars().skip(1);
let chars = nodes.iter().map(|n| n.value.chars().next().unwrap()).chain(tail);
let passphrase = chars.collect::<String>().trim().to_string();
(passphrase, entropy)
}
}
|
#![no_std]
#![crate_name = "raw_cpuid"]
#![crate_type = "lib"]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
mod tests;
#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate bitflags;
/// Provides `cpuid` on stable by linking against a C implementation.
#[cfg(not(feature = "use_arch"))]
mod native_cpuid {
use super::CpuIdResult;
extern "C" {
fn cpuid(a: *mut u32, b: *mut u32, c: *mut u32, d: *mut u32);
}
pub fn cpuid_count(mut eax: u32, mut ecx: u32) -> CpuIdResult {
let mut ebx = 0u32;
let mut edx = 0u32;
unsafe {
cpuid(&mut eax, &mut ebx, &mut ecx, &mut edx);
}
CpuIdResult { eax, ebx, ecx, edx }
}
}
/// Uses Rust's `cpuid` function from the `arch` module.
#[cfg(feature = "use_arch")]
mod native_cpuid {
use super::CpuIdResult;
#[cfg(target_arch = "x86")]
use core::arch::x86 as arch;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64 as arch;
pub fn cpuid_count(a: u32, c: u32) -> CpuIdResult {
let result = unsafe { self::arch::__cpuid_count(a, c) };
CpuIdResult {
eax: result.eax,
ebx: result.ebx,
ecx: result.ecx,
edx: result.edx,
}
}
}
use core::cmp::min;
use core::fmt;
use core::mem::transmute;
use core::slice;
use core::str;
#[cfg(not(test))]
mod std {
pub use core::ops;
pub use core::option;
}
/// Macro which queries cpuid directly.
///
/// First parameter is cpuid leaf (EAX register value),
/// second optional parameter is the subleaf (ECX register value).
macro_rules! cpuid {
($eax:expr) => {
$crate::native_cpuid::cpuid_count($eax as u32, 0)
};
($eax:expr, $ecx:expr) => {
$crate::native_cpuid::cpuid_count($eax as u32, $ecx as u32)
};
}
fn as_bytes(v: &u32) -> &[u8] {
let start = v as *const u32 as *const u8;
unsafe { slice::from_raw_parts(start, 4) }
}
fn get_bits(r: u32, from: u32, to: u32) -> u32 {
assert!(from <= 31);
assert!(to <= 31);
assert!(from <= to);
let mask = match to {
31 => 0xffffffff,
_ => (1 << (to + 1)) - 1,
};
(r & mask) >> from
}
macro_rules! check_flag {
($doc:meta, $fun:ident, $flags:ident, $flag:expr) => (
#[$doc]
pub fn $fun(&self) -> bool {
self.$flags.contains($flag)
}
)
}
macro_rules! is_bit_set {
($field:expr, $bit:expr) => {
$field & (1 << $bit) > 0
};
}
macro_rules! check_bit_fn {
($doc:meta, $fun:ident, $field:ident, $bit:expr) => (
#[$doc]
pub fn $fun(&self) -> bool {
is_bit_set!(self.$field, $bit)
}
)
}
/// Main type used to query for information about the CPU we're running on.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CpuId {
max_eax_value: u32,
}
/// Low-level data-structure to store result of cpuid instruction.
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CpuIdResult {
/// Return value EAX register
pub eax: u32,
/// Return value EBX register
pub ebx: u32,
/// Return value ECX register
pub ecx: u32,
/// Return value EDX register
pub edx: u32,
}
const EAX_VENDOR_INFO: u32 = 0x0;
const EAX_FEATURE_INFO: u32 = 0x1;
const EAX_CACHE_INFO: u32 = 0x2;
const EAX_PROCESSOR_SERIAL: u32 = 0x3;
const EAX_CACHE_PARAMETERS: u32 = 0x4;
const EAX_MONITOR_MWAIT_INFO: u32 = 0x5;
const EAX_THERMAL_POWER_INFO: u32 = 0x6;
const EAX_STRUCTURED_EXTENDED_FEATURE_INFO: u32 = 0x7;
const EAX_DIRECT_CACHE_ACCESS_INFO: u32 = 0x9;
const EAX_PERFORMANCE_MONITOR_INFO: u32 = 0xA;
const EAX_EXTENDED_TOPOLOGY_INFO: u32 = 0xB;
const EAX_EXTENDED_STATE_INFO: u32 = 0xD;
const EAX_RDT_MONITORING: u32 = 0xF;
const EAX_RDT_ALLOCATION: u32 = 0x10;
const EAX_SGX: u32 = 0x12;
const EAX_TRACE_INFO: u32 = 0x14;
const EAX_TIME_STAMP_COUNTER_INFO: u32 = 0x15;
const EAX_FREQUENCY_INFO: u32 = 0x16;
const EAX_SOC_VENDOR_INFO: u32 = 0x17;
const EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO: u32 = 0x18;
const EAX_EXTENDED_FUNCTION_INFO: u32 = 0x80000000;
impl CpuId {
/// Return new CPUID struct.
pub fn new() -> CpuId {
let res = cpuid!(EAX_VENDOR_INFO);
CpuId {
max_eax_value: res.eax,
}
}
fn leaf_is_supported(&self, val: u32) -> bool {
val <= self.max_eax_value
}
/// Return information about vendor.
/// This is typically a ASCII readable string such as
/// GenuineIntel for Intel CPUs or AuthenticAMD for AMD CPUs.
pub fn get_vendor_info(&self) -> Option<VendorInfo> {
if self.leaf_is_supported(EAX_VENDOR_INFO) {
let res = cpuid!(EAX_VENDOR_INFO);
Some(VendorInfo {
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Query a set of features that are available on this CPU.
pub fn get_feature_info(&self) -> Option<FeatureInfo> {
if self.leaf_is_supported(EAX_FEATURE_INFO) {
let res = cpuid!(EAX_FEATURE_INFO);
Some(FeatureInfo {
eax: res.eax,
ebx: res.ebx,
edx_ecx: FeatureInfoFlags {
bits: (((res.edx as u64) << 32) | (res.ecx as u64)),
},
})
} else {
None
}
}
/// Query basic information about caches. This will just return an index
/// into a static table of cache descriptions (see `CACHE_INFO_TABLE`).
pub fn get_cache_info(&self) -> Option<CacheInfoIter> {
if self.leaf_is_supported(EAX_CACHE_INFO) {
let res = cpuid!(EAX_CACHE_INFO);
Some(CacheInfoIter {
current: 1,
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Retrieve serial number of processor.
pub fn get_processor_serial(&self) -> Option<ProcessorSerial> {
if self.leaf_is_supported(EAX_PROCESSOR_SERIAL) {
let res = cpuid!(EAX_PROCESSOR_SERIAL);
Some(ProcessorSerial {
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Retrieve more elaborate information about caches (as opposed
/// to `get_cache_info`). This will tell us about associativity,
/// set size, line size etc. for each level of the cache hierarchy.
pub fn get_cache_parameters(&self) -> Option<CacheParametersIter> {
if self.leaf_is_supported(EAX_CACHE_PARAMETERS) {
Some(CacheParametersIter { current: 0 })
} else {
None
}
}
/// Information about how monitor/mwait works on this CPU.
pub fn get_monitor_mwait_info(&self) -> Option<MonitorMwaitInfo> {
if self.leaf_is_supported(EAX_MONITOR_MWAIT_INFO) {
let res = cpuid!(EAX_MONITOR_MWAIT_INFO);
Some(MonitorMwaitInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Query information about thermal and power management features of the CPU.
pub fn get_thermal_power_info(&self) -> Option<ThermalPowerInfo> {
if self.leaf_is_supported(EAX_THERMAL_POWER_INFO) {
let res = cpuid!(EAX_THERMAL_POWER_INFO);
Some(ThermalPowerInfo {
eax: ThermalPowerFeaturesEax { bits: res.eax },
ebx: res.ebx,
ecx: ThermalPowerFeaturesEcx { bits: res.ecx },
edx: res.edx,
})
} else {
None
}
}
/// Find out about more features supported by this CPU.
pub fn get_extended_feature_info(&self) -> Option<ExtendedFeatures> {
if self.leaf_is_supported(EAX_STRUCTURED_EXTENDED_FEATURE_INFO) {
let res = cpuid!(EAX_STRUCTURED_EXTENDED_FEATURE_INFO);
assert!(res.eax == 0);
Some(ExtendedFeatures {
eax: res.eax,
ebx: ExtendedFeaturesEbx { bits: res.ebx },
ecx: ExtendedFeaturesEcx { bits: res.ecx },
edx: res.edx,
})
} else {
None
}
}
/// Direct cache access info.
pub fn get_direct_cache_access_info(&self) -> Option<DirectCacheAccessInfo> {
if self.leaf_is_supported(EAX_DIRECT_CACHE_ACCESS_INFO) {
let res = cpuid!(EAX_DIRECT_CACHE_ACCESS_INFO);
Some(DirectCacheAccessInfo { eax: res.eax })
} else {
None
}
}
/// Info about performance monitoring (how many counters etc.).
pub fn get_performance_monitoring_info(&self) -> Option<PerformanceMonitoringInfo> {
if self.leaf_is_supported(EAX_PERFORMANCE_MONITOR_INFO) {
let res = cpuid!(EAX_PERFORMANCE_MONITOR_INFO);
Some(PerformanceMonitoringInfo {
eax: res.eax,
ebx: PerformanceMonitoringFeaturesEbx { bits: res.ebx },
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Information about topology (how many cores and what kind of cores).
pub fn get_extended_topology_info(&self) -> Option<ExtendedTopologyIter> {
if self.leaf_is_supported(EAX_EXTENDED_TOPOLOGY_INFO) {
Some(ExtendedTopologyIter { level: 0 })
} else {
None
}
}
/// Information for saving/restoring extended register state.
pub fn get_extended_state_info(&self) -> Option<ExtendedStateInfo> {
if self.leaf_is_supported(EAX_EXTENDED_STATE_INFO) {
let res = cpuid!(EAX_EXTENDED_STATE_INFO, 0);
let res1 = cpuid!(EAX_EXTENDED_STATE_INFO, 1);
Some(ExtendedStateInfo {
eax: ExtendedStateInfoXCR0Flags { bits: res.eax },
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
eax1: res1.eax,
ebx1: res1.ebx,
ecx1: ExtendedStateInfoXSSFlags { bits: res1.ecx },
edx1: res1.edx,
})
} else {
None
}
}
/// Quality of service informations.
pub fn get_rdt_monitoring_info(&self) -> Option<RdtMonitoringInfo> {
let res = cpuid!(EAX_RDT_MONITORING, 0);
if self.leaf_is_supported(EAX_RDT_MONITORING) {
Some(RdtMonitoringInfo {
ebx: res.ebx,
edx: res.edx,
})
} else {
None
}
}
/// Quality of service enforcement information.
pub fn get_rdt_allocation_info(&self) -> Option<RdtAllocationInfo> {
let res = cpuid!(EAX_RDT_ALLOCATION, 0);
if self.leaf_is_supported(EAX_RDT_ALLOCATION) {
Some(RdtAllocationInfo { ebx: res.ebx })
} else {
None
}
}
pub fn get_sgx_info(&self) -> Option<SgxInfo> {
// Leaf 12H sub-leaf 0 (ECX = 0) is supported if CPUID.(EAX=07H, ECX=0H):EBX[SGX] = 1.
self.get_extended_feature_info().and_then(|info| {
if self.leaf_is_supported(EAX_SGX) && info.has_sgx() {
let res = cpuid!(EAX_SGX, 0);
let res1 = cpuid!(EAX_SGX, 1);
Some(SgxInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
eax1: res1.eax,
ebx1: res1.ebx,
ecx1: res1.ecx,
edx1: res1.edx,
})
} else {
None
}
})
}
/// Intel Processor Trace Enumeration Information.
pub fn get_processor_trace_info(&self) -> Option<ProcessorTraceInfo> {
let res = cpuid!(EAX_TRACE_INFO, 0);
if self.leaf_is_supported(EAX_TRACE_INFO) {
let res1 = if res.eax >= 1 {
Some(cpuid!(EAX_TRACE_INFO, 1))
} else {
None
};
Some(ProcessorTraceInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
leaf1: res1,
})
} else {
None
}
}
/// Time Stamp Counter/Core Crystal Clock Information.
pub fn get_tsc_info(&self) -> Option<TscInfo> {
let res = cpuid!(EAX_TIME_STAMP_COUNTER_INFO, 0);
if self.leaf_is_supported(EAX_TIME_STAMP_COUNTER_INFO) {
Some(TscInfo {
eax: res.eax,
ebx: res.ebx,
})
} else {
None
}
}
/// Processor Frequency Information.
pub fn get_processor_frequency_info(&self) -> Option<ProcessorFrequencyInfo> {
let res = cpuid!(EAX_FREQUENCY_INFO, 0);
if self.leaf_is_supported(EAX_FREQUENCY_INFO) {
Some(ProcessorFrequencyInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
})
} else {
None
}
}
pub fn deterministic_address_translation_info(&self) -> Option<DatIter> {
if self.leaf_is_supported(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO) {
let res = cpuid!(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO, 0);
Some(DatIter {
current: 0,
count: res.eax,
})
} else {
None
}
}
pub fn get_soc_vendor_info(&self) -> Option<SoCVendorInfo> {
let res = cpuid!(EAX_SOC_VENDOR_INFO, 0);
if self.leaf_is_supported(EAX_SOC_VENDOR_INFO) {
Some(SoCVendorInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Extended functionality of CPU described here (including more supported features).
/// This also contains a more detailed CPU model identifier.
pub fn get_extended_function_info(&self) -> Option<ExtendedFunctionInfo> {
let res = cpuid!(EAX_EXTENDED_FUNCTION_INFO);
if res.eax == 0 {
return None;
}
let mut ef = ExtendedFunctionInfo {
max_eax_value: res.eax - EAX_EXTENDED_FUNCTION_INFO,
data: [
CpuIdResult {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
],
};
let max_eax_value = min(ef.max_eax_value + 1, ef.data.len() as u32);
for i in 1..max_eax_value {
ef.data[i as usize] = cpuid!(EAX_EXTENDED_FUNCTION_INFO + i);
}
Some(ef)
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct VendorInfo {
ebx: u32,
edx: u32,
ecx: u32,
}
impl VendorInfo {
/// Return vendor identification as human readable string.
pub fn as_string<'a>(&'a self) -> &'a str {
unsafe {
let brand_string_start = self as *const VendorInfo as *const u8;
let slice = slice::from_raw_parts(brand_string_start, 3 * 4);
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
}
}
}
/// Used to iterate over cache information contained in cpuid instruction.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheInfoIter {
current: u32,
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl Iterator for CacheInfoIter {
type Item = CacheInfo;
/// Iterate over all cache information.
fn next(&mut self) -> Option<CacheInfo> {
// Every byte of the 4 register values returned by cpuid
// can contain information about a cache (except the
// very first one).
if self.current >= 4 * 4 {
return None;
}
let reg_index = self.current % 4;
let byte_index = self.current / 4;
let reg = match reg_index {
0 => self.eax,
1 => self.ebx,
2 => self.ecx,
3 => self.edx,
_ => unreachable!(),
};
let byte = as_bytes(®)[byte_index as usize];
if byte == 0 {
self.current += 1;
return self.next();
}
for cache_info in CACHE_INFO_TABLE.into_iter() {
if cache_info.num == byte {
self.current += 1;
return Some(*cache_info);
}
}
None
}
}
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum CacheInfoType {
GENERAL,
CACHE,
TLB,
STLB,
DTLB,
PREFETCH,
}
impl Default for CacheInfoType {
fn default() -> CacheInfoType {
CacheInfoType::GENERAL
}
}
/// Describes any kind of cache (TLB, Data and Instruction caches plus prefetchers).
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheInfo {
/// Number as retrieved from cpuid
pub num: u8,
/// Cache type
pub typ: CacheInfoType,
}
impl CacheInfo {
/// Description of the cache (from Intel Manual)
pub fn desc(&self) -> &'static str {
match self.num {
0x00 => "Null descriptor, this byte contains no information",
0x01 => "Instruction TLB: 4 KByte pages, 4-way set associative, 32 entries",
0x02 => "Instruction TLB: 4 MByte pages, fully associative, 2 entries",
0x03 => "Data TLB: 4 KByte pages, 4-way set associative, 64 entries",
0x04 => "Data TLB: 4 MByte pages, 4-way set associative, 8 entries",
0x05 => "Data TLB1: 4 MByte pages, 4-way set associative, 32 entries",
0x06 => "1st-level instruction cache: 8 KBytes, 4-way set associative, 32 byte line size",
0x08 => "1st-level instruction cache: 16 KBytes, 4-way set associative, 32 byte line size",
0x09 => "1st-level instruction cache: 32KBytes, 4-way set associative, 64 byte line size",
0x0A => "1st-level data cache: 8 KBytes, 2-way set associative, 32 byte line size",
0x0B => "Instruction TLB: 4 MByte pages, 4-way set associative, 4 entries",
0x0C => "1st-level data cache: 16 KBytes, 4-way set associative, 32 byte line size",
0x0D => "1st-level data cache: 16 KBytes, 4-way set associative, 64 byte line size",
0x0E => "1st-level data cache: 24 KBytes, 6-way set associative, 64 byte line size",
0x1D => "2nd-level cache: 128 KBytes, 2-way set associative, 64 byte line size",
0x21 => "2nd-level cache: 256 KBytes, 8-way set associative, 64 byte line size",
0x22 => "3rd-level cache: 512 KBytes, 4-way set associative, 64 byte line size, 2 lines per sector",
0x23 => "3rd-level cache: 1 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x24 => "2nd-level cache: 1 MBytes, 16-way set associative, 64 byte line size",
0x25 => "3rd-level cache: 2 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x29 => "3rd-level cache: 4 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x2C => "1st-level data cache: 32 KBytes, 8-way set associative, 64 byte line size",
0x30 => "1st-level instruction cache: 32 KBytes, 8-way set associative, 64 byte line size",
0x40 => "No 2nd-level cache or, if processor contains a valid 2nd-level cache, no 3rd-level cache",
0x41 => "2nd-level cache: 128 KBytes, 4-way set associative, 32 byte line size",
0x42 => "2nd-level cache: 256 KBytes, 4-way set associative, 32 byte line size",
0x43 => "2nd-level cache: 512 KBytes, 4-way set associative, 32 byte line size",
0x44 => "2nd-level cache: 1 MByte, 4-way set associative, 32 byte line size",
0x45 => "2nd-level cache: 2 MByte, 4-way set associative, 32 byte line size",
0x46 => "3rd-level cache: 4 MByte, 4-way set associative, 64 byte line size",
0x47 => "3rd-level cache: 8 MByte, 8-way set associative, 64 byte line size",
0x48 => "2nd-level cache: 3MByte, 12-way set associative, 64 byte line size",
0x49 => "3rd-level cache: 4MB, 16-way set associative, 64-byte line size (Intel Xeon processor MP, Family 0FH, Model 06H); 2nd-level cache: 4 MByte, 16-way set ssociative, 64 byte line size",
0x4A => "3rd-level cache: 6MByte, 12-way set associative, 64 byte line size",
0x4B => "3rd-level cache: 8MByte, 16-way set associative, 64 byte line size",
0x4C => "3rd-level cache: 12MByte, 12-way set associative, 64 byte line size",
0x4D => "3rd-level cache: 16MByte, 16-way set associative, 64 byte line size",
0x4E => "2nd-level cache: 6MByte, 24-way set associative, 64 byte line size",
0x4F => "Instruction TLB: 4 KByte pages, 32 entries",
0x50 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 64 entries",
0x51 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 128 entries",
0x52 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 256 entries",
0x55 => "Instruction TLB: 2-MByte or 4-MByte pages, fully associative, 7 entries",
0x56 => "Data TLB0: 4 MByte pages, 4-way set associative, 16 entries",
0x57 => "Data TLB0: 4 KByte pages, 4-way associative, 16 entries",
0x59 => "Data TLB0: 4 KByte pages, fully associative, 16 entries",
0x5A => "Data TLB0: 2-MByte or 4 MByte pages, 4-way set associative, 32 entries",
0x5B => "Data TLB: 4 KByte and 4 MByte pages, 64 entries",
0x5C => "Data TLB: 4 KByte and 4 MByte pages,128 entries",
0x5D => "Data TLB: 4 KByte and 4 MByte pages,256 entries",
0x60 => "1st-level data cache: 16 KByte, 8-way set associative, 64 byte line size",
0x61 => "Instruction TLB: 4 KByte pages, fully associative, 48 entries",
0x63 => "Data TLB: 2 MByte or 4 MByte pages, 4-way set associative, 32 entries and a separate array with 1 GByte pages, 4-way set associative, 4 entries",
0x64 => "Data TLB: 4 KByte pages, 4-way set associative, 512 entries",
0x66 => "1st-level data cache: 8 KByte, 4-way set associative, 64 byte line size",
0x67 => "1st-level data cache: 16 KByte, 4-way set associative, 64 byte line size",
0x68 => "1st-level data cache: 32 KByte, 4-way set associative, 64 byte line size",
0x6A => "uTLB: 4 KByte pages, 8-way set associative, 64 entries",
0x6B => "DTLB: 4 KByte pages, 8-way set associative, 256 entries",
0x6C => "DTLB: 2M/4M pages, 8-way set associative, 128 entries",
0x6D => "DTLB: 1 GByte pages, fully associative, 16 entries",
0x70 => "Trace cache: 12 K-μop, 8-way set associative",
0x71 => "Trace cache: 16 K-μop, 8-way set associative",
0x72 => "Trace cache: 32 K-μop, 8-way set associative",
0x76 => "Instruction TLB: 2M/4M pages, fully associative, 8 entries",
0x78 => "2nd-level cache: 1 MByte, 4-way set associative, 64byte line size",
0x79 => "2nd-level cache: 128 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7A => "2nd-level cache: 256 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7B => "2nd-level cache: 512 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7C => "2nd-level cache: 1 MByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7D => "2nd-level cache: 2 MByte, 8-way set associative, 64byte line size",
0x7F => "2nd-level cache: 512 KByte, 2-way set associative, 64-byte line size",
0x80 => "2nd-level cache: 512 KByte, 8-way set associative, 64-byte line size",
0x82 => "2nd-level cache: 256 KByte, 8-way set associative, 32 byte line size",
0x83 => "2nd-level cache: 512 KByte, 8-way set associative, 32 byte line size",
0x84 => "2nd-level cache: 1 MByte, 8-way set associative, 32 byte line size",
0x85 => "2nd-level cache: 2 MByte, 8-way set associative, 32 byte line size",
0x86 => "2nd-level cache: 512 KByte, 4-way set associative, 64 byte line size",
0x87 => "2nd-level cache: 1 MByte, 8-way set associative, 64 byte line size",
0xA0 => "DTLB: 4k pages, fully associative, 32 entries",
0xB0 => "Instruction TLB: 4 KByte pages, 4-way set associative, 128 entries",
0xB1 => "Instruction TLB: 2M pages, 4-way, 8 entries or 4M pages, 4-way, 4 entries",
0xB2 => "Instruction TLB: 4KByte pages, 4-way set associative, 64 entries",
0xB3 => "Data TLB: 4 KByte pages, 4-way set associative, 128 entries",
0xB4 => "Data TLB1: 4 KByte pages, 4-way associative, 256 entries",
0xB5 => "Instruction TLB: 4KByte pages, 8-way set associative, 64 entries",
0xB6 => "Instruction TLB: 4KByte pages, 8-way set associative, 128 entries",
0xBA => "Data TLB1: 4 KByte pages, 4-way associative, 64 entries",
0xC0 => "Data TLB: 4 KByte and 4 MByte pages, 4-way associative, 8 entries",
0xC1 => "Shared 2nd-Level TLB: 4 KByte/2MByte pages, 8-way associative, 1024 entries",
0xC2 => "DTLB: 2 MByte/$MByte pages, 4-way associative, 16 entries",
0xC3 => "Shared 2nd-Level TLB: 4 KByte /2 MByte pages, 6-way associative, 1536 entries. Also 1GBbyte pages, 4-way, 16 entries.",
0xC4 => "DTLB: 2M/4M Byte pages, 4-way associative, 32 entries",
0xCA => "Shared 2nd-Level TLB: 4 KByte pages, 4-way associative, 512 entries",
0xD0 => "3rd-level cache: 512 KByte, 4-way set associative, 64 byte line size",
0xD1 => "3rd-level cache: 1 MByte, 4-way set associative, 64 byte line size",
0xD2 => "3rd-level cache: 2 MByte, 4-way set associative, 64 byte line size",
0xD6 => "3rd-level cache: 1 MByte, 8-way set associative, 64 byte line size",
0xD7 => "3rd-level cache: 2 MByte, 8-way set associative, 64 byte line size",
0xD8 => "3rd-level cache: 4 MByte, 8-way set associative, 64 byte line size",
0xDC => "3rd-level cache: 1.5 MByte, 12-way set associative, 64 byte line size",
0xDD => "3rd-level cache: 3 MByte, 12-way set associative, 64 byte line size",
0xDE => "3rd-level cache: 6 MByte, 12-way set associative, 64 byte line size",
0xE2 => "3rd-level cache: 2 MByte, 16-way set associative, 64 byte line size",
0xE3 => "3rd-level cache: 4 MByte, 16-way set associative, 64 byte line size",
0xE4 => "3rd-level cache: 8 MByte, 16-way set associative, 64 byte line size",
0xEA => "3rd-level cache: 12MByte, 24-way set associative, 64 byte line size",
0xEB => "3rd-level cache: 18MByte, 24-way set associative, 64 byte line size",
0xEC => "3rd-level cache: 24MByte, 24-way set associative, 64 byte line size",
0xF0 => "64-Byte prefetching",
0xF1 => "128-Byte prefetching",
0xFE => "CPUID leaf 2 does not report TLB descriptor information; use CPUID leaf 18H to query TLB and other address translation parameters.",
0xFF => "CPUID leaf 2 does not report cache descriptor information, use CPUID leaf 4 to query cache parameters",
_ => "Unknown cache type!"
}
}
}
impl fmt::Display for CacheInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let typ = match self.typ {
CacheInfoType::GENERAL => "N/A",
CacheInfoType::CACHE => "Cache",
CacheInfoType::TLB => "TLB",
CacheInfoType::STLB => "STLB",
CacheInfoType::DTLB => "DTLB",
CacheInfoType::PREFETCH => "Prefetcher",
};
write!(f, "{:x}:\t {}: {}", self.num, typ, self.desc())
}
}
/// This table is taken from Intel manual (Section CPUID instruction).
pub const CACHE_INFO_TABLE: [CacheInfo; 108] = [
CacheInfo {
num: 0x00,
typ: CacheInfoType::GENERAL,
},
CacheInfo {
num: 0x01,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x02,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x03,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x04,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x05,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x06,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x08,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x09,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0B,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x0C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0E,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x21,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x22,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x23,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x24,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x25,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x29,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x2C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x30,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x40,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x41,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x42,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x43,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x44,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x45,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x46,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x47,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x48,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x49,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4E,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4F,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x50,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x51,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x52,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x55,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x56,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x57,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x59,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5A,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5B,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5C,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5D,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x60,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x61,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x63,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x66,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x67,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x68,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x70,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x71,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x72,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x76,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x78,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x79,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7F,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x80,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x82,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x83,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x84,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x85,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x86,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x87,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xB0,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB1,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB2,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB3,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB4,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB5,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB6,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xBA,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xC0,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xC1,
typ: CacheInfoType::STLB,
},
CacheInfo {
num: 0xC2,
typ: CacheInfoType::DTLB,
},
CacheInfo {
num: 0xCA,
typ: CacheInfoType::STLB,
},
CacheInfo {
num: 0xD0,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD1,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD2,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD6,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD7,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD8,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDC,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDD,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDE,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE2,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE3,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE4,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEA,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEB,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEC,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xF0,
typ: CacheInfoType::PREFETCH,
},
CacheInfo {
num: 0xF1,
typ: CacheInfoType::PREFETCH,
},
CacheInfo {
num: 0xFE,
typ: CacheInfoType::GENERAL,
},
CacheInfo {
num: 0xFF,
typ: CacheInfoType::GENERAL,
},
];
impl fmt::Display for VendorInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_string())
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorSerial {
ecx: u32,
edx: u32,
}
impl ProcessorSerial {
/// Bits 00-31 of 96 bit processor serial number.
/// (Available in Pentium III processor only; otherwise, the value in this register is reserved.)
pub fn serial_lower(&self) -> u32 {
self.ecx
}
/// Bits 32-63 of 96 bit processor serial number.
/// (Available in Pentium III processor only; otherwise, the value in this register is reserved.)
pub fn serial_middle(&self) -> u32 {
self.edx
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct FeatureInfo {
eax: u32,
ebx: u32,
edx_ecx: FeatureInfoFlags,
}
impl FeatureInfo {
/// Version Information: Extended Family
pub fn extended_family_id(&self) -> u8 {
get_bits(self.eax, 20, 27) as u8
}
/// Version Information: Extended Model
pub fn extended_model_id(&self) -> u8 {
get_bits(self.eax, 16, 19) as u8
}
/// Version Information: Family
pub fn family_id(&self) -> u8 {
get_bits(self.eax, 8, 11) as u8
}
/// Version Information: Model
pub fn model_id(&self) -> u8 {
get_bits(self.eax, 4, 7) as u8
}
/// Version Information: Stepping ID
pub fn stepping_id(&self) -> u8 {
get_bits(self.eax, 0, 3) as u8
}
/// Brand Index
pub fn brand_index(&self) -> u8 {
get_bits(self.ebx, 0, 7) as u8
}
/// CLFLUSH line size (Value ∗ 8 = cache line size in bytes)
pub fn cflush_cache_line_size(&self) -> u8 {
get_bits(self.ebx, 8, 15) as u8
}
/// Initial APIC ID
pub fn initial_local_apic_id(&self) -> u8 {
get_bits(self.ebx, 24, 31) as u8
}
/// Maximum number of addressable IDs for logical processors in this physical package.
pub fn max_logical_processor_ids(&self) -> u8 {
get_bits(self.ebx, 16, 23) as u8
}
check_flag!(
doc = "Streaming SIMD Extensions 3 (SSE3). A value of 1 indicates the processor \
supports this technology.",
has_sse3,
edx_ecx,
FeatureInfoFlags::SSE3
);
check_flag!(
doc = "PCLMULQDQ. A value of 1 indicates the processor supports the PCLMULQDQ \
instruction",
has_pclmulqdq,
edx_ecx,
FeatureInfoFlags::PCLMULQDQ
);
check_flag!(
doc = "64-bit DS Area. A value of 1 indicates the processor supports DS area \
using 64-bit layout",
has_ds_area,
edx_ecx,
FeatureInfoFlags::DTES64
);
check_flag!(
doc = "MONITOR/MWAIT. A value of 1 indicates the processor supports this feature.",
has_monitor_mwait,
edx_ecx,
FeatureInfoFlags::MONITOR
);
check_flag!(
doc = "CPL Qualified Debug Store. A value of 1 indicates the processor supports \
the extensions to the Debug Store feature to allow for branch message \
storage qualified by CPL.",
has_cpl,
edx_ecx,
FeatureInfoFlags::DSCPL
);
check_flag!(
doc = "Virtual Machine Extensions. A value of 1 indicates that the processor \
supports this technology.",
has_vmx,
edx_ecx,
FeatureInfoFlags::VMX
);
check_flag!(
doc = "Safer Mode Extensions. A value of 1 indicates that the processor supports \
this technology. See Chapter 5, Safer Mode Extensions Reference.",
has_smx,
edx_ecx,
FeatureInfoFlags::SMX
);
check_flag!(
doc = "Enhanced Intel SpeedStep® technology. A value of 1 indicates that the \
processor supports this technology.",
has_eist,
edx_ecx,
FeatureInfoFlags::EIST
);
check_flag!(
doc = "Thermal Monitor 2. A value of 1 indicates whether the processor supports \
this technology.",
has_tm2,
edx_ecx,
FeatureInfoFlags::TM2
);
check_flag!(
doc = "A value of 1 indicates the presence of the Supplemental Streaming SIMD \
Extensions 3 (SSSE3). A value of 0 indicates the instruction extensions \
are not present in the processor",
has_ssse3,
edx_ecx,
FeatureInfoFlags::SSSE3
);
check_flag!(
doc = "L1 Context ID. A value of 1 indicates the L1 data cache mode can be set \
to either adaptive mode or shared mode. A value of 0 indicates this \
feature is not supported. See definition of the IA32_MISC_ENABLE MSR Bit \
24 (L1 Data Cache Context Mode) for details.",
has_cnxtid,
edx_ecx,
FeatureInfoFlags::CNXTID
);
check_flag!(
doc = "A value of 1 indicates the processor supports FMA extensions using YMM \
state.",
has_fma,
edx_ecx,
FeatureInfoFlags::FMA
);
check_flag!(
doc = "CMPXCHG16B Available. A value of 1 indicates that the feature is \
available. See the CMPXCHG8B/CMPXCHG16B Compare and Exchange Bytes \
section. 14",
has_cmpxchg16b,
edx_ecx,
FeatureInfoFlags::CMPXCHG16B
);
check_flag!(
doc = "Perfmon and Debug Capability: A value of 1 indicates the processor \
supports the performance and debug feature indication MSR \
IA32_PERF_CAPABILITIES.",
has_pdcm,
edx_ecx,
FeatureInfoFlags::PDCM
);
check_flag!(
doc = "Process-context identifiers. A value of 1 indicates that the processor \
supports PCIDs and the software may set CR4.PCIDE to 1.",
has_pcid,
edx_ecx,
FeatureInfoFlags::PCID
);
check_flag!(
doc = "A value of 1 indicates the processor supports the ability to prefetch \
data from a memory mapped device.",
has_dca,
edx_ecx,
FeatureInfoFlags::DCA
);
check_flag!(
doc = "A value of 1 indicates that the processor supports SSE4.1.",
has_sse41,
edx_ecx,
FeatureInfoFlags::SSE41
);
check_flag!(
doc = "A value of 1 indicates that the processor supports SSE4.2.",
has_sse42,
edx_ecx,
FeatureInfoFlags::SSE42
);
check_flag!(
doc = "A value of 1 indicates that the processor supports x2APIC feature.",
has_x2apic,
edx_ecx,
FeatureInfoFlags::X2APIC
);
check_flag!(
doc = "A value of 1 indicates that the processor supports MOVBE instruction.",
has_movbe,
edx_ecx,
FeatureInfoFlags::MOVBE
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the POPCNT instruction.",
has_popcnt,
edx_ecx,
FeatureInfoFlags::POPCNT
);
check_flag!(
doc = "A value of 1 indicates that the processors local APIC timer supports \
one-shot operation using a TSC deadline value.",
has_tsc_deadline,
edx_ecx,
FeatureInfoFlags::TSC_DEADLINE
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the AESNI instruction \
extensions.",
has_aesni,
edx_ecx,
FeatureInfoFlags::AESNI
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the XSAVE/XRSTOR \
processor extended states feature, the XSETBV/XGETBV instructions, and \
XCR0.",
has_xsave,
edx_ecx,
FeatureInfoFlags::XSAVE
);
check_flag!(
doc = "A value of 1 indicates that the OS has enabled XSETBV/XGETBV instructions \
to access XCR0, and support for processor extended state management using \
XSAVE/XRSTOR.",
has_oxsave,
edx_ecx,
FeatureInfoFlags::OSXSAVE
);
check_flag!(
doc = "A value of 1 indicates the processor supports the AVX instruction \
extensions.",
has_avx,
edx_ecx,
FeatureInfoFlags::AVX
);
check_flag!(
doc = "A value of 1 indicates that processor supports 16-bit floating-point \
conversion instructions.",
has_f16c,
edx_ecx,
FeatureInfoFlags::F16C
);
check_flag!(
doc = "A value of 1 indicates that processor supports RDRAND instruction.",
has_rdrand,
edx_ecx,
FeatureInfoFlags::RDRAND
);
check_flag!(
doc = "Floating Point Unit On-Chip. The processor contains an x87 FPU.",
has_fpu,
edx_ecx,
FeatureInfoFlags::FPU
);
check_flag!(
doc = "Virtual 8086 Mode Enhancements. Virtual 8086 mode enhancements, including \
CR4.VME for controlling the feature, CR4.PVI for protected mode virtual \
interrupts, software interrupt indirection, expansion of the TSS with the \
software indirection bitmap, and EFLAGS.VIF and EFLAGS.VIP flags.",
has_vme,
edx_ecx,
FeatureInfoFlags::VME
);
check_flag!(
doc = "Debugging Extensions. Support for I/O breakpoints, including CR4.DE for \
controlling the feature, and optional trapping of accesses to DR4 and DR5.",
has_de,
edx_ecx,
FeatureInfoFlags::DE
);
check_flag!(
doc = "Page Size Extension. Large pages of size 4 MByte are supported, including \
CR4.PSE for controlling the feature, the defined dirty bit in PDE (Page \
Directory Entries), optional reserved bit trapping in CR3, PDEs, and PTEs.",
has_pse,
edx_ecx,
FeatureInfoFlags::PSE
);
check_flag!(
doc = "Time Stamp Counter. The RDTSC instruction is supported, including CR4.TSD \
for controlling privilege.",
has_tsc,
edx_ecx,
FeatureInfoFlags::TSC
);
check_flag!(
doc = "Model Specific Registers RDMSR and WRMSR Instructions. The RDMSR and \
WRMSR instructions are supported. Some of the MSRs are implementation \
dependent.",
has_msr,
edx_ecx,
FeatureInfoFlags::MSR
);
check_flag!(
doc = "Physical Address Extension. Physical addresses greater than 32 bits are \
supported: extended page table entry formats, an extra level in the page \
translation tables is defined, 2-MByte pages are supported instead of 4 \
Mbyte pages if PAE bit is 1.",
has_pae,
edx_ecx,
FeatureInfoFlags::PAE
);
check_flag!(
doc = "Machine Check Exception. Exception 18 is defined for Machine Checks, \
including CR4.MCE for controlling the feature. This feature does not \
define the model-specific implementations of machine-check error logging, \
reporting, and processor shutdowns. Machine Check exception handlers may \
have to depend on processor version to do model specific processing of \
the exception, or test for the presence of the Machine Check feature.",
has_mce,
edx_ecx,
FeatureInfoFlags::MCE
);
check_flag!(
doc = "CMPXCHG8B Instruction. The compare-and-exchange 8 bytes (64 bits) \
instruction is supported (implicitly locked and atomic).",
has_cmpxchg8b,
edx_ecx,
FeatureInfoFlags::CX8
);
check_flag!(
doc = "APIC On-Chip. The processor contains an Advanced Programmable Interrupt \
Controller (APIC), responding to memory mapped commands in the physical \
address range FFFE0000H to FFFE0FFFH (by default - some processors permit \
the APIC to be relocated).",
has_apic,
edx_ecx,
FeatureInfoFlags::APIC
);
check_flag!(
doc = "SYSENTER and SYSEXIT Instructions. The SYSENTER and SYSEXIT and \
associated MSRs are supported.",
has_sysenter_sysexit,
edx_ecx,
FeatureInfoFlags::SEP
);
check_flag!(
doc = "Memory Type Range Registers. MTRRs are supported. The MTRRcap MSR \
contains feature bits that describe what memory types are supported, how \
many variable MTRRs are supported, and whether fixed MTRRs are supported.",
has_mtrr,
edx_ecx,
FeatureInfoFlags::MTRR
);
check_flag!(
doc = "Page Global Bit. The global bit is supported in paging-structure entries \
that map a page, indicating TLB entries that are common to different \
processes and need not be flushed. The CR4.PGE bit controls this feature.",
has_pge,
edx_ecx,
FeatureInfoFlags::PGE
);
check_flag!(
doc = "Machine Check Architecture. A value of 1 indicates the Machine Check \
Architecture of reporting machine errors is supported. The MCG_CAP MSR \
contains feature bits describing how many banks of error reporting MSRs \
are supported.",
has_mca,
edx_ecx,
FeatureInfoFlags::MCA
);
check_flag!(
doc = "Conditional Move Instructions. The conditional move instruction CMOV is \
supported. In addition, if x87 FPU is present as indicated by the \
CPUID.FPU feature bit, then the FCOMI and FCMOV instructions are supported",
has_cmov,
edx_ecx,
FeatureInfoFlags::CMOV
);
check_flag!(
doc = "Page Attribute Table. Page Attribute Table is supported. This feature \
augments the Memory Type Range Registers (MTRRs), allowing an operating \
system to specify attributes of memory accessed through a linear address \
on a 4KB granularity.",
has_pat,
edx_ecx,
FeatureInfoFlags::PAT
);
check_flag!(
doc = "36-Bit Page Size Extension. 4-MByte pages addressing physical memory \
beyond 4 GBytes are supported with 32-bit paging. This feature indicates \
that upper bits of the physical address of a 4-MByte page are encoded in \
bits 20:13 of the page-directory entry. Such physical addresses are \
limited by MAXPHYADDR and may be up to 40 bits in size.",
has_pse36,
edx_ecx,
FeatureInfoFlags::PSE36
);
check_flag!(
doc = "Processor Serial Number. The processor supports the 96-bit processor \
identification number feature and the feature is enabled.",
has_psn,
edx_ecx,
FeatureInfoFlags::PSN
);
check_flag!(
doc = "CLFLUSH Instruction. CLFLUSH Instruction is supported.",
has_clflush,
edx_ecx,
FeatureInfoFlags::CLFSH
);
check_flag!(
doc = "Debug Store. The processor supports the ability to write debug \
information into a memory resident buffer. This feature is used by the \
branch trace store (BTS) and processor event-based sampling (PEBS) \
facilities (see Chapter 23, Introduction to Virtual-Machine Extensions, \
in the Intel® 64 and IA-32 Architectures Software Developers Manual, \
Volume 3C).",
has_ds,
edx_ecx,
FeatureInfoFlags::DS
);
check_flag!(
doc = "Thermal Monitor and Software Controlled Clock Facilities. The processor \
implements internal MSRs that allow processor temperature to be monitored \
and processor performance to be modulated in predefined duty cycles under \
software control.",
has_acpi,
edx_ecx,
FeatureInfoFlags::ACPI
);
check_flag!(
doc = "Intel MMX Technology. The processor supports the Intel MMX technology.",
has_mmx,
edx_ecx,
FeatureInfoFlags::MMX
);
check_flag!(
doc = "FXSAVE and FXRSTOR Instructions. The FXSAVE and FXRSTOR instructions are \
supported for fast save and restore of the floating point context. \
Presence of this bit also indicates that CR4.OSFXSR is available for an \
operating system to indicate that it supports the FXSAVE and FXRSTOR \
instructions.",
has_fxsave_fxstor,
edx_ecx,
FeatureInfoFlags::FXSR
);
check_flag!(
doc = "SSE. The processor supports the SSE extensions.",
has_sse,
edx_ecx,
FeatureInfoFlags::SSE
);
check_flag!(
doc = "SSE2. The processor supports the SSE2 extensions.",
has_sse2,
edx_ecx,
FeatureInfoFlags::SSE2
);
check_flag!(
doc = "Self Snoop. The processor supports the management of conflicting memory \
types by performing a snoop of its own cache structure for transactions \
issued to the bus.",
has_ss,
edx_ecx,
FeatureInfoFlags::SS
);
check_flag!(
doc = "Max APIC IDs reserved field is Valid. A value of 0 for HTT indicates \
there is only a single logical processor in the package and software \
should assume only a single APIC ID is reserved. A value of 1 for HTT \
indicates the value in CPUID.1.EBX[23:16] (the Maximum number of \
addressable IDs for logical processors in this package) is valid for the \
package.",
has_htt,
edx_ecx,
FeatureInfoFlags::HTT
);
check_flag!(
doc = "Thermal Monitor. The processor implements the thermal monitor automatic \
thermal control circuitry (TCC).",
has_tm,
edx_ecx,
FeatureInfoFlags::TM
);
check_flag!(
doc = "Pending Break Enable. The processor supports the use of the FERR#/PBE# \
pin when the processor is in the stop-clock state (STPCLK# is asserted) \
to signal the processor that an interrupt is pending and that the \
processor should return to normal operation to handle the interrupt. Bit \
10 (PBE enable) in the IA32_MISC_ENABLE MSR enables this capability.",
has_pbe,
edx_ecx,
FeatureInfoFlags::PBE
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct FeatureInfoFlags: u64 {
// ECX flags
/// Streaming SIMD Extensions 3 (SSE3). A value of 1 indicates the processor supports this technology.
const SSE3 = 1 << 0;
/// PCLMULQDQ. A value of 1 indicates the processor supports the PCLMULQDQ instruction
const PCLMULQDQ = 1 << 1;
/// 64-bit DS Area. A value of 1 indicates the processor supports DS area using 64-bit layout
const DTES64 = 1 << 2;
/// MONITOR/MWAIT. A value of 1 indicates the processor supports this feature.
const MONITOR = 1 << 3;
/// CPL Qualified Debug Store. A value of 1 indicates the processor supports the extensions to the Debug Store feature to allow for branch message storage qualified by CPL.
const DSCPL = 1 << 4;
/// Virtual Machine Extensions. A value of 1 indicates that the processor supports this technology.
const VMX = 1 << 5;
/// Safer Mode Extensions. A value of 1 indicates that the processor supports this technology. See Chapter 5, Safer Mode Extensions Reference.
const SMX = 1 << 6;
/// Enhanced Intel SpeedStep® technology. A value of 1 indicates that the processor supports this technology.
const EIST = 1 << 7;
/// Thermal Monitor 2. A value of 1 indicates whether the processor supports this technology.
const TM2 = 1 << 8;
/// A value of 1 indicates the presence of the Supplemental Streaming SIMD Extensions 3 (SSSE3). A value of 0 indicates the instruction extensions are not present in the processor
const SSSE3 = 1 << 9;
/// L1 Context ID. A value of 1 indicates the L1 data cache mode can be set to either adaptive mode or shared mode. A value of 0 indicates this feature is not supported. See definition of the IA32_MISC_ENABLE MSR Bit 24 (L1 Data Cache Context Mode) for details.
const CNXTID = 1 << 10;
/// A value of 1 indicates the processor supports FMA extensions using YMM state.
const FMA = 1 << 12;
/// CMPXCHG16B Available. A value of 1 indicates that the feature is available. See the CMPXCHG8B/CMPXCHG16B Compare and Exchange Bytes section. 14
const CMPXCHG16B = 1 << 13;
/// Perfmon and Debug Capability: A value of 1 indicates the processor supports the performance and debug feature indication MSR IA32_PERF_CAPABILITIES.
const PDCM = 1 << 15;
/// Process-context identifiers. A value of 1 indicates that the processor supports PCIDs and the software may set CR4.PCIDE to 1.
const PCID = 1 << 17;
/// A value of 1 indicates the processor supports the ability to prefetch data from a memory mapped device.
const DCA = 1 << 18;
/// A value of 1 indicates that the processor supports SSE4.1.
const SSE41 = 1 << 19;
/// A value of 1 indicates that the processor supports SSE4.2.
const SSE42 = 1 << 20;
/// A value of 1 indicates that the processor supports x2APIC feature.
const X2APIC = 1 << 21;
/// A value of 1 indicates that the processor supports MOVBE instruction.
const MOVBE = 1 << 22;
/// A value of 1 indicates that the processor supports the POPCNT instruction.
const POPCNT = 1 << 23;
/// A value of 1 indicates that the processors local APIC timer supports one-shot operation using a TSC deadline value.
const TSC_DEADLINE = 1 << 24;
/// A value of 1 indicates that the processor supports the AESNI instruction extensions.
const AESNI = 1 << 25;
/// A value of 1 indicates that the processor supports the XSAVE/XRSTOR processor extended states feature, the XSETBV/XGETBV instructions, and XCR0.
const XSAVE = 1 << 26;
/// A value of 1 indicates that the OS has enabled XSETBV/XGETBV instructions to access XCR0, and support for processor extended state management using XSAVE/XRSTOR.
const OSXSAVE = 1 << 27;
/// A value of 1 indicates the processor supports the AVX instruction extensions.
const AVX = 1 << 28;
/// A value of 1 indicates that processor supports 16-bit floating-point conversion instructions.
const F16C = 1 << 29;
/// A value of 1 indicates that processor supports RDRAND instruction.
const RDRAND = 1 << 30;
// EDX flags
/// Floating Point Unit On-Chip. The processor contains an x87 FPU.
const FPU = 1 << (32 + 0);
/// Virtual 8086 Mode Enhancements. Virtual 8086 mode enhancements, including CR4.VME for controlling the feature, CR4.PVI for protected mode virtual interrupts, software interrupt indirection, expansion of the TSS with the software indirection bitmap, and EFLAGS.VIF and EFLAGS.VIP flags.
const VME = 1 << (32 + 1);
/// Debugging Extensions. Support for I/O breakpoints, including CR4.DE for controlling the feature, and optional trapping of accesses to DR4 and DR5.
const DE = 1 << (32 + 2);
/// Page Size Extension. Large pages of size 4 MByte are supported, including CR4.PSE for controlling the feature, the defined dirty bit in PDE (Page Directory Entries), optional reserved bit trapping in CR3, PDEs, and PTEs.
const PSE = 1 << (32 + 3);
/// Time Stamp Counter. The RDTSC instruction is supported, including CR4.TSD for controlling privilege.
const TSC = 1 << (32 + 4);
/// Model Specific Registers RDMSR and WRMSR Instructions. The RDMSR and WRMSR instructions are supported. Some of the MSRs are implementation dependent.
const MSR = 1 << (32 + 5);
/// Physical Address Extension. Physical addresses greater than 32 bits are supported: extended page table entry formats, an extra level in the page translation tables is defined, 2-MByte pages are supported instead of 4 Mbyte pages if PAE bit is 1.
const PAE = 1 << (32 + 6);
/// Machine Check Exception. Exception 18 is defined for Machine Checks, including CR4.MCE for controlling the feature. This feature does not define the model-specific implementations of machine-check error logging, reporting, and processor shutdowns. Machine Check exception handlers may have to depend on processor version to do model specific processing of the exception, or test for the presence of the Machine Check feature.
const MCE = 1 << (32 + 7);
/// CMPXCHG8B Instruction. The compare-and-exchange 8 bytes (64 bits) instruction is supported (implicitly locked and atomic).
const CX8 = 1 << (32 + 8);
/// APIC On-Chip. The processor contains an Advanced Programmable Interrupt Controller (APIC), responding to memory mapped commands in the physical address range FFFE0000H to FFFE0FFFH (by default - some processors permit the APIC to be relocated).
const APIC = 1 << (32 + 9);
/// SYSENTER and SYSEXIT Instructions. The SYSENTER and SYSEXIT and associated MSRs are supported.
const SEP = 1 << (32 + 11);
/// Memory Type Range Registers. MTRRs are supported. The MTRRcap MSR contains feature bits that describe what memory types are supported, how many variable MTRRs are supported, and whether fixed MTRRs are supported.
const MTRR = 1 << (32 + 12);
/// Page Global Bit. The global bit is supported in paging-structure entries that map a page, indicating TLB entries that are common to different processes and need not be flushed. The CR4.PGE bit controls this feature.
const PGE = 1 << (32 + 13);
/// Machine Check Architecture. The Machine Check exArchitecture, which provides a compatible mechanism for error reporting in P6 family, Pentium 4, Intel Xeon processors, and future processors, is supported. The MCG_CAP MSR contains feature bits describing how many banks of error reporting MSRs are supported.
const MCA = 1 << (32 + 14);
/// Conditional Move Instructions. The conditional move instruction CMOV is supported. In addition, if x87 FPU is present as indicated by the CPUID.FPU feature bit, then the FCOMI and FCMOV instructions are supported
const CMOV = 1 << (32 + 15);
/// Page Attribute Table. Page Attribute Table is supported. This feature augments the Memory Type Range Registers (MTRRs), allowing an operating system to specify attributes of memory accessed through a linear address on a 4KB granularity.
const PAT = 1 << (32 + 16);
/// 36-Bit Page Size Extension. 4-MByte pages addressing physical memory beyond 4 GBytes are supported with 32-bit paging. This feature indicates that upper bits of the physical address of a 4-MByte page are encoded in bits 20:13 of the page-directory entry. Such physical addresses are limited by MAXPHYADDR and may be up to 40 bits in size.
const PSE36 = 1 << (32 + 17);
/// Processor Serial Number. The processor supports the 96-bit processor identification number feature and the feature is enabled.
const PSN = 1 << (32 + 18);
/// CLFLUSH Instruction. CLFLUSH Instruction is supported.
const CLFSH = 1 << (32 + 19);
/// Debug Store. The processor supports the ability to write debug information into a memory resident buffer. This feature is used by the branch trace store (BTS) and precise event-based sampling (PEBS) facilities (see Chapter 23, Introduction to Virtual-Machine Extensions, in the Intel® 64 and IA-32 Architectures Software Developers Manual, Volume 3C).
const DS = 1 << (32 + 21);
/// Thermal Monitor and Software Controlled Clock Facilities. The processor implements internal MSRs that allow processor temperature to be monitored and processor performance to be modulated in predefined duty cycles under software control.
const ACPI = 1 << (32 + 22);
/// Intel MMX Technology. The processor supports the Intel MMX technology.
const MMX = 1 << (32 + 23);
/// FXSAVE and FXRSTOR Instructions. The FXSAVE and FXRSTOR instructions are supported for fast save and restore of the floating point context. Presence of this bit also indicates that CR4.OSFXSR is available for an operating system to indicate that it supports the FXSAVE and FXRSTOR instructions.
const FXSR = 1 << (32 + 24);
/// SSE. The processor supports the SSE extensions.
const SSE = 1 << (32 + 25);
/// SSE2. The processor supports the SSE2 extensions.
const SSE2 = 1 << (32 + 26);
/// Self Snoop. The processor supports the management of conflicting memory types by performing a snoop of its own cache structure for transactions issued to the bus.
const SS = 1 << (32 + 27);
/// Max APIC IDs reserved field is Valid. A value of 0 for HTT indicates there is only a single logical processor in the package and software should assume only a single APIC ID is reserved. A value of 1 for HTT indicates the value in CPUID.1.EBX[23:16] (the Maximum number of addressable IDs for logical processors in this package) is valid for the package.
const HTT = 1 << (32 + 28);
/// Thermal Monitor. The processor implements the thermal monitor automatic thermal control circuitry (TCC).
const TM = 1 << (32 + 29);
/// Pending Break Enable. The processor supports the use of the FERR#/PBE# pin when the processor is in the stop-clock state (STPCLK# is asserted) to signal the processor that an interrupt is pending and that the processor should return to normal operation to handle the interrupt. Bit 10 (PBE enable) in the IA32_MISC_ENABLE MSR enables this capability.
const PBE = 1 << (32 + 31);
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheParametersIter {
current: u32,
}
impl Iterator for CacheParametersIter {
type Item = CacheParameter;
/// Iterate over all caches for this CPU.
/// Note: cpuid is called every-time we this function to get information
/// about next cache.
fn next(&mut self) -> Option<CacheParameter> {
let res = cpuid!(EAX_CACHE_PARAMETERS, self.current);
let cp = CacheParameter {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
};
match cp.cache_type() {
CacheType::NULL => None,
CacheType::RESERVED => None,
_ => {
self.current += 1;
Some(cp)
}
}
}
}
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheParameter {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum CacheType {
/// Null - No more caches
NULL = 0,
DATA,
INSTRUCTION,
UNIFIED,
/// 4-31 = Reserved
RESERVED,
}
impl Default for CacheType {
fn default() -> CacheType {
CacheType::NULL
}
}
impl CacheParameter {
/// Cache Type
pub fn cache_type(&self) -> CacheType {
let typ = get_bits(self.eax, 0, 4) as u8;
match typ {
0 => CacheType::NULL,
1 => CacheType::DATA,
2 => CacheType::INSTRUCTION,
3 => CacheType::UNIFIED,
_ => CacheType::RESERVED,
}
}
/// Cache Level (starts at 1)
pub fn level(&self) -> u8 {
get_bits(self.eax, 5, 7) as u8
}
/// Self Initializing cache level (does not need SW initialization).
pub fn is_self_initializing(&self) -> bool {
get_bits(self.eax, 8, 8) == 1
}
/// Fully Associative cache
pub fn is_fully_associative(&self) -> bool {
get_bits(self.eax, 9, 9) == 1
}
/// Maximum number of addressable IDs for logical processors sharing this cache
pub fn max_cores_for_cache(&self) -> usize {
(get_bits(self.eax, 14, 25) + 1) as usize
}
/// Maximum number of addressable IDs for processor cores in the physical package
pub fn max_cores_for_package(&self) -> usize {
(get_bits(self.eax, 26, 31) + 1) as usize
}
/// System Coherency Line Size (Bits 11-00)
pub fn coherency_line_size(&self) -> usize {
(get_bits(self.ebx, 0, 11) + 1) as usize
}
/// Physical Line partitions (Bits 21-12)
pub fn physical_line_partitions(&self) -> usize {
(get_bits(self.ebx, 12, 21) + 1) as usize
}
/// Ways of associativity (Bits 31-22)
pub fn associativity(&self) -> usize {
(get_bits(self.ebx, 22, 31) + 1) as usize
}
/// Number of Sets (Bits 31-00)
pub fn sets(&self) -> usize {
(self.ecx + 1) as usize
}
/// Write-Back Invalidate/Invalidate (Bit 0)
/// False: WBINVD/INVD from threads sharing this cache acts upon lower level caches for threads sharing this cache.
/// True: WBINVD/INVD is not guaranteed to act upon lower level caches of non-originating threads sharing this cache.
pub fn is_write_back_invalidate(&self) -> bool {
get_bits(self.edx, 0, 0) == 1
}
/// Cache Inclusiveness (Bit 1)
/// False: Cache is not inclusive of lower cache levels.
/// True: Cache is inclusive of lower cache levels.
pub fn is_inclusive(&self) -> bool {
get_bits(self.edx, 1, 1) == 1
}
/// Complex Cache Indexing (Bit 2)
/// False: Direct mapped cache.
/// True: A complex function is used to index the cache, potentially using all address bits.
pub fn has_complex_indexing(&self) -> bool {
get_bits(self.edx, 2, 2) == 1
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct MonitorMwaitInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl MonitorMwaitInfo {
/// Smallest monitor-line size in bytes (default is processor's monitor granularity)
pub fn smallest_monitor_line(&self) -> u16 {
get_bits(self.eax, 0, 15) as u16
}
/// Largest monitor-line size in bytes (default is processor's monitor granularity
pub fn largest_monitor_line(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Enumeration of Monitor-Mwait extensions (beyond EAX and EBX registers) supported
pub fn extensions_supported(&self) -> bool {
get_bits(self.ecx, 0, 0) == 1
}
/// Supports treating interrupts as break-event for MWAIT, even when interrupts disabled
pub fn interrupts_as_break_event(&self) -> bool {
get_bits(self.ecx, 1, 1) == 1
}
/// Number of C0 sub C-states supported using MWAIT (Bits 03 - 00)
pub fn supported_c0_states(&self) -> u16 {
get_bits(self.edx, 0, 3) as u16
}
/// Number of C1 sub C-states supported using MWAIT (Bits 07 - 04)
pub fn supported_c1_states(&self) -> u16 {
get_bits(self.edx, 4, 7) as u16
}
/// Number of C2 sub C-states supported using MWAIT (Bits 11 - 08)
pub fn supported_c2_states(&self) -> u16 {
get_bits(self.edx, 8, 11) as u16
}
/// Number of C3 sub C-states supported using MWAIT (Bits 15 - 12)
pub fn supported_c3_states(&self) -> u16 {
get_bits(self.edx, 12, 15) as u16
}
/// Number of C4 sub C-states supported using MWAIT (Bits 19 - 16)
pub fn supported_c4_states(&self) -> u16 {
get_bits(self.edx, 16, 19) as u16
}
/// Number of C5 sub C-states supported using MWAIT (Bits 23 - 20)
pub fn supported_c5_states(&self) -> u16 {
get_bits(self.edx, 20, 23) as u16
}
/// Number of C6 sub C-states supported using MWAIT (Bits 27 - 24)
pub fn supported_c6_states(&self) -> u16 {
get_bits(self.edx, 24, 27) as u16
}
/// Number of C7 sub C-states supported using MWAIT (Bits 31 - 28)
pub fn supported_c7_states(&self) -> u16 {
get_bits(self.edx, 28, 31) as u16
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ThermalPowerInfo {
eax: ThermalPowerFeaturesEax,
ebx: u32,
ecx: ThermalPowerFeaturesEcx,
edx: u32,
}
impl ThermalPowerInfo {
/// Number of Interrupt Thresholds in Digital Thermal Sensor
pub fn dts_irq_threshold(&self) -> u8 {
get_bits(self.ebx, 0, 3) as u8
}
check_flag!(
doc = "Digital temperature sensor is supported if set.",
has_dts,
eax,
ThermalPowerFeaturesEax::DTS
);
check_flag!(
doc = "Intel Turbo Boost Technology Available (see description of \
IA32_MISC_ENABLE[38]).",
has_turbo_boost,
eax,
ThermalPowerFeaturesEax::TURBO_BOOST
);
check_flag!(
doc = "ARAT. APIC-Timer-always-running feature is supported if set.",
has_arat,
eax,
ThermalPowerFeaturesEax::ARAT
);
check_flag!(
doc = "PLN. Power limit notification controls are supported if set.",
has_pln,
eax,
ThermalPowerFeaturesEax::PLN
);
check_flag!(
doc = "ECMD. Clock modulation duty cycle extension is supported if set.",
has_ecmd,
eax,
ThermalPowerFeaturesEax::ECMD
);
check_flag!(
doc = "PTM. Package thermal management is supported if set.",
has_ptm,
eax,
ThermalPowerFeaturesEax::PTM
);
check_flag!(
doc = "HWP. HWP base registers (IA32_PM_ENABLE[bit 0], IA32_HWP_CAPABILITIES, \
IA32_HWP_REQUEST, IA32_HWP_STATUS) are supported if set.",
has_hwp,
eax,
ThermalPowerFeaturesEax::HWP
);
check_flag!(
doc = "HWP Notification. IA32_HWP_INTERRUPT MSR is supported if set.",
has_hwp_notification,
eax,
ThermalPowerFeaturesEax::HWP_NOTIFICATION
);
check_flag!(
doc = "HWP Activity Window. IA32_HWP_REQUEST[bits 41:32] is supported if set.",
has_hwp_activity_window,
eax,
ThermalPowerFeaturesEax::HWP_ACTIVITY_WINDOW
);
check_flag!(
doc =
"HWP Energy Performance Preference. IA32_HWP_REQUEST[bits 31:24] is supported if set.",
has_hwp_energy_performance_preference,
eax,
ThermalPowerFeaturesEax::HWP_ENERGY_PERFORMANCE_PREFERENCE
);
check_flag!(
doc = "HWP Package Level Request. IA32_HWP_REQUEST_PKG MSR is supported if set.",
has_hwp_package_level_request,
eax,
ThermalPowerFeaturesEax::HWP_PACKAGE_LEVEL_REQUEST
);
check_flag!(
doc = "HDC. HDC base registers IA32_PKG_HDC_CTL, IA32_PM_CTL1, IA32_THREAD_STALL \
MSRs are supported if set.",
has_hdc,
eax,
ThermalPowerFeaturesEax::HDC
);
check_flag!(
doc = "Intel® Turbo Boost Max Technology 3.0 available.",
has_turbo_boost3,
eax,
ThermalPowerFeaturesEax::TURBO_BOOST_3
);
check_flag!(
doc = "HWP Capabilities. Highest Performance change is supported if set.",
has_hwp_capabilities,
eax,
ThermalPowerFeaturesEax::HWP_CAPABILITIES
);
check_flag!(
doc = "HWP PECI override is supported if set.",
has_hwp_peci_override,
eax,
ThermalPowerFeaturesEax::HWP_PECI_OVERRIDE
);
check_flag!(
doc = "Flexible HWP is supported if set.",
has_flexible_hwp,
eax,
ThermalPowerFeaturesEax::FLEXIBLE_HWP
);
check_flag!(
doc = "Fast access mode for the IA32_HWP_REQUEST MSR is supported if set.",
has_hwp_fast_access_mode,
eax,
ThermalPowerFeaturesEax::HWP_REQUEST_MSR_FAST_ACCESS
);
check_flag!(
doc = "Ignoring Idle Logical Processor HWP request is supported if set.",
has_ignore_idle_processor_hwp_request,
eax,
ThermalPowerFeaturesEax::IGNORE_IDLE_PROCESSOR_HWP_REQUEST
);
check_flag!(
doc = "Hardware Coordination Feedback Capability (Presence of IA32_MPERF and \
IA32_APERF). The capability to provide a measure of delivered processor \
performance (since last reset of the counters), as a percentage of \
expected processor performance at frequency specified in CPUID Brand \
String Bits 02 - 01",
has_hw_coord_feedback,
ecx,
ThermalPowerFeaturesEcx::HW_COORD_FEEDBACK
);
check_flag!(
doc = "The processor supports performance-energy bias preference if \
CPUID.06H:ECX.SETBH[bit 3] is set and it also implies the presence of a \
new architectural MSR called IA32_ENERGY_PERF_BIAS (1B0H)",
has_energy_bias_pref,
ecx,
ThermalPowerFeaturesEcx::ENERGY_BIAS_PREF
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ThermalPowerFeaturesEax: u32 {
/// Digital temperature sensor is supported if set. (Bit 00)
const DTS = 1 << 0;
/// Intel Turbo Boost Technology Available (see description of IA32_MISC_ENABLE[38]). (Bit 01)
const TURBO_BOOST = 1 << 1;
/// ARAT. APIC-Timer-always-running feature is supported if set. (Bit 02)
const ARAT = 1 << 2;
/// Bit 3: Reserved.
const RESERVED_3 = 1 << 3;
/// PLN. Power limit notification controls are supported if set. (Bit 04)
const PLN = 1 << 4;
/// ECMD. Clock modulation duty cycle extension is supported if set. (Bit 05)
const ECMD = 1 << 5;
/// PTM. Package thermal management is supported if set. (Bit 06)
const PTM = 1 << 6;
/// Bit 07: HWP. HWP base registers (IA32_PM_ENABLE[bit 0], IA32_HWP_CAPABILITIES, IA32_HWP_REQUEST, IA32_HWP_STATUS) are supported if set.
const HWP = 1 << 7;
/// Bit 08: HWP_Notification. IA32_HWP_INTERRUPT MSR is supported if set.
const HWP_NOTIFICATION = 1 << 8;
/// Bit 09: HWP_Activity_Window. IA32_HWP_REQUEST[bits 41:32] is supported if set.
const HWP_ACTIVITY_WINDOW = 1 << 9;
/// Bit 10: HWP_Energy_Performance_Preference. IA32_HWP_REQUEST[bits 31:24] is supported if set.
const HWP_ENERGY_PERFORMANCE_PREFERENCE = 1 << 10;
/// Bit 11: HWP_Package_Level_Request. IA32_HWP_REQUEST_PKG MSR is supported if set.
const HWP_PACKAGE_LEVEL_REQUEST = 1 << 11;
/// Bit 12: Reserved.
const RESERVED_12 = 1 << 12;
/// Bit 13: HDC. HDC base registers IA32_PKG_HDC_CTL, IA32_PM_CTL1, IA32_THREAD_STALL MSRs are supported if set.
const HDC = 1 << 13;
/// Bit 14: Intel® Turbo Boost Max Technology 3.0 available.
const TURBO_BOOST_3 = 1 << 14;
/// Bit 15: HWP Capabilities. Highest Performance change is supported if set.
const HWP_CAPABILITIES = 1 << 15;
/// Bit 16: HWP PECI override is supported if set.
const HWP_PECI_OVERRIDE = 1 << 16;
/// Bit 17: Flexible HWP is supported if set.
const FLEXIBLE_HWP = 1 << 17;
/// Bit 18: Fast access mode for the IA32_HWP_REQUEST MSR is supported if set.
const HWP_REQUEST_MSR_FAST_ACCESS = 1 << 18;
/// Bit 19: Reserved.
const RESERVED_19 = 1 << 19;
/// Bit 20: Ignoring Idle Logical Processor HWP request is supported if set.
const IGNORE_IDLE_PROCESSOR_HWP_REQUEST = 1 << 20;
// Bits 31 - 21: Reserved
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ThermalPowerFeaturesEcx: u32 {
/// Hardware Coordination Feedback Capability (Presence of IA32_MPERF and IA32_APERF). The capability to provide a measure of delivered processor performance (since last reset of the counters), as a percentage of expected processor performance at frequency specified in CPUID Brand String Bits 02 - 01
const HW_COORD_FEEDBACK = 1 << 0;
/// The processor supports performance-energy bias preference if CPUID.06H:ECX.SETBH[bit 3] is set and it also implies the presence of a new architectural MSR called IA32_ENERGY_PERF_BIAS (1B0H)
const ENERGY_BIAS_PREF = 1 << 3;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedFeatures {
eax: u32,
ebx: ExtendedFeaturesEbx,
ecx: ExtendedFeaturesEcx,
edx: u32,
}
impl ExtendedFeatures {
check_flag!(
doc = "FSGSBASE. Supports RDFSBASE/RDGSBASE/WRFSBASE/WRGSBASE if 1.",
has_fsgsbase,
ebx,
ExtendedFeaturesEbx::FSGSBASE
);
check_flag!(
doc = "IA32_TSC_ADJUST MSR is supported if 1.",
has_tsc_adjust_msr,
ebx,
ExtendedFeaturesEbx::ADJUST_MSR
);
check_flag!(doc = "BMI1", has_bmi1, ebx, ExtendedFeaturesEbx::BMI1);
check_flag!(doc = "HLE", has_hle, ebx, ExtendedFeaturesEbx::HLE);
check_flag!(doc = "AVX2", has_avx2, ebx, ExtendedFeaturesEbx::AVX2);
check_flag!(
doc = "FDP_EXCPTN_ONLY. x87 FPU Data Pointer updated only on x87 exceptions if 1.",
has_fdp,
ebx,
ExtendedFeaturesEbx::FDP
);
check_flag!(
doc = "SMEP. Supports Supervisor-Mode Execution Prevention if 1.",
has_smep,
ebx,
ExtendedFeaturesEbx::SMEP
);
check_flag!(doc = "BMI2", has_bmi2, ebx, ExtendedFeaturesEbx::BMI2);
check_flag!(
doc = "Supports Enhanced REP MOVSB/STOSB if 1.",
has_rep_movsb_stosb,
ebx,
ExtendedFeaturesEbx::REP_MOVSB_STOSB
);
check_flag!(
doc = "INVPCID. If 1, supports INVPCID instruction for system software that \
manages process-context identifiers.",
has_invpcid,
ebx,
ExtendedFeaturesEbx::INVPCID
);
check_flag!(doc = "RTM", has_rtm, ebx, ExtendedFeaturesEbx::RTM);
check_flag!(
doc = "Supports Intel Resource Director Technology (RDT) Monitoring capability.",
has_rdtm,
ebx,
ExtendedFeaturesEbx::RDTM
);
check_flag!(
doc = "Deprecates FPU CS and FPU DS values if 1.",
has_fpu_cs_ds_deprecated,
ebx,
ExtendedFeaturesEbx::DEPRECATE_FPU_CS_DS
);
check_flag!(
doc = "MPX. Supports Intel Memory Protection Extensions if 1.",
has_mpx,
ebx,
ExtendedFeaturesEbx::MPX
);
check_flag!(
doc = "Supports Intel Resource Director Technology (RDT) Allocation capability.",
has_rdta,
ebx,
ExtendedFeaturesEbx::RDTA
);
check_flag!(
doc = "Supports RDSEED.",
has_rdseed,
ebx,
ExtendedFeaturesEbx::RDSEED
);
#[deprecated(
since = "3.2",
note = "Deprecated due to typo in name, users should use has_rdseed() instead."
)]
check_flag!(
doc = "Supports RDSEED (deprecated alias).",
has_rdseet,
ebx,
ExtendedFeaturesEbx::RDSEED
);
check_flag!(
doc = "Supports ADX.",
has_adx,
ebx,
ExtendedFeaturesEbx::ADX
);
check_flag!(doc = "SMAP. Supports Supervisor-Mode Access Prevention (and the CLAC/STAC instructions) if 1.",
has_smap,
ebx,
ExtendedFeaturesEbx::SMAP);
check_flag!(
doc = "Supports CLFLUSHOPT.",
has_clflushopt,
ebx,
ExtendedFeaturesEbx::CLFLUSHOPT
);
check_flag!(
doc = "Supports Intel Processor Trace.",
has_processor_trace,
ebx,
ExtendedFeaturesEbx::PROCESSOR_TRACE
);
check_flag!(
doc = "Supports SHA Instructions.",
has_sha,
ebx,
ExtendedFeaturesEbx::SHA
);
check_flag!(
doc = "Supports Intel® Software Guard Extensions (Intel® SGX Extensions).",
has_sgx,
ebx,
ExtendedFeaturesEbx::SGX
);
check_flag!(
doc = "Supports AVX512F.",
has_avx512f,
ebx,
ExtendedFeaturesEbx::AVX512F
);
check_flag!(
doc = "Supports AVX512DQ.",
has_avx512dq,
ebx,
ExtendedFeaturesEbx::AVX512DQ
);
check_flag!(
doc = "AVX512_IFMA",
has_avx512_ifma,
ebx,
ExtendedFeaturesEbx::AVX512_IFMA
);
check_flag!(
doc = "AVX512PF",
has_avx512pf,
ebx,
ExtendedFeaturesEbx::AVX512PF
);
check_flag!(
doc = "AVX512ER",
has_avx512er,
ebx,
ExtendedFeaturesEbx::AVX512ER
);
check_flag!(
doc = "AVX512CD",
has_avx512cd,
ebx,
ExtendedFeaturesEbx::AVX512CD
);
check_flag!(
doc = "AVX512BW",
has_avx512bw,
ebx,
ExtendedFeaturesEbx::AVX512BW
);
check_flag!(
doc = "AVX512VL",
has_avx512vl,
ebx,
ExtendedFeaturesEbx::AVX512VL
);
check_flag!(doc = "CLWB", has_clwb, ebx, ExtendedFeaturesEbx::CLWB);
check_flag!(
doc = "Has PREFETCHWT1 (Intel® Xeon Phi™ only).",
has_prefetchwt1,
ecx,
ExtendedFeaturesEcx::PREFETCHWT1
);
check_flag!(
doc = "Supports user-mode instruction prevention if 1.",
has_umip,
ecx,
ExtendedFeaturesEcx::UMIP
);
check_flag!(
doc = "Supports protection keys for user-mode pages.",
has_pku,
ecx,
ExtendedFeaturesEcx::PKU
);
check_flag!(
doc = "OS has set CR4.PKE to enable protection keys (and the RDPKRU/WRPKRU instructions.",
has_ospke,
ecx,
ExtendedFeaturesEcx::OSPKE
);
check_flag!(
doc = "RDPID and IA32_TSC_AUX are available.",
has_rdpid,
ecx,
ExtendedFeaturesEcx::RDPID
);
check_flag!(
doc = "Supports SGX Launch Configuration.",
has_sgx_lc,
ecx,
ExtendedFeaturesEcx::SGX_LC
);
/// The value of MAWAU used by the BNDLDX and BNDSTX instructions in 64-bit mode.
pub fn mawau_value(&self) -> u8 {
get_bits(self.ecx.bits(), 17, 21) as u8
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFeaturesEbx: u32 {
/// FSGSBASE. Supports RDFSBASE/RDGSBASE/WRFSBASE/WRGSBASE if 1. (Bit 00)
const FSGSBASE = 1 << 0;
/// IA32_TSC_ADJUST MSR is supported if 1. (Bit 01)
const ADJUST_MSR = 1 << 1;
/// Bit 02: SGX. Supports Intel® Software Guard Extensions (Intel® SGX Extensions) if 1.
const SGX = 1 << 2;
/// BMI1 (Bit 03)
const BMI1 = 1 << 3;
/// HLE (Bit 04)
const HLE = 1 << 4;
/// AVX2 (Bit 05)
const AVX2 = 1 << 5;
/// FDP_EXCPTN_ONLY. x87 FPU Data Pointer updated only on x87 exceptions if 1.
const FDP = 1 << 6;
/// SMEP. Supports Supervisor-Mode Execution Prevention if 1. (Bit 07)
const SMEP = 1 << 7;
/// BMI2 (Bit 08)
const BMI2 = 1 << 8;
/// Supports Enhanced REP MOVSB/STOSB if 1. (Bit 09)
const REP_MOVSB_STOSB = 1 << 9;
/// INVPCID. If 1, supports INVPCID instruction for system software that manages process-context identifiers. (Bit 10)
const INVPCID = 1 << 10;
/// RTM (Bit 11)
const RTM = 1 << 11;
/// Supports Intel Resource Director Technology (RDT) Monitoring. (Bit 12)
const RDTM = 1 << 12;
/// Deprecates FPU CS and FPU DS values if 1. (Bit 13)
const DEPRECATE_FPU_CS_DS = 1 << 13;
/// Deprecates FPU CS and FPU DS values if 1. (Bit 14)
const MPX = 1 << 14;
/// Supports Intel Resource Director Technology (RDT) Allocation capability if 1.
const RDTA = 1 << 15;
/// Bit 16: AVX512F.
const AVX512F = 1 << 16;
/// Bit 17: AVX512DQ.
const AVX512DQ = 1 << 17;
/// Supports RDSEED.
const RDSEED = 1 << 18;
/// Supports ADX.
const ADX = 1 << 19;
/// SMAP. Supports Supervisor-Mode Access Prevention (and the CLAC/STAC instructions) if 1.
const SMAP = 1 << 20;
/// Bit 21: AVX512_IFMA.
const AVX512_IFMA = 1 << 21;
// Bit 22: Reserved.
/// Bit 23: CLFLUSHOPT
const CLFLUSHOPT = 1 << 23;
/// Bit 24: CLWB.
const CLWB = 1 << 24;
/// Bit 25: Intel Processor Trace
const PROCESSOR_TRACE = 1 << 25;
/// Bit 26: AVX512PF. (Intel® Xeon Phi™ only.)
const AVX512PF = 1 << 26;
/// Bit 27: AVX512ER. (Intel® Xeon Phi™ only.)
const AVX512ER = 1 << 27;
/// Bit 28: AVX512CD.
const AVX512CD = 1 << 28;
/// Bit 29: Intel SHA Extensions
const SHA = 1 << 29;
/// Bit 30: AVX512BW.
const AVX512BW = 1 << 30;
/// Bit 31: AVX512VL.
const AVX512VL = 1 << 31;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFeaturesEcx: u32 {
/// Bit 0: Prefetch WT1. (Intel® Xeon Phi™ only).
const PREFETCHWT1 = 1 << 0;
// Bit 01: AVX512_VBMI
const AVX512VBMI = 1 << 1;
/// Bit 02: UMIP. Supports user-mode instruction prevention if 1.
const UMIP = 1 << 2;
/// Bit 03: PKU. Supports protection keys for user-mode pages if 1.
const PKU = 1 << 3;
/// Bit 04: OSPKE. If 1, OS has set CR4.PKE to enable protection keys (and the RDPKRU/WRPKRU instruc-tions).
const OSPKE = 1 << 4;
// Bits 16 - 5: Reserved.
// Bits 21 - 17: The value of MAWAU used by the BNDLDX and BNDSTX instructions in 64-bit mode.
/// Bit 22: RDPID. RDPID and IA32_TSC_AUX are available if 1.
const RDPID = 1 << 22;
// Bits 29 - 23: Reserved.
/// Bit 30: SGX_LC. Supports SGX Launch Configuration if 1.
const SGX_LC = 1 << 30;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DirectCacheAccessInfo {
eax: u32,
}
impl DirectCacheAccessInfo {
/// Value of bits [31:0] of IA32_PLATFORM_DCA_CAP MSR (address 1F8H)
pub fn get_dca_cap_value(&self) -> u32 {
self.eax
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct PerformanceMonitoringInfo {
eax: u32,
ebx: PerformanceMonitoringFeaturesEbx,
ecx: u32,
edx: u32,
}
impl PerformanceMonitoringInfo {
/// Version ID of architectural performance monitoring. (Bits 07 - 00)
pub fn version_id(&self) -> u8 {
get_bits(self.eax, 0, 7) as u8
}
/// Number of general-purpose performance monitoring counter per logical processor. (Bits 15- 08)
pub fn number_of_counters(&self) -> u8 {
get_bits(self.eax, 8, 15) as u8
}
/// Bit width of general-purpose, performance monitoring counter. (Bits 23 - 16)
pub fn counter_bit_width(&self) -> u8 {
get_bits(self.eax, 16, 23) as u8
}
/// Length of EBX bit vector to enumerate architectural performance monitoring events. (Bits 31 - 24)
pub fn ebx_length(&self) -> u8 {
get_bits(self.eax, 24, 31) as u8
}
/// Number of fixed-function performance counters (if Version ID > 1). (Bits 04 - 00)
pub fn fixed_function_counters(&self) -> u8 {
get_bits(self.edx, 0, 4) as u8
}
/// Bit width of fixed-function performance counters (if Version ID > 1). (Bits 12- 05)
pub fn fixed_function_counters_bit_width(&self) -> u8 {
get_bits(self.edx, 5, 12) as u8
}
check_bit_fn!(
doc = "AnyThread deprecation",
has_any_thread_deprecation,
edx,
15
);
check_flag!(
doc = "Core cycle event not available if 1.",
is_core_cyc_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::CORE_CYC_EV_UNAVAILABLE
);
check_flag!(
doc = "Instruction retired event not available if 1.",
is_inst_ret_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::INST_RET_EV_UNAVAILABLE
);
check_flag!(
doc = "Reference cycles event not available if 1.",
is_ref_cycle_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::REF_CYC_EV_UNAVAILABLE
);
check_flag!(
doc = "Last-level cache reference event not available if 1.",
is_cache_ref_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::CACHE_REF_EV_UNAVAILABLE
);
check_flag!(
doc = "Last-level cache misses event not available if 1.",
is_ll_cache_miss_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::LL_CACHE_MISS_EV_UNAVAILABLE
);
check_flag!(
doc = "Branch instruction retired event not available if 1.",
is_branch_inst_ret_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::BRANCH_INST_RET_EV_UNAVAILABLE
);
check_flag!(
doc = "Branch mispredict retired event not available if 1.",
is_branch_midpred_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::BRANCH_MISPRED_EV_UNAVAILABLE
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct PerformanceMonitoringFeaturesEbx: u32 {
/// Core cycle event not available if 1. (Bit 0)
const CORE_CYC_EV_UNAVAILABLE = 1 << 0;
/// Instruction retired event not available if 1. (Bit 01)
const INST_RET_EV_UNAVAILABLE = 1 << 1;
/// Reference cycles event not available if 1. (Bit 02)
const REF_CYC_EV_UNAVAILABLE = 1 << 2;
/// Last-level cache reference event not available if 1. (Bit 03)
const CACHE_REF_EV_UNAVAILABLE = 1 << 3;
/// Last-level cache misses event not available if 1. (Bit 04)
const LL_CACHE_MISS_EV_UNAVAILABLE = 1 << 4;
/// Branch instruction retired event not available if 1. (Bit 05)
const BRANCH_INST_RET_EV_UNAVAILABLE = 1 << 5;
/// Branch mispredict retired event not available if 1. (Bit 06)
const BRANCH_MISPRED_EV_UNAVAILABLE = 1 << 6;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedTopologyIter {
level: u32,
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedTopologyLevel {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl ExtendedTopologyLevel {
/// Number of logical processors at this level type.
/// The number reflects configuration as shipped.
pub fn processors(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Level number.
pub fn level_number(&self) -> u8 {
get_bits(self.ecx, 0, 7) as u8
}
// Level type.
pub fn level_type(&self) -> TopologyType {
match get_bits(self.ecx, 8, 15) {
0 => TopologyType::INVALID,
1 => TopologyType::SMT,
2 => TopologyType::CORE,
_ => unreachable!(),
}
}
/// x2APIC ID the current logical processor. (Bits 31-00)
pub fn x2apic_id(&self) -> u32 {
self.edx
}
/// Number of bits to shift right on x2APIC ID to get a unique topology ID of the next level type. (Bits 04-00)
/// All logical processors with the same next level ID share current level.
pub fn shift_right_for_next_apic_id(&self) -> u32 {
get_bits(self.eax, 0, 4)
}
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum TopologyType {
INVALID = 0,
/// Hyper-thread (Simultaneous multithreading)
SMT = 1,
CORE = 2,
}
impl Default for TopologyType {
fn default() -> TopologyType {
TopologyType::INVALID
}
}
impl Iterator for ExtendedTopologyIter {
type Item = ExtendedTopologyLevel;
fn next(&mut self) -> Option<ExtendedTopologyLevel> {
let res = cpuid!(EAX_EXTENDED_TOPOLOGY_INFO, self.level);
self.level += 1;
let et = ExtendedTopologyLevel {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
};
match et.level_type() {
TopologyType::INVALID => None,
_ => Some(et),
}
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedStateInfoXCR0Flags: u32 {
/// legacy x87 (Bit 00).
const LEGACY_X87 = 1 << 0;
/// 128-bit SSE (Bit 01).
const SSE128 = 1 << 1;
/// 256-bit AVX (Bit 02).
const AVX256 = 1 << 2;
/// MPX BNDREGS (Bit 03).
const MPX_BNDREGS = 1 << 3;
/// MPX BNDCSR (Bit 04).
const MPX_BNDCSR = 1 << 4;
/// AVX512 OPMASK (Bit 05).
const AVX512_OPMASK = 1 << 5;
/// AVX ZMM Hi256 (Bit 06).
const AVX512_ZMM_HI256 = 1 << 6;
/// AVX 512 ZMM Hi16 (Bit 07).
const AVX512_ZMM_HI16 = 1 << 7;
/// PKRU state (Bit 09).
const PKRU = 1 << 9;
/// IA32_XSS HDC State (Bit 13).
const IA32_XSS_HDC = 1 << 13;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedStateInfoXSSFlags: u32 {
/// IA32_XSS PT (Trace Packet) State (Bit 08).
const PT = 1 << 8;
/// IA32_XSS HDC State (Bit 13).
const HDC = 1 << 13;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedStateInfo {
eax: ExtendedStateInfoXCR0Flags,
ebx: u32,
ecx: u32,
edx: u32,
eax1: u32,
ebx1: u32,
ecx1: ExtendedStateInfoXSSFlags,
edx1: u32,
}
impl ExtendedStateInfo {
check_flag!(
doc = "Support for legacy x87 in XCR0.",
xcr0_supports_legacy_x87,
eax,
ExtendedStateInfoXCR0Flags::LEGACY_X87
);
check_flag!(
doc = "Support for SSE 128-bit in XCR0.",
xcr0_supports_sse_128,
eax,
ExtendedStateInfoXCR0Flags::SSE128
);
check_flag!(
doc = "Support for AVX 256-bit in XCR0.",
xcr0_supports_avx_256,
eax,
ExtendedStateInfoXCR0Flags::AVX256
);
check_flag!(
doc = "Support for MPX BNDREGS in XCR0.",
xcr0_supports_mpx_bndregs,
eax,
ExtendedStateInfoXCR0Flags::MPX_BNDREGS
);
check_flag!(
doc = "Support for MPX BNDCSR in XCR0.",
xcr0_supports_mpx_bndcsr,
eax,
ExtendedStateInfoXCR0Flags::MPX_BNDCSR
);
check_flag!(
doc = "Support for AVX512 OPMASK in XCR0.",
xcr0_supports_avx512_opmask,
eax,
ExtendedStateInfoXCR0Flags::AVX512_OPMASK
);
check_flag!(
doc = "Support for AVX512 ZMM Hi256 XCR0.",
xcr0_supports_avx512_zmm_hi256,
eax,
ExtendedStateInfoXCR0Flags::AVX512_ZMM_HI256
);
check_flag!(
doc = "Support for AVX512 ZMM Hi16 in XCR0.",
xcr0_supports_avx512_zmm_hi16,
eax,
ExtendedStateInfoXCR0Flags::AVX512_ZMM_HI16
);
check_flag!(
doc = "Support for PKRU in XCR0.",
xcr0_supports_pkru,
eax,
ExtendedStateInfoXCR0Flags::PKRU
);
check_flag!(
doc = "Support for PT in IA32_XSS.",
ia32_xss_supports_pt,
ecx1,
ExtendedStateInfoXSSFlags::PT
);
check_flag!(
doc = "Support for HDC in IA32_XSS.",
ia32_xss_supports_hdc,
ecx1,
ExtendedStateInfoXSSFlags::HDC
);
/// Maximum size (bytes, from the beginning of the XSAVE/XRSTOR save area) required by
/// enabled features in XCR0. May be different than ECX if some features at the end of the XSAVE save area
/// are not enabled.
pub fn xsave_area_size_enabled_features(&self) -> u32 {
self.ebx
}
/// Maximum size (bytes, from the beginning of the XSAVE/XRSTOR save area) of the
/// XSAVE/XRSTOR save area required by all supported features in the processor,
/// i.e all the valid bit fields in XCR0.
pub fn xsave_area_size_supported_features(&self) -> u32 {
self.ecx
}
/// CPU has xsaveopt feature.
pub fn has_xsaveopt(&self) -> bool {
self.eax1 & 0x1 > 0
}
/// Supports XSAVEC and the compacted form of XRSTOR if set.
pub fn has_xsavec(&self) -> bool {
self.eax1 & 0b10 > 0
}
/// Supports XGETBV with ECX = 1 if set.
pub fn has_xgetbv(&self) -> bool {
self.eax1 & 0b100 > 0
}
/// Supports XSAVES/XRSTORS and IA32_XSS if set.
pub fn has_xsaves_xrstors(&self) -> bool {
self.eax1 & 0b1000 > 0
}
/// The size in bytes of the XSAVE area containing all states enabled by XCRO | IA32_XSS.
pub fn xsave_size(&self) -> u32 {
self.ebx1
}
/// Iterator over extended state enumeration levels >= 2.
pub fn iter(&self) -> ExtendedStateIter {
ExtendedStateIter {
level: 1,
supported_xcr0: self.eax.bits(),
supported_xss: self.ecx1.bits(),
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedStateIter {
level: u32,
supported_xcr0: u32,
supported_xss: u32,
}
/// When CPUID executes with EAX set to 0DH and ECX = n (n > 1,
/// and is a valid sub-leaf index), the processor returns information
/// about the size and offset of each processor extended state save area
/// within the XSAVE/XRSTOR area. Software can use the forward-extendable
/// technique depicted below to query the valid sub-leaves and obtain size
/// and offset information for each processor extended state save area:///
///
/// For i = 2 to 62 // sub-leaf 1 is reserved
/// IF (CPUID.(EAX=0DH, ECX=0):VECTOR[i] = 1 ) // VECTOR is the 64-bit value of EDX:EAX
/// Execute CPUID.(EAX=0DH, ECX = i) to examine size and offset for sub-leaf i;
/// FI;
impl Iterator for ExtendedStateIter {
type Item = ExtendedState;
fn next(&mut self) -> Option<ExtendedState> {
self.level += 1;
if self.level > 31 {
return None;
}
let bit = 1 << self.level;
if (self.supported_xcr0 & bit > 0) || (self.supported_xss & bit > 0) {
let res = cpuid!(EAX_EXTENDED_STATE_INFO, self.level);
return Some(ExtendedState {
subleaf: self.level,
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
});
}
self.next()
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedState {
pub subleaf: u32,
eax: u32,
ebx: u32,
ecx: u32,
}
impl ExtendedState {
/// The size in bytes (from the offset specified in EBX) of the save area
/// for an extended state feature associated with a valid sub-leaf index, n.
/// This field reports 0 if the sub-leaf index, n, is invalid.
pub fn size(&self) -> u32 {
self.eax
}
/// The offset in bytes of this extended state components save area
/// from the beginning of the XSAVE/XRSTOR area.
pub fn offset(&self) -> u32 {
self.ebx
}
/// True if the bit n (corresponding to the sub-leaf index)
/// is supported in the IA32_XSS MSR;
pub fn is_in_ia32_xss(&self) -> bool {
self.ecx & 0b1 > 0
}
/// True if bit n is supported in XCR0.
pub fn is_in_xcr0(&self) -> bool {
self.ecx & 0b1 == 0
}
/// Returns true when the compacted format of an XSAVE area is used,
/// this extended state component located on the next 64-byte
/// boundary following the preceding state component
/// (otherwise, it is located immediately following the preceding state component).
pub fn is_compacted_format(&self) -> bool {
self.ecx & 0b10 > 0
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct RdtMonitoringInfo {
ebx: u32,
edx: u32,
}
/// Intel Resource Director Technology (Intel RDT) Monitoring Enumeration Sub-leaf (EAX = 0FH, ECX = 0 and ECX = 1)
impl RdtMonitoringInfo {
/// Maximum range (zero-based) of RMID within this physical processor of all types.
pub fn rmid_range(&self) -> u32 {
self.ebx
}
check_bit_fn!(
doc = "Supports L3 Cache Intel RDT Monitoring.",
has_l3_monitoring,
edx,
1
);
/// L3 Cache Monitoring.
pub fn l3_monitoring(&self) -> Option<L3MonitoringInfo> {
if self.has_l3_monitoring() {
let res = cpuid!(EAX_RDT_MONITORING, 1);
return Some(L3MonitoringInfo {
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L3MonitoringInfo {
ebx: u32,
ecx: u32,
edx: u32,
}
impl L3MonitoringInfo {
/// Conversion factor from reported IA32_QM_CTR value to occupancy metric (bytes).
pub fn conversion_factor(&self) -> u32 {
self.ebx
}
/// Maximum range (zero-based) of RMID of L3.
pub fn maximum_rmid_range(&self) -> u32 {
self.ecx
}
check_bit_fn!(
doc = "Supports occupancy monitoring.",
has_occupancy_monitoring,
edx,
0
);
check_bit_fn!(
doc = "Supports total bandwidth monitoring.",
has_total_bandwidth_monitoring,
edx,
1
);
check_bit_fn!(
doc = "Supports local bandwidth monitoring.",
has_local_bandwidth_monitoring,
edx,
2
);
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct RdtAllocationInfo {
ebx: u32,
}
impl RdtAllocationInfo {
check_bit_fn!(doc = "Supports L3 Cache Allocation.", has_l3_cat, ebx, 1);
check_bit_fn!(doc = "Supports L2 Cache Allocation.", has_l2_cat, ebx, 2);
check_bit_fn!(
doc = "Supports Memory Bandwidth Allocation.",
has_memory_bandwidth_allocation,
ebx,
1
);
/// L3 Cache Allocation Information.
pub fn l3_cat(&self) -> Option<L3CatInfo> {
if self.has_l3_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 1);
return Some(L3CatInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
/// L2 Cache Allocation Information.
pub fn l2_cat(&self) -> Option<L2CatInfo> {
if self.has_l2_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 2);
return Some(L2CatInfo {
eax: res.eax,
ebx: res.ebx,
edx: res.edx,
});
} else {
return None;
}
}
/// Memory Bandwidth Allocation Information.
pub fn memory_bandwidth_allocation(&self) -> Option<MemBwAllocationInfo> {
if self.has_l2_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 3);
return Some(MemBwAllocationInfo {
eax: res.eax,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
}
/// L3 Cache Allocation Technology Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 1).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L3CatInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl L3CatInfo {
/// Length of the capacity bit mask using minus-one notation.
pub fn capacity_mask_length(&self) -> u8 {
get_bits(self.eax, 0, 4) as u8
}
/// Bit-granular map of isolation/contention of allocation units.
pub fn isolation_bitmap(&self) -> u32 {
self.ebx
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
check_bit_fn!(
doc = "Is Code and Data Prioritization Technology supported?",
has_code_data_prioritization,
ecx,
2
);
}
/// L2 Cache Allocation Technology Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 2).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L2CatInfo {
eax: u32,
ebx: u32,
edx: u32,
}
impl L2CatInfo {
/// Length of the capacity bit mask using minus-one notation.
pub fn capacity_mask_length(&self) -> u8 {
get_bits(self.eax, 0, 4) as u8
}
/// Bit-granular map of isolation/contention of allocation units.
pub fn isolation_bitmap(&self) -> u32 {
self.ebx
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
}
/// Memory Bandwidth Allocation Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 3).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct MemBwAllocationInfo {
eax: u32,
ecx: u32,
edx: u32,
}
impl MemBwAllocationInfo {
/// Reports the maximum MBA throttling value supported for the corresponding ResID using minus-one notation.
pub fn max_hba_throttling(&self) -> u16 {
get_bits(self.eax, 0, 11) as u16
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
check_bit_fn!(
doc = "Reports whether the response of the delay values is linear.",
has_linear_response_delay,
ecx,
2
);
}
/// Intel SGX Capability Enumeration Leaf, sub-leaf 0 (EAX = 12H, ECX = 0 and ECX = 1)
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SgxInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
eax1: u32,
ebx1: u32,
ecx1: u32,
edx1: u32,
}
impl SgxInfo {
check_bit_fn!(doc = "Has SGX1 support.", has_sgx1, eax, 0);
check_bit_fn!(doc = "Has SGX2 support.", has_sgx2, eax, 1);
check_bit_fn!(
doc = "Supports ENCLV instruction leaves EINCVIRTCHILD, EDECVIRTCHILD, and ESETCONTEXT.",
has_enclv_leaves_einvirtchild_edecvirtchild_esetcontext,
eax,
5
);
check_bit_fn!(
doc = "Supports ENCLS instruction leaves ETRACKC, ERDINFO, ELDBC, and ELDUC.",
has_encls_leaves_etrackc_erdinfo_eldbc_elduc,
eax,
6
);
/// Bit vector of supported extended SGX features.
pub fn miscselect(&self) -> u32 {
self.ebx
}
/// The maximum supported enclave size in non-64-bit mode is 2^retval.
pub fn max_enclave_size_non_64bit(&self) -> u8 {
get_bits(self.edx, 0, 7) as u8
}
/// The maximum supported enclave size in 64-bit mode is 2^retval.
pub fn max_enclave_size_64bit(&self) -> u8 {
get_bits(self.edx, 8, 15) as u8
}
/// Reports the valid bits of SECS.ATTRIBUTES[127:0] that software can set with ECREATE.
pub fn secs_attributes(&self) -> (u64, u64) {
let lower = self.eax1 as u64 | (self.ebx1 as u64) << 32;
let upper = self.ecx1 as u64 | (self.edx1 as u64) << 32;
(lower, upper)
}
/// Iterator over SGX sub-leafs.
pub fn iter(&self) -> SgxSectionIter {
SgxSectionIter { current: 2 }
}
}
/// Iterator over the SGX sub-leafs (ECX >= 2).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SgxSectionIter {
current: u32,
}
impl Iterator for SgxSectionIter {
type Item = SgxSectionInfo;
fn next(&mut self) -> Option<SgxSectionInfo> {
self.current += 1;
let res = cpuid!(EAX_SGX, self.current);
match get_bits(res.eax, 0, 3) {
0b0001 => Some(SgxSectionInfo::Epc(EpcSection {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})),
_ => None,
}
}
}
/// Intel SGX EPC Enumeration Leaf, sub-leaves (EAX = 12H, ECX = 2 or higher)
#[derive(Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum SgxSectionInfo {
// This would be nice: https://github.com/rust-lang/rfcs/pull/1450
Epc(EpcSection),
}
impl Default for SgxSectionInfo {
fn default() -> SgxSectionInfo {
SgxSectionInfo::Epc(Default::default())
}
}
/// EBX:EAX and EDX:ECX provide information on the Enclave Page Cache (EPC) section
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct EpcSection {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl EpcSection {
/// The physical address of the base of the EPC section
pub fn physical_base(&self) -> u64 {
let lower = (get_bits(self.eax, 12, 31) << 12) as u64;
let upper = (get_bits(self.ebx, 0, 19) as u64) << 32;
lower | upper
}
/// Size of the corresponding EPC section within the Processor Reserved Memory.
pub fn size(&self) -> u64 {
let lower = (get_bits(self.ecx, 12, 31) << 12) as u64;
let upper = (get_bits(self.edx, 0, 19) as u64) << 32;
lower | upper
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorTraceInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
leaf1: Option<CpuIdResult>,
}
impl ProcessorTraceInfo {
// EBX features
check_bit_fn!(
doc = "If true, Indicates that IA32_RTIT_CTL.CR3Filter can be set to 1, and \
that IA32_RTIT_CR3_MATCH MSR can be accessed.",
has_rtit_cr3_match,
ebx,
0
);
check_bit_fn!(
doc = "If true, Indicates support of Configurable PSB and Cycle-Accurate Mode.",
has_configurable_psb_and_cycle_accurate_mode,
ebx,
1
);
check_bit_fn!(
doc = "If true, Indicates support of IP Filtering, TraceStop filtering, and \
preservation of Intel PT MSRs across warm reset.",
has_ip_tracestop_filtering,
ebx,
2
);
check_bit_fn!(
doc = "If true, Indicates support of MTC timing packet and suppression of \
COFI-based packets.",
has_mtc_timing_packet_coefi_suppression,
ebx,
3
);
check_bit_fn!(
doc = "Indicates support of PTWRITE. Writes can set IA32_RTIT_CTL[12] (PTWEn \
and IA32_RTIT_CTL[5] (FUPonPTW), and PTWRITE can generate packets",
has_ptwrite,
ebx,
4
);
check_bit_fn!(
doc = "Support of Power Event Trace. Writes can set IA32_RTIT_CTL[4] (PwrEvtEn) \
enabling Power Event Trace packet generation.",
has_power_event_trace,
ebx,
5
);
// ECX features
check_bit_fn!(
doc = "If true, Tracing can be enabled with IA32_RTIT_CTL.ToPA = 1, hence \
utilizing the ToPA output scheme; IA32_RTIT_OUTPUT_BASE and \
IA32_RTIT_OUTPUT_MASK_PTRS MSRs can be accessed.",
has_topa,
ecx,
0
);
check_bit_fn!(
doc = "If true, ToPA tables can hold any number of output entries, up to the \
maximum allowed by the MaskOrTableOffset field of \
IA32_RTIT_OUTPUT_MASK_PTRS.",
has_topa_maximum_entries,
ecx,
1
);
check_bit_fn!(
doc = "If true, Indicates support of Single-Range Output scheme.",
has_single_range_output_scheme,
ecx,
2
);
check_bit_fn!(
doc = "If true, Indicates support of output to Trace Transport subsystem.",
has_trace_transport_subsystem,
ecx,
3
);
check_bit_fn!(
doc = "If true, Generated packets which contain IP payloads have LIP values, \
which include the CS base component.",
has_lip_with_cs_base,
ecx,
31
);
/// Number of configurable Address Ranges for filtering (Bits 2:0).
pub fn configurable_address_ranges(&self) -> u8 {
self.leaf1.map_or(0, |res| get_bits(res.eax, 0, 2) as u8)
}
/// Bitmap of supported MTC period encodings (Bit 31:16).
pub fn supported_mtc_period_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.eax, 16, 31) as u16)
}
/// Bitmap of supported Cycle Threshold value encodings (Bits 15-0).
pub fn supported_cycle_threshold_value_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.ebx, 0, 15) as u16)
}
/// Bitmap of supported Configurable PSB frequency encodings (Bit 31:16)
pub fn supported_psb_frequency_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.ebx, 16, 31) as u16)
}
}
/// Contains time stamp counter information.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct TscInfo {
eax: u32,
ebx: u32,
}
impl TscInfo {
/// An unsigned integer which is the denominator of the TSC/”core crystal clock” ratio (Bits 31:0).
pub fn get_tsc_ratio_denominator(&self) -> u32 {
self.eax
}
/// An unsigned integer which is the numerator of the TSC/”core crystal clock” ratio (Bits 31-0).
pub fn get_tsc_ratio_numerator(&self) -> u32 {
self.ebx
}
}
/// Processor Frequency Information
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorFrequencyInfo {
eax: u32,
ebx: u32,
ecx: u32,
}
impl ProcessorFrequencyInfo {
/// Processor Base Frequency (in MHz).
pub fn processor_base_frequency(&self) -> u16 {
get_bits(self.eax, 0, 15) as u16
}
/// Maximum Frequency (in MHz).
pub fn processor_max_frequency(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Bus (Reference) Frequency (in MHz).
pub fn bus_frequency(&self) -> u16 {
get_bits(self.ecx, 0, 15) as u16
}
}
/// Deterministic Address Translation Structure Iterator
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DatIter {
current: u32,
count: u32,
}
impl Iterator for DatIter {
type Item = DatInfo;
/// Iterate over each sub-leaf with an address translation structure.
fn next(&mut self) -> Option<DatInfo> {
loop {
// Sub-leaf index n is invalid if n exceeds the value that sub-leaf 0 returns in EAX
if self.current > self.count {
return None;
}
let res = cpuid!(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO, self.current);
self.current += 1;
// A sub-leaf index is also invalid if EDX[4:0] returns 0.
if get_bits(res.edx, 0, 4) == 0 {
// Valid sub-leaves do not need to be contiguous or in any particular order.
// A valid sub-leaf may be in a higher input ECX value than an invalid sub-leaf
// or than a valid sub-leaf of a higher or lower-level struc-ture
continue;
}
return Some(DatInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
}
}
}
/// Deterministic Address Translation Structure
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DatInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl DatInfo {
check_bit_fn!(
doc = "4K page size entries supported by this structure",
has_4k_entries,
ebx,
0
);
check_bit_fn!(
doc = "2MB page size entries supported by this structure",
has_2mb_entries,
ebx,
1
);
check_bit_fn!(
doc = "4MB page size entries supported by this structure",
has_4mb_entries,
ebx,
2
);
check_bit_fn!(
doc = "1GB page size entries supported by this structure",
has_1gb_entries,
ebx,
3
);
check_bit_fn!(
doc = "Fully associative structure",
is_fully_associative,
edx,
8
);
/// Partitioning (0: Soft partitioning between the logical processors sharing this structure).
pub fn partitioning(&self) -> u8 {
get_bits(self.ebx, 8, 10) as u8
}
/// Ways of associativity.
pub fn ways(&self) -> u16 {
get_bits(self.ebx, 16, 31) as u16
}
/// Number of Sets.
pub fn sets(&self) -> u32 {
self.ecx
}
/// Translation cache type field.
pub fn cache_type(&self) -> DatType {
match get_bits(self.edx, 0, 4) as u8 {
0b00001 => DatType::DataTLB,
0b00010 => DatType::InstructionTLB,
0b00011 => DatType::UnifiedTLB,
0b00000 => DatType::Null, // should never be returned as this indicates invalid struct!
_ => DatType::Unknown,
}
}
/// Translation cache level (starts at 1)
pub fn cache_level(&self) -> u8 {
get_bits(self.edx, 5, 7) as u8
}
/// Maximum number of addressable IDs for logical processors sharing this translation cache
pub fn max_addressable_ids(&self) -> u16 {
// Add one to the return value to get the result:
(get_bits(self.edx, 14, 25) + 1) as u16
}
}
/// Deterministic Address Translation cache type (EDX bits 04 -- 00)
#[derive(Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum DatType {
/// Null (indicates this sub-leaf is not valid).
Null = 0b00000,
DataTLB = 0b00001,
InstructionTLB = 0b00010,
/// Some unified TLBs will allow a single TLB entry to satisfy data read/write
/// and instruction fetches. Others will require separate entries (e.g., one
/// loaded on data read/write and another loaded on an instruction fetch) .
/// Please see the Intel® 64 and IA-32 Architectures Optimization Reference Manual
/// for details of a particular product.
UnifiedTLB = 0b00011,
Unknown,
}
impl Default for DatType {
fn default() -> DatType {
DatType::Null
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorInfo {
/// MaxSOCID_Index
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl SoCVendorInfo {
pub fn get_soc_vendor_id(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
pub fn get_project_id(&self) -> u32 {
self.ecx
}
pub fn get_stepping_id(&self) -> u32 {
self.edx
}
pub fn get_vendor_brand(&self) -> SoCVendorBrand {
assert!(self.eax >= 3); // Leaf 17H is valid if MaxSOCID_Index >= 3.
let r1 = cpuid!(EAX_SOC_VENDOR_INFO, 1);
let r2 = cpuid!(EAX_SOC_VENDOR_INFO, 2);
let r3 = cpuid!(EAX_SOC_VENDOR_INFO, 3);
SoCVendorBrand { data: [r1, r2, r3] }
}
pub fn get_vendor_attributes(&self) -> Option<SoCVendorAttributesIter> {
if self.eax > 3 {
Some(SoCVendorAttributesIter {
count: self.eax,
current: 3,
})
} else {
None
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorAttributesIter {
count: u32,
current: u32,
}
impl Iterator for SoCVendorAttributesIter {
type Item = CpuIdResult;
/// Iterate over all SoC vendor specific attributes.
fn next(&mut self) -> Option<CpuIdResult> {
if self.current > self.count {
return None;
}
self.count += 1;
Some(cpuid!(EAX_SOC_VENDOR_INFO, self.count))
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorBrand {
#[allow(dead_code)]
data: [CpuIdResult; 3],
}
impl SoCVendorBrand {
pub fn as_string<'a>(&'a self) -> &'a str {
unsafe {
let brand_string_start = self as *const SoCVendorBrand as *const u8;
let slice =
slice::from_raw_parts(brand_string_start, core::mem::size_of::<SoCVendorBrand>());
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
}
}
}
impl fmt::Display for SoCVendorBrand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_string())
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedFunctionInfo {
max_eax_value: u32,
data: [CpuIdResult; 9],
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum L2Associativity {
Disabled = 0x0,
DirectMapped = 0x1,
TwoWay = 0x2,
FourWay = 0x4,
EightWay = 0x6,
SixteenWay = 0x8,
FullyAssiciative = 0xF,
Unknown,
}
impl Default for L2Associativity {
fn default() -> L2Associativity {
L2Associativity::Unknown
}
}
const EAX_EXTENDED_PROC_SIGNATURE: u32 = 0x1;
const EAX_EXTENDED_BRAND_STRING: u32 = 0x4;
const EAX_EXTENDED_CACHE_INFO: u32 = 0x6;
impl ExtendedFunctionInfo {
fn leaf_is_supported(&self, val: u32) -> bool {
val <= self.max_eax_value
}
/// Retrieve processor brand string.
pub fn processor_brand_string<'a>(&'a self) -> Option<&'a str> {
if self.leaf_is_supported(EAX_EXTENDED_BRAND_STRING) {
Some(unsafe {
let brand_string_start = &self.data[2] as *const CpuIdResult as *const u8;
let mut slice = slice::from_raw_parts(brand_string_start, 3 * 4 * 4);
match slice.iter().position(|&x| x == 0) {
Some(index) => slice = slice::from_raw_parts(brand_string_start, index),
None => (),
}
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
})
} else {
None
}
}
/// Extended Processor Signature and Feature Bits.
pub fn extended_signature(&self) -> Option<u32> {
if self.leaf_is_supported(EAX_EXTENDED_PROC_SIGNATURE) {
Some(self.data[1].eax)
} else {
None
}
}
/// Cache Line size in bytes
pub fn cache_line_size(&self) -> Option<u8> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(get_bits(self.data[6].ecx, 0, 7) as u8)
} else {
None
}
}
/// L2 Associativity field
pub fn l2_associativity(&self) -> Option<L2Associativity> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(match get_bits(self.data[6].ecx, 12, 15) {
0x0 => L2Associativity::Disabled,
0x1 => L2Associativity::DirectMapped,
0x2 => L2Associativity::TwoWay,
0x4 => L2Associativity::FourWay,
0x6 => L2Associativity::EightWay,
0x8 => L2Associativity::SixteenWay,
0xF => L2Associativity::FullyAssiciative,
_ => L2Associativity::Unknown,
})
} else {
None
}
}
/// Cache size in 1K units
pub fn cache_size(&self) -> Option<u16> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(get_bits(self.data[6].ecx, 16, 31) as u16)
} else {
None
}
}
/// #Physical Address Bits
pub fn physical_address_bits(&self) -> Option<u8> {
if self.leaf_is_supported(8) {
Some(get_bits(self.data[8].eax, 0, 7) as u8)
} else {
None
}
}
/// #Linear Address Bits
pub fn linear_address_bits(&self) -> Option<u8> {
if self.leaf_is_supported(8) {
Some(get_bits(self.data[8].eax, 8, 15) as u8)
} else {
None
}
}
/// Is Invariant TSC available?
pub fn has_invariant_tsc(&self) -> bool {
self.leaf_is_supported(7) && self.data[7].edx & (1 << 8) > 0
}
/// Is LAHF/SAHF available in 64-bit mode?
pub fn has_lahf_sahf(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::LAHF_SAHF)
}
/// Is LZCNT available?
pub fn has_lzcnt(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::LZCNT)
}
/// Is PREFETCHW available?
pub fn has_prefetchw(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::PREFETCHW)
}
/// Are fast system calls available.
pub fn has_syscall_sysret(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::SYSCALL_SYSRET)
}
/// Is there support for execute disable bit.
pub fn has_execute_disable(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::EXECUTE_DISABLE)
}
/// Is there support for 1GiB pages.
pub fn has_1gib_pages(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::GIB_PAGES)
}
/// Check support for rdtscp instruction.
pub fn has_rdtscp(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::RDTSCP)
}
/// Check support for 64-bit mode.
pub fn has_64bit_mode(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::I64BIT_MODE)
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFunctionInfoEcx: u32 {
/// LAHF/SAHF available in 64-bit mode.
const LAHF_SAHF = 1 << 0;
/// Bit 05: LZCNT
const LZCNT = 1 << 5;
/// Bit 08: PREFETCHW
const PREFETCHW = 1 << 8;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFunctionInfoEdx: u32 {
/// SYSCALL/SYSRET available in 64-bit mode (Bit 11).
const SYSCALL_SYSRET = 1 << 11;
/// Execute Disable Bit available (Bit 20).
const EXECUTE_DISABLE = 1 << 20;
/// 1-GByte pages are available if 1 (Bit 26).
const GIB_PAGES = 1 << 26;
/// RDTSCP and IA32_TSC_AUX are available if 1 (Bit 27).
const RDTSCP = 1 << 27;
/// Intel ® 64 Architecture available if 1 (Bit 29).
const I64BIT_MODE = 1 << 29;
}
}
Add nomimal frequency and tsc frequency to TscInfo struct.
Signed-off-by: Gerd Zellweger <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@gerdzellweger.com>
#![no_std]
#![crate_name = "raw_cpuid"]
#![crate_type = "lib"]
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
mod tests;
#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate bitflags;
/// Provides `cpuid` on stable by linking against a C implementation.
#[cfg(not(feature = "use_arch"))]
mod native_cpuid {
use super::CpuIdResult;
extern "C" {
fn cpuid(a: *mut u32, b: *mut u32, c: *mut u32, d: *mut u32);
}
pub fn cpuid_count(mut eax: u32, mut ecx: u32) -> CpuIdResult {
let mut ebx = 0u32;
let mut edx = 0u32;
unsafe {
cpuid(&mut eax, &mut ebx, &mut ecx, &mut edx);
}
CpuIdResult { eax, ebx, ecx, edx }
}
}
/// Uses Rust's `cpuid` function from the `arch` module.
#[cfg(feature = "use_arch")]
mod native_cpuid {
use super::CpuIdResult;
#[cfg(target_arch = "x86")]
use core::arch::x86 as arch;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64 as arch;
pub fn cpuid_count(a: u32, c: u32) -> CpuIdResult {
let result = unsafe { self::arch::__cpuid_count(a, c) };
CpuIdResult {
eax: result.eax,
ebx: result.ebx,
ecx: result.ecx,
edx: result.edx,
}
}
}
use core::cmp::min;
use core::fmt;
use core::mem::transmute;
use core::slice;
use core::str;
#[cfg(not(test))]
mod std {
pub use core::ops;
pub use core::option;
}
/// Macro which queries cpuid directly.
///
/// First parameter is cpuid leaf (EAX register value),
/// second optional parameter is the subleaf (ECX register value).
macro_rules! cpuid {
($eax:expr) => {
$crate::native_cpuid::cpuid_count($eax as u32, 0)
};
($eax:expr, $ecx:expr) => {
$crate::native_cpuid::cpuid_count($eax as u32, $ecx as u32)
};
}
fn as_bytes(v: &u32) -> &[u8] {
let start = v as *const u32 as *const u8;
unsafe { slice::from_raw_parts(start, 4) }
}
fn get_bits(r: u32, from: u32, to: u32) -> u32 {
assert!(from <= 31);
assert!(to <= 31);
assert!(from <= to);
let mask = match to {
31 => 0xffffffff,
_ => (1 << (to + 1)) - 1,
};
(r & mask) >> from
}
macro_rules! check_flag {
($doc:meta, $fun:ident, $flags:ident, $flag:expr) => (
#[$doc]
pub fn $fun(&self) -> bool {
self.$flags.contains($flag)
}
)
}
macro_rules! is_bit_set {
($field:expr, $bit:expr) => {
$field & (1 << $bit) > 0
};
}
macro_rules! check_bit_fn {
($doc:meta, $fun:ident, $field:ident, $bit:expr) => (
#[$doc]
pub fn $fun(&self) -> bool {
is_bit_set!(self.$field, $bit)
}
)
}
/// Main type used to query for information about the CPU we're running on.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CpuId {
max_eax_value: u32,
}
/// Low-level data-structure to store result of cpuid instruction.
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CpuIdResult {
/// Return value EAX register
pub eax: u32,
/// Return value EBX register
pub ebx: u32,
/// Return value ECX register
pub ecx: u32,
/// Return value EDX register
pub edx: u32,
}
const EAX_VENDOR_INFO: u32 = 0x0;
const EAX_FEATURE_INFO: u32 = 0x1;
const EAX_CACHE_INFO: u32 = 0x2;
const EAX_PROCESSOR_SERIAL: u32 = 0x3;
const EAX_CACHE_PARAMETERS: u32 = 0x4;
const EAX_MONITOR_MWAIT_INFO: u32 = 0x5;
const EAX_THERMAL_POWER_INFO: u32 = 0x6;
const EAX_STRUCTURED_EXTENDED_FEATURE_INFO: u32 = 0x7;
const EAX_DIRECT_CACHE_ACCESS_INFO: u32 = 0x9;
const EAX_PERFORMANCE_MONITOR_INFO: u32 = 0xA;
const EAX_EXTENDED_TOPOLOGY_INFO: u32 = 0xB;
const EAX_EXTENDED_STATE_INFO: u32 = 0xD;
const EAX_RDT_MONITORING: u32 = 0xF;
const EAX_RDT_ALLOCATION: u32 = 0x10;
const EAX_SGX: u32 = 0x12;
const EAX_TRACE_INFO: u32 = 0x14;
const EAX_TIME_STAMP_COUNTER_INFO: u32 = 0x15;
const EAX_FREQUENCY_INFO: u32 = 0x16;
const EAX_SOC_VENDOR_INFO: u32 = 0x17;
const EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO: u32 = 0x18;
const EAX_EXTENDED_FUNCTION_INFO: u32 = 0x80000000;
impl CpuId {
/// Return new CPUID struct.
pub fn new() -> CpuId {
let res = cpuid!(EAX_VENDOR_INFO);
CpuId {
max_eax_value: res.eax,
}
}
fn leaf_is_supported(&self, val: u32) -> bool {
val <= self.max_eax_value
}
/// Return information about vendor.
/// This is typically a ASCII readable string such as
/// GenuineIntel for Intel CPUs or AuthenticAMD for AMD CPUs.
pub fn get_vendor_info(&self) -> Option<VendorInfo> {
if self.leaf_is_supported(EAX_VENDOR_INFO) {
let res = cpuid!(EAX_VENDOR_INFO);
Some(VendorInfo {
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Query a set of features that are available on this CPU.
pub fn get_feature_info(&self) -> Option<FeatureInfo> {
if self.leaf_is_supported(EAX_FEATURE_INFO) {
let res = cpuid!(EAX_FEATURE_INFO);
Some(FeatureInfo {
eax: res.eax,
ebx: res.ebx,
edx_ecx: FeatureInfoFlags {
bits: (((res.edx as u64) << 32) | (res.ecx as u64)),
},
})
} else {
None
}
}
/// Query basic information about caches. This will just return an index
/// into a static table of cache descriptions (see `CACHE_INFO_TABLE`).
pub fn get_cache_info(&self) -> Option<CacheInfoIter> {
if self.leaf_is_supported(EAX_CACHE_INFO) {
let res = cpuid!(EAX_CACHE_INFO);
Some(CacheInfoIter {
current: 1,
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Retrieve serial number of processor.
pub fn get_processor_serial(&self) -> Option<ProcessorSerial> {
if self.leaf_is_supported(EAX_PROCESSOR_SERIAL) {
let res = cpuid!(EAX_PROCESSOR_SERIAL);
Some(ProcessorSerial {
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Retrieve more elaborate information about caches (as opposed
/// to `get_cache_info`). This will tell us about associativity,
/// set size, line size etc. for each level of the cache hierarchy.
pub fn get_cache_parameters(&self) -> Option<CacheParametersIter> {
if self.leaf_is_supported(EAX_CACHE_PARAMETERS) {
Some(CacheParametersIter { current: 0 })
} else {
None
}
}
/// Information about how monitor/mwait works on this CPU.
pub fn get_monitor_mwait_info(&self) -> Option<MonitorMwaitInfo> {
if self.leaf_is_supported(EAX_MONITOR_MWAIT_INFO) {
let res = cpuid!(EAX_MONITOR_MWAIT_INFO);
Some(MonitorMwaitInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Query information about thermal and power management features of the CPU.
pub fn get_thermal_power_info(&self) -> Option<ThermalPowerInfo> {
if self.leaf_is_supported(EAX_THERMAL_POWER_INFO) {
let res = cpuid!(EAX_THERMAL_POWER_INFO);
Some(ThermalPowerInfo {
eax: ThermalPowerFeaturesEax { bits: res.eax },
ebx: res.ebx,
ecx: ThermalPowerFeaturesEcx { bits: res.ecx },
edx: res.edx,
})
} else {
None
}
}
/// Find out about more features supported by this CPU.
pub fn get_extended_feature_info(&self) -> Option<ExtendedFeatures> {
if self.leaf_is_supported(EAX_STRUCTURED_EXTENDED_FEATURE_INFO) {
let res = cpuid!(EAX_STRUCTURED_EXTENDED_FEATURE_INFO);
assert!(res.eax == 0);
Some(ExtendedFeatures {
eax: res.eax,
ebx: ExtendedFeaturesEbx { bits: res.ebx },
ecx: ExtendedFeaturesEcx { bits: res.ecx },
edx: res.edx,
})
} else {
None
}
}
/// Direct cache access info.
pub fn get_direct_cache_access_info(&self) -> Option<DirectCacheAccessInfo> {
if self.leaf_is_supported(EAX_DIRECT_CACHE_ACCESS_INFO) {
let res = cpuid!(EAX_DIRECT_CACHE_ACCESS_INFO);
Some(DirectCacheAccessInfo { eax: res.eax })
} else {
None
}
}
/// Info about performance monitoring (how many counters etc.).
pub fn get_performance_monitoring_info(&self) -> Option<PerformanceMonitoringInfo> {
if self.leaf_is_supported(EAX_PERFORMANCE_MONITOR_INFO) {
let res = cpuid!(EAX_PERFORMANCE_MONITOR_INFO);
Some(PerformanceMonitoringInfo {
eax: res.eax,
ebx: PerformanceMonitoringFeaturesEbx { bits: res.ebx },
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Information about topology (how many cores and what kind of cores).
pub fn get_extended_topology_info(&self) -> Option<ExtendedTopologyIter> {
if self.leaf_is_supported(EAX_EXTENDED_TOPOLOGY_INFO) {
Some(ExtendedTopologyIter { level: 0 })
} else {
None
}
}
/// Information for saving/restoring extended register state.
pub fn get_extended_state_info(&self) -> Option<ExtendedStateInfo> {
if self.leaf_is_supported(EAX_EXTENDED_STATE_INFO) {
let res = cpuid!(EAX_EXTENDED_STATE_INFO, 0);
let res1 = cpuid!(EAX_EXTENDED_STATE_INFO, 1);
Some(ExtendedStateInfo {
eax: ExtendedStateInfoXCR0Flags { bits: res.eax },
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
eax1: res1.eax,
ebx1: res1.ebx,
ecx1: ExtendedStateInfoXSSFlags { bits: res1.ecx },
edx1: res1.edx,
})
} else {
None
}
}
/// Quality of service informations.
pub fn get_rdt_monitoring_info(&self) -> Option<RdtMonitoringInfo> {
let res = cpuid!(EAX_RDT_MONITORING, 0);
if self.leaf_is_supported(EAX_RDT_MONITORING) {
Some(RdtMonitoringInfo {
ebx: res.ebx,
edx: res.edx,
})
} else {
None
}
}
/// Quality of service enforcement information.
pub fn get_rdt_allocation_info(&self) -> Option<RdtAllocationInfo> {
let res = cpuid!(EAX_RDT_ALLOCATION, 0);
if self.leaf_is_supported(EAX_RDT_ALLOCATION) {
Some(RdtAllocationInfo { ebx: res.ebx })
} else {
None
}
}
pub fn get_sgx_info(&self) -> Option<SgxInfo> {
// Leaf 12H sub-leaf 0 (ECX = 0) is supported if CPUID.(EAX=07H, ECX=0H):EBX[SGX] = 1.
self.get_extended_feature_info().and_then(|info| {
if self.leaf_is_supported(EAX_SGX) && info.has_sgx() {
let res = cpuid!(EAX_SGX, 0);
let res1 = cpuid!(EAX_SGX, 1);
Some(SgxInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
eax1: res1.eax,
ebx1: res1.ebx,
ecx1: res1.ecx,
edx1: res1.edx,
})
} else {
None
}
})
}
/// Intel Processor Trace Enumeration Information.
pub fn get_processor_trace_info(&self) -> Option<ProcessorTraceInfo> {
let res = cpuid!(EAX_TRACE_INFO, 0);
if self.leaf_is_supported(EAX_TRACE_INFO) {
let res1 = if res.eax >= 1 {
Some(cpuid!(EAX_TRACE_INFO, 1))
} else {
None
};
Some(ProcessorTraceInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
leaf1: res1,
})
} else {
None
}
}
/// Time Stamp Counter/Core Crystal Clock Information.
pub fn get_tsc_info(&self) -> Option<TscInfo> {
let res = cpuid!(EAX_TIME_STAMP_COUNTER_INFO, 0);
if self.leaf_is_supported(EAX_TIME_STAMP_COUNTER_INFO) {
Some(TscInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
})
} else {
None
}
}
/// Processor Frequency Information.
pub fn get_processor_frequency_info(&self) -> Option<ProcessorFrequencyInfo> {
let res = cpuid!(EAX_FREQUENCY_INFO, 0);
if self.leaf_is_supported(EAX_FREQUENCY_INFO) {
Some(ProcessorFrequencyInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
})
} else {
None
}
}
pub fn deterministic_address_translation_info(&self) -> Option<DatIter> {
if self.leaf_is_supported(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO) {
let res = cpuid!(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO, 0);
Some(DatIter {
current: 0,
count: res.eax,
})
} else {
None
}
}
pub fn get_soc_vendor_info(&self) -> Option<SoCVendorInfo> {
let res = cpuid!(EAX_SOC_VENDOR_INFO, 0);
if self.leaf_is_supported(EAX_SOC_VENDOR_INFO) {
Some(SoCVendorInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})
} else {
None
}
}
/// Extended functionality of CPU described here (including more supported features).
/// This also contains a more detailed CPU model identifier.
pub fn get_extended_function_info(&self) -> Option<ExtendedFunctionInfo> {
let res = cpuid!(EAX_EXTENDED_FUNCTION_INFO);
if res.eax == 0 {
return None;
}
let mut ef = ExtendedFunctionInfo {
max_eax_value: res.eax - EAX_EXTENDED_FUNCTION_INFO,
data: [
CpuIdResult {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
},
],
};
let max_eax_value = min(ef.max_eax_value + 1, ef.data.len() as u32);
for i in 1..max_eax_value {
ef.data[i as usize] = cpuid!(EAX_EXTENDED_FUNCTION_INFO + i);
}
Some(ef)
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct VendorInfo {
ebx: u32,
edx: u32,
ecx: u32,
}
impl VendorInfo {
/// Return vendor identification as human readable string.
pub fn as_string<'a>(&'a self) -> &'a str {
unsafe {
let brand_string_start = self as *const VendorInfo as *const u8;
let slice = slice::from_raw_parts(brand_string_start, 3 * 4);
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
}
}
}
/// Used to iterate over cache information contained in cpuid instruction.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheInfoIter {
current: u32,
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl Iterator for CacheInfoIter {
type Item = CacheInfo;
/// Iterate over all cache information.
fn next(&mut self) -> Option<CacheInfo> {
// Every byte of the 4 register values returned by cpuid
// can contain information about a cache (except the
// very first one).
if self.current >= 4 * 4 {
return None;
}
let reg_index = self.current % 4;
let byte_index = self.current / 4;
let reg = match reg_index {
0 => self.eax,
1 => self.ebx,
2 => self.ecx,
3 => self.edx,
_ => unreachable!(),
};
let byte = as_bytes(®)[byte_index as usize];
if byte == 0 {
self.current += 1;
return self.next();
}
for cache_info in CACHE_INFO_TABLE.into_iter() {
if cache_info.num == byte {
self.current += 1;
return Some(*cache_info);
}
}
None
}
}
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum CacheInfoType {
GENERAL,
CACHE,
TLB,
STLB,
DTLB,
PREFETCH,
}
impl Default for CacheInfoType {
fn default() -> CacheInfoType {
CacheInfoType::GENERAL
}
}
/// Describes any kind of cache (TLB, Data and Instruction caches plus prefetchers).
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheInfo {
/// Number as retrieved from cpuid
pub num: u8,
/// Cache type
pub typ: CacheInfoType,
}
impl CacheInfo {
/// Description of the cache (from Intel Manual)
pub fn desc(&self) -> &'static str {
match self.num {
0x00 => "Null descriptor, this byte contains no information",
0x01 => "Instruction TLB: 4 KByte pages, 4-way set associative, 32 entries",
0x02 => "Instruction TLB: 4 MByte pages, fully associative, 2 entries",
0x03 => "Data TLB: 4 KByte pages, 4-way set associative, 64 entries",
0x04 => "Data TLB: 4 MByte pages, 4-way set associative, 8 entries",
0x05 => "Data TLB1: 4 MByte pages, 4-way set associative, 32 entries",
0x06 => "1st-level instruction cache: 8 KBytes, 4-way set associative, 32 byte line size",
0x08 => "1st-level instruction cache: 16 KBytes, 4-way set associative, 32 byte line size",
0x09 => "1st-level instruction cache: 32KBytes, 4-way set associative, 64 byte line size",
0x0A => "1st-level data cache: 8 KBytes, 2-way set associative, 32 byte line size",
0x0B => "Instruction TLB: 4 MByte pages, 4-way set associative, 4 entries",
0x0C => "1st-level data cache: 16 KBytes, 4-way set associative, 32 byte line size",
0x0D => "1st-level data cache: 16 KBytes, 4-way set associative, 64 byte line size",
0x0E => "1st-level data cache: 24 KBytes, 6-way set associative, 64 byte line size",
0x1D => "2nd-level cache: 128 KBytes, 2-way set associative, 64 byte line size",
0x21 => "2nd-level cache: 256 KBytes, 8-way set associative, 64 byte line size",
0x22 => "3rd-level cache: 512 KBytes, 4-way set associative, 64 byte line size, 2 lines per sector",
0x23 => "3rd-level cache: 1 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x24 => "2nd-level cache: 1 MBytes, 16-way set associative, 64 byte line size",
0x25 => "3rd-level cache: 2 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x29 => "3rd-level cache: 4 MBytes, 8-way set associative, 64 byte line size, 2 lines per sector",
0x2C => "1st-level data cache: 32 KBytes, 8-way set associative, 64 byte line size",
0x30 => "1st-level instruction cache: 32 KBytes, 8-way set associative, 64 byte line size",
0x40 => "No 2nd-level cache or, if processor contains a valid 2nd-level cache, no 3rd-level cache",
0x41 => "2nd-level cache: 128 KBytes, 4-way set associative, 32 byte line size",
0x42 => "2nd-level cache: 256 KBytes, 4-way set associative, 32 byte line size",
0x43 => "2nd-level cache: 512 KBytes, 4-way set associative, 32 byte line size",
0x44 => "2nd-level cache: 1 MByte, 4-way set associative, 32 byte line size",
0x45 => "2nd-level cache: 2 MByte, 4-way set associative, 32 byte line size",
0x46 => "3rd-level cache: 4 MByte, 4-way set associative, 64 byte line size",
0x47 => "3rd-level cache: 8 MByte, 8-way set associative, 64 byte line size",
0x48 => "2nd-level cache: 3MByte, 12-way set associative, 64 byte line size",
0x49 => "3rd-level cache: 4MB, 16-way set associative, 64-byte line size (Intel Xeon processor MP, Family 0FH, Model 06H); 2nd-level cache: 4 MByte, 16-way set ssociative, 64 byte line size",
0x4A => "3rd-level cache: 6MByte, 12-way set associative, 64 byte line size",
0x4B => "3rd-level cache: 8MByte, 16-way set associative, 64 byte line size",
0x4C => "3rd-level cache: 12MByte, 12-way set associative, 64 byte line size",
0x4D => "3rd-level cache: 16MByte, 16-way set associative, 64 byte line size",
0x4E => "2nd-level cache: 6MByte, 24-way set associative, 64 byte line size",
0x4F => "Instruction TLB: 4 KByte pages, 32 entries",
0x50 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 64 entries",
0x51 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 128 entries",
0x52 => "Instruction TLB: 4 KByte and 2-MByte or 4-MByte pages, 256 entries",
0x55 => "Instruction TLB: 2-MByte or 4-MByte pages, fully associative, 7 entries",
0x56 => "Data TLB0: 4 MByte pages, 4-way set associative, 16 entries",
0x57 => "Data TLB0: 4 KByte pages, 4-way associative, 16 entries",
0x59 => "Data TLB0: 4 KByte pages, fully associative, 16 entries",
0x5A => "Data TLB0: 2-MByte or 4 MByte pages, 4-way set associative, 32 entries",
0x5B => "Data TLB: 4 KByte and 4 MByte pages, 64 entries",
0x5C => "Data TLB: 4 KByte and 4 MByte pages,128 entries",
0x5D => "Data TLB: 4 KByte and 4 MByte pages,256 entries",
0x60 => "1st-level data cache: 16 KByte, 8-way set associative, 64 byte line size",
0x61 => "Instruction TLB: 4 KByte pages, fully associative, 48 entries",
0x63 => "Data TLB: 2 MByte or 4 MByte pages, 4-way set associative, 32 entries and a separate array with 1 GByte pages, 4-way set associative, 4 entries",
0x64 => "Data TLB: 4 KByte pages, 4-way set associative, 512 entries",
0x66 => "1st-level data cache: 8 KByte, 4-way set associative, 64 byte line size",
0x67 => "1st-level data cache: 16 KByte, 4-way set associative, 64 byte line size",
0x68 => "1st-level data cache: 32 KByte, 4-way set associative, 64 byte line size",
0x6A => "uTLB: 4 KByte pages, 8-way set associative, 64 entries",
0x6B => "DTLB: 4 KByte pages, 8-way set associative, 256 entries",
0x6C => "DTLB: 2M/4M pages, 8-way set associative, 128 entries",
0x6D => "DTLB: 1 GByte pages, fully associative, 16 entries",
0x70 => "Trace cache: 12 K-μop, 8-way set associative",
0x71 => "Trace cache: 16 K-μop, 8-way set associative",
0x72 => "Trace cache: 32 K-μop, 8-way set associative",
0x76 => "Instruction TLB: 2M/4M pages, fully associative, 8 entries",
0x78 => "2nd-level cache: 1 MByte, 4-way set associative, 64byte line size",
0x79 => "2nd-level cache: 128 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7A => "2nd-level cache: 256 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7B => "2nd-level cache: 512 KByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7C => "2nd-level cache: 1 MByte, 8-way set associative, 64 byte line size, 2 lines per sector",
0x7D => "2nd-level cache: 2 MByte, 8-way set associative, 64byte line size",
0x7F => "2nd-level cache: 512 KByte, 2-way set associative, 64-byte line size",
0x80 => "2nd-level cache: 512 KByte, 8-way set associative, 64-byte line size",
0x82 => "2nd-level cache: 256 KByte, 8-way set associative, 32 byte line size",
0x83 => "2nd-level cache: 512 KByte, 8-way set associative, 32 byte line size",
0x84 => "2nd-level cache: 1 MByte, 8-way set associative, 32 byte line size",
0x85 => "2nd-level cache: 2 MByte, 8-way set associative, 32 byte line size",
0x86 => "2nd-level cache: 512 KByte, 4-way set associative, 64 byte line size",
0x87 => "2nd-level cache: 1 MByte, 8-way set associative, 64 byte line size",
0xA0 => "DTLB: 4k pages, fully associative, 32 entries",
0xB0 => "Instruction TLB: 4 KByte pages, 4-way set associative, 128 entries",
0xB1 => "Instruction TLB: 2M pages, 4-way, 8 entries or 4M pages, 4-way, 4 entries",
0xB2 => "Instruction TLB: 4KByte pages, 4-way set associative, 64 entries",
0xB3 => "Data TLB: 4 KByte pages, 4-way set associative, 128 entries",
0xB4 => "Data TLB1: 4 KByte pages, 4-way associative, 256 entries",
0xB5 => "Instruction TLB: 4KByte pages, 8-way set associative, 64 entries",
0xB6 => "Instruction TLB: 4KByte pages, 8-way set associative, 128 entries",
0xBA => "Data TLB1: 4 KByte pages, 4-way associative, 64 entries",
0xC0 => "Data TLB: 4 KByte and 4 MByte pages, 4-way associative, 8 entries",
0xC1 => "Shared 2nd-Level TLB: 4 KByte/2MByte pages, 8-way associative, 1024 entries",
0xC2 => "DTLB: 2 MByte/$MByte pages, 4-way associative, 16 entries",
0xC3 => "Shared 2nd-Level TLB: 4 KByte /2 MByte pages, 6-way associative, 1536 entries. Also 1GBbyte pages, 4-way, 16 entries.",
0xC4 => "DTLB: 2M/4M Byte pages, 4-way associative, 32 entries",
0xCA => "Shared 2nd-Level TLB: 4 KByte pages, 4-way associative, 512 entries",
0xD0 => "3rd-level cache: 512 KByte, 4-way set associative, 64 byte line size",
0xD1 => "3rd-level cache: 1 MByte, 4-way set associative, 64 byte line size",
0xD2 => "3rd-level cache: 2 MByte, 4-way set associative, 64 byte line size",
0xD6 => "3rd-level cache: 1 MByte, 8-way set associative, 64 byte line size",
0xD7 => "3rd-level cache: 2 MByte, 8-way set associative, 64 byte line size",
0xD8 => "3rd-level cache: 4 MByte, 8-way set associative, 64 byte line size",
0xDC => "3rd-level cache: 1.5 MByte, 12-way set associative, 64 byte line size",
0xDD => "3rd-level cache: 3 MByte, 12-way set associative, 64 byte line size",
0xDE => "3rd-level cache: 6 MByte, 12-way set associative, 64 byte line size",
0xE2 => "3rd-level cache: 2 MByte, 16-way set associative, 64 byte line size",
0xE3 => "3rd-level cache: 4 MByte, 16-way set associative, 64 byte line size",
0xE4 => "3rd-level cache: 8 MByte, 16-way set associative, 64 byte line size",
0xEA => "3rd-level cache: 12MByte, 24-way set associative, 64 byte line size",
0xEB => "3rd-level cache: 18MByte, 24-way set associative, 64 byte line size",
0xEC => "3rd-level cache: 24MByte, 24-way set associative, 64 byte line size",
0xF0 => "64-Byte prefetching",
0xF1 => "128-Byte prefetching",
0xFE => "CPUID leaf 2 does not report TLB descriptor information; use CPUID leaf 18H to query TLB and other address translation parameters.",
0xFF => "CPUID leaf 2 does not report cache descriptor information, use CPUID leaf 4 to query cache parameters",
_ => "Unknown cache type!"
}
}
}
impl fmt::Display for CacheInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let typ = match self.typ {
CacheInfoType::GENERAL => "N/A",
CacheInfoType::CACHE => "Cache",
CacheInfoType::TLB => "TLB",
CacheInfoType::STLB => "STLB",
CacheInfoType::DTLB => "DTLB",
CacheInfoType::PREFETCH => "Prefetcher",
};
write!(f, "{:x}:\t {}: {}", self.num, typ, self.desc())
}
}
/// This table is taken from Intel manual (Section CPUID instruction).
pub const CACHE_INFO_TABLE: [CacheInfo; 108] = [
CacheInfo {
num: 0x00,
typ: CacheInfoType::GENERAL,
},
CacheInfo {
num: 0x01,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x02,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x03,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x04,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x05,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x06,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x08,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x09,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0B,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x0C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x0E,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x21,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x22,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x23,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x24,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x25,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x29,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x2C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x30,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x40,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x41,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x42,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x43,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x44,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x45,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x46,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x47,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x48,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x49,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4E,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x4F,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x50,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x51,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x52,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x55,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x56,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x57,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x59,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5A,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5B,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5C,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x5D,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x60,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x61,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x63,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x66,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x67,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x68,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x6D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x70,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x71,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x72,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x76,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0x78,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x79,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7A,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7B,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7C,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7D,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x7F,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x80,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x82,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x83,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x84,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x85,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x86,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0x87,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xB0,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB1,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB2,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB3,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB4,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB5,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xB6,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xBA,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xC0,
typ: CacheInfoType::TLB,
},
CacheInfo {
num: 0xC1,
typ: CacheInfoType::STLB,
},
CacheInfo {
num: 0xC2,
typ: CacheInfoType::DTLB,
},
CacheInfo {
num: 0xCA,
typ: CacheInfoType::STLB,
},
CacheInfo {
num: 0xD0,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD1,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD2,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD6,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD7,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xD8,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDC,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDD,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xDE,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE2,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE3,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xE4,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEA,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEB,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xEC,
typ: CacheInfoType::CACHE,
},
CacheInfo {
num: 0xF0,
typ: CacheInfoType::PREFETCH,
},
CacheInfo {
num: 0xF1,
typ: CacheInfoType::PREFETCH,
},
CacheInfo {
num: 0xFE,
typ: CacheInfoType::GENERAL,
},
CacheInfo {
num: 0xFF,
typ: CacheInfoType::GENERAL,
},
];
impl fmt::Display for VendorInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_string())
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorSerial {
ecx: u32,
edx: u32,
}
impl ProcessorSerial {
/// Bits 00-31 of 96 bit processor serial number.
/// (Available in Pentium III processor only; otherwise, the value in this register is reserved.)
pub fn serial_lower(&self) -> u32 {
self.ecx
}
/// Bits 32-63 of 96 bit processor serial number.
/// (Available in Pentium III processor only; otherwise, the value in this register is reserved.)
pub fn serial_middle(&self) -> u32 {
self.edx
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct FeatureInfo {
eax: u32,
ebx: u32,
edx_ecx: FeatureInfoFlags,
}
impl FeatureInfo {
/// Version Information: Extended Family
pub fn extended_family_id(&self) -> u8 {
get_bits(self.eax, 20, 27) as u8
}
/// Version Information: Extended Model
pub fn extended_model_id(&self) -> u8 {
get_bits(self.eax, 16, 19) as u8
}
/// Version Information: Family
pub fn family_id(&self) -> u8 {
get_bits(self.eax, 8, 11) as u8
}
/// Version Information: Model
pub fn model_id(&self) -> u8 {
get_bits(self.eax, 4, 7) as u8
}
/// Version Information: Stepping ID
pub fn stepping_id(&self) -> u8 {
get_bits(self.eax, 0, 3) as u8
}
/// Brand Index
pub fn brand_index(&self) -> u8 {
get_bits(self.ebx, 0, 7) as u8
}
/// CLFLUSH line size (Value ∗ 8 = cache line size in bytes)
pub fn cflush_cache_line_size(&self) -> u8 {
get_bits(self.ebx, 8, 15) as u8
}
/// Initial APIC ID
pub fn initial_local_apic_id(&self) -> u8 {
get_bits(self.ebx, 24, 31) as u8
}
/// Maximum number of addressable IDs for logical processors in this physical package.
pub fn max_logical_processor_ids(&self) -> u8 {
get_bits(self.ebx, 16, 23) as u8
}
check_flag!(
doc = "Streaming SIMD Extensions 3 (SSE3). A value of 1 indicates the processor \
supports this technology.",
has_sse3,
edx_ecx,
FeatureInfoFlags::SSE3
);
check_flag!(
doc = "PCLMULQDQ. A value of 1 indicates the processor supports the PCLMULQDQ \
instruction",
has_pclmulqdq,
edx_ecx,
FeatureInfoFlags::PCLMULQDQ
);
check_flag!(
doc = "64-bit DS Area. A value of 1 indicates the processor supports DS area \
using 64-bit layout",
has_ds_area,
edx_ecx,
FeatureInfoFlags::DTES64
);
check_flag!(
doc = "MONITOR/MWAIT. A value of 1 indicates the processor supports this feature.",
has_monitor_mwait,
edx_ecx,
FeatureInfoFlags::MONITOR
);
check_flag!(
doc = "CPL Qualified Debug Store. A value of 1 indicates the processor supports \
the extensions to the Debug Store feature to allow for branch message \
storage qualified by CPL.",
has_cpl,
edx_ecx,
FeatureInfoFlags::DSCPL
);
check_flag!(
doc = "Virtual Machine Extensions. A value of 1 indicates that the processor \
supports this technology.",
has_vmx,
edx_ecx,
FeatureInfoFlags::VMX
);
check_flag!(
doc = "Safer Mode Extensions. A value of 1 indicates that the processor supports \
this technology. See Chapter 5, Safer Mode Extensions Reference.",
has_smx,
edx_ecx,
FeatureInfoFlags::SMX
);
check_flag!(
doc = "Enhanced Intel SpeedStep® technology. A value of 1 indicates that the \
processor supports this technology.",
has_eist,
edx_ecx,
FeatureInfoFlags::EIST
);
check_flag!(
doc = "Thermal Monitor 2. A value of 1 indicates whether the processor supports \
this technology.",
has_tm2,
edx_ecx,
FeatureInfoFlags::TM2
);
check_flag!(
doc = "A value of 1 indicates the presence of the Supplemental Streaming SIMD \
Extensions 3 (SSSE3). A value of 0 indicates the instruction extensions \
are not present in the processor",
has_ssse3,
edx_ecx,
FeatureInfoFlags::SSSE3
);
check_flag!(
doc = "L1 Context ID. A value of 1 indicates the L1 data cache mode can be set \
to either adaptive mode or shared mode. A value of 0 indicates this \
feature is not supported. See definition of the IA32_MISC_ENABLE MSR Bit \
24 (L1 Data Cache Context Mode) for details.",
has_cnxtid,
edx_ecx,
FeatureInfoFlags::CNXTID
);
check_flag!(
doc = "A value of 1 indicates the processor supports FMA extensions using YMM \
state.",
has_fma,
edx_ecx,
FeatureInfoFlags::FMA
);
check_flag!(
doc = "CMPXCHG16B Available. A value of 1 indicates that the feature is \
available. See the CMPXCHG8B/CMPXCHG16B Compare and Exchange Bytes \
section. 14",
has_cmpxchg16b,
edx_ecx,
FeatureInfoFlags::CMPXCHG16B
);
check_flag!(
doc = "Perfmon and Debug Capability: A value of 1 indicates the processor \
supports the performance and debug feature indication MSR \
IA32_PERF_CAPABILITIES.",
has_pdcm,
edx_ecx,
FeatureInfoFlags::PDCM
);
check_flag!(
doc = "Process-context identifiers. A value of 1 indicates that the processor \
supports PCIDs and the software may set CR4.PCIDE to 1.",
has_pcid,
edx_ecx,
FeatureInfoFlags::PCID
);
check_flag!(
doc = "A value of 1 indicates the processor supports the ability to prefetch \
data from a memory mapped device.",
has_dca,
edx_ecx,
FeatureInfoFlags::DCA
);
check_flag!(
doc = "A value of 1 indicates that the processor supports SSE4.1.",
has_sse41,
edx_ecx,
FeatureInfoFlags::SSE41
);
check_flag!(
doc = "A value of 1 indicates that the processor supports SSE4.2.",
has_sse42,
edx_ecx,
FeatureInfoFlags::SSE42
);
check_flag!(
doc = "A value of 1 indicates that the processor supports x2APIC feature.",
has_x2apic,
edx_ecx,
FeatureInfoFlags::X2APIC
);
check_flag!(
doc = "A value of 1 indicates that the processor supports MOVBE instruction.",
has_movbe,
edx_ecx,
FeatureInfoFlags::MOVBE
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the POPCNT instruction.",
has_popcnt,
edx_ecx,
FeatureInfoFlags::POPCNT
);
check_flag!(
doc = "A value of 1 indicates that the processors local APIC timer supports \
one-shot operation using a TSC deadline value.",
has_tsc_deadline,
edx_ecx,
FeatureInfoFlags::TSC_DEADLINE
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the AESNI instruction \
extensions.",
has_aesni,
edx_ecx,
FeatureInfoFlags::AESNI
);
check_flag!(
doc = "A value of 1 indicates that the processor supports the XSAVE/XRSTOR \
processor extended states feature, the XSETBV/XGETBV instructions, and \
XCR0.",
has_xsave,
edx_ecx,
FeatureInfoFlags::XSAVE
);
check_flag!(
doc = "A value of 1 indicates that the OS has enabled XSETBV/XGETBV instructions \
to access XCR0, and support for processor extended state management using \
XSAVE/XRSTOR.",
has_oxsave,
edx_ecx,
FeatureInfoFlags::OSXSAVE
);
check_flag!(
doc = "A value of 1 indicates the processor supports the AVX instruction \
extensions.",
has_avx,
edx_ecx,
FeatureInfoFlags::AVX
);
check_flag!(
doc = "A value of 1 indicates that processor supports 16-bit floating-point \
conversion instructions.",
has_f16c,
edx_ecx,
FeatureInfoFlags::F16C
);
check_flag!(
doc = "A value of 1 indicates that processor supports RDRAND instruction.",
has_rdrand,
edx_ecx,
FeatureInfoFlags::RDRAND
);
check_flag!(
doc = "Floating Point Unit On-Chip. The processor contains an x87 FPU.",
has_fpu,
edx_ecx,
FeatureInfoFlags::FPU
);
check_flag!(
doc = "Virtual 8086 Mode Enhancements. Virtual 8086 mode enhancements, including \
CR4.VME for controlling the feature, CR4.PVI for protected mode virtual \
interrupts, software interrupt indirection, expansion of the TSS with the \
software indirection bitmap, and EFLAGS.VIF and EFLAGS.VIP flags.",
has_vme,
edx_ecx,
FeatureInfoFlags::VME
);
check_flag!(
doc = "Debugging Extensions. Support for I/O breakpoints, including CR4.DE for \
controlling the feature, and optional trapping of accesses to DR4 and DR5.",
has_de,
edx_ecx,
FeatureInfoFlags::DE
);
check_flag!(
doc = "Page Size Extension. Large pages of size 4 MByte are supported, including \
CR4.PSE for controlling the feature, the defined dirty bit in PDE (Page \
Directory Entries), optional reserved bit trapping in CR3, PDEs, and PTEs.",
has_pse,
edx_ecx,
FeatureInfoFlags::PSE
);
check_flag!(
doc = "Time Stamp Counter. The RDTSC instruction is supported, including CR4.TSD \
for controlling privilege.",
has_tsc,
edx_ecx,
FeatureInfoFlags::TSC
);
check_flag!(
doc = "Model Specific Registers RDMSR and WRMSR Instructions. The RDMSR and \
WRMSR instructions are supported. Some of the MSRs are implementation \
dependent.",
has_msr,
edx_ecx,
FeatureInfoFlags::MSR
);
check_flag!(
doc = "Physical Address Extension. Physical addresses greater than 32 bits are \
supported: extended page table entry formats, an extra level in the page \
translation tables is defined, 2-MByte pages are supported instead of 4 \
Mbyte pages if PAE bit is 1.",
has_pae,
edx_ecx,
FeatureInfoFlags::PAE
);
check_flag!(
doc = "Machine Check Exception. Exception 18 is defined for Machine Checks, \
including CR4.MCE for controlling the feature. This feature does not \
define the model-specific implementations of machine-check error logging, \
reporting, and processor shutdowns. Machine Check exception handlers may \
have to depend on processor version to do model specific processing of \
the exception, or test for the presence of the Machine Check feature.",
has_mce,
edx_ecx,
FeatureInfoFlags::MCE
);
check_flag!(
doc = "CMPXCHG8B Instruction. The compare-and-exchange 8 bytes (64 bits) \
instruction is supported (implicitly locked and atomic).",
has_cmpxchg8b,
edx_ecx,
FeatureInfoFlags::CX8
);
check_flag!(
doc = "APIC On-Chip. The processor contains an Advanced Programmable Interrupt \
Controller (APIC), responding to memory mapped commands in the physical \
address range FFFE0000H to FFFE0FFFH (by default - some processors permit \
the APIC to be relocated).",
has_apic,
edx_ecx,
FeatureInfoFlags::APIC
);
check_flag!(
doc = "SYSENTER and SYSEXIT Instructions. The SYSENTER and SYSEXIT and \
associated MSRs are supported.",
has_sysenter_sysexit,
edx_ecx,
FeatureInfoFlags::SEP
);
check_flag!(
doc = "Memory Type Range Registers. MTRRs are supported. The MTRRcap MSR \
contains feature bits that describe what memory types are supported, how \
many variable MTRRs are supported, and whether fixed MTRRs are supported.",
has_mtrr,
edx_ecx,
FeatureInfoFlags::MTRR
);
check_flag!(
doc = "Page Global Bit. The global bit is supported in paging-structure entries \
that map a page, indicating TLB entries that are common to different \
processes and need not be flushed. The CR4.PGE bit controls this feature.",
has_pge,
edx_ecx,
FeatureInfoFlags::PGE
);
check_flag!(
doc = "Machine Check Architecture. A value of 1 indicates the Machine Check \
Architecture of reporting machine errors is supported. The MCG_CAP MSR \
contains feature bits describing how many banks of error reporting MSRs \
are supported.",
has_mca,
edx_ecx,
FeatureInfoFlags::MCA
);
check_flag!(
doc = "Conditional Move Instructions. The conditional move instruction CMOV is \
supported. In addition, if x87 FPU is present as indicated by the \
CPUID.FPU feature bit, then the FCOMI and FCMOV instructions are supported",
has_cmov,
edx_ecx,
FeatureInfoFlags::CMOV
);
check_flag!(
doc = "Page Attribute Table. Page Attribute Table is supported. This feature \
augments the Memory Type Range Registers (MTRRs), allowing an operating \
system to specify attributes of memory accessed through a linear address \
on a 4KB granularity.",
has_pat,
edx_ecx,
FeatureInfoFlags::PAT
);
check_flag!(
doc = "36-Bit Page Size Extension. 4-MByte pages addressing physical memory \
beyond 4 GBytes are supported with 32-bit paging. This feature indicates \
that upper bits of the physical address of a 4-MByte page are encoded in \
bits 20:13 of the page-directory entry. Such physical addresses are \
limited by MAXPHYADDR and may be up to 40 bits in size.",
has_pse36,
edx_ecx,
FeatureInfoFlags::PSE36
);
check_flag!(
doc = "Processor Serial Number. The processor supports the 96-bit processor \
identification number feature and the feature is enabled.",
has_psn,
edx_ecx,
FeatureInfoFlags::PSN
);
check_flag!(
doc = "CLFLUSH Instruction. CLFLUSH Instruction is supported.",
has_clflush,
edx_ecx,
FeatureInfoFlags::CLFSH
);
check_flag!(
doc = "Debug Store. The processor supports the ability to write debug \
information into a memory resident buffer. This feature is used by the \
branch trace store (BTS) and processor event-based sampling (PEBS) \
facilities (see Chapter 23, Introduction to Virtual-Machine Extensions, \
in the Intel® 64 and IA-32 Architectures Software Developers Manual, \
Volume 3C).",
has_ds,
edx_ecx,
FeatureInfoFlags::DS
);
check_flag!(
doc = "Thermal Monitor and Software Controlled Clock Facilities. The processor \
implements internal MSRs that allow processor temperature to be monitored \
and processor performance to be modulated in predefined duty cycles under \
software control.",
has_acpi,
edx_ecx,
FeatureInfoFlags::ACPI
);
check_flag!(
doc = "Intel MMX Technology. The processor supports the Intel MMX technology.",
has_mmx,
edx_ecx,
FeatureInfoFlags::MMX
);
check_flag!(
doc = "FXSAVE and FXRSTOR Instructions. The FXSAVE and FXRSTOR instructions are \
supported for fast save and restore of the floating point context. \
Presence of this bit also indicates that CR4.OSFXSR is available for an \
operating system to indicate that it supports the FXSAVE and FXRSTOR \
instructions.",
has_fxsave_fxstor,
edx_ecx,
FeatureInfoFlags::FXSR
);
check_flag!(
doc = "SSE. The processor supports the SSE extensions.",
has_sse,
edx_ecx,
FeatureInfoFlags::SSE
);
check_flag!(
doc = "SSE2. The processor supports the SSE2 extensions.",
has_sse2,
edx_ecx,
FeatureInfoFlags::SSE2
);
check_flag!(
doc = "Self Snoop. The processor supports the management of conflicting memory \
types by performing a snoop of its own cache structure for transactions \
issued to the bus.",
has_ss,
edx_ecx,
FeatureInfoFlags::SS
);
check_flag!(
doc = "Max APIC IDs reserved field is Valid. A value of 0 for HTT indicates \
there is only a single logical processor in the package and software \
should assume only a single APIC ID is reserved. A value of 1 for HTT \
indicates the value in CPUID.1.EBX[23:16] (the Maximum number of \
addressable IDs for logical processors in this package) is valid for the \
package.",
has_htt,
edx_ecx,
FeatureInfoFlags::HTT
);
check_flag!(
doc = "Thermal Monitor. The processor implements the thermal monitor automatic \
thermal control circuitry (TCC).",
has_tm,
edx_ecx,
FeatureInfoFlags::TM
);
check_flag!(
doc = "Pending Break Enable. The processor supports the use of the FERR#/PBE# \
pin when the processor is in the stop-clock state (STPCLK# is asserted) \
to signal the processor that an interrupt is pending and that the \
processor should return to normal operation to handle the interrupt. Bit \
10 (PBE enable) in the IA32_MISC_ENABLE MSR enables this capability.",
has_pbe,
edx_ecx,
FeatureInfoFlags::PBE
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct FeatureInfoFlags: u64 {
// ECX flags
/// Streaming SIMD Extensions 3 (SSE3). A value of 1 indicates the processor supports this technology.
const SSE3 = 1 << 0;
/// PCLMULQDQ. A value of 1 indicates the processor supports the PCLMULQDQ instruction
const PCLMULQDQ = 1 << 1;
/// 64-bit DS Area. A value of 1 indicates the processor supports DS area using 64-bit layout
const DTES64 = 1 << 2;
/// MONITOR/MWAIT. A value of 1 indicates the processor supports this feature.
const MONITOR = 1 << 3;
/// CPL Qualified Debug Store. A value of 1 indicates the processor supports the extensions to the Debug Store feature to allow for branch message storage qualified by CPL.
const DSCPL = 1 << 4;
/// Virtual Machine Extensions. A value of 1 indicates that the processor supports this technology.
const VMX = 1 << 5;
/// Safer Mode Extensions. A value of 1 indicates that the processor supports this technology. See Chapter 5, Safer Mode Extensions Reference.
const SMX = 1 << 6;
/// Enhanced Intel SpeedStep® technology. A value of 1 indicates that the processor supports this technology.
const EIST = 1 << 7;
/// Thermal Monitor 2. A value of 1 indicates whether the processor supports this technology.
const TM2 = 1 << 8;
/// A value of 1 indicates the presence of the Supplemental Streaming SIMD Extensions 3 (SSSE3). A value of 0 indicates the instruction extensions are not present in the processor
const SSSE3 = 1 << 9;
/// L1 Context ID. A value of 1 indicates the L1 data cache mode can be set to either adaptive mode or shared mode. A value of 0 indicates this feature is not supported. See definition of the IA32_MISC_ENABLE MSR Bit 24 (L1 Data Cache Context Mode) for details.
const CNXTID = 1 << 10;
/// A value of 1 indicates the processor supports FMA extensions using YMM state.
const FMA = 1 << 12;
/// CMPXCHG16B Available. A value of 1 indicates that the feature is available. See the CMPXCHG8B/CMPXCHG16B Compare and Exchange Bytes section. 14
const CMPXCHG16B = 1 << 13;
/// Perfmon and Debug Capability: A value of 1 indicates the processor supports the performance and debug feature indication MSR IA32_PERF_CAPABILITIES.
const PDCM = 1 << 15;
/// Process-context identifiers. A value of 1 indicates that the processor supports PCIDs and the software may set CR4.PCIDE to 1.
const PCID = 1 << 17;
/// A value of 1 indicates the processor supports the ability to prefetch data from a memory mapped device.
const DCA = 1 << 18;
/// A value of 1 indicates that the processor supports SSE4.1.
const SSE41 = 1 << 19;
/// A value of 1 indicates that the processor supports SSE4.2.
const SSE42 = 1 << 20;
/// A value of 1 indicates that the processor supports x2APIC feature.
const X2APIC = 1 << 21;
/// A value of 1 indicates that the processor supports MOVBE instruction.
const MOVBE = 1 << 22;
/// A value of 1 indicates that the processor supports the POPCNT instruction.
const POPCNT = 1 << 23;
/// A value of 1 indicates that the processors local APIC timer supports one-shot operation using a TSC deadline value.
const TSC_DEADLINE = 1 << 24;
/// A value of 1 indicates that the processor supports the AESNI instruction extensions.
const AESNI = 1 << 25;
/// A value of 1 indicates that the processor supports the XSAVE/XRSTOR processor extended states feature, the XSETBV/XGETBV instructions, and XCR0.
const XSAVE = 1 << 26;
/// A value of 1 indicates that the OS has enabled XSETBV/XGETBV instructions to access XCR0, and support for processor extended state management using XSAVE/XRSTOR.
const OSXSAVE = 1 << 27;
/// A value of 1 indicates the processor supports the AVX instruction extensions.
const AVX = 1 << 28;
/// A value of 1 indicates that processor supports 16-bit floating-point conversion instructions.
const F16C = 1 << 29;
/// A value of 1 indicates that processor supports RDRAND instruction.
const RDRAND = 1 << 30;
// EDX flags
/// Floating Point Unit On-Chip. The processor contains an x87 FPU.
const FPU = 1 << (32 + 0);
/// Virtual 8086 Mode Enhancements. Virtual 8086 mode enhancements, including CR4.VME for controlling the feature, CR4.PVI for protected mode virtual interrupts, software interrupt indirection, expansion of the TSS with the software indirection bitmap, and EFLAGS.VIF and EFLAGS.VIP flags.
const VME = 1 << (32 + 1);
/// Debugging Extensions. Support for I/O breakpoints, including CR4.DE for controlling the feature, and optional trapping of accesses to DR4 and DR5.
const DE = 1 << (32 + 2);
/// Page Size Extension. Large pages of size 4 MByte are supported, including CR4.PSE for controlling the feature, the defined dirty bit in PDE (Page Directory Entries), optional reserved bit trapping in CR3, PDEs, and PTEs.
const PSE = 1 << (32 + 3);
/// Time Stamp Counter. The RDTSC instruction is supported, including CR4.TSD for controlling privilege.
const TSC = 1 << (32 + 4);
/// Model Specific Registers RDMSR and WRMSR Instructions. The RDMSR and WRMSR instructions are supported. Some of the MSRs are implementation dependent.
const MSR = 1 << (32 + 5);
/// Physical Address Extension. Physical addresses greater than 32 bits are supported: extended page table entry formats, an extra level in the page translation tables is defined, 2-MByte pages are supported instead of 4 Mbyte pages if PAE bit is 1.
const PAE = 1 << (32 + 6);
/// Machine Check Exception. Exception 18 is defined for Machine Checks, including CR4.MCE for controlling the feature. This feature does not define the model-specific implementations of machine-check error logging, reporting, and processor shutdowns. Machine Check exception handlers may have to depend on processor version to do model specific processing of the exception, or test for the presence of the Machine Check feature.
const MCE = 1 << (32 + 7);
/// CMPXCHG8B Instruction. The compare-and-exchange 8 bytes (64 bits) instruction is supported (implicitly locked and atomic).
const CX8 = 1 << (32 + 8);
/// APIC On-Chip. The processor contains an Advanced Programmable Interrupt Controller (APIC), responding to memory mapped commands in the physical address range FFFE0000H to FFFE0FFFH (by default - some processors permit the APIC to be relocated).
const APIC = 1 << (32 + 9);
/// SYSENTER and SYSEXIT Instructions. The SYSENTER and SYSEXIT and associated MSRs are supported.
const SEP = 1 << (32 + 11);
/// Memory Type Range Registers. MTRRs are supported. The MTRRcap MSR contains feature bits that describe what memory types are supported, how many variable MTRRs are supported, and whether fixed MTRRs are supported.
const MTRR = 1 << (32 + 12);
/// Page Global Bit. The global bit is supported in paging-structure entries that map a page, indicating TLB entries that are common to different processes and need not be flushed. The CR4.PGE bit controls this feature.
const PGE = 1 << (32 + 13);
/// Machine Check Architecture. The Machine Check exArchitecture, which provides a compatible mechanism for error reporting in P6 family, Pentium 4, Intel Xeon processors, and future processors, is supported. The MCG_CAP MSR contains feature bits describing how many banks of error reporting MSRs are supported.
const MCA = 1 << (32 + 14);
/// Conditional Move Instructions. The conditional move instruction CMOV is supported. In addition, if x87 FPU is present as indicated by the CPUID.FPU feature bit, then the FCOMI and FCMOV instructions are supported
const CMOV = 1 << (32 + 15);
/// Page Attribute Table. Page Attribute Table is supported. This feature augments the Memory Type Range Registers (MTRRs), allowing an operating system to specify attributes of memory accessed through a linear address on a 4KB granularity.
const PAT = 1 << (32 + 16);
/// 36-Bit Page Size Extension. 4-MByte pages addressing physical memory beyond 4 GBytes are supported with 32-bit paging. This feature indicates that upper bits of the physical address of a 4-MByte page are encoded in bits 20:13 of the page-directory entry. Such physical addresses are limited by MAXPHYADDR and may be up to 40 bits in size.
const PSE36 = 1 << (32 + 17);
/// Processor Serial Number. The processor supports the 96-bit processor identification number feature and the feature is enabled.
const PSN = 1 << (32 + 18);
/// CLFLUSH Instruction. CLFLUSH Instruction is supported.
const CLFSH = 1 << (32 + 19);
/// Debug Store. The processor supports the ability to write debug information into a memory resident buffer. This feature is used by the branch trace store (BTS) and precise event-based sampling (PEBS) facilities (see Chapter 23, Introduction to Virtual-Machine Extensions, in the Intel® 64 and IA-32 Architectures Software Developers Manual, Volume 3C).
const DS = 1 << (32 + 21);
/// Thermal Monitor and Software Controlled Clock Facilities. The processor implements internal MSRs that allow processor temperature to be monitored and processor performance to be modulated in predefined duty cycles under software control.
const ACPI = 1 << (32 + 22);
/// Intel MMX Technology. The processor supports the Intel MMX technology.
const MMX = 1 << (32 + 23);
/// FXSAVE and FXRSTOR Instructions. The FXSAVE and FXRSTOR instructions are supported for fast save and restore of the floating point context. Presence of this bit also indicates that CR4.OSFXSR is available for an operating system to indicate that it supports the FXSAVE and FXRSTOR instructions.
const FXSR = 1 << (32 + 24);
/// SSE. The processor supports the SSE extensions.
const SSE = 1 << (32 + 25);
/// SSE2. The processor supports the SSE2 extensions.
const SSE2 = 1 << (32 + 26);
/// Self Snoop. The processor supports the management of conflicting memory types by performing a snoop of its own cache structure for transactions issued to the bus.
const SS = 1 << (32 + 27);
/// Max APIC IDs reserved field is Valid. A value of 0 for HTT indicates there is only a single logical processor in the package and software should assume only a single APIC ID is reserved. A value of 1 for HTT indicates the value in CPUID.1.EBX[23:16] (the Maximum number of addressable IDs for logical processors in this package) is valid for the package.
const HTT = 1 << (32 + 28);
/// Thermal Monitor. The processor implements the thermal monitor automatic thermal control circuitry (TCC).
const TM = 1 << (32 + 29);
/// Pending Break Enable. The processor supports the use of the FERR#/PBE# pin when the processor is in the stop-clock state (STPCLK# is asserted) to signal the processor that an interrupt is pending and that the processor should return to normal operation to handle the interrupt. Bit 10 (PBE enable) in the IA32_MISC_ENABLE MSR enables this capability.
const PBE = 1 << (32 + 31);
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheParametersIter {
current: u32,
}
impl Iterator for CacheParametersIter {
type Item = CacheParameter;
/// Iterate over all caches for this CPU.
/// Note: cpuid is called every-time we this function to get information
/// about next cache.
fn next(&mut self) -> Option<CacheParameter> {
let res = cpuid!(EAX_CACHE_PARAMETERS, self.current);
let cp = CacheParameter {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
};
match cp.cache_type() {
CacheType::NULL => None,
CacheType::RESERVED => None,
_ => {
self.current += 1;
Some(cp)
}
}
}
}
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct CacheParameter {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum CacheType {
/// Null - No more caches
NULL = 0,
DATA,
INSTRUCTION,
UNIFIED,
/// 4-31 = Reserved
RESERVED,
}
impl Default for CacheType {
fn default() -> CacheType {
CacheType::NULL
}
}
impl CacheParameter {
/// Cache Type
pub fn cache_type(&self) -> CacheType {
let typ = get_bits(self.eax, 0, 4) as u8;
match typ {
0 => CacheType::NULL,
1 => CacheType::DATA,
2 => CacheType::INSTRUCTION,
3 => CacheType::UNIFIED,
_ => CacheType::RESERVED,
}
}
/// Cache Level (starts at 1)
pub fn level(&self) -> u8 {
get_bits(self.eax, 5, 7) as u8
}
/// Self Initializing cache level (does not need SW initialization).
pub fn is_self_initializing(&self) -> bool {
get_bits(self.eax, 8, 8) == 1
}
/// Fully Associative cache
pub fn is_fully_associative(&self) -> bool {
get_bits(self.eax, 9, 9) == 1
}
/// Maximum number of addressable IDs for logical processors sharing this cache
pub fn max_cores_for_cache(&self) -> usize {
(get_bits(self.eax, 14, 25) + 1) as usize
}
/// Maximum number of addressable IDs for processor cores in the physical package
pub fn max_cores_for_package(&self) -> usize {
(get_bits(self.eax, 26, 31) + 1) as usize
}
/// System Coherency Line Size (Bits 11-00)
pub fn coherency_line_size(&self) -> usize {
(get_bits(self.ebx, 0, 11) + 1) as usize
}
/// Physical Line partitions (Bits 21-12)
pub fn physical_line_partitions(&self) -> usize {
(get_bits(self.ebx, 12, 21) + 1) as usize
}
/// Ways of associativity (Bits 31-22)
pub fn associativity(&self) -> usize {
(get_bits(self.ebx, 22, 31) + 1) as usize
}
/// Number of Sets (Bits 31-00)
pub fn sets(&self) -> usize {
(self.ecx + 1) as usize
}
/// Write-Back Invalidate/Invalidate (Bit 0)
/// False: WBINVD/INVD from threads sharing this cache acts upon lower level caches for threads sharing this cache.
/// True: WBINVD/INVD is not guaranteed to act upon lower level caches of non-originating threads sharing this cache.
pub fn is_write_back_invalidate(&self) -> bool {
get_bits(self.edx, 0, 0) == 1
}
/// Cache Inclusiveness (Bit 1)
/// False: Cache is not inclusive of lower cache levels.
/// True: Cache is inclusive of lower cache levels.
pub fn is_inclusive(&self) -> bool {
get_bits(self.edx, 1, 1) == 1
}
/// Complex Cache Indexing (Bit 2)
/// False: Direct mapped cache.
/// True: A complex function is used to index the cache, potentially using all address bits.
pub fn has_complex_indexing(&self) -> bool {
get_bits(self.edx, 2, 2) == 1
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct MonitorMwaitInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl MonitorMwaitInfo {
/// Smallest monitor-line size in bytes (default is processor's monitor granularity)
pub fn smallest_monitor_line(&self) -> u16 {
get_bits(self.eax, 0, 15) as u16
}
/// Largest monitor-line size in bytes (default is processor's monitor granularity
pub fn largest_monitor_line(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Enumeration of Monitor-Mwait extensions (beyond EAX and EBX registers) supported
pub fn extensions_supported(&self) -> bool {
get_bits(self.ecx, 0, 0) == 1
}
/// Supports treating interrupts as break-event for MWAIT, even when interrupts disabled
pub fn interrupts_as_break_event(&self) -> bool {
get_bits(self.ecx, 1, 1) == 1
}
/// Number of C0 sub C-states supported using MWAIT (Bits 03 - 00)
pub fn supported_c0_states(&self) -> u16 {
get_bits(self.edx, 0, 3) as u16
}
/// Number of C1 sub C-states supported using MWAIT (Bits 07 - 04)
pub fn supported_c1_states(&self) -> u16 {
get_bits(self.edx, 4, 7) as u16
}
/// Number of C2 sub C-states supported using MWAIT (Bits 11 - 08)
pub fn supported_c2_states(&self) -> u16 {
get_bits(self.edx, 8, 11) as u16
}
/// Number of C3 sub C-states supported using MWAIT (Bits 15 - 12)
pub fn supported_c3_states(&self) -> u16 {
get_bits(self.edx, 12, 15) as u16
}
/// Number of C4 sub C-states supported using MWAIT (Bits 19 - 16)
pub fn supported_c4_states(&self) -> u16 {
get_bits(self.edx, 16, 19) as u16
}
/// Number of C5 sub C-states supported using MWAIT (Bits 23 - 20)
pub fn supported_c5_states(&self) -> u16 {
get_bits(self.edx, 20, 23) as u16
}
/// Number of C6 sub C-states supported using MWAIT (Bits 27 - 24)
pub fn supported_c6_states(&self) -> u16 {
get_bits(self.edx, 24, 27) as u16
}
/// Number of C7 sub C-states supported using MWAIT (Bits 31 - 28)
pub fn supported_c7_states(&self) -> u16 {
get_bits(self.edx, 28, 31) as u16
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ThermalPowerInfo {
eax: ThermalPowerFeaturesEax,
ebx: u32,
ecx: ThermalPowerFeaturesEcx,
edx: u32,
}
impl ThermalPowerInfo {
/// Number of Interrupt Thresholds in Digital Thermal Sensor
pub fn dts_irq_threshold(&self) -> u8 {
get_bits(self.ebx, 0, 3) as u8
}
check_flag!(
doc = "Digital temperature sensor is supported if set.",
has_dts,
eax,
ThermalPowerFeaturesEax::DTS
);
check_flag!(
doc = "Intel Turbo Boost Technology Available (see description of \
IA32_MISC_ENABLE[38]).",
has_turbo_boost,
eax,
ThermalPowerFeaturesEax::TURBO_BOOST
);
check_flag!(
doc = "ARAT. APIC-Timer-always-running feature is supported if set.",
has_arat,
eax,
ThermalPowerFeaturesEax::ARAT
);
check_flag!(
doc = "PLN. Power limit notification controls are supported if set.",
has_pln,
eax,
ThermalPowerFeaturesEax::PLN
);
check_flag!(
doc = "ECMD. Clock modulation duty cycle extension is supported if set.",
has_ecmd,
eax,
ThermalPowerFeaturesEax::ECMD
);
check_flag!(
doc = "PTM. Package thermal management is supported if set.",
has_ptm,
eax,
ThermalPowerFeaturesEax::PTM
);
check_flag!(
doc = "HWP. HWP base registers (IA32_PM_ENABLE[bit 0], IA32_HWP_CAPABILITIES, \
IA32_HWP_REQUEST, IA32_HWP_STATUS) are supported if set.",
has_hwp,
eax,
ThermalPowerFeaturesEax::HWP
);
check_flag!(
doc = "HWP Notification. IA32_HWP_INTERRUPT MSR is supported if set.",
has_hwp_notification,
eax,
ThermalPowerFeaturesEax::HWP_NOTIFICATION
);
check_flag!(
doc = "HWP Activity Window. IA32_HWP_REQUEST[bits 41:32] is supported if set.",
has_hwp_activity_window,
eax,
ThermalPowerFeaturesEax::HWP_ACTIVITY_WINDOW
);
check_flag!(
doc =
"HWP Energy Performance Preference. IA32_HWP_REQUEST[bits 31:24] is supported if set.",
has_hwp_energy_performance_preference,
eax,
ThermalPowerFeaturesEax::HWP_ENERGY_PERFORMANCE_PREFERENCE
);
check_flag!(
doc = "HWP Package Level Request. IA32_HWP_REQUEST_PKG MSR is supported if set.",
has_hwp_package_level_request,
eax,
ThermalPowerFeaturesEax::HWP_PACKAGE_LEVEL_REQUEST
);
check_flag!(
doc = "HDC. HDC base registers IA32_PKG_HDC_CTL, IA32_PM_CTL1, IA32_THREAD_STALL \
MSRs are supported if set.",
has_hdc,
eax,
ThermalPowerFeaturesEax::HDC
);
check_flag!(
doc = "Intel® Turbo Boost Max Technology 3.0 available.",
has_turbo_boost3,
eax,
ThermalPowerFeaturesEax::TURBO_BOOST_3
);
check_flag!(
doc = "HWP Capabilities. Highest Performance change is supported if set.",
has_hwp_capabilities,
eax,
ThermalPowerFeaturesEax::HWP_CAPABILITIES
);
check_flag!(
doc = "HWP PECI override is supported if set.",
has_hwp_peci_override,
eax,
ThermalPowerFeaturesEax::HWP_PECI_OVERRIDE
);
check_flag!(
doc = "Flexible HWP is supported if set.",
has_flexible_hwp,
eax,
ThermalPowerFeaturesEax::FLEXIBLE_HWP
);
check_flag!(
doc = "Fast access mode for the IA32_HWP_REQUEST MSR is supported if set.",
has_hwp_fast_access_mode,
eax,
ThermalPowerFeaturesEax::HWP_REQUEST_MSR_FAST_ACCESS
);
check_flag!(
doc = "Ignoring Idle Logical Processor HWP request is supported if set.",
has_ignore_idle_processor_hwp_request,
eax,
ThermalPowerFeaturesEax::IGNORE_IDLE_PROCESSOR_HWP_REQUEST
);
check_flag!(
doc = "Hardware Coordination Feedback Capability (Presence of IA32_MPERF and \
IA32_APERF). The capability to provide a measure of delivered processor \
performance (since last reset of the counters), as a percentage of \
expected processor performance at frequency specified in CPUID Brand \
String Bits 02 - 01",
has_hw_coord_feedback,
ecx,
ThermalPowerFeaturesEcx::HW_COORD_FEEDBACK
);
check_flag!(
doc = "The processor supports performance-energy bias preference if \
CPUID.06H:ECX.SETBH[bit 3] is set and it also implies the presence of a \
new architectural MSR called IA32_ENERGY_PERF_BIAS (1B0H)",
has_energy_bias_pref,
ecx,
ThermalPowerFeaturesEcx::ENERGY_BIAS_PREF
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ThermalPowerFeaturesEax: u32 {
/// Digital temperature sensor is supported if set. (Bit 00)
const DTS = 1 << 0;
/// Intel Turbo Boost Technology Available (see description of IA32_MISC_ENABLE[38]). (Bit 01)
const TURBO_BOOST = 1 << 1;
/// ARAT. APIC-Timer-always-running feature is supported if set. (Bit 02)
const ARAT = 1 << 2;
/// Bit 3: Reserved.
const RESERVED_3 = 1 << 3;
/// PLN. Power limit notification controls are supported if set. (Bit 04)
const PLN = 1 << 4;
/// ECMD. Clock modulation duty cycle extension is supported if set. (Bit 05)
const ECMD = 1 << 5;
/// PTM. Package thermal management is supported if set. (Bit 06)
const PTM = 1 << 6;
/// Bit 07: HWP. HWP base registers (IA32_PM_ENABLE[bit 0], IA32_HWP_CAPABILITIES, IA32_HWP_REQUEST, IA32_HWP_STATUS) are supported if set.
const HWP = 1 << 7;
/// Bit 08: HWP_Notification. IA32_HWP_INTERRUPT MSR is supported if set.
const HWP_NOTIFICATION = 1 << 8;
/// Bit 09: HWP_Activity_Window. IA32_HWP_REQUEST[bits 41:32] is supported if set.
const HWP_ACTIVITY_WINDOW = 1 << 9;
/// Bit 10: HWP_Energy_Performance_Preference. IA32_HWP_REQUEST[bits 31:24] is supported if set.
const HWP_ENERGY_PERFORMANCE_PREFERENCE = 1 << 10;
/// Bit 11: HWP_Package_Level_Request. IA32_HWP_REQUEST_PKG MSR is supported if set.
const HWP_PACKAGE_LEVEL_REQUEST = 1 << 11;
/// Bit 12: Reserved.
const RESERVED_12 = 1 << 12;
/// Bit 13: HDC. HDC base registers IA32_PKG_HDC_CTL, IA32_PM_CTL1, IA32_THREAD_STALL MSRs are supported if set.
const HDC = 1 << 13;
/// Bit 14: Intel® Turbo Boost Max Technology 3.0 available.
const TURBO_BOOST_3 = 1 << 14;
/// Bit 15: HWP Capabilities. Highest Performance change is supported if set.
const HWP_CAPABILITIES = 1 << 15;
/// Bit 16: HWP PECI override is supported if set.
const HWP_PECI_OVERRIDE = 1 << 16;
/// Bit 17: Flexible HWP is supported if set.
const FLEXIBLE_HWP = 1 << 17;
/// Bit 18: Fast access mode for the IA32_HWP_REQUEST MSR is supported if set.
const HWP_REQUEST_MSR_FAST_ACCESS = 1 << 18;
/// Bit 19: Reserved.
const RESERVED_19 = 1 << 19;
/// Bit 20: Ignoring Idle Logical Processor HWP request is supported if set.
const IGNORE_IDLE_PROCESSOR_HWP_REQUEST = 1 << 20;
// Bits 31 - 21: Reserved
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ThermalPowerFeaturesEcx: u32 {
/// Hardware Coordination Feedback Capability (Presence of IA32_MPERF and IA32_APERF). The capability to provide a measure of delivered processor performance (since last reset of the counters), as a percentage of expected processor performance at frequency specified in CPUID Brand String Bits 02 - 01
const HW_COORD_FEEDBACK = 1 << 0;
/// The processor supports performance-energy bias preference if CPUID.06H:ECX.SETBH[bit 3] is set and it also implies the presence of a new architectural MSR called IA32_ENERGY_PERF_BIAS (1B0H)
const ENERGY_BIAS_PREF = 1 << 3;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedFeatures {
eax: u32,
ebx: ExtendedFeaturesEbx,
ecx: ExtendedFeaturesEcx,
edx: u32,
}
impl ExtendedFeatures {
check_flag!(
doc = "FSGSBASE. Supports RDFSBASE/RDGSBASE/WRFSBASE/WRGSBASE if 1.",
has_fsgsbase,
ebx,
ExtendedFeaturesEbx::FSGSBASE
);
check_flag!(
doc = "IA32_TSC_ADJUST MSR is supported if 1.",
has_tsc_adjust_msr,
ebx,
ExtendedFeaturesEbx::ADJUST_MSR
);
check_flag!(doc = "BMI1", has_bmi1, ebx, ExtendedFeaturesEbx::BMI1);
check_flag!(doc = "HLE", has_hle, ebx, ExtendedFeaturesEbx::HLE);
check_flag!(doc = "AVX2", has_avx2, ebx, ExtendedFeaturesEbx::AVX2);
check_flag!(
doc = "FDP_EXCPTN_ONLY. x87 FPU Data Pointer updated only on x87 exceptions if 1.",
has_fdp,
ebx,
ExtendedFeaturesEbx::FDP
);
check_flag!(
doc = "SMEP. Supports Supervisor-Mode Execution Prevention if 1.",
has_smep,
ebx,
ExtendedFeaturesEbx::SMEP
);
check_flag!(doc = "BMI2", has_bmi2, ebx, ExtendedFeaturesEbx::BMI2);
check_flag!(
doc = "Supports Enhanced REP MOVSB/STOSB if 1.",
has_rep_movsb_stosb,
ebx,
ExtendedFeaturesEbx::REP_MOVSB_STOSB
);
check_flag!(
doc = "INVPCID. If 1, supports INVPCID instruction for system software that \
manages process-context identifiers.",
has_invpcid,
ebx,
ExtendedFeaturesEbx::INVPCID
);
check_flag!(doc = "RTM", has_rtm, ebx, ExtendedFeaturesEbx::RTM);
check_flag!(
doc = "Supports Intel Resource Director Technology (RDT) Monitoring capability.",
has_rdtm,
ebx,
ExtendedFeaturesEbx::RDTM
);
check_flag!(
doc = "Deprecates FPU CS and FPU DS values if 1.",
has_fpu_cs_ds_deprecated,
ebx,
ExtendedFeaturesEbx::DEPRECATE_FPU_CS_DS
);
check_flag!(
doc = "MPX. Supports Intel Memory Protection Extensions if 1.",
has_mpx,
ebx,
ExtendedFeaturesEbx::MPX
);
check_flag!(
doc = "Supports Intel Resource Director Technology (RDT) Allocation capability.",
has_rdta,
ebx,
ExtendedFeaturesEbx::RDTA
);
check_flag!(
doc = "Supports RDSEED.",
has_rdseed,
ebx,
ExtendedFeaturesEbx::RDSEED
);
#[deprecated(
since = "3.2",
note = "Deprecated due to typo in name, users should use has_rdseed() instead."
)]
check_flag!(
doc = "Supports RDSEED (deprecated alias).",
has_rdseet,
ebx,
ExtendedFeaturesEbx::RDSEED
);
check_flag!(
doc = "Supports ADX.",
has_adx,
ebx,
ExtendedFeaturesEbx::ADX
);
check_flag!(doc = "SMAP. Supports Supervisor-Mode Access Prevention (and the CLAC/STAC instructions) if 1.",
has_smap,
ebx,
ExtendedFeaturesEbx::SMAP);
check_flag!(
doc = "Supports CLFLUSHOPT.",
has_clflushopt,
ebx,
ExtendedFeaturesEbx::CLFLUSHOPT
);
check_flag!(
doc = "Supports Intel Processor Trace.",
has_processor_trace,
ebx,
ExtendedFeaturesEbx::PROCESSOR_TRACE
);
check_flag!(
doc = "Supports SHA Instructions.",
has_sha,
ebx,
ExtendedFeaturesEbx::SHA
);
check_flag!(
doc = "Supports Intel® Software Guard Extensions (Intel® SGX Extensions).",
has_sgx,
ebx,
ExtendedFeaturesEbx::SGX
);
check_flag!(
doc = "Supports AVX512F.",
has_avx512f,
ebx,
ExtendedFeaturesEbx::AVX512F
);
check_flag!(
doc = "Supports AVX512DQ.",
has_avx512dq,
ebx,
ExtendedFeaturesEbx::AVX512DQ
);
check_flag!(
doc = "AVX512_IFMA",
has_avx512_ifma,
ebx,
ExtendedFeaturesEbx::AVX512_IFMA
);
check_flag!(
doc = "AVX512PF",
has_avx512pf,
ebx,
ExtendedFeaturesEbx::AVX512PF
);
check_flag!(
doc = "AVX512ER",
has_avx512er,
ebx,
ExtendedFeaturesEbx::AVX512ER
);
check_flag!(
doc = "AVX512CD",
has_avx512cd,
ebx,
ExtendedFeaturesEbx::AVX512CD
);
check_flag!(
doc = "AVX512BW",
has_avx512bw,
ebx,
ExtendedFeaturesEbx::AVX512BW
);
check_flag!(
doc = "AVX512VL",
has_avx512vl,
ebx,
ExtendedFeaturesEbx::AVX512VL
);
check_flag!(doc = "CLWB", has_clwb, ebx, ExtendedFeaturesEbx::CLWB);
check_flag!(
doc = "Has PREFETCHWT1 (Intel® Xeon Phi™ only).",
has_prefetchwt1,
ecx,
ExtendedFeaturesEcx::PREFETCHWT1
);
check_flag!(
doc = "Supports user-mode instruction prevention if 1.",
has_umip,
ecx,
ExtendedFeaturesEcx::UMIP
);
check_flag!(
doc = "Supports protection keys for user-mode pages.",
has_pku,
ecx,
ExtendedFeaturesEcx::PKU
);
check_flag!(
doc = "OS has set CR4.PKE to enable protection keys (and the RDPKRU/WRPKRU instructions.",
has_ospke,
ecx,
ExtendedFeaturesEcx::OSPKE
);
check_flag!(
doc = "RDPID and IA32_TSC_AUX are available.",
has_rdpid,
ecx,
ExtendedFeaturesEcx::RDPID
);
check_flag!(
doc = "Supports SGX Launch Configuration.",
has_sgx_lc,
ecx,
ExtendedFeaturesEcx::SGX_LC
);
/// The value of MAWAU used by the BNDLDX and BNDSTX instructions in 64-bit mode.
pub fn mawau_value(&self) -> u8 {
get_bits(self.ecx.bits(), 17, 21) as u8
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFeaturesEbx: u32 {
/// FSGSBASE. Supports RDFSBASE/RDGSBASE/WRFSBASE/WRGSBASE if 1. (Bit 00)
const FSGSBASE = 1 << 0;
/// IA32_TSC_ADJUST MSR is supported if 1. (Bit 01)
const ADJUST_MSR = 1 << 1;
/// Bit 02: SGX. Supports Intel® Software Guard Extensions (Intel® SGX Extensions) if 1.
const SGX = 1 << 2;
/// BMI1 (Bit 03)
const BMI1 = 1 << 3;
/// HLE (Bit 04)
const HLE = 1 << 4;
/// AVX2 (Bit 05)
const AVX2 = 1 << 5;
/// FDP_EXCPTN_ONLY. x87 FPU Data Pointer updated only on x87 exceptions if 1.
const FDP = 1 << 6;
/// SMEP. Supports Supervisor-Mode Execution Prevention if 1. (Bit 07)
const SMEP = 1 << 7;
/// BMI2 (Bit 08)
const BMI2 = 1 << 8;
/// Supports Enhanced REP MOVSB/STOSB if 1. (Bit 09)
const REP_MOVSB_STOSB = 1 << 9;
/// INVPCID. If 1, supports INVPCID instruction for system software that manages process-context identifiers. (Bit 10)
const INVPCID = 1 << 10;
/// RTM (Bit 11)
const RTM = 1 << 11;
/// Supports Intel Resource Director Technology (RDT) Monitoring. (Bit 12)
const RDTM = 1 << 12;
/// Deprecates FPU CS and FPU DS values if 1. (Bit 13)
const DEPRECATE_FPU_CS_DS = 1 << 13;
/// Deprecates FPU CS and FPU DS values if 1. (Bit 14)
const MPX = 1 << 14;
/// Supports Intel Resource Director Technology (RDT) Allocation capability if 1.
const RDTA = 1 << 15;
/// Bit 16: AVX512F.
const AVX512F = 1 << 16;
/// Bit 17: AVX512DQ.
const AVX512DQ = 1 << 17;
/// Supports RDSEED.
const RDSEED = 1 << 18;
/// Supports ADX.
const ADX = 1 << 19;
/// SMAP. Supports Supervisor-Mode Access Prevention (and the CLAC/STAC instructions) if 1.
const SMAP = 1 << 20;
/// Bit 21: AVX512_IFMA.
const AVX512_IFMA = 1 << 21;
// Bit 22: Reserved.
/// Bit 23: CLFLUSHOPT
const CLFLUSHOPT = 1 << 23;
/// Bit 24: CLWB.
const CLWB = 1 << 24;
/// Bit 25: Intel Processor Trace
const PROCESSOR_TRACE = 1 << 25;
/// Bit 26: AVX512PF. (Intel® Xeon Phi™ only.)
const AVX512PF = 1 << 26;
/// Bit 27: AVX512ER. (Intel® Xeon Phi™ only.)
const AVX512ER = 1 << 27;
/// Bit 28: AVX512CD.
const AVX512CD = 1 << 28;
/// Bit 29: Intel SHA Extensions
const SHA = 1 << 29;
/// Bit 30: AVX512BW.
const AVX512BW = 1 << 30;
/// Bit 31: AVX512VL.
const AVX512VL = 1 << 31;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFeaturesEcx: u32 {
/// Bit 0: Prefetch WT1. (Intel® Xeon Phi™ only).
const PREFETCHWT1 = 1 << 0;
// Bit 01: AVX512_VBMI
const AVX512VBMI = 1 << 1;
/// Bit 02: UMIP. Supports user-mode instruction prevention if 1.
const UMIP = 1 << 2;
/// Bit 03: PKU. Supports protection keys for user-mode pages if 1.
const PKU = 1 << 3;
/// Bit 04: OSPKE. If 1, OS has set CR4.PKE to enable protection keys (and the RDPKRU/WRPKRU instruc-tions).
const OSPKE = 1 << 4;
// Bits 16 - 5: Reserved.
// Bits 21 - 17: The value of MAWAU used by the BNDLDX and BNDSTX instructions in 64-bit mode.
/// Bit 22: RDPID. RDPID and IA32_TSC_AUX are available if 1.
const RDPID = 1 << 22;
// Bits 29 - 23: Reserved.
/// Bit 30: SGX_LC. Supports SGX Launch Configuration if 1.
const SGX_LC = 1 << 30;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DirectCacheAccessInfo {
eax: u32,
}
impl DirectCacheAccessInfo {
/// Value of bits [31:0] of IA32_PLATFORM_DCA_CAP MSR (address 1F8H)
pub fn get_dca_cap_value(&self) -> u32 {
self.eax
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct PerformanceMonitoringInfo {
eax: u32,
ebx: PerformanceMonitoringFeaturesEbx,
ecx: u32,
edx: u32,
}
impl PerformanceMonitoringInfo {
/// Version ID of architectural performance monitoring. (Bits 07 - 00)
pub fn version_id(&self) -> u8 {
get_bits(self.eax, 0, 7) as u8
}
/// Number of general-purpose performance monitoring counter per logical processor. (Bits 15- 08)
pub fn number_of_counters(&self) -> u8 {
get_bits(self.eax, 8, 15) as u8
}
/// Bit width of general-purpose, performance monitoring counter. (Bits 23 - 16)
pub fn counter_bit_width(&self) -> u8 {
get_bits(self.eax, 16, 23) as u8
}
/// Length of EBX bit vector to enumerate architectural performance monitoring events. (Bits 31 - 24)
pub fn ebx_length(&self) -> u8 {
get_bits(self.eax, 24, 31) as u8
}
/// Number of fixed-function performance counters (if Version ID > 1). (Bits 04 - 00)
pub fn fixed_function_counters(&self) -> u8 {
get_bits(self.edx, 0, 4) as u8
}
/// Bit width of fixed-function performance counters (if Version ID > 1). (Bits 12- 05)
pub fn fixed_function_counters_bit_width(&self) -> u8 {
get_bits(self.edx, 5, 12) as u8
}
check_bit_fn!(
doc = "AnyThread deprecation",
has_any_thread_deprecation,
edx,
15
);
check_flag!(
doc = "Core cycle event not available if 1.",
is_core_cyc_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::CORE_CYC_EV_UNAVAILABLE
);
check_flag!(
doc = "Instruction retired event not available if 1.",
is_inst_ret_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::INST_RET_EV_UNAVAILABLE
);
check_flag!(
doc = "Reference cycles event not available if 1.",
is_ref_cycle_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::REF_CYC_EV_UNAVAILABLE
);
check_flag!(
doc = "Last-level cache reference event not available if 1.",
is_cache_ref_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::CACHE_REF_EV_UNAVAILABLE
);
check_flag!(
doc = "Last-level cache misses event not available if 1.",
is_ll_cache_miss_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::LL_CACHE_MISS_EV_UNAVAILABLE
);
check_flag!(
doc = "Branch instruction retired event not available if 1.",
is_branch_inst_ret_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::BRANCH_INST_RET_EV_UNAVAILABLE
);
check_flag!(
doc = "Branch mispredict retired event not available if 1.",
is_branch_midpred_ev_unavailable,
ebx,
PerformanceMonitoringFeaturesEbx::BRANCH_MISPRED_EV_UNAVAILABLE
);
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct PerformanceMonitoringFeaturesEbx: u32 {
/// Core cycle event not available if 1. (Bit 0)
const CORE_CYC_EV_UNAVAILABLE = 1 << 0;
/// Instruction retired event not available if 1. (Bit 01)
const INST_RET_EV_UNAVAILABLE = 1 << 1;
/// Reference cycles event not available if 1. (Bit 02)
const REF_CYC_EV_UNAVAILABLE = 1 << 2;
/// Last-level cache reference event not available if 1. (Bit 03)
const CACHE_REF_EV_UNAVAILABLE = 1 << 3;
/// Last-level cache misses event not available if 1. (Bit 04)
const LL_CACHE_MISS_EV_UNAVAILABLE = 1 << 4;
/// Branch instruction retired event not available if 1. (Bit 05)
const BRANCH_INST_RET_EV_UNAVAILABLE = 1 << 5;
/// Branch mispredict retired event not available if 1. (Bit 06)
const BRANCH_MISPRED_EV_UNAVAILABLE = 1 << 6;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedTopologyIter {
level: u32,
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedTopologyLevel {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl ExtendedTopologyLevel {
/// Number of logical processors at this level type.
/// The number reflects configuration as shipped.
pub fn processors(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Level number.
pub fn level_number(&self) -> u8 {
get_bits(self.ecx, 0, 7) as u8
}
// Level type.
pub fn level_type(&self) -> TopologyType {
match get_bits(self.ecx, 8, 15) {
0 => TopologyType::INVALID,
1 => TopologyType::SMT,
2 => TopologyType::CORE,
_ => unreachable!(),
}
}
/// x2APIC ID the current logical processor. (Bits 31-00)
pub fn x2apic_id(&self) -> u32 {
self.edx
}
/// Number of bits to shift right on x2APIC ID to get a unique topology ID of the next level type. (Bits 04-00)
/// All logical processors with the same next level ID share current level.
pub fn shift_right_for_next_apic_id(&self) -> u32 {
get_bits(self.eax, 0, 4)
}
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum TopologyType {
INVALID = 0,
/// Hyper-thread (Simultaneous multithreading)
SMT = 1,
CORE = 2,
}
impl Default for TopologyType {
fn default() -> TopologyType {
TopologyType::INVALID
}
}
impl Iterator for ExtendedTopologyIter {
type Item = ExtendedTopologyLevel;
fn next(&mut self) -> Option<ExtendedTopologyLevel> {
let res = cpuid!(EAX_EXTENDED_TOPOLOGY_INFO, self.level);
self.level += 1;
let et = ExtendedTopologyLevel {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
};
match et.level_type() {
TopologyType::INVALID => None,
_ => Some(et),
}
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedStateInfoXCR0Flags: u32 {
/// legacy x87 (Bit 00).
const LEGACY_X87 = 1 << 0;
/// 128-bit SSE (Bit 01).
const SSE128 = 1 << 1;
/// 256-bit AVX (Bit 02).
const AVX256 = 1 << 2;
/// MPX BNDREGS (Bit 03).
const MPX_BNDREGS = 1 << 3;
/// MPX BNDCSR (Bit 04).
const MPX_BNDCSR = 1 << 4;
/// AVX512 OPMASK (Bit 05).
const AVX512_OPMASK = 1 << 5;
/// AVX ZMM Hi256 (Bit 06).
const AVX512_ZMM_HI256 = 1 << 6;
/// AVX 512 ZMM Hi16 (Bit 07).
const AVX512_ZMM_HI16 = 1 << 7;
/// PKRU state (Bit 09).
const PKRU = 1 << 9;
/// IA32_XSS HDC State (Bit 13).
const IA32_XSS_HDC = 1 << 13;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedStateInfoXSSFlags: u32 {
/// IA32_XSS PT (Trace Packet) State (Bit 08).
const PT = 1 << 8;
/// IA32_XSS HDC State (Bit 13).
const HDC = 1 << 13;
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedStateInfo {
eax: ExtendedStateInfoXCR0Flags,
ebx: u32,
ecx: u32,
edx: u32,
eax1: u32,
ebx1: u32,
ecx1: ExtendedStateInfoXSSFlags,
edx1: u32,
}
impl ExtendedStateInfo {
check_flag!(
doc = "Support for legacy x87 in XCR0.",
xcr0_supports_legacy_x87,
eax,
ExtendedStateInfoXCR0Flags::LEGACY_X87
);
check_flag!(
doc = "Support for SSE 128-bit in XCR0.",
xcr0_supports_sse_128,
eax,
ExtendedStateInfoXCR0Flags::SSE128
);
check_flag!(
doc = "Support for AVX 256-bit in XCR0.",
xcr0_supports_avx_256,
eax,
ExtendedStateInfoXCR0Flags::AVX256
);
check_flag!(
doc = "Support for MPX BNDREGS in XCR0.",
xcr0_supports_mpx_bndregs,
eax,
ExtendedStateInfoXCR0Flags::MPX_BNDREGS
);
check_flag!(
doc = "Support for MPX BNDCSR in XCR0.",
xcr0_supports_mpx_bndcsr,
eax,
ExtendedStateInfoXCR0Flags::MPX_BNDCSR
);
check_flag!(
doc = "Support for AVX512 OPMASK in XCR0.",
xcr0_supports_avx512_opmask,
eax,
ExtendedStateInfoXCR0Flags::AVX512_OPMASK
);
check_flag!(
doc = "Support for AVX512 ZMM Hi256 XCR0.",
xcr0_supports_avx512_zmm_hi256,
eax,
ExtendedStateInfoXCR0Flags::AVX512_ZMM_HI256
);
check_flag!(
doc = "Support for AVX512 ZMM Hi16 in XCR0.",
xcr0_supports_avx512_zmm_hi16,
eax,
ExtendedStateInfoXCR0Flags::AVX512_ZMM_HI16
);
check_flag!(
doc = "Support for PKRU in XCR0.",
xcr0_supports_pkru,
eax,
ExtendedStateInfoXCR0Flags::PKRU
);
check_flag!(
doc = "Support for PT in IA32_XSS.",
ia32_xss_supports_pt,
ecx1,
ExtendedStateInfoXSSFlags::PT
);
check_flag!(
doc = "Support for HDC in IA32_XSS.",
ia32_xss_supports_hdc,
ecx1,
ExtendedStateInfoXSSFlags::HDC
);
/// Maximum size (bytes, from the beginning of the XSAVE/XRSTOR save area) required by
/// enabled features in XCR0. May be different than ECX if some features at the end of the XSAVE save area
/// are not enabled.
pub fn xsave_area_size_enabled_features(&self) -> u32 {
self.ebx
}
/// Maximum size (bytes, from the beginning of the XSAVE/XRSTOR save area) of the
/// XSAVE/XRSTOR save area required by all supported features in the processor,
/// i.e all the valid bit fields in XCR0.
pub fn xsave_area_size_supported_features(&self) -> u32 {
self.ecx
}
/// CPU has xsaveopt feature.
pub fn has_xsaveopt(&self) -> bool {
self.eax1 & 0x1 > 0
}
/// Supports XSAVEC and the compacted form of XRSTOR if set.
pub fn has_xsavec(&self) -> bool {
self.eax1 & 0b10 > 0
}
/// Supports XGETBV with ECX = 1 if set.
pub fn has_xgetbv(&self) -> bool {
self.eax1 & 0b100 > 0
}
/// Supports XSAVES/XRSTORS and IA32_XSS if set.
pub fn has_xsaves_xrstors(&self) -> bool {
self.eax1 & 0b1000 > 0
}
/// The size in bytes of the XSAVE area containing all states enabled by XCRO | IA32_XSS.
pub fn xsave_size(&self) -> u32 {
self.ebx1
}
/// Iterator over extended state enumeration levels >= 2.
pub fn iter(&self) -> ExtendedStateIter {
ExtendedStateIter {
level: 1,
supported_xcr0: self.eax.bits(),
supported_xss: self.ecx1.bits(),
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedStateIter {
level: u32,
supported_xcr0: u32,
supported_xss: u32,
}
/// When CPUID executes with EAX set to 0DH and ECX = n (n > 1,
/// and is a valid sub-leaf index), the processor returns information
/// about the size and offset of each processor extended state save area
/// within the XSAVE/XRSTOR area. Software can use the forward-extendable
/// technique depicted below to query the valid sub-leaves and obtain size
/// and offset information for each processor extended state save area:///
///
/// For i = 2 to 62 // sub-leaf 1 is reserved
/// IF (CPUID.(EAX=0DH, ECX=0):VECTOR[i] = 1 ) // VECTOR is the 64-bit value of EDX:EAX
/// Execute CPUID.(EAX=0DH, ECX = i) to examine size and offset for sub-leaf i;
/// FI;
impl Iterator for ExtendedStateIter {
type Item = ExtendedState;
fn next(&mut self) -> Option<ExtendedState> {
self.level += 1;
if self.level > 31 {
return None;
}
let bit = 1 << self.level;
if (self.supported_xcr0 & bit > 0) || (self.supported_xss & bit > 0) {
let res = cpuid!(EAX_EXTENDED_STATE_INFO, self.level);
return Some(ExtendedState {
subleaf: self.level,
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
});
}
self.next()
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedState {
pub subleaf: u32,
eax: u32,
ebx: u32,
ecx: u32,
}
impl ExtendedState {
/// The size in bytes (from the offset specified in EBX) of the save area
/// for an extended state feature associated with a valid sub-leaf index, n.
/// This field reports 0 if the sub-leaf index, n, is invalid.
pub fn size(&self) -> u32 {
self.eax
}
/// The offset in bytes of this extended state components save area
/// from the beginning of the XSAVE/XRSTOR area.
pub fn offset(&self) -> u32 {
self.ebx
}
/// True if the bit n (corresponding to the sub-leaf index)
/// is supported in the IA32_XSS MSR;
pub fn is_in_ia32_xss(&self) -> bool {
self.ecx & 0b1 > 0
}
/// True if bit n is supported in XCR0.
pub fn is_in_xcr0(&self) -> bool {
self.ecx & 0b1 == 0
}
/// Returns true when the compacted format of an XSAVE area is used,
/// this extended state component located on the next 64-byte
/// boundary following the preceding state component
/// (otherwise, it is located immediately following the preceding state component).
pub fn is_compacted_format(&self) -> bool {
self.ecx & 0b10 > 0
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct RdtMonitoringInfo {
ebx: u32,
edx: u32,
}
/// Intel Resource Director Technology (Intel RDT) Monitoring Enumeration Sub-leaf (EAX = 0FH, ECX = 0 and ECX = 1)
impl RdtMonitoringInfo {
/// Maximum range (zero-based) of RMID within this physical processor of all types.
pub fn rmid_range(&self) -> u32 {
self.ebx
}
check_bit_fn!(
doc = "Supports L3 Cache Intel RDT Monitoring.",
has_l3_monitoring,
edx,
1
);
/// L3 Cache Monitoring.
pub fn l3_monitoring(&self) -> Option<L3MonitoringInfo> {
if self.has_l3_monitoring() {
let res = cpuid!(EAX_RDT_MONITORING, 1);
return Some(L3MonitoringInfo {
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L3MonitoringInfo {
ebx: u32,
ecx: u32,
edx: u32,
}
impl L3MonitoringInfo {
/// Conversion factor from reported IA32_QM_CTR value to occupancy metric (bytes).
pub fn conversion_factor(&self) -> u32 {
self.ebx
}
/// Maximum range (zero-based) of RMID of L3.
pub fn maximum_rmid_range(&self) -> u32 {
self.ecx
}
check_bit_fn!(
doc = "Supports occupancy monitoring.",
has_occupancy_monitoring,
edx,
0
);
check_bit_fn!(
doc = "Supports total bandwidth monitoring.",
has_total_bandwidth_monitoring,
edx,
1
);
check_bit_fn!(
doc = "Supports local bandwidth monitoring.",
has_local_bandwidth_monitoring,
edx,
2
);
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct RdtAllocationInfo {
ebx: u32,
}
impl RdtAllocationInfo {
check_bit_fn!(doc = "Supports L3 Cache Allocation.", has_l3_cat, ebx, 1);
check_bit_fn!(doc = "Supports L2 Cache Allocation.", has_l2_cat, ebx, 2);
check_bit_fn!(
doc = "Supports Memory Bandwidth Allocation.",
has_memory_bandwidth_allocation,
ebx,
1
);
/// L3 Cache Allocation Information.
pub fn l3_cat(&self) -> Option<L3CatInfo> {
if self.has_l3_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 1);
return Some(L3CatInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
/// L2 Cache Allocation Information.
pub fn l2_cat(&self) -> Option<L2CatInfo> {
if self.has_l2_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 2);
return Some(L2CatInfo {
eax: res.eax,
ebx: res.ebx,
edx: res.edx,
});
} else {
return None;
}
}
/// Memory Bandwidth Allocation Information.
pub fn memory_bandwidth_allocation(&self) -> Option<MemBwAllocationInfo> {
if self.has_l2_cat() {
let res = cpuid!(EAX_RDT_ALLOCATION, 3);
return Some(MemBwAllocationInfo {
eax: res.eax,
ecx: res.ecx,
edx: res.edx,
});
} else {
return None;
}
}
}
/// L3 Cache Allocation Technology Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 1).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L3CatInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl L3CatInfo {
/// Length of the capacity bit mask using minus-one notation.
pub fn capacity_mask_length(&self) -> u8 {
get_bits(self.eax, 0, 4) as u8
}
/// Bit-granular map of isolation/contention of allocation units.
pub fn isolation_bitmap(&self) -> u32 {
self.ebx
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
check_bit_fn!(
doc = "Is Code and Data Prioritization Technology supported?",
has_code_data_prioritization,
ecx,
2
);
}
/// L2 Cache Allocation Technology Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 2).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct L2CatInfo {
eax: u32,
ebx: u32,
edx: u32,
}
impl L2CatInfo {
/// Length of the capacity bit mask using minus-one notation.
pub fn capacity_mask_length(&self) -> u8 {
get_bits(self.eax, 0, 4) as u8
}
/// Bit-granular map of isolation/contention of allocation units.
pub fn isolation_bitmap(&self) -> u32 {
self.ebx
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
}
/// Memory Bandwidth Allocation Enumeration Sub-leaf (EAX = 10H, ECX = ResID = 3).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct MemBwAllocationInfo {
eax: u32,
ecx: u32,
edx: u32,
}
impl MemBwAllocationInfo {
/// Reports the maximum MBA throttling value supported for the corresponding ResID using minus-one notation.
pub fn max_hba_throttling(&self) -> u16 {
get_bits(self.eax, 0, 11) as u16
}
/// Highest COS number supported for this Leaf.
pub fn highest_cos(&self) -> u16 {
get_bits(self.edx, 0, 15) as u16
}
check_bit_fn!(
doc = "Reports whether the response of the delay values is linear.",
has_linear_response_delay,
ecx,
2
);
}
/// Intel SGX Capability Enumeration Leaf, sub-leaf 0 (EAX = 12H, ECX = 0 and ECX = 1)
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SgxInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
eax1: u32,
ebx1: u32,
ecx1: u32,
edx1: u32,
}
impl SgxInfo {
check_bit_fn!(doc = "Has SGX1 support.", has_sgx1, eax, 0);
check_bit_fn!(doc = "Has SGX2 support.", has_sgx2, eax, 1);
check_bit_fn!(
doc = "Supports ENCLV instruction leaves EINCVIRTCHILD, EDECVIRTCHILD, and ESETCONTEXT.",
has_enclv_leaves_einvirtchild_edecvirtchild_esetcontext,
eax,
5
);
check_bit_fn!(
doc = "Supports ENCLS instruction leaves ETRACKC, ERDINFO, ELDBC, and ELDUC.",
has_encls_leaves_etrackc_erdinfo_eldbc_elduc,
eax,
6
);
/// Bit vector of supported extended SGX features.
pub fn miscselect(&self) -> u32 {
self.ebx
}
/// The maximum supported enclave size in non-64-bit mode is 2^retval.
pub fn max_enclave_size_non_64bit(&self) -> u8 {
get_bits(self.edx, 0, 7) as u8
}
/// The maximum supported enclave size in 64-bit mode is 2^retval.
pub fn max_enclave_size_64bit(&self) -> u8 {
get_bits(self.edx, 8, 15) as u8
}
/// Reports the valid bits of SECS.ATTRIBUTES[127:0] that software can set with ECREATE.
pub fn secs_attributes(&self) -> (u64, u64) {
let lower = self.eax1 as u64 | (self.ebx1 as u64) << 32;
let upper = self.ecx1 as u64 | (self.edx1 as u64) << 32;
(lower, upper)
}
/// Iterator over SGX sub-leafs.
pub fn iter(&self) -> SgxSectionIter {
SgxSectionIter { current: 2 }
}
}
/// Iterator over the SGX sub-leafs (ECX >= 2).
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SgxSectionIter {
current: u32,
}
impl Iterator for SgxSectionIter {
type Item = SgxSectionInfo;
fn next(&mut self) -> Option<SgxSectionInfo> {
self.current += 1;
let res = cpuid!(EAX_SGX, self.current);
match get_bits(res.eax, 0, 3) {
0b0001 => Some(SgxSectionInfo::Epc(EpcSection {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
})),
_ => None,
}
}
}
/// Intel SGX EPC Enumeration Leaf, sub-leaves (EAX = 12H, ECX = 2 or higher)
#[derive(Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum SgxSectionInfo {
// This would be nice: https://github.com/rust-lang/rfcs/pull/1450
Epc(EpcSection),
}
impl Default for SgxSectionInfo {
fn default() -> SgxSectionInfo {
SgxSectionInfo::Epc(Default::default())
}
}
/// EBX:EAX and EDX:ECX provide information on the Enclave Page Cache (EPC) section
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct EpcSection {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl EpcSection {
/// The physical address of the base of the EPC section
pub fn physical_base(&self) -> u64 {
let lower = (get_bits(self.eax, 12, 31) << 12) as u64;
let upper = (get_bits(self.ebx, 0, 19) as u64) << 32;
lower | upper
}
/// Size of the corresponding EPC section within the Processor Reserved Memory.
pub fn size(&self) -> u64 {
let lower = (get_bits(self.ecx, 12, 31) << 12) as u64;
let upper = (get_bits(self.edx, 0, 19) as u64) << 32;
lower | upper
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorTraceInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
leaf1: Option<CpuIdResult>,
}
impl ProcessorTraceInfo {
// EBX features
check_bit_fn!(
doc = "If true, Indicates that IA32_RTIT_CTL.CR3Filter can be set to 1, and \
that IA32_RTIT_CR3_MATCH MSR can be accessed.",
has_rtit_cr3_match,
ebx,
0
);
check_bit_fn!(
doc = "If true, Indicates support of Configurable PSB and Cycle-Accurate Mode.",
has_configurable_psb_and_cycle_accurate_mode,
ebx,
1
);
check_bit_fn!(
doc = "If true, Indicates support of IP Filtering, TraceStop filtering, and \
preservation of Intel PT MSRs across warm reset.",
has_ip_tracestop_filtering,
ebx,
2
);
check_bit_fn!(
doc = "If true, Indicates support of MTC timing packet and suppression of \
COFI-based packets.",
has_mtc_timing_packet_coefi_suppression,
ebx,
3
);
check_bit_fn!(
doc = "Indicates support of PTWRITE. Writes can set IA32_RTIT_CTL[12] (PTWEn \
and IA32_RTIT_CTL[5] (FUPonPTW), and PTWRITE can generate packets",
has_ptwrite,
ebx,
4
);
check_bit_fn!(
doc = "Support of Power Event Trace. Writes can set IA32_RTIT_CTL[4] (PwrEvtEn) \
enabling Power Event Trace packet generation.",
has_power_event_trace,
ebx,
5
);
// ECX features
check_bit_fn!(
doc = "If true, Tracing can be enabled with IA32_RTIT_CTL.ToPA = 1, hence \
utilizing the ToPA output scheme; IA32_RTIT_OUTPUT_BASE and \
IA32_RTIT_OUTPUT_MASK_PTRS MSRs can be accessed.",
has_topa,
ecx,
0
);
check_bit_fn!(
doc = "If true, ToPA tables can hold any number of output entries, up to the \
maximum allowed by the MaskOrTableOffset field of \
IA32_RTIT_OUTPUT_MASK_PTRS.",
has_topa_maximum_entries,
ecx,
1
);
check_bit_fn!(
doc = "If true, Indicates support of Single-Range Output scheme.",
has_single_range_output_scheme,
ecx,
2
);
check_bit_fn!(
doc = "If true, Indicates support of output to Trace Transport subsystem.",
has_trace_transport_subsystem,
ecx,
3
);
check_bit_fn!(
doc = "If true, Generated packets which contain IP payloads have LIP values, \
which include the CS base component.",
has_lip_with_cs_base,
ecx,
31
);
/// Number of configurable Address Ranges for filtering (Bits 2:0).
pub fn configurable_address_ranges(&self) -> u8 {
self.leaf1.map_or(0, |res| get_bits(res.eax, 0, 2) as u8)
}
/// Bitmap of supported MTC period encodings (Bit 31:16).
pub fn supported_mtc_period_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.eax, 16, 31) as u16)
}
/// Bitmap of supported Cycle Threshold value encodings (Bits 15-0).
pub fn supported_cycle_threshold_value_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.ebx, 0, 15) as u16)
}
/// Bitmap of supported Configurable PSB frequency encodings (Bit 31:16)
pub fn supported_psb_frequency_encodings(&self) -> u16 {
self.leaf1.map_or(0, |res| get_bits(res.ebx, 16, 31) as u16)
}
}
/// Contains time stamp counter information.
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct TscInfo {
eax: u32,
ebx: u32,
ecx: u32,
}
impl TscInfo {
/// An unsigned integer which is the denominator of the TSC/”core crystal clock” ratio.
pub fn denominator(&self) -> u32 {
self.eax
}
/// An unsigned integer which is the numerator of the TSC/”core crystal clock” ratio.
pub fn numerator(&self) -> u32 {
self.ebx
}
/// An unsigned integer which is the nominal frequency of the core crystal clock in Hz.
pub fn nominal_frequency(&self) -> u32 {
self.ecx
}
pub fn tsc_frequency(&self) -> u64 {
self.nominal_frequency() as u64 * self.numerator() as u64 / self.denominator() as u64
}
}
/// Processor Frequency Information
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ProcessorFrequencyInfo {
eax: u32,
ebx: u32,
ecx: u32,
}
impl ProcessorFrequencyInfo {
/// Processor Base Frequency (in MHz).
pub fn processor_base_frequency(&self) -> u16 {
get_bits(self.eax, 0, 15) as u16
}
/// Maximum Frequency (in MHz).
pub fn processor_max_frequency(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
/// Bus (Reference) Frequency (in MHz).
pub fn bus_frequency(&self) -> u16 {
get_bits(self.ecx, 0, 15) as u16
}
}
/// Deterministic Address Translation Structure Iterator
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DatIter {
current: u32,
count: u32,
}
impl Iterator for DatIter {
type Item = DatInfo;
/// Iterate over each sub-leaf with an address translation structure.
fn next(&mut self) -> Option<DatInfo> {
loop {
// Sub-leaf index n is invalid if n exceeds the value that sub-leaf 0 returns in EAX
if self.current > self.count {
return None;
}
let res = cpuid!(EAX_DETERMINISTIC_ADDRESS_TRANSLATION_INFO, self.current);
self.current += 1;
// A sub-leaf index is also invalid if EDX[4:0] returns 0.
if get_bits(res.edx, 0, 4) == 0 {
// Valid sub-leaves do not need to be contiguous or in any particular order.
// A valid sub-leaf may be in a higher input ECX value than an invalid sub-leaf
// or than a valid sub-leaf of a higher or lower-level struc-ture
continue;
}
return Some(DatInfo {
eax: res.eax,
ebx: res.ebx,
ecx: res.ecx,
edx: res.edx,
});
}
}
}
/// Deterministic Address Translation Structure
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DatInfo {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl DatInfo {
check_bit_fn!(
doc = "4K page size entries supported by this structure",
has_4k_entries,
ebx,
0
);
check_bit_fn!(
doc = "2MB page size entries supported by this structure",
has_2mb_entries,
ebx,
1
);
check_bit_fn!(
doc = "4MB page size entries supported by this structure",
has_4mb_entries,
ebx,
2
);
check_bit_fn!(
doc = "1GB page size entries supported by this structure",
has_1gb_entries,
ebx,
3
);
check_bit_fn!(
doc = "Fully associative structure",
is_fully_associative,
edx,
8
);
/// Partitioning (0: Soft partitioning between the logical processors sharing this structure).
pub fn partitioning(&self) -> u8 {
get_bits(self.ebx, 8, 10) as u8
}
/// Ways of associativity.
pub fn ways(&self) -> u16 {
get_bits(self.ebx, 16, 31) as u16
}
/// Number of Sets.
pub fn sets(&self) -> u32 {
self.ecx
}
/// Translation cache type field.
pub fn cache_type(&self) -> DatType {
match get_bits(self.edx, 0, 4) as u8 {
0b00001 => DatType::DataTLB,
0b00010 => DatType::InstructionTLB,
0b00011 => DatType::UnifiedTLB,
0b00000 => DatType::Null, // should never be returned as this indicates invalid struct!
_ => DatType::Unknown,
}
}
/// Translation cache level (starts at 1)
pub fn cache_level(&self) -> u8 {
get_bits(self.edx, 5, 7) as u8
}
/// Maximum number of addressable IDs for logical processors sharing this translation cache
pub fn max_addressable_ids(&self) -> u16 {
// Add one to the return value to get the result:
(get_bits(self.edx, 14, 25) + 1) as u16
}
}
/// Deterministic Address Translation cache type (EDX bits 04 -- 00)
#[derive(Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum DatType {
/// Null (indicates this sub-leaf is not valid).
Null = 0b00000,
DataTLB = 0b00001,
InstructionTLB = 0b00010,
/// Some unified TLBs will allow a single TLB entry to satisfy data read/write
/// and instruction fetches. Others will require separate entries (e.g., one
/// loaded on data read/write and another loaded on an instruction fetch) .
/// Please see the Intel® 64 and IA-32 Architectures Optimization Reference Manual
/// for details of a particular product.
UnifiedTLB = 0b00011,
Unknown,
}
impl Default for DatType {
fn default() -> DatType {
DatType::Null
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorInfo {
/// MaxSOCID_Index
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
}
impl SoCVendorInfo {
pub fn get_soc_vendor_id(&self) -> u16 {
get_bits(self.ebx, 0, 15) as u16
}
pub fn get_project_id(&self) -> u32 {
self.ecx
}
pub fn get_stepping_id(&self) -> u32 {
self.edx
}
pub fn get_vendor_brand(&self) -> SoCVendorBrand {
assert!(self.eax >= 3); // Leaf 17H is valid if MaxSOCID_Index >= 3.
let r1 = cpuid!(EAX_SOC_VENDOR_INFO, 1);
let r2 = cpuid!(EAX_SOC_VENDOR_INFO, 2);
let r3 = cpuid!(EAX_SOC_VENDOR_INFO, 3);
SoCVendorBrand { data: [r1, r2, r3] }
}
pub fn get_vendor_attributes(&self) -> Option<SoCVendorAttributesIter> {
if self.eax > 3 {
Some(SoCVendorAttributesIter {
count: self.eax,
current: 3,
})
} else {
None
}
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorAttributesIter {
count: u32,
current: u32,
}
impl Iterator for SoCVendorAttributesIter {
type Item = CpuIdResult;
/// Iterate over all SoC vendor specific attributes.
fn next(&mut self) -> Option<CpuIdResult> {
if self.current > self.count {
return None;
}
self.count += 1;
Some(cpuid!(EAX_SOC_VENDOR_INFO, self.count))
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoCVendorBrand {
#[allow(dead_code)]
data: [CpuIdResult; 3],
}
impl SoCVendorBrand {
pub fn as_string<'a>(&'a self) -> &'a str {
unsafe {
let brand_string_start = self as *const SoCVendorBrand as *const u8;
let slice =
slice::from_raw_parts(brand_string_start, core::mem::size_of::<SoCVendorBrand>());
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
}
}
}
impl fmt::Display for SoCVendorBrand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_string())
}
}
#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct ExtendedFunctionInfo {
max_eax_value: u32,
data: [CpuIdResult; 9],
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum L2Associativity {
Disabled = 0x0,
DirectMapped = 0x1,
TwoWay = 0x2,
FourWay = 0x4,
EightWay = 0x6,
SixteenWay = 0x8,
FullyAssiciative = 0xF,
Unknown,
}
impl Default for L2Associativity {
fn default() -> L2Associativity {
L2Associativity::Unknown
}
}
const EAX_EXTENDED_PROC_SIGNATURE: u32 = 0x1;
const EAX_EXTENDED_BRAND_STRING: u32 = 0x4;
const EAX_EXTENDED_CACHE_INFO: u32 = 0x6;
impl ExtendedFunctionInfo {
fn leaf_is_supported(&self, val: u32) -> bool {
val <= self.max_eax_value
}
/// Retrieve processor brand string.
pub fn processor_brand_string<'a>(&'a self) -> Option<&'a str> {
if self.leaf_is_supported(EAX_EXTENDED_BRAND_STRING) {
Some(unsafe {
let brand_string_start = &self.data[2] as *const CpuIdResult as *const u8;
let mut slice = slice::from_raw_parts(brand_string_start, 3 * 4 * 4);
match slice.iter().position(|&x| x == 0) {
Some(index) => slice = slice::from_raw_parts(brand_string_start, index),
None => (),
}
let byte_array: &'a [u8] = transmute(slice);
str::from_utf8_unchecked(byte_array)
})
} else {
None
}
}
/// Extended Processor Signature and Feature Bits.
pub fn extended_signature(&self) -> Option<u32> {
if self.leaf_is_supported(EAX_EXTENDED_PROC_SIGNATURE) {
Some(self.data[1].eax)
} else {
None
}
}
/// Cache Line size in bytes
pub fn cache_line_size(&self) -> Option<u8> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(get_bits(self.data[6].ecx, 0, 7) as u8)
} else {
None
}
}
/// L2 Associativity field
pub fn l2_associativity(&self) -> Option<L2Associativity> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(match get_bits(self.data[6].ecx, 12, 15) {
0x0 => L2Associativity::Disabled,
0x1 => L2Associativity::DirectMapped,
0x2 => L2Associativity::TwoWay,
0x4 => L2Associativity::FourWay,
0x6 => L2Associativity::EightWay,
0x8 => L2Associativity::SixteenWay,
0xF => L2Associativity::FullyAssiciative,
_ => L2Associativity::Unknown,
})
} else {
None
}
}
/// Cache size in 1K units
pub fn cache_size(&self) -> Option<u16> {
if self.leaf_is_supported(EAX_EXTENDED_CACHE_INFO) {
Some(get_bits(self.data[6].ecx, 16, 31) as u16)
} else {
None
}
}
/// #Physical Address Bits
pub fn physical_address_bits(&self) -> Option<u8> {
if self.leaf_is_supported(8) {
Some(get_bits(self.data[8].eax, 0, 7) as u8)
} else {
None
}
}
/// #Linear Address Bits
pub fn linear_address_bits(&self) -> Option<u8> {
if self.leaf_is_supported(8) {
Some(get_bits(self.data[8].eax, 8, 15) as u8)
} else {
None
}
}
/// Is Invariant TSC available?
pub fn has_invariant_tsc(&self) -> bool {
self.leaf_is_supported(7) && self.data[7].edx & (1 << 8) > 0
}
/// Is LAHF/SAHF available in 64-bit mode?
pub fn has_lahf_sahf(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::LAHF_SAHF)
}
/// Is LZCNT available?
pub fn has_lzcnt(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::LZCNT)
}
/// Is PREFETCHW available?
pub fn has_prefetchw(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEcx {
bits: self.data[1].ecx,
}.contains(ExtendedFunctionInfoEcx::PREFETCHW)
}
/// Are fast system calls available.
pub fn has_syscall_sysret(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::SYSCALL_SYSRET)
}
/// Is there support for execute disable bit.
pub fn has_execute_disable(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::EXECUTE_DISABLE)
}
/// Is there support for 1GiB pages.
pub fn has_1gib_pages(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::GIB_PAGES)
}
/// Check support for rdtscp instruction.
pub fn has_rdtscp(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::RDTSCP)
}
/// Check support for 64-bit mode.
pub fn has_64bit_mode(&self) -> bool {
self.leaf_is_supported(1) && ExtendedFunctionInfoEdx {
bits: self.data[1].edx,
}.contains(ExtendedFunctionInfoEdx::I64BIT_MODE)
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFunctionInfoEcx: u32 {
/// LAHF/SAHF available in 64-bit mode.
const LAHF_SAHF = 1 << 0;
/// Bit 05: LZCNT
const LZCNT = 1 << 5;
/// Bit 08: PREFETCHW
const PREFETCHW = 1 << 8;
}
}
bitflags! {
#[derive(Default)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
struct ExtendedFunctionInfoEdx: u32 {
/// SYSCALL/SYSRET available in 64-bit mode (Bit 11).
const SYSCALL_SYSRET = 1 << 11;
/// Execute Disable Bit available (Bit 20).
const EXECUTE_DISABLE = 1 << 20;
/// 1-GByte pages are available if 1 (Bit 26).
const GIB_PAGES = 1 << 26;
/// RDTSCP and IA32_TSC_AUX are available if 1 (Bit 27).
const RDTSCP = 1 << 27;
/// Intel ® 64 Architecture available if 1 (Bit 29).
const I64BIT_MODE = 1 << 29;
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Simple numerics.
//!
//! This crate contains arbitrary-sized integer, rational, and complex types.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! extern crate num;
//!
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! fn approx_sqrt(number: u64, iterations: uint) -> BigRational {
//! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//! let mut approx = start.clone();
//!
//! for _ in range(0, iterations) {
//! approx = (approx + (start / approx)) /
//! Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//! }
//!
//! approx
//! }
//!
//! fn main() {
//! println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![feature(macro_rules)]
#![feature(default_type_params)]
#![feature(slicing_syntax)]
#![crate_name = "num"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(deprecated)] // from_str_radix
extern crate rand;
extern crate serialize;
pub use bigint::{BigInt, BigUint};
pub use rational::{Rational, BigRational};
pub use complex::Complex;
pub use integer::Integer;
pub use iter::{range, range_inclusive, range_step, range_step_inclusive};
pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded,
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
pub mod bigint;
pub mod complex;
pub mod integer;
pub mod iter;
pub mod traits;
pub mod rational;
/// Returns the additive identity, `0`.
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
/// Returns the multiplicative identity, `1`.
#[inline(always)] pub fn one<T: One>() -> T { One::one() }
/// Computes the absolute value.
///
/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
///
/// For signed integers, `::MIN` will be returned if the number is `::MIN`.
#[inline(always)]
pub fn abs<T: Signed>(value: T) -> T {
value.abs()
}
/// The positive difference of two numbers.
///
/// Returns zero if `x` is less than or equal to `y`, otherwise the difference
/// between `x` and `y` is returned.
#[inline(always)]
pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
x.abs_sub(&y)
}
/// Returns the sign of the number.
///
/// For `f32` and `f64`:
///
/// * `1.0` if the number is positive, `+0.0` or `INFINITY`
/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// * `NaN` if the number is `NaN`
///
/// For signed integers:
///
/// * `0` if the number is zero
/// * `1` if the number is positive
/// * `-1` if the number is negative
#[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num;
///
/// assert_eq!(num::pow(2i, 4), 16);
/// ```
#[inline]
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
if exp == 1 { base }
else {
let mut acc = one::<T>();
while exp > 0 {
if (exp & 1) == 1 {
acc = acc * base;
}
base = base * base;
exp = exp >> 1;
}
acc
}
}
don't allow deprecated items.
We don't actually use any.
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Simple numerics.
//!
//! This crate contains arbitrary-sized integer, rational, and complex types.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! extern crate num;
//!
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! fn approx_sqrt(number: u64, iterations: uint) -> BigRational {
//! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//! let mut approx = start.clone();
//!
//! for _ in range(0, iterations) {
//! approx = (approx + (start / approx)) /
//! Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//! }
//!
//! approx
//! }
//!
//! fn main() {
//! println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![feature(macro_rules)]
#![feature(default_type_params)]
#![feature(slicing_syntax)]
#![crate_name = "num"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
extern crate rand;
extern crate serialize;
pub use bigint::{BigInt, BigUint};
pub use rational::{Rational, BigRational};
pub use complex::Complex;
pub use integer::Integer;
pub use iter::{range, range_inclusive, range_step, range_step_inclusive};
pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded,
Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
pub mod bigint;
pub mod complex;
pub mod integer;
pub mod iter;
pub mod traits;
pub mod rational;
/// Returns the additive identity, `0`.
#[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
/// Returns the multiplicative identity, `1`.
#[inline(always)] pub fn one<T: One>() -> T { One::one() }
/// Computes the absolute value.
///
/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
///
/// For signed integers, `::MIN` will be returned if the number is `::MIN`.
#[inline(always)]
pub fn abs<T: Signed>(value: T) -> T {
value.abs()
}
/// The positive difference of two numbers.
///
/// Returns zero if `x` is less than or equal to `y`, otherwise the difference
/// between `x` and `y` is returned.
#[inline(always)]
pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
x.abs_sub(&y)
}
/// Returns the sign of the number.
///
/// For `f32` and `f64`:
///
/// * `1.0` if the number is positive, `+0.0` or `INFINITY`
/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
/// * `NaN` if the number is `NaN`
///
/// For signed integers:
///
/// * `0` if the number is zero
/// * `1` if the number is positive
/// * `-1` if the number is negative
#[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
/// Raises a value to the power of exp, using exponentiation by squaring.
///
/// # Example
///
/// ```rust
/// use num;
///
/// assert_eq!(num::pow(2i, 4), 16);
/// ```
#[inline]
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
if exp == 1 { base }
else {
let mut acc = one::<T>();
while exp > 0 {
if (exp & 1) == 1 {
acc = acc * base;
}
base = base * base;
exp = exp >> 1;
}
acc
}
}
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Generate and parse UUIDs.
//!
//! Provides support for Universally Unique Identifiers (UUIDs). A UUID is a
//! unique 128-bit number, stored as 16 octets. UUIDs are used to assign
//! unique identifiers to entities without requiring a central allocating
//! authority.
//!
//! They are particularly useful in distributed systems, though can be used in
//! disparate areas, such as databases and network protocols. Typically a UUID
//! is displayed in a readable string form as a sequence of hexadecimal digits,
//! separated into groups by hyphens.
//!
//! The uniqueness property is not strictly guaranteed, however for all
//! practical purposes, it can be assumed that an unintentional collision would
//! be extremely unlikely.
//!
//! # Dependencies
//!
//! By default, this crate depends on nothing but `std` and cannot generate
//! [`Uuid`]s. You need to enable the following Cargo features to enable
//! various pieces of functionality:
//!
//! * `v1` - adds the `Uuid::new_v1` function and the ability to create a V1
//! using an implementation of `UuidV1ClockSequence` (usually `UuidV1Context`)
//! and a timestamp from `time::timespec`.
//! * `v3` - adds the `Uuid::new_v3` function and the ability to create a V3
//! UUID based on the MD5 hash of some data.
//! * `v4` - adds the `Uuid::new_v4` function and the ability to randomly
//! generate a `Uuid`.
//! * `v5` - adds the `Uuid::new_v5` function and the ability to create a V5
//! UUID based on the SHA1 hash of some data.
//! * `serde` - adds the ability to serialize and deserialize a `Uuid` using the
//! `serde` crate.
//!
//! By default, `uuid` can be depended on with:
//!
//! ```toml
//! [dependencies]
//! uuid = "0.6"
//! ```
//!
//! To activate various features, use syntax like:
//!
//! ```toml
//! [dependencies]
//! uuid = { version = "0.6", features = ["serde", "v4"] }
//! ```
//!
//! You can disable default features with:
//!
//! ```toml
//! [dependencies]
//! uuid = { version = "0.6", default-features = false }
//! ```
//!
//! # Examples
//!
//! To parse a UUID given in the simple format and print it as a urn:
//!
//! ```rust
//! use uuid::Uuid;
//!
//! fn main() {
//! let my_uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
//! println!("{}", my_uuid.urn());
//! }
//! ```
//!
//! To create a new random (V4) UUID and print it out in hexadecimal form:
//!
//! ```ignore,rust
//! // Note that this requires the `v4` feature enabled in the uuid crate.
//!
//! use uuid::Uuid;
//!
//! fn main() {
//! let my_uuid = Uuid::new_v4();
//! println!("{}", my_uuid);
//! }
//! ```
//!
//! # Strings
//!
//! Examples of string representations:
//!
//! * simple: `936DA01F9ABD4d9d80C702AF85C822A8`
//! * hyphenated: `550e8400-e29b-41d4-a716-446655440000`
//! * urn: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
//!
//! # References
//!
//! * [Wikipedia: Universally Unique Identifier](
//! http://en.wikipedia.org/wiki/Universally_unique_identifier)
//! * [RFC4122: A Universally Unique IDentifier (UUID) URN Namespace](
//! http://tools.ietf.org/html/rfc4122)
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/uuid"
)]
#![deny(warnings)]
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(const_fn)]
#[macro_use]
extern crate cfg_if;
cfg_if! {
if #[cfg(feature = "md5")] {
extern crate md5;
}
}
cfg_if! {
if #[cfg(feature = "rand")] {
extern crate rand;
}
}
cfg_if! {
if #[cfg(feature = "serde")] {
extern crate serde;
}
}
cfg_if! {
if #[cfg(feature = "sha1")] {
extern crate sha1;
}
}
cfg_if! {
if #[cfg(all(feature = "slog", not(test)))] {
extern crate slog;
} else if #[cfg(all(feature = "slog", test))] {
#[macro_use]
extern crate slog;
}
}
cfg_if! {
if #[cfg(feature = "std")] {
use std::fmt;
use std::str;
cfg_if! {
if #[cfg(feature = "v1")] {
use std::sync::atomic;
}
}
} else if #[cfg(not(feature = "std"))] {
use core::fmt;
use core::str;
cfg_if! {
if #[cfg(feature = "v1")] {
use core::sync::atomic;
}
}
}
}
pub mod adapter;
pub mod prelude;
mod core_support;
cfg_if! {
if #[cfg(feature = "serde")] {
mod serde_support;
}
}
cfg_if! {
if #[cfg(feature = "slog")] {
mod slog_support;
}
}
cfg_if! {
if #[cfg(feature = "std")] {
mod std_support;
}
}
cfg_if! {
if #[cfg(test)] {
mod test_util;
}
}
/// A 128-bit (16 byte) buffer containing the ID.
pub type UuidBytes = [u8; 16];
/// The version of the UUID, denoting the generating algorithm.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum UuidVersion {
/// Version 1: MAC address
Mac = 1,
/// Version 2: DCE Security
Dce = 2,
/// Version 3: MD5 hash
Md5 = 3,
/// Version 4: Random
Random = 4,
/// Version 5: SHA-1 hash
Sha1 = 5,
}
/// The reserved variants of UUIDs.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UuidVariant {
/// Reserved by the NCS for backward compatibility
NCS,
/// As described in the RFC4122 Specification (default)
RFC4122,
/// Reserved by Microsoft for backward compatibility
Microsoft,
/// Reserved for future expansion
Future,
}
/// A Universally Unique Identifier (UUID).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Uuid {
/// The 128-bit number stored in 16 bytes
bytes: UuidBytes,
}
/// An adaptor for formatting a `Uuid` as a simple string.
pub struct Simple<'a> {
inner: &'a Uuid,
}
/// An adaptor for formatting a `Uuid` as a hyphenated string.
pub struct Hyphenated<'a> {
inner: &'a Uuid,
}
/// A UUID of the namespace of fully-qualified domain names
pub const NAMESPACE_DNS: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of URLs
pub const NAMESPACE_URL: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of ISO OIDs
pub const NAMESPACE_OID: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of X.500 DNs (in DER or a text output format)
pub const NAMESPACE_X500: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// The number of 100 ns ticks between
/// the UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00
#[cfg(feature = "v1")]
const UUID_TICKS_BETWEEN_EPOCHS: u64 = 0x01B2_1DD2_1381_4000;
/// An adaptor for formatting a `Uuid` as a URN string.
pub struct Urn<'a> {
inner: &'a Uuid,
}
cfg_if! {
if #[cfg(feature = "v1")] {
/// A trait that abstracts over generation of Uuid v1 "Clock Sequence"
/// values.
pub trait UuidV1ClockSequence {
/// Return a 16-bit number that will be used as the "clock
/// sequence" in the Uuid. The number must be different if the
/// time has changed since the last time a clock sequence was
/// requested.
fn generate_sequence(&self, seconds: u64, nano_seconds: u32) -> u16;
}
/// A thread-safe, stateful context for the v1 generator to help
/// ensure process-wide uniqueness.
pub struct UuidV1Context {
count: atomic::AtomicUsize,
}
impl UuidV1Context {
/// Creates a thread-safe, internally mutable context to help
/// ensure uniqueness.
///
/// This is a context which can be shared across threads. It
/// maintains an internal counter that is incremented at every
/// request, the value ends up in the clock_seq portion of the
/// Uuid (the fourth group). This will improve the probability
/// that the Uuid is unique across the process.
pub fn new(count: u16) -> UuidV1Context {
UuidV1Context {
count: atomic::AtomicUsize::new(count as usize),
}
}
}
impl UuidV1ClockSequence for UuidV1Context {
fn generate_sequence(&self, _: u64, _: u32) -> u16 {
(self.count.fetch_add(1, atomic::Ordering::SeqCst) & 0xffff) as u16
}
}
}
}
/// Error details for string parsing failures.
#[allow(missing_docs)]
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ParseError {
InvalidLength(usize),
InvalidCharacter(char, usize),
InvalidGroups(usize),
InvalidGroupLength(usize, usize, u8),
}
/// Converts a `ParseError` to a string.
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::InvalidLength(found) => write!(
f,
"Invalid length; expecting {} or {} chars, found {}",
adapter::UUID_SIMPLE_LENGTH, adapter::UUID_HYPHENATED_LENGTH, found
),
ParseError::InvalidCharacter(found, pos) => write!(
f,
"Invalid character; found `{}` (0x{:02x}) at offset {}",
found, found as usize, pos
),
ParseError::InvalidGroups(found) => write!(
f,
"Malformed; wrong number of groups: expected 1 or 5, found {}",
found
),
ParseError::InvalidGroupLength(group, found, expecting) => write!(
f,
"Malformed; length of group {} was {}, expecting {}",
group, found, expecting
),
}
}
}
// Length of each hyphenated group in hex digits.
const GROUP_LENS: [u8; 5] = [8, 4, 4, 4, 12];
// Accumulated length of each hyphenated group in hex digits.
const ACC_GROUP_LENS: [u8; 5] = [8, 12, 16, 20, 32];
impl Uuid {
/// The 'nil UUID'.
///
/// The nil UUID is special form of UUID that is specified to have all
/// 128 bits set to zero, as defined in [IETF RFC 4122 Section 4.1.7][RFC].
///
/// [RFC]: https://tools.ietf.org/html/rfc4122.html#section-4.1.7
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
///
/// assert_eq!(uuid.hyphenated().to_string(),
/// "00000000-0000-0000-0000-000000000000");
/// ```
pub fn nil() -> Uuid {
Uuid { bytes: [0; 16] }
}
/// Creates a new `Uuid`.
///
/// Note that not all versions can be generated currently and `None` will be
/// returned if the specified version cannot be generated.
///
/// To generate a random UUID (`UuidVersion::Md5`), then the `v3`
/// feature must be enabled for this crate.
///
/// To generate a random UUID (`UuidVersion::Random`), then the `v4`
/// feature must be enabled for this crate.
///
/// To generate a random UUID (`UuidVersion::Sha1`), then the `v5`
/// feature must be enabled for this crate.
pub fn new(v: UuidVersion) -> Option<Uuid> {
// Why 23? Ascii has roughly 6bit randomness per 8bit.
// So to reach 128bit at-least 21.333 (128/6) Bytes are required.
#[cfg(any(feature = "v3", feature = "v5"))]
let iv: String = {
use rand::Rng;
rand::thread_rng().gen_ascii_chars().take(23).collect()
};
match v {
#[cfg(feature = "v3")]
UuidVersion::Md5 => Some(Uuid::new_v3(&NAMESPACE_DNS, &*iv)),
#[cfg(feature = "v4")]
UuidVersion::Random => Some(Uuid::new_v4()),
#[cfg(feature = "v5")]
UuidVersion::Sha1 => Some(Uuid::new_v5(&NAMESPACE_DNS, &*iv)),
_ => None,
}
}
/// Creates a new `Uuid` (version 1 style) using a time value + seq + NodeID.
///
/// This expects two values representing a monotonically increasing value
/// as well as a unique 6 byte NodeId, and an implementation of `UuidV1ClockSequence`.
/// This function is only guaranteed to produce unique values if the following conditions hold:
///
/// 1. The NodeID is unique for this process,
/// 2. The Context is shared across all threads which are generating V1 UUIDs,
/// 3. The `UuidV1ClockSequence` implementation reliably returns unique clock sequences
/// (this crate provides `UuidV1Context` for this purpose).
///
/// The NodeID must be exactly 6 bytes long. If the NodeID is not a valid length
/// this will return a `ParseError::InvalidLength`.
///
/// The function is not guaranteed to produce monotonically increasing values
/// however. There is a slight possibility that two successive equal time values
/// could be supplied and the sequence counter wraps back over to 0.
///
/// If uniqueness and monotonicity is required, the user is responsibile for ensuring
/// that the time value always increases between calls
/// (including between restarts of the process and device).
///
/// Note that usage of this method requires the `v1` feature of this crate
/// to be enabled.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use uuid::{Uuid, UuidV1Context};
///
/// let ctx = UuidV1Context::new(42);
/// let v1uuid = Uuid::new_v1(&ctx, 1497624119, 1234, &[1,2,3,4,5,6]).unwrap();
///
/// assert_eq!(v1uuid.hyphenated().to_string(), "f3b4958c-52a1-11e7-802a-010203040506");
/// ```
#[cfg(feature = "v1")]
pub fn new_v1<T: UuidV1ClockSequence>(
context: &T,
seconds: u64,
nsecs: u32,
node: &[u8],
) -> Result<Uuid, ParseError> {
if node.len() != 6 {
return Err(ParseError::InvalidLength(node.len()));
}
let count = context.generate_sequence(seconds, nsecs);
let timestamp = seconds * 10_000_000 + u64::from(nsecs / 100);
let uuidtime = timestamp + UUID_TICKS_BETWEEN_EPOCHS;
let time_low: u32 = (uuidtime & 0xFFFF_FFFF) as u32;
let time_mid: u16 = ((uuidtime >> 32) & 0xFFFF) as u16;
let time_hi_and_ver: u16 = (((uuidtime >> 48) & 0x0FFF) as u16) | (1 << 12);
let mut d4 = [0_u8; 8];
d4[0] = (((count & 0x3F00) >> 8) as u8) | 0x80;
d4[1] = (count & 0xFF) as u8;
d4[2..].copy_from_slice(node);
Uuid::from_fields(time_low, time_mid, time_hi_and_ver, &d4)
}
/// Creates a UUID using a name from a namespace, based on the MD5 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * `NAMESPACE_DNS`
/// * `NAMESPACE_URL`
/// * `NAMESPACE_OID`
/// * `NAMESPACE_X500`
///
/// Note that usage of this method requires the `v3` feature of this crate
/// to be enabled.
#[cfg(feature = "v3")]
pub fn new_v3(namespace: &Uuid, name: &str) -> Uuid {
let mut ctx = md5::Context::new();
ctx.consume(namespace.as_bytes());
ctx.consume(name.as_bytes());
let mut uuid = Uuid {
bytes: ctx.compute().into(),
};
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Md5);
uuid
}
/// Creates a random `Uuid`.
///
/// This uses the `rand` crate's default task RNG as the source of random numbers.
/// If you'd like to use a custom generator, don't use this method: use the
/// [`rand::Rand trait`]'s `rand()` method instead.
///
/// [`rand::Rand trait`]: ../../rand/rand/trait.Rand.html#tymethod.rand
///
/// Note that usage of this method requires the `v4` feature of this crate
/// to be enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::new_v4();
/// ```
#[cfg(feature = "v4")]
pub fn new_v4() -> Uuid {
use rand::Rng;
let mut rng = rand::thread_rng();
let mut bytes = [0; 16];
rng.fill_bytes(&mut bytes);
Uuid::from_random_bytes(bytes)
}
/// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * `NAMESPACE_DNS`
/// * `NAMESPACE_URL`
/// * `NAMESPACE_OID`
/// * `NAMESPACE_X500`
///
/// Note that usage of this method requires the `v5` feature of this crate
/// to be enabled.
#[cfg(feature = "v5")]
pub fn new_v5(namespace: &Uuid, name: &str) -> Uuid {
let mut hash = sha1::Sha1::new();
hash.update(namespace.as_bytes());
hash.update(name.as_bytes());
let buffer = hash.digest().bytes();
let mut uuid = Uuid { bytes: [0; 16] };
uuid.bytes.copy_from_slice(&buffer[..16]);
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Sha1);
uuid
}
/// Creates a `Uuid` from four field values.
///
/// # Errors
///
/// This function will return an error if `d4`'s length is not 8 bytes.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let d4 = [12, 3, 9, 56, 54, 43, 8, 9];
///
/// let uuid = Uuid::from_fields(42, 12, 5, &d4);
/// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
///
/// let expected_uuid = Ok(String::from("0000002a-000c-0005-0c03-0938362b0809"));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An invalid length:
///
/// ```
/// use uuid::Uuid;
/// use uuid::ParseError;
///
/// let d4 = [12];
///
/// let uuid = Uuid::from_fields(42, 12, 5, &d4);
///
/// let expected_uuid = Err(ParseError::InvalidLength(1));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
pub fn from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8]) -> Result<Uuid, ParseError> {
if d4.len() != 8 {
return Err(ParseError::InvalidLength(d4.len()));
}
Ok(Uuid {
bytes: [
(d1 >> 24) as u8,
(d1 >> 16) as u8,
(d1 >> 8) as u8,
d1 as u8,
(d2 >> 8) as u8,
d2 as u8,
(d3 >> 8) as u8,
d3 as u8,
d4[0],
d4[1],
d4[2],
d4[3],
d4[4],
d4[5],
d4[6],
d4[7],
],
})
}
/// Creates a `Uuid` using the supplied bytes.
///
/// # Errors
///
/// This function will return an error if `b` has any length other than 16.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let bytes = [4, 54, 67, 12, 43, 2, 98, 76,
/// 32, 50, 87, 5, 1, 33, 43, 87];
///
/// let uuid = Uuid::from_bytes(&bytes);
/// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
///
/// let expected_uuid = Ok(String::from("0436430c-2b02-624c-2032-570501212b57"));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An incorrect number of bytes:
///
/// ```
/// use uuid::Uuid;
/// use uuid::ParseError;
///
/// let bytes = [4, 54, 67, 12, 43, 2, 98, 76];
///
/// let uuid = Uuid::from_bytes(&bytes);
///
/// let expected_uuid = Err(ParseError::InvalidLength(8));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
pub fn from_bytes(b: &[u8]) -> Result<Uuid, ParseError> {
let len = b.len();
if len != 16 {
return Err(ParseError::InvalidLength(len));
}
let mut uuid = Uuid { bytes: [0; 16] };
uuid.bytes.copy_from_slice(b);
Ok(uuid)
}
/// Creates a `Uuid` using the supplied bytes.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
/// let bytes:UuidBytes = [70, 235, 208, 238, 14, 109, 67, 201, 185, 13, 204, 195, 90, 145, 63, 62];
///
/// let uuid = Uuid::from_uuid_bytes(bytes);
/// let uuid = uuid.hyphenated().to_string();
///
/// let expected_uuid = String::from("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e");
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An incorrect number of bytes:
///
/// ```compile_fail
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
/// let bytes:UuidBytes = [4, 54, 67, 12, 43, 2, 98, 76]; // doesn't compile
///
/// let uuid = Uuid::from_uuid_bytes(bytes);
/// ```
#[cfg(not(feature = "nightly"))]
pub fn from_uuid_bytes(b: UuidBytes) -> Uuid {
Uuid { bytes: b }
}
#[cfg(feature = "nightly")]
pub const fn from_uuid_bytes(b: UuidBytes) -> Uuid {
Uuid { bytes: b }
}
/// Creates a v4 Uuid from random bytes (e.g. bytes supplied from `Rand` crate)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
///
/// let bytes:UuidBytes = [70, 235, 208, 238, 14, 109, 67, 201, 185, 13, 204, 195, 90, 145, 63, 62];
/// let uuid = Uuid::from_random_bytes(bytes);
/// let uuid = uuid.hyphenated().to_string();
///
/// let expected_uuid = String::from("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e");
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
pub fn from_random_bytes(b: [u8; 16]) -> Uuid {
let mut uuid = Uuid { bytes: b };
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Random);
uuid
}
/// Specifies the variant of the UUID structure
#[allow(dead_code)]
fn set_variant(&mut self, v: UuidVariant) {
// Octet 8 contains the variant in the most significant 3 bits
self.bytes[8] = match v {
UuidVariant::NCS => self.bytes[8] & 0x7f, // b0xx...
UuidVariant::RFC4122 => (self.bytes[8] & 0x3f) | 0x80, // b10x...
UuidVariant::Microsoft => (self.bytes[8] & 0x1f) | 0xc0, // b110...
UuidVariant::Future => (self.bytes[8] & 0x1f) | 0xe0, // b111...
}
}
/// Returns the variant of the `Uuid` structure.
///
/// This determines the interpretation of the structure of the UUID.
/// Currently only the RFC4122 variant is generated by this module.
///
/// * [Variant Reference](http://tools.ietf.org/html/rfc4122#section-4.1.1)
pub fn get_variant(&self) -> Option<UuidVariant> {
match self.bytes[8] {
x if x & 0x80 == 0x00 => Some(UuidVariant::NCS),
x if x & 0xc0 == 0x80 => Some(UuidVariant::RFC4122),
x if x & 0xe0 == 0xc0 => Some(UuidVariant::Microsoft),
x if x & 0xe0 == 0xe0 => Some(UuidVariant::Future),
_ => None,
}
}
/// Specifies the version number of the `Uuid`.
#[allow(dead_code)]
fn set_version(&mut self, v: UuidVersion) {
self.bytes[6] = (self.bytes[6] & 0xF) | ((v as u8) << 4);
}
/// Returns the version number of the `Uuid`.
///
/// This represents the algorithm used to generate the contents.
///
/// Currently only the Random (V4) algorithm is supported by this
/// module. There are security and privacy implications for using
/// older versions - see [Wikipedia: Universally Unique Identifier](
/// http://en.wikipedia.org/wiki/Universally_unique_identifier) for
/// details.
///
/// * [Version Reference](http://tools.ietf.org/html/rfc4122#section-4.1.3)
pub fn get_version_num(&self) -> usize {
(self.bytes[6] >> 4) as usize
}
/// Returns the version of the `Uuid`.
///
/// This represents the algorithm used to generate the contents
pub fn get_version(&self) -> Option<UuidVersion> {
let v = self.bytes[6] >> 4;
match v {
1 => Some(UuidVersion::Mac),
2 => Some(UuidVersion::Dce),
3 => Some(UuidVersion::Md5),
4 => Some(UuidVersion::Random),
5 => Some(UuidVersion::Sha1),
_ => None,
}
}
/// Returns the four field values of the UUID.
///
/// These values can be passed to the `from_fields()` method to get the
/// original `Uuid` back.
///
/// * The first field value represents the first group of (eight) hex
/// digits, taken as a big-endian `u32` value. For V1 UUIDs, this field
/// represents the low 32 bits of the timestamp.
/// * The second field value represents the second group of (four) hex
/// digits, taken as a big-endian `u16` value. For V1 UUIDs, this field
/// represents the middle 16 bits of the timestamp.
/// * The third field value represents the third group of (four) hex
/// digits, taken as a big-endian `u16` value. The 4 most significant
/// bits give the UUID version, and for V1 UUIDs, the last 12 bits
/// represent the high 12 bits of the timestamp.
/// * The last field value represents the last two groups of four and
/// twelve hex digits, taken in order. The first 1-3 bits of this
/// indicate the UUID variant, and for V1 UUIDs, the next 13-15 bits
/// indicate the clock sequence and the last 48 bits indicate the node
/// ID.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.as_fields(), (0, 0, 0, &[0u8; 8]));
///
/// let uuid = Uuid::parse_str("936DA01F-9ABD-4D9D-80C7-02AF85C822A8").unwrap();
/// assert_eq!(uuid.as_fields(),
/// (0x936DA01F, 0x9ABD, 0x4D9D, b"\x80\xC7\x02\xAF\x85\xC8\x22\xA8"));
/// ```
pub fn as_fields(&self) -> (u32, u16, u16, &[u8; 8]) {
let d1 = u32::from(self.bytes[0]) << 24 | u32::from(self.bytes[1]) << 16
| u32::from(self.bytes[2]) << 8 | u32::from(self.bytes[3]);
let d2 = u16::from(self.bytes[4]) << 8 | u16::from(self.bytes[5]);
let d3 = u16::from(self.bytes[6]) << 8 | u16::from(self.bytes[7]);
let d4: &[u8; 8] = unsafe { &*(self.bytes[8..16].as_ptr() as *const [u8; 8]) };
(d1, d2, d3, d4)
}
/// Returns an array of 16 octets containing the UUID data.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.as_bytes(), &[0; 16]);
///
/// let uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
/// assert_eq!(uuid.as_bytes(),
/// &[147, 109, 160, 31, 154, 189, 77, 157,
/// 128, 199, 2, 175, 133, 200, 34, 168]);
/// ```
pub fn as_bytes(&self) -> &[u8; 16] {
&self.bytes
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of 32 hexadecimal digits.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.simple().to_string(),
/// "00000000000000000000000000000000");
/// ```
pub fn simple(&self) -> Simple {
Simple { inner: self }
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of hexadecimal digits separated into groups with a hyphen.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.hyphenated().to_string(),
/// "00000000-0000-0000-0000-000000000000");
/// ```
pub fn hyphenated(&self) -> Hyphenated {
Hyphenated { inner: self }
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of the UUID as a full URN string.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.urn().to_string(),
/// "urn:uuid:00000000-0000-0000-0000-000000000000");
/// ```
pub fn urn(&self) -> Urn {
Urn { inner: self }
}
/// Returns an Optional Tuple of (u64, u16) representing the timestamp and
/// counter portion of a V1 UUID. If the supplied UUID is not V1, this
/// will return None
pub fn to_timestamp(&self) -> Option<(u64, u16)> {
if self.get_version()
.map(|v| v != UuidVersion::Mac)
.unwrap_or(true)
{
return None;
}
let ts: u64 = u64::from(self.bytes[6] & 0x0F) << 56 | u64::from(self.bytes[7]) << 48
| u64::from(self.bytes[4]) << 40 | u64::from(self.bytes[5]) << 32
| u64::from(self.bytes[0]) << 24 | u64::from(self.bytes[1]) << 16
| u64::from(self.bytes[2]) << 8 | u64::from(self.bytes[3]);
let count: u16 = u16::from(self.bytes[8] & 0x3F) << 8 | u16::from(self.bytes[9]);
Some((ts, count))
}
/// Parses a `Uuid` from a string of hexadecimal digits with optional hyphens.
///
/// Any of the formats generated by this module (simple, hyphenated, urn) are
/// supported by this parsing function.
pub fn parse_str(mut input: &str) -> Result<Uuid, ParseError> {
// Ensure length is valid for any of the supported formats
let len = input.len();
if len == (adapter::UUID_HYPHENATED_LENGTH + 9) && input.starts_with("urn:uuid:") {
input = &input[9..];
} else if len != adapter::UUID_SIMPLE_LENGTH && len != adapter::UUID_HYPHENATED_LENGTH {
return Err(ParseError::InvalidLength(len));
}
// `digit` counts only hexadecimal digits, `i_char` counts all chars.
let mut digit = 0;
let mut group = 0;
let mut acc = 0;
let mut buffer = [0u8; 16];
for (i_char, chr) in input.bytes().enumerate() {
if digit as usize >= adapter::UUID_SIMPLE_LENGTH && group != 4 {
if group == 0 {
return Err(ParseError::InvalidLength(len));
}
return Err(ParseError::InvalidGroups(group + 1));
}
if digit % 2 == 0 {
// First digit of the byte.
match chr {
// Calulate upper half.
b'0'...b'9' => acc = chr - b'0',
b'a'...b'f' => acc = chr - b'a' + 10,
b'A'...b'F' => acc = chr - b'A' + 10,
// Found a group delimiter
b'-' => {
if ACC_GROUP_LENS[group] != digit {
// Calculate how many digits this group consists of in the input.
let found = if group > 0 {
digit - ACC_GROUP_LENS[group - 1]
} else {
digit
};
return Err(ParseError::InvalidGroupLength(
group,
found as usize,
GROUP_LENS[group],
));
}
// Next group, decrement digit, it is incremented again at the bottom.
group += 1;
digit -= 1;
}
_ => {
return Err(ParseError::InvalidCharacter(
input[i_char..].chars().next().unwrap(),
i_char,
))
}
}
} else {
// Second digit of the byte, shift the upper half.
acc *= 16;
match chr {
b'0'...b'9' => acc += chr - b'0',
b'a'...b'f' => acc += chr - b'a' + 10,
b'A'...b'F' => acc += chr - b'A' + 10,
b'-' => {
// The byte isn't complete yet.
let found = if group > 0 {
digit - ACC_GROUP_LENS[group - 1]
} else {
digit
};
return Err(ParseError::InvalidGroupLength(
group,
found as usize,
GROUP_LENS[group],
));
}
_ => {
return Err(ParseError::InvalidCharacter(
input[i_char..].chars().next().unwrap(),
i_char,
))
}
}
buffer[(digit / 2) as usize] = acc;
}
digit += 1;
}
// Now check the last group.
if ACC_GROUP_LENS[4] != digit {
return Err(ParseError::InvalidGroupLength(
group,
(digit - ACC_GROUP_LENS[3]) as usize,
GROUP_LENS[4],
));
}
Ok(Uuid::from_bytes(&buffer).unwrap())
}
/// Tests if the UUID is nil
pub fn is_nil(&self) -> bool {
self.bytes.iter().all(|&b| b == 0)
}
}
impl<'a> fmt::Display for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl<'a> fmt::UpperHex for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in &self.inner.bytes {
write!(f, "{:02X}", byte)?;
}
Ok(())
}
}
impl<'a> fmt::LowerHex for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in &self.inner.bytes {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
impl<'a> fmt::Display for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
macro_rules! hyphenated_write {
($f:expr, $format:expr, $bytes:expr) => {{
let data1 = u32::from($bytes[0]) << 24 | u32::from($bytes[1]) << 16
| u32::from($bytes[2]) << 8 | u32::from($bytes[3]);
let data2 = u16::from($bytes[4]) << 8 | u16::from($bytes[5]);
let data3 = u16::from($bytes[6]) << 8 | u16::from($bytes[7]);
write!(
$f,
$format,
data1,
data2,
data3,
$bytes[8],
$bytes[9],
$bytes[10],
$bytes[11],
$bytes[12],
$bytes[13],
$bytes[14],
$bytes[15]
)
}};
}
impl<'a> fmt::UpperHex for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hyphenated_write!(
f,
"{:08X}-\
{:04X}-\
{:04X}-\
{:02X}{:02X}-\
{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
self.inner.bytes
)
}
}
impl<'a> fmt::LowerHex for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hyphenated_write!(
f,
"{:08x}-\
{:04x}-\
{:04x}-\
{:02x}{:02x}-\
{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
self.inner.bytes
)
}
}
impl<'a> fmt::Display for Urn<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "urn:uuid:{}", self.inner.hyphenated())
}
}
#[cfg(test)]
mod tests {
extern crate std;
use self::std::prelude::v1::*;
use super::test_util;
use super::{NAMESPACE_X500, NAMESPACE_DNS, NAMESPACE_OID, NAMESPACE_URL};
use super::{Uuid, UuidVariant, UuidVersion};
#[cfg(feature = "v3")]
static FIXTURE_V3: &'static [(&'static Uuid, &'static str, &'static str)] = &[
(
&NAMESPACE_DNS,
"example.org",
"04738bdf-b25a-3829-a801-b21a1d25095b",
),
(
&NAMESPACE_DNS,
"rust-lang.org",
"c6db027c-615c-3b4d-959e-1a917747ca5a",
),
(&NAMESPACE_DNS, "42", "5aab6e0c-b7d3-379c-92e3-2bfbb5572511"),
(
&NAMESPACE_DNS,
"lorem ipsum",
"4f8772e9-b59c-3cc9-91a9-5c823df27281",
),
(
&NAMESPACE_URL,
"example.org",
"39682ca1-9168-3da2-a1bb-f4dbcde99bf9",
),
(
&NAMESPACE_URL,
"rust-lang.org",
"7ed45aaf-e75b-3130-8e33-ee4d9253b19f",
),
(&NAMESPACE_URL, "42", "08998a0c-fcf4-34a9-b444-f2bfc15731dc"),
(
&NAMESPACE_URL,
"lorem ipsum",
"e55ad2e6-fb89-34e8-b012-c5dde3cd67f0",
),
(
&NAMESPACE_OID,
"example.org",
"f14eec63-2812-3110-ad06-1625e5a4a5b2",
),
(
&NAMESPACE_OID,
"rust-lang.org",
"6506a0ec-4d79-3e18-8c2b-f2b6b34f2b6d",
),
(&NAMESPACE_OID, "42", "ce6925a5-2cd7-327b-ab1c-4b375ac044e4"),
(
&NAMESPACE_OID,
"lorem ipsum",
"5dd8654f-76ba-3d47-bc2e-4d6d3a78cb09",
),
(
&NAMESPACE_X500,
"example.org",
"64606f3f-bd63-363e-b946-fca13611b6f7",
),
(
&NAMESPACE_X500,
"rust-lang.org",
"bcee7a9c-52f1-30c6-a3cc-8c72ba634990",
),
(
&NAMESPACE_X500,
"42",
"c1073fa2-d4a6-3104-b21d-7a6bdcf39a23",
),
(
&NAMESPACE_X500,
"lorem ipsum",
"02f09a3f-1624-3b1d-8409-44eff7708208",
),
];
#[cfg(feature = "v5")]
static FIXTURE_V5: &'static [(&'static Uuid, &'static str, &'static str)] = &[
(
&NAMESPACE_DNS,
"example.org",
"aad03681-8b63-5304-89e0-8ca8f49461b5",
),
(
&NAMESPACE_DNS,
"rust-lang.org",
"c66bbb60-d62e-5f17-a399-3a0bd237c503",
),
(&NAMESPACE_DNS, "42", "7c411b5e-9d3f-50b5-9c28-62096e41c4ed"),
(
&NAMESPACE_DNS,
"lorem ipsum",
"97886a05-8a68-5743-ad55-56ab2d61cf7b",
),
(
&NAMESPACE_URL,
"example.org",
"54a35416-963c-5dd6-a1e2-5ab7bb5bafc7",
),
(
&NAMESPACE_URL,
"rust-lang.org",
"c48d927f-4122-5413-968c-598b1780e749",
),
(&NAMESPACE_URL, "42", "5c2b23de-4bad-58ee-a4b3-f22f3b9cfd7d"),
(
&NAMESPACE_URL,
"lorem ipsum",
"15c67689-4b85-5253-86b4-49fbb138569f",
),
(
&NAMESPACE_OID,
"example.org",
"34784df9-b065-5094-92c7-00bb3da97a30",
),
(
&NAMESPACE_OID,
"rust-lang.org",
"8ef61ecb-977a-5844-ab0f-c25ef9b8d5d6",
),
(&NAMESPACE_OID, "42", "ba293c61-ad33-57b9-9671-f3319f57d789"),
(
&NAMESPACE_OID,
"lorem ipsum",
"6485290d-f79e-5380-9e64-cb4312c7b4a6",
),
(
&NAMESPACE_X500,
"example.org",
"e3635e86-f82b-5bbc-a54a-da97923e5c76",
),
(
&NAMESPACE_X500,
"rust-lang.org",
"26c9c3e9-49b7-56da-8b9f-a0fb916a71a3",
),
(
&NAMESPACE_X500,
"42",
"e4b88014-47c6-5fe0-a195-13710e5f6e27",
),
(
&NAMESPACE_X500,
"lorem ipsum",
"b11f79a5-1e6d-57ce-a4b5-ba8531ea03d0",
),
];
#[test]
fn test_nil() {
let nil = Uuid::nil();
let not_nil = test_util::new();
assert!(nil.is_nil());
assert!(!not_nil.is_nil());
}
#[test]
fn test_new() {
if cfg!(feature = "v3") {
let u = Uuid::new(UuidVersion::Md5);
assert!(u.is_some(), "{:?}", u);
assert_eq!(u.unwrap().get_version().unwrap(), UuidVersion::Md5);
} else {
assert_eq!(Uuid::new(UuidVersion::Md5), None);
}
if cfg!(feature = "v4") {
let uuid1 = Uuid::new(UuidVersion::Random).unwrap();
let s = uuid1.simple().to_string();
assert_eq!(s.len(), 32);
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
} else {
assert!(Uuid::new(UuidVersion::Random).is_none());
}
if cfg!(feature = "v5") {
let u = Uuid::new(UuidVersion::Sha1);
assert!(u.is_some(), "{:?}", u);
assert_eq!(u.unwrap().get_version().unwrap(), UuidVersion::Sha1);
} else {
assert_eq!(Uuid::new(UuidVersion::Sha1), None);
}
// Test unsupported versions
assert_eq!(Uuid::new(UuidVersion::Mac), None);
assert_eq!(Uuid::new(UuidVersion::Dce), None);
}
#[cfg(feature = "v1")]
#[test]
fn test_new_v1() {
use UuidV1Context;
let time: u64 = 1_496_854_535;
let timefrac: u32 = 812_946_000;
let node = [1, 2, 3, 4, 5, 6];
let ctx = UuidV1Context::new(0);
let uuid = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Mac);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(
uuid.hyphenated().to_string(),
"20616934-4ba2-11e7-8000-010203040506"
);
let uuid2 = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
assert_eq!(
uuid2.hyphenated().to_string(),
"20616934-4ba2-11e7-8001-010203040506"
);
let ts = uuid.to_timestamp().unwrap();
assert_eq!(ts.0 - 0x01B21DD213814000, 1_496_854_535_812_946_0);
assert_eq!(ts.1, 0);
assert_eq!(uuid2.to_timestamp().unwrap().1, 1);
}
#[cfg(feature = "v3")]
#[test]
fn test_new_v3() {
for &(ref ns, ref name, _) in FIXTURE_V3 {
let uuid = Uuid::new_v3(*ns, *name);
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Md5);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
}
}
#[test]
#[cfg(feature = "v4")]
fn test_new_v4() {
let uuid1 = Uuid::new_v4();
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
assert_eq!(uuid1.get_variant().unwrap(), UuidVariant::RFC4122);
}
#[cfg(feature = "v5")]
#[test]
fn test_new_v5() {
for &(ref ns, ref name, _) in FIXTURE_V5 {
let uuid = Uuid::new_v5(*ns, *name);
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Sha1);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
}
}
#[test]
fn test_predefined_namespaces() {
assert_eq!(
NAMESPACE_DNS.hyphenated().to_string(),
"6ba7b810-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_URL.hyphenated().to_string(),
"6ba7b811-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_OID.hyphenated().to_string(),
"6ba7b812-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_X500.hyphenated().to_string(),
"6ba7b814-9dad-11d1-80b4-00c04fd430c8"
);
}
#[cfg(feature = "v3")]
#[test]
fn test_get_version_v3() {
let uuid = Uuid::new_v3(&NAMESPACE_DNS, "rust-lang.org");
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Md5);
assert_eq!(uuid.get_version_num(), 3);
}
#[test]
#[cfg(feature = "v4")]
fn test_get_version_v4() {
let uuid1 = Uuid::new_v4();
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
assert_eq!(uuid1.get_version_num(), 4);
}
#[cfg(feature = "v5")]
#[test]
fn test_get_version_v5() {
let uuid2 = Uuid::new_v5(&NAMESPACE_DNS, "rust-lang.org");
assert_eq!(uuid2.get_version().unwrap(), UuidVersion::Sha1);
assert_eq!(uuid2.get_version_num(), 5);
}
#[test]
fn test_get_variant() {
let uuid1 = test_util::new();
let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
let uuid3 = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
let uuid4 = Uuid::parse_str("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
let uuid5 = Uuid::parse_str("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
let uuid6 = Uuid::parse_str("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();
assert_eq!(uuid1.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid2.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid3.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid4.get_variant().unwrap(), UuidVariant::Microsoft);
assert_eq!(uuid5.get_variant().unwrap(), UuidVariant::Microsoft);
assert_eq!(uuid6.get_variant().unwrap(), UuidVariant::NCS);
}
#[test]
fn test_parse_uuid_v4() {
use super::ParseError::*;
// Invalid
assert_eq!(Uuid::parse_str(""), Err(InvalidLength(0)));
assert_eq!(Uuid::parse_str("!"), Err(InvalidLength(1)));
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45"),
Err(InvalidLength(37))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4"),
Err(InvalidLength(35))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4"),
Err(InvalidCharacter('G', 20))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2F4faaFB6BFF329BF39FA1E4"),
Err(InvalidGroups(2))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faaFB6BFF329BF39FA1E4"),
Err(InvalidGroups(3))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4"),
Err(InvalidGroups(4))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa"),
Err(InvalidLength(18))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4"),
Err(InvalidCharacter('X', 18))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4"),
Err(InvalidGroupLength(1, 3, 4))
);
assert_eq!(
Uuid::parse_str("01020304-1112-2122-3132-41424344"),
Err(InvalidGroupLength(4, 8, 12))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
Err(InvalidLength(31))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c88"),
Err(InvalidLength(33))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0cg8"),
Err(InvalidLength(33))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426%9247bb680e5fe0c8"),
Err(InvalidCharacter('%', 15))
);
assert_eq!(
Uuid::parse_str("231231212212423424324323477343246663"),
Err(InvalidLength(36))
);
// Valid
assert!(Uuid::parse_str("00000000000000000000000000000000").is_ok());
assert!(Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
assert!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok());
assert!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8").is_ok());
assert!(Uuid::parse_str("01020304-1112-2122-3132-414243444546").is_ok());
assert!(Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
// Nil
let nil = Uuid::nil();
assert_eq!(
Uuid::parse_str("00000000000000000000000000000000").unwrap(),
nil
);
assert_eq!(
Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(),
nil
);
// Round-trip
let uuid_orig = test_util::new();
let orig_str = uuid_orig.to_string();
let uuid_out = Uuid::parse_str(&orig_str).unwrap();
assert_eq!(uuid_orig, uuid_out);
// Test error reporting
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
Err(InvalidLength(31))
);
assert_eq!(
Uuid::parse_str("67e550X410b1426f9247bb680e5fe0cd"),
Err(InvalidCharacter('X', 6))
);
assert_eq!(
Uuid::parse_str("67e550-4105b1426f9247bb680e5fe0c"),
Err(InvalidGroupLength(0, 6, 8))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4"),
Err(InvalidGroupLength(3, 5, 4))
);
}
#[test]
fn test_to_simple_string() {
let uuid1 = test_util::new();
let s = uuid1.simple().to_string();
assert_eq!(s.len(), 32);
assert!(s.chars().all(|c| c.is_digit(16)));
}
#[test]
fn test_to_hyphenated_string() {
let uuid1 = test_util::new();
let s = uuid1.hyphenated().to_string();
assert!(s.len() == 36);
assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
}
#[test]
fn test_upper_lower_hex() {
use super::fmt::Write;
let mut buf = String::new();
let u = test_util::new();
macro_rules! check {
($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
$buf.clear();
write!($buf, $format, $target).unwrap();
assert!(buf.len() == $len);
assert!($buf.chars().all($cond), "{}", $buf);
};
}
check!(buf, "{:X}", u, 36, |c| c.is_uppercase() || c.is_digit(10)
|| c == '-');
check!(
buf,
"{:X}",
u.hyphenated(),
36,
|c| c.is_uppercase() || c.is_digit(10) || c == '-'
);
check!(buf, "{:X}", u.simple(), 32, |c| c.is_uppercase()
|| c.is_digit(10));
check!(
buf,
"{:x}",
u.hyphenated(),
36,
|c| c.is_lowercase() || c.is_digit(10) || c == '-'
);
check!(buf, "{:x}", u.simple(), 32, |c| c.is_lowercase()
|| c.is_digit(10));
}
#[cfg(feature = "v3")]
#[test]
fn test_v3_to_hypenated_string() {
for &(ref ns, ref name, ref expected) in FIXTURE_V3 {
let uuid = Uuid::new_v3(*ns, *name);
assert_eq!(uuid.hyphenated().to_string(), *expected);
}
}
#[cfg(feature = "v5")]
#[test]
fn test_v5_to_hypenated_string() {
for &(ref ns, ref name, ref expected) in FIXTURE_V5 {
let uuid = Uuid::new_v5(*ns, *name);
assert_eq!(uuid.hyphenated().to_string(), *expected);
}
}
#[test]
fn test_to_urn_string() {
let uuid1 = test_util::new();
let ss = uuid1.urn().to_string();
let s = &ss[9..];
assert!(ss.starts_with("urn:uuid:"));
assert_eq!(s.len(), 36);
assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
}
#[test]
fn test_to_simple_string_matching() {
let uuid1 = test_util::new();
let hs = uuid1.hyphenated().to_string();
let ss = uuid1.simple().to_string();
let hsn = hs.chars().filter(|&c| c != '-').collect::<String>();
assert_eq!(hsn, ss);
}
#[test]
fn test_string_roundtrip() {
let uuid = test_util::new();
let hs = uuid.hyphenated().to_string();
let uuid_hs = Uuid::parse_str(&hs).unwrap();
assert_eq!(uuid_hs, uuid);
let ss = uuid.to_string();
let uuid_ss = Uuid::parse_str(&ss).unwrap();
assert_eq!(uuid_ss, uuid);
}
#[test]
fn test_from_fields() {
let d1: u32 = 0xa1a2a3a4;
let d2: u16 = 0xb1b2;
let d3: u16 = 0xc1c2;
let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
let u = Uuid::from_fields(d1, d2, d3, &d4).unwrap();
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
let result = u.simple().to_string();
assert_eq!(result, expected);
}
#[test]
fn test_as_fields() {
let u = test_util::new();
let (d1, d2, d3, d4) = u.as_fields();
assert_ne!(d1, 0);
assert_ne!(d2, 0);
assert_ne!(d3, 0);
assert_eq!(d4.len(), 8);
assert!(!d4.iter().all(|&b| b == 0));
}
#[test]
fn test_fields_roundtrip() {
let d1_in: u32 = 0xa1a2a3a4;
let d2_in: u16 = 0xb1b2;
let d3_in: u16 = 0xc1c2;
let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in).unwrap();
let (d1_out, d2_out, d3_out, d4_out) = u.as_fields();
assert_eq!(d1_in, d1_out);
assert_eq!(d2_in, d2_out);
assert_eq!(d3_in, d3_out);
assert_eq!(d4_in, d4_out);
}
#[test]
fn test_from_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_bytes(&b).unwrap();
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_from_uuid_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_uuid_bytes(b);
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_as_bytes() {
let u = test_util::new();
let ub = u.as_bytes();
assert_eq!(ub.len(), 16);
assert!(!ub.iter().all(|&b| b == 0));
}
#[test]
fn test_bytes_roundtrip() {
let b_in: [u8; 16] = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_bytes(&b_in).unwrap();
let b_out = u.as_bytes();
assert_eq!(&b_in, b_out);
}
#[test]
fn test_from_random_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_random_bytes(b);
let expected = "a1a2a3a4b1b241c291d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_iterbytes_impl_for_uuid() {
let mut set = std::collections::HashSet::new();
let id1 = test_util::new();
let id2 = test_util::new2();
set.insert(id1.clone());
assert!(set.contains(&id1));
assert!(!set.contains(&id2));
}
}
fix ![feature(const_fn)] when stable channle
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Generate and parse UUIDs.
//!
//! Provides support for Universally Unique Identifiers (UUIDs). A UUID is a
//! unique 128-bit number, stored as 16 octets. UUIDs are used to assign
//! unique identifiers to entities without requiring a central allocating
//! authority.
//!
//! They are particularly useful in distributed systems, though can be used in
//! disparate areas, such as databases and network protocols. Typically a UUID
//! is displayed in a readable string form as a sequence of hexadecimal digits,
//! separated into groups by hyphens.
//!
//! The uniqueness property is not strictly guaranteed, however for all
//! practical purposes, it can be assumed that an unintentional collision would
//! be extremely unlikely.
//!
//! # Dependencies
//!
//! By default, this crate depends on nothing but `std` and cannot generate
//! [`Uuid`]s. You need to enable the following Cargo features to enable
//! various pieces of functionality:
//!
//! * `v1` - adds the `Uuid::new_v1` function and the ability to create a V1
//! using an implementation of `UuidV1ClockSequence` (usually `UuidV1Context`)
//! and a timestamp from `time::timespec`.
//! * `v3` - adds the `Uuid::new_v3` function and the ability to create a V3
//! UUID based on the MD5 hash of some data.
//! * `v4` - adds the `Uuid::new_v4` function and the ability to randomly
//! generate a `Uuid`.
//! * `v5` - adds the `Uuid::new_v5` function and the ability to create a V5
//! UUID based on the SHA1 hash of some data.
//! * `serde` - adds the ability to serialize and deserialize a `Uuid` using the
//! `serde` crate.
//!
//! By default, `uuid` can be depended on with:
//!
//! ```toml
//! [dependencies]
//! uuid = "0.6"
//! ```
//!
//! To activate various features, use syntax like:
//!
//! ```toml
//! [dependencies]
//! uuid = { version = "0.6", features = ["serde", "v4"] }
//! ```
//!
//! You can disable default features with:
//!
//! ```toml
//! [dependencies]
//! uuid = { version = "0.6", default-features = false }
//! ```
//!
//! # Examples
//!
//! To parse a UUID given in the simple format and print it as a urn:
//!
//! ```rust
//! use uuid::Uuid;
//!
//! fn main() {
//! let my_uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
//! println!("{}", my_uuid.urn());
//! }
//! ```
//!
//! To create a new random (V4) UUID and print it out in hexadecimal form:
//!
//! ```ignore,rust
//! // Note that this requires the `v4` feature enabled in the uuid crate.
//!
//! use uuid::Uuid;
//!
//! fn main() {
//! let my_uuid = Uuid::new_v4();
//! println!("{}", my_uuid);
//! }
//! ```
//!
//! # Strings
//!
//! Examples of string representations:
//!
//! * simple: `936DA01F9ABD4d9d80C702AF85C822A8`
//! * hyphenated: `550e8400-e29b-41d4-a716-446655440000`
//! * urn: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
//!
//! # References
//!
//! * [Wikipedia: Universally Unique Identifier](
//! http://en.wikipedia.org/wiki/Universally_unique_identifier)
//! * [RFC4122: A Universally Unique IDentifier (UUID) URN Namespace](
//! http://tools.ietf.org/html/rfc4122)
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/uuid"
)]
#![deny(warnings)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(const_fn))]
#[macro_use]
extern crate cfg_if;
cfg_if! {
if #[cfg(feature = "md5")] {
extern crate md5;
}
}
cfg_if! {
if #[cfg(feature = "rand")] {
extern crate rand;
}
}
cfg_if! {
if #[cfg(feature = "serde")] {
extern crate serde;
}
}
cfg_if! {
if #[cfg(feature = "sha1")] {
extern crate sha1;
}
}
cfg_if! {
if #[cfg(all(feature = "slog", not(test)))] {
extern crate slog;
} else if #[cfg(all(feature = "slog", test))] {
#[macro_use]
extern crate slog;
}
}
cfg_if! {
if #[cfg(feature = "std")] {
use std::fmt;
use std::str;
cfg_if! {
if #[cfg(feature = "v1")] {
use std::sync::atomic;
}
}
} else if #[cfg(not(feature = "std"))] {
use core::fmt;
use core::str;
cfg_if! {
if #[cfg(feature = "v1")] {
use core::sync::atomic;
}
}
}
}
pub mod adapter;
pub mod prelude;
mod core_support;
cfg_if! {
if #[cfg(feature = "serde")] {
mod serde_support;
}
}
cfg_if! {
if #[cfg(feature = "slog")] {
mod slog_support;
}
}
cfg_if! {
if #[cfg(feature = "std")] {
mod std_support;
}
}
cfg_if! {
if #[cfg(test)] {
mod test_util;
}
}
/// A 128-bit (16 byte) buffer containing the ID.
pub type UuidBytes = [u8; 16];
/// The version of the UUID, denoting the generating algorithm.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum UuidVersion {
/// Version 1: MAC address
Mac = 1,
/// Version 2: DCE Security
Dce = 2,
/// Version 3: MD5 hash
Md5 = 3,
/// Version 4: Random
Random = 4,
/// Version 5: SHA-1 hash
Sha1 = 5,
}
/// The reserved variants of UUIDs.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UuidVariant {
/// Reserved by the NCS for backward compatibility
NCS,
/// As described in the RFC4122 Specification (default)
RFC4122,
/// Reserved by Microsoft for backward compatibility
Microsoft,
/// Reserved for future expansion
Future,
}
/// A Universally Unique Identifier (UUID).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Uuid {
/// The 128-bit number stored in 16 bytes
bytes: UuidBytes,
}
/// An adaptor for formatting a `Uuid` as a simple string.
pub struct Simple<'a> {
inner: &'a Uuid,
}
/// An adaptor for formatting a `Uuid` as a hyphenated string.
pub struct Hyphenated<'a> {
inner: &'a Uuid,
}
/// A UUID of the namespace of fully-qualified domain names
pub const NAMESPACE_DNS: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of URLs
pub const NAMESPACE_URL: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of ISO OIDs
pub const NAMESPACE_OID: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// A UUID of the namespace of X.500 DNs (in DER or a text output format)
pub const NAMESPACE_X500: Uuid = Uuid {
bytes: [
0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
0xc8,
],
};
/// The number of 100 ns ticks between
/// the UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00
#[cfg(feature = "v1")]
const UUID_TICKS_BETWEEN_EPOCHS: u64 = 0x01B2_1DD2_1381_4000;
/// An adaptor for formatting a `Uuid` as a URN string.
pub struct Urn<'a> {
inner: &'a Uuid,
}
cfg_if! {
if #[cfg(feature = "v1")] {
/// A trait that abstracts over generation of Uuid v1 "Clock Sequence"
/// values.
pub trait UuidV1ClockSequence {
/// Return a 16-bit number that will be used as the "clock
/// sequence" in the Uuid. The number must be different if the
/// time has changed since the last time a clock sequence was
/// requested.
fn generate_sequence(&self, seconds: u64, nano_seconds: u32) -> u16;
}
/// A thread-safe, stateful context for the v1 generator to help
/// ensure process-wide uniqueness.
pub struct UuidV1Context {
count: atomic::AtomicUsize,
}
impl UuidV1Context {
/// Creates a thread-safe, internally mutable context to help
/// ensure uniqueness.
///
/// This is a context which can be shared across threads. It
/// maintains an internal counter that is incremented at every
/// request, the value ends up in the clock_seq portion of the
/// Uuid (the fourth group). This will improve the probability
/// that the Uuid is unique across the process.
pub fn new(count: u16) -> UuidV1Context {
UuidV1Context {
count: atomic::AtomicUsize::new(count as usize),
}
}
}
impl UuidV1ClockSequence for UuidV1Context {
fn generate_sequence(&self, _: u64, _: u32) -> u16 {
(self.count.fetch_add(1, atomic::Ordering::SeqCst) & 0xffff) as u16
}
}
}
}
/// Error details for string parsing failures.
#[allow(missing_docs)]
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ParseError {
InvalidLength(usize),
InvalidCharacter(char, usize),
InvalidGroups(usize),
InvalidGroupLength(usize, usize, u8),
}
/// Converts a `ParseError` to a string.
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::InvalidLength(found) => write!(
f,
"Invalid length; expecting {} or {} chars, found {}",
adapter::UUID_SIMPLE_LENGTH, adapter::UUID_HYPHENATED_LENGTH, found
),
ParseError::InvalidCharacter(found, pos) => write!(
f,
"Invalid character; found `{}` (0x{:02x}) at offset {}",
found, found as usize, pos
),
ParseError::InvalidGroups(found) => write!(
f,
"Malformed; wrong number of groups: expected 1 or 5, found {}",
found
),
ParseError::InvalidGroupLength(group, found, expecting) => write!(
f,
"Malformed; length of group {} was {}, expecting {}",
group, found, expecting
),
}
}
}
// Length of each hyphenated group in hex digits.
const GROUP_LENS: [u8; 5] = [8, 4, 4, 4, 12];
// Accumulated length of each hyphenated group in hex digits.
const ACC_GROUP_LENS: [u8; 5] = [8, 12, 16, 20, 32];
impl Uuid {
/// The 'nil UUID'.
///
/// The nil UUID is special form of UUID that is specified to have all
/// 128 bits set to zero, as defined in [IETF RFC 4122 Section 4.1.7][RFC].
///
/// [RFC]: https://tools.ietf.org/html/rfc4122.html#section-4.1.7
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
///
/// assert_eq!(uuid.hyphenated().to_string(),
/// "00000000-0000-0000-0000-000000000000");
/// ```
pub fn nil() -> Uuid {
Uuid { bytes: [0; 16] }
}
/// Creates a new `Uuid`.
///
/// Note that not all versions can be generated currently and `None` will be
/// returned if the specified version cannot be generated.
///
/// To generate a random UUID (`UuidVersion::Md5`), then the `v3`
/// feature must be enabled for this crate.
///
/// To generate a random UUID (`UuidVersion::Random`), then the `v4`
/// feature must be enabled for this crate.
///
/// To generate a random UUID (`UuidVersion::Sha1`), then the `v5`
/// feature must be enabled for this crate.
pub fn new(v: UuidVersion) -> Option<Uuid> {
// Why 23? Ascii has roughly 6bit randomness per 8bit.
// So to reach 128bit at-least 21.333 (128/6) Bytes are required.
#[cfg(any(feature = "v3", feature = "v5"))]
let iv: String = {
use rand::Rng;
rand::thread_rng().gen_ascii_chars().take(23).collect()
};
match v {
#[cfg(feature = "v3")]
UuidVersion::Md5 => Some(Uuid::new_v3(&NAMESPACE_DNS, &*iv)),
#[cfg(feature = "v4")]
UuidVersion::Random => Some(Uuid::new_v4()),
#[cfg(feature = "v5")]
UuidVersion::Sha1 => Some(Uuid::new_v5(&NAMESPACE_DNS, &*iv)),
_ => None,
}
}
/// Creates a new `Uuid` (version 1 style) using a time value + seq + NodeID.
///
/// This expects two values representing a monotonically increasing value
/// as well as a unique 6 byte NodeId, and an implementation of `UuidV1ClockSequence`.
/// This function is only guaranteed to produce unique values if the following conditions hold:
///
/// 1. The NodeID is unique for this process,
/// 2. The Context is shared across all threads which are generating V1 UUIDs,
/// 3. The `UuidV1ClockSequence` implementation reliably returns unique clock sequences
/// (this crate provides `UuidV1Context` for this purpose).
///
/// The NodeID must be exactly 6 bytes long. If the NodeID is not a valid length
/// this will return a `ParseError::InvalidLength`.
///
/// The function is not guaranteed to produce monotonically increasing values
/// however. There is a slight possibility that two successive equal time values
/// could be supplied and the sequence counter wraps back over to 0.
///
/// If uniqueness and monotonicity is required, the user is responsibile for ensuring
/// that the time value always increases between calls
/// (including between restarts of the process and device).
///
/// Note that usage of this method requires the `v1` feature of this crate
/// to be enabled.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use uuid::{Uuid, UuidV1Context};
///
/// let ctx = UuidV1Context::new(42);
/// let v1uuid = Uuid::new_v1(&ctx, 1497624119, 1234, &[1,2,3,4,5,6]).unwrap();
///
/// assert_eq!(v1uuid.hyphenated().to_string(), "f3b4958c-52a1-11e7-802a-010203040506");
/// ```
#[cfg(feature = "v1")]
pub fn new_v1<T: UuidV1ClockSequence>(
context: &T,
seconds: u64,
nsecs: u32,
node: &[u8],
) -> Result<Uuid, ParseError> {
if node.len() != 6 {
return Err(ParseError::InvalidLength(node.len()));
}
let count = context.generate_sequence(seconds, nsecs);
let timestamp = seconds * 10_000_000 + u64::from(nsecs / 100);
let uuidtime = timestamp + UUID_TICKS_BETWEEN_EPOCHS;
let time_low: u32 = (uuidtime & 0xFFFF_FFFF) as u32;
let time_mid: u16 = ((uuidtime >> 32) & 0xFFFF) as u16;
let time_hi_and_ver: u16 = (((uuidtime >> 48) & 0x0FFF) as u16) | (1 << 12);
let mut d4 = [0_u8; 8];
d4[0] = (((count & 0x3F00) >> 8) as u8) | 0x80;
d4[1] = (count & 0xFF) as u8;
d4[2..].copy_from_slice(node);
Uuid::from_fields(time_low, time_mid, time_hi_and_ver, &d4)
}
/// Creates a UUID using a name from a namespace, based on the MD5 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * `NAMESPACE_DNS`
/// * `NAMESPACE_URL`
/// * `NAMESPACE_OID`
/// * `NAMESPACE_X500`
///
/// Note that usage of this method requires the `v3` feature of this crate
/// to be enabled.
#[cfg(feature = "v3")]
pub fn new_v3(namespace: &Uuid, name: &str) -> Uuid {
let mut ctx = md5::Context::new();
ctx.consume(namespace.as_bytes());
ctx.consume(name.as_bytes());
let mut uuid = Uuid {
bytes: ctx.compute().into(),
};
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Md5);
uuid
}
/// Creates a random `Uuid`.
///
/// This uses the `rand` crate's default task RNG as the source of random numbers.
/// If you'd like to use a custom generator, don't use this method: use the
/// [`rand::Rand trait`]'s `rand()` method instead.
///
/// [`rand::Rand trait`]: ../../rand/rand/trait.Rand.html#tymethod.rand
///
/// Note that usage of this method requires the `v4` feature of this crate
/// to be enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::new_v4();
/// ```
#[cfg(feature = "v4")]
pub fn new_v4() -> Uuid {
use rand::Rng;
let mut rng = rand::thread_rng();
let mut bytes = [0; 16];
rng.fill_bytes(&mut bytes);
Uuid::from_random_bytes(bytes)
}
/// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * `NAMESPACE_DNS`
/// * `NAMESPACE_URL`
/// * `NAMESPACE_OID`
/// * `NAMESPACE_X500`
///
/// Note that usage of this method requires the `v5` feature of this crate
/// to be enabled.
#[cfg(feature = "v5")]
pub fn new_v5(namespace: &Uuid, name: &str) -> Uuid {
let mut hash = sha1::Sha1::new();
hash.update(namespace.as_bytes());
hash.update(name.as_bytes());
let buffer = hash.digest().bytes();
let mut uuid = Uuid { bytes: [0; 16] };
uuid.bytes.copy_from_slice(&buffer[..16]);
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Sha1);
uuid
}
/// Creates a `Uuid` from four field values.
///
/// # Errors
///
/// This function will return an error if `d4`'s length is not 8 bytes.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let d4 = [12, 3, 9, 56, 54, 43, 8, 9];
///
/// let uuid = Uuid::from_fields(42, 12, 5, &d4);
/// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
///
/// let expected_uuid = Ok(String::from("0000002a-000c-0005-0c03-0938362b0809"));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An invalid length:
///
/// ```
/// use uuid::Uuid;
/// use uuid::ParseError;
///
/// let d4 = [12];
///
/// let uuid = Uuid::from_fields(42, 12, 5, &d4);
///
/// let expected_uuid = Err(ParseError::InvalidLength(1));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
pub fn from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8]) -> Result<Uuid, ParseError> {
if d4.len() != 8 {
return Err(ParseError::InvalidLength(d4.len()));
}
Ok(Uuid {
bytes: [
(d1 >> 24) as u8,
(d1 >> 16) as u8,
(d1 >> 8) as u8,
d1 as u8,
(d2 >> 8) as u8,
d2 as u8,
(d3 >> 8) as u8,
d3 as u8,
d4[0],
d4[1],
d4[2],
d4[3],
d4[4],
d4[5],
d4[6],
d4[7],
],
})
}
/// Creates a `Uuid` using the supplied bytes.
///
/// # Errors
///
/// This function will return an error if `b` has any length other than 16.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
///
/// let bytes = [4, 54, 67, 12, 43, 2, 98, 76,
/// 32, 50, 87, 5, 1, 33, 43, 87];
///
/// let uuid = Uuid::from_bytes(&bytes);
/// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
///
/// let expected_uuid = Ok(String::from("0436430c-2b02-624c-2032-570501212b57"));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An incorrect number of bytes:
///
/// ```
/// use uuid::Uuid;
/// use uuid::ParseError;
///
/// let bytes = [4, 54, 67, 12, 43, 2, 98, 76];
///
/// let uuid = Uuid::from_bytes(&bytes);
///
/// let expected_uuid = Err(ParseError::InvalidLength(8));
///
/// assert_eq!(expected_uuid, uuid);
/// ```
pub fn from_bytes(b: &[u8]) -> Result<Uuid, ParseError> {
let len = b.len();
if len != 16 {
return Err(ParseError::InvalidLength(len));
}
let mut uuid = Uuid { bytes: [0; 16] };
uuid.bytes.copy_from_slice(b);
Ok(uuid)
}
/// Creates a `Uuid` using the supplied bytes.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
/// let bytes:UuidBytes = [70, 235, 208, 238, 14, 109, 67, 201, 185, 13, 204, 195, 90, 145, 63, 62];
///
/// let uuid = Uuid::from_uuid_bytes(bytes);
/// let uuid = uuid.hyphenated().to_string();
///
/// let expected_uuid = String::from("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e");
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
/// An incorrect number of bytes:
///
/// ```compile_fail
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
/// let bytes:UuidBytes = [4, 54, 67, 12, 43, 2, 98, 76]; // doesn't compile
///
/// let uuid = Uuid::from_uuid_bytes(bytes);
/// ```
#[cfg(not(feature = "nightly"))]
pub fn from_uuid_bytes(b: UuidBytes) -> Uuid {
Uuid { bytes: b }
}
#[cfg(feature = "nightly")]
pub const fn from_uuid_bytes(b: UuidBytes) -> Uuid {
Uuid { bytes: b }
}
/// Creates a v4 Uuid from random bytes (e.g. bytes supplied from `Rand` crate)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
///
/// let bytes:UuidBytes = [70, 235, 208, 238, 14, 109, 67, 201, 185, 13, 204, 195, 90, 145, 63, 62];
/// let uuid = Uuid::from_random_bytes(bytes);
/// let uuid = uuid.hyphenated().to_string();
///
/// let expected_uuid = String::from("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e");
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
pub fn from_random_bytes(b: [u8; 16]) -> Uuid {
let mut uuid = Uuid { bytes: b };
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Random);
uuid
}
/// Specifies the variant of the UUID structure
#[allow(dead_code)]
fn set_variant(&mut self, v: UuidVariant) {
// Octet 8 contains the variant in the most significant 3 bits
self.bytes[8] = match v {
UuidVariant::NCS => self.bytes[8] & 0x7f, // b0xx...
UuidVariant::RFC4122 => (self.bytes[8] & 0x3f) | 0x80, // b10x...
UuidVariant::Microsoft => (self.bytes[8] & 0x1f) | 0xc0, // b110...
UuidVariant::Future => (self.bytes[8] & 0x1f) | 0xe0, // b111...
}
}
/// Returns the variant of the `Uuid` structure.
///
/// This determines the interpretation of the structure of the UUID.
/// Currently only the RFC4122 variant is generated by this module.
///
/// * [Variant Reference](http://tools.ietf.org/html/rfc4122#section-4.1.1)
pub fn get_variant(&self) -> Option<UuidVariant> {
match self.bytes[8] {
x if x & 0x80 == 0x00 => Some(UuidVariant::NCS),
x if x & 0xc0 == 0x80 => Some(UuidVariant::RFC4122),
x if x & 0xe0 == 0xc0 => Some(UuidVariant::Microsoft),
x if x & 0xe0 == 0xe0 => Some(UuidVariant::Future),
_ => None,
}
}
/// Specifies the version number of the `Uuid`.
#[allow(dead_code)]
fn set_version(&mut self, v: UuidVersion) {
self.bytes[6] = (self.bytes[6] & 0xF) | ((v as u8) << 4);
}
/// Returns the version number of the `Uuid`.
///
/// This represents the algorithm used to generate the contents.
///
/// Currently only the Random (V4) algorithm is supported by this
/// module. There are security and privacy implications for using
/// older versions - see [Wikipedia: Universally Unique Identifier](
/// http://en.wikipedia.org/wiki/Universally_unique_identifier) for
/// details.
///
/// * [Version Reference](http://tools.ietf.org/html/rfc4122#section-4.1.3)
pub fn get_version_num(&self) -> usize {
(self.bytes[6] >> 4) as usize
}
/// Returns the version of the `Uuid`.
///
/// This represents the algorithm used to generate the contents
pub fn get_version(&self) -> Option<UuidVersion> {
let v = self.bytes[6] >> 4;
match v {
1 => Some(UuidVersion::Mac),
2 => Some(UuidVersion::Dce),
3 => Some(UuidVersion::Md5),
4 => Some(UuidVersion::Random),
5 => Some(UuidVersion::Sha1),
_ => None,
}
}
/// Returns the four field values of the UUID.
///
/// These values can be passed to the `from_fields()` method to get the
/// original `Uuid` back.
///
/// * The first field value represents the first group of (eight) hex
/// digits, taken as a big-endian `u32` value. For V1 UUIDs, this field
/// represents the low 32 bits of the timestamp.
/// * The second field value represents the second group of (four) hex
/// digits, taken as a big-endian `u16` value. For V1 UUIDs, this field
/// represents the middle 16 bits of the timestamp.
/// * The third field value represents the third group of (four) hex
/// digits, taken as a big-endian `u16` value. The 4 most significant
/// bits give the UUID version, and for V1 UUIDs, the last 12 bits
/// represent the high 12 bits of the timestamp.
/// * The last field value represents the last two groups of four and
/// twelve hex digits, taken in order. The first 1-3 bits of this
/// indicate the UUID variant, and for V1 UUIDs, the next 13-15 bits
/// indicate the clock sequence and the last 48 bits indicate the node
/// ID.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.as_fields(), (0, 0, 0, &[0u8; 8]));
///
/// let uuid = Uuid::parse_str("936DA01F-9ABD-4D9D-80C7-02AF85C822A8").unwrap();
/// assert_eq!(uuid.as_fields(),
/// (0x936DA01F, 0x9ABD, 0x4D9D, b"\x80\xC7\x02\xAF\x85\xC8\x22\xA8"));
/// ```
pub fn as_fields(&self) -> (u32, u16, u16, &[u8; 8]) {
let d1 = u32::from(self.bytes[0]) << 24 | u32::from(self.bytes[1]) << 16
| u32::from(self.bytes[2]) << 8 | u32::from(self.bytes[3]);
let d2 = u16::from(self.bytes[4]) << 8 | u16::from(self.bytes[5]);
let d3 = u16::from(self.bytes[6]) << 8 | u16::from(self.bytes[7]);
let d4: &[u8; 8] = unsafe { &*(self.bytes[8..16].as_ptr() as *const [u8; 8]) };
(d1, d2, d3, d4)
}
/// Returns an array of 16 octets containing the UUID data.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.as_bytes(), &[0; 16]);
///
/// let uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
/// assert_eq!(uuid.as_bytes(),
/// &[147, 109, 160, 31, 154, 189, 77, 157,
/// 128, 199, 2, 175, 133, 200, 34, 168]);
/// ```
pub fn as_bytes(&self) -> &[u8; 16] {
&self.bytes
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of 32 hexadecimal digits.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.simple().to_string(),
/// "00000000000000000000000000000000");
/// ```
pub fn simple(&self) -> Simple {
Simple { inner: self }
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of hexadecimal digits separated into groups with a hyphen.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.hyphenated().to_string(),
/// "00000000-0000-0000-0000-000000000000");
/// ```
pub fn hyphenated(&self) -> Hyphenated {
Hyphenated { inner: self }
}
/// Returns a wrapper which when formatted via `fmt::Display` will format a
/// string of the UUID as a full URN string.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// let uuid = Uuid::nil();
/// assert_eq!(uuid.urn().to_string(),
/// "urn:uuid:00000000-0000-0000-0000-000000000000");
/// ```
pub fn urn(&self) -> Urn {
Urn { inner: self }
}
/// Returns an Optional Tuple of (u64, u16) representing the timestamp and
/// counter portion of a V1 UUID. If the supplied UUID is not V1, this
/// will return None
pub fn to_timestamp(&self) -> Option<(u64, u16)> {
if self.get_version()
.map(|v| v != UuidVersion::Mac)
.unwrap_or(true)
{
return None;
}
let ts: u64 = u64::from(self.bytes[6] & 0x0F) << 56 | u64::from(self.bytes[7]) << 48
| u64::from(self.bytes[4]) << 40 | u64::from(self.bytes[5]) << 32
| u64::from(self.bytes[0]) << 24 | u64::from(self.bytes[1]) << 16
| u64::from(self.bytes[2]) << 8 | u64::from(self.bytes[3]);
let count: u16 = u16::from(self.bytes[8] & 0x3F) << 8 | u16::from(self.bytes[9]);
Some((ts, count))
}
/// Parses a `Uuid` from a string of hexadecimal digits with optional hyphens.
///
/// Any of the formats generated by this module (simple, hyphenated, urn) are
/// supported by this parsing function.
pub fn parse_str(mut input: &str) -> Result<Uuid, ParseError> {
// Ensure length is valid for any of the supported formats
let len = input.len();
if len == (adapter::UUID_HYPHENATED_LENGTH + 9) && input.starts_with("urn:uuid:") {
input = &input[9..];
} else if len != adapter::UUID_SIMPLE_LENGTH && len != adapter::UUID_HYPHENATED_LENGTH {
return Err(ParseError::InvalidLength(len));
}
// `digit` counts only hexadecimal digits, `i_char` counts all chars.
let mut digit = 0;
let mut group = 0;
let mut acc = 0;
let mut buffer = [0u8; 16];
for (i_char, chr) in input.bytes().enumerate() {
if digit as usize >= adapter::UUID_SIMPLE_LENGTH && group != 4 {
if group == 0 {
return Err(ParseError::InvalidLength(len));
}
return Err(ParseError::InvalidGroups(group + 1));
}
if digit % 2 == 0 {
// First digit of the byte.
match chr {
// Calulate upper half.
b'0'...b'9' => acc = chr - b'0',
b'a'...b'f' => acc = chr - b'a' + 10,
b'A'...b'F' => acc = chr - b'A' + 10,
// Found a group delimiter
b'-' => {
if ACC_GROUP_LENS[group] != digit {
// Calculate how many digits this group consists of in the input.
let found = if group > 0 {
digit - ACC_GROUP_LENS[group - 1]
} else {
digit
};
return Err(ParseError::InvalidGroupLength(
group,
found as usize,
GROUP_LENS[group],
));
}
// Next group, decrement digit, it is incremented again at the bottom.
group += 1;
digit -= 1;
}
_ => {
return Err(ParseError::InvalidCharacter(
input[i_char..].chars().next().unwrap(),
i_char,
))
}
}
} else {
// Second digit of the byte, shift the upper half.
acc *= 16;
match chr {
b'0'...b'9' => acc += chr - b'0',
b'a'...b'f' => acc += chr - b'a' + 10,
b'A'...b'F' => acc += chr - b'A' + 10,
b'-' => {
// The byte isn't complete yet.
let found = if group > 0 {
digit - ACC_GROUP_LENS[group - 1]
} else {
digit
};
return Err(ParseError::InvalidGroupLength(
group,
found as usize,
GROUP_LENS[group],
));
}
_ => {
return Err(ParseError::InvalidCharacter(
input[i_char..].chars().next().unwrap(),
i_char,
))
}
}
buffer[(digit / 2) as usize] = acc;
}
digit += 1;
}
// Now check the last group.
if ACC_GROUP_LENS[4] != digit {
return Err(ParseError::InvalidGroupLength(
group,
(digit - ACC_GROUP_LENS[3]) as usize,
GROUP_LENS[4],
));
}
Ok(Uuid::from_bytes(&buffer).unwrap())
}
/// Tests if the UUID is nil
pub fn is_nil(&self) -> bool {
self.bytes.iter().all(|&b| b == 0)
}
}
impl<'a> fmt::Display for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
impl<'a> fmt::UpperHex for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in &self.inner.bytes {
write!(f, "{:02X}", byte)?;
}
Ok(())
}
}
impl<'a> fmt::LowerHex for Simple<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in &self.inner.bytes {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
impl<'a> fmt::Display for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(self, f)
}
}
macro_rules! hyphenated_write {
($f:expr, $format:expr, $bytes:expr) => {{
let data1 = u32::from($bytes[0]) << 24 | u32::from($bytes[1]) << 16
| u32::from($bytes[2]) << 8 | u32::from($bytes[3]);
let data2 = u16::from($bytes[4]) << 8 | u16::from($bytes[5]);
let data3 = u16::from($bytes[6]) << 8 | u16::from($bytes[7]);
write!(
$f,
$format,
data1,
data2,
data3,
$bytes[8],
$bytes[9],
$bytes[10],
$bytes[11],
$bytes[12],
$bytes[13],
$bytes[14],
$bytes[15]
)
}};
}
impl<'a> fmt::UpperHex for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hyphenated_write!(
f,
"{:08X}-\
{:04X}-\
{:04X}-\
{:02X}{:02X}-\
{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
self.inner.bytes
)
}
}
impl<'a> fmt::LowerHex for Hyphenated<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hyphenated_write!(
f,
"{:08x}-\
{:04x}-\
{:04x}-\
{:02x}{:02x}-\
{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
self.inner.bytes
)
}
}
impl<'a> fmt::Display for Urn<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "urn:uuid:{}", self.inner.hyphenated())
}
}
#[cfg(test)]
mod tests {
extern crate std;
use self::std::prelude::v1::*;
use super::test_util;
use super::{NAMESPACE_X500, NAMESPACE_DNS, NAMESPACE_OID, NAMESPACE_URL};
use super::{Uuid, UuidVariant, UuidVersion};
#[cfg(feature = "v3")]
static FIXTURE_V3: &'static [(&'static Uuid, &'static str, &'static str)] = &[
(
&NAMESPACE_DNS,
"example.org",
"04738bdf-b25a-3829-a801-b21a1d25095b",
),
(
&NAMESPACE_DNS,
"rust-lang.org",
"c6db027c-615c-3b4d-959e-1a917747ca5a",
),
(&NAMESPACE_DNS, "42", "5aab6e0c-b7d3-379c-92e3-2bfbb5572511"),
(
&NAMESPACE_DNS,
"lorem ipsum",
"4f8772e9-b59c-3cc9-91a9-5c823df27281",
),
(
&NAMESPACE_URL,
"example.org",
"39682ca1-9168-3da2-a1bb-f4dbcde99bf9",
),
(
&NAMESPACE_URL,
"rust-lang.org",
"7ed45aaf-e75b-3130-8e33-ee4d9253b19f",
),
(&NAMESPACE_URL, "42", "08998a0c-fcf4-34a9-b444-f2bfc15731dc"),
(
&NAMESPACE_URL,
"lorem ipsum",
"e55ad2e6-fb89-34e8-b012-c5dde3cd67f0",
),
(
&NAMESPACE_OID,
"example.org",
"f14eec63-2812-3110-ad06-1625e5a4a5b2",
),
(
&NAMESPACE_OID,
"rust-lang.org",
"6506a0ec-4d79-3e18-8c2b-f2b6b34f2b6d",
),
(&NAMESPACE_OID, "42", "ce6925a5-2cd7-327b-ab1c-4b375ac044e4"),
(
&NAMESPACE_OID,
"lorem ipsum",
"5dd8654f-76ba-3d47-bc2e-4d6d3a78cb09",
),
(
&NAMESPACE_X500,
"example.org",
"64606f3f-bd63-363e-b946-fca13611b6f7",
),
(
&NAMESPACE_X500,
"rust-lang.org",
"bcee7a9c-52f1-30c6-a3cc-8c72ba634990",
),
(
&NAMESPACE_X500,
"42",
"c1073fa2-d4a6-3104-b21d-7a6bdcf39a23",
),
(
&NAMESPACE_X500,
"lorem ipsum",
"02f09a3f-1624-3b1d-8409-44eff7708208",
),
];
#[cfg(feature = "v5")]
static FIXTURE_V5: &'static [(&'static Uuid, &'static str, &'static str)] = &[
(
&NAMESPACE_DNS,
"example.org",
"aad03681-8b63-5304-89e0-8ca8f49461b5",
),
(
&NAMESPACE_DNS,
"rust-lang.org",
"c66bbb60-d62e-5f17-a399-3a0bd237c503",
),
(&NAMESPACE_DNS, "42", "7c411b5e-9d3f-50b5-9c28-62096e41c4ed"),
(
&NAMESPACE_DNS,
"lorem ipsum",
"97886a05-8a68-5743-ad55-56ab2d61cf7b",
),
(
&NAMESPACE_URL,
"example.org",
"54a35416-963c-5dd6-a1e2-5ab7bb5bafc7",
),
(
&NAMESPACE_URL,
"rust-lang.org",
"c48d927f-4122-5413-968c-598b1780e749",
),
(&NAMESPACE_URL, "42", "5c2b23de-4bad-58ee-a4b3-f22f3b9cfd7d"),
(
&NAMESPACE_URL,
"lorem ipsum",
"15c67689-4b85-5253-86b4-49fbb138569f",
),
(
&NAMESPACE_OID,
"example.org",
"34784df9-b065-5094-92c7-00bb3da97a30",
),
(
&NAMESPACE_OID,
"rust-lang.org",
"8ef61ecb-977a-5844-ab0f-c25ef9b8d5d6",
),
(&NAMESPACE_OID, "42", "ba293c61-ad33-57b9-9671-f3319f57d789"),
(
&NAMESPACE_OID,
"lorem ipsum",
"6485290d-f79e-5380-9e64-cb4312c7b4a6",
),
(
&NAMESPACE_X500,
"example.org",
"e3635e86-f82b-5bbc-a54a-da97923e5c76",
),
(
&NAMESPACE_X500,
"rust-lang.org",
"26c9c3e9-49b7-56da-8b9f-a0fb916a71a3",
),
(
&NAMESPACE_X500,
"42",
"e4b88014-47c6-5fe0-a195-13710e5f6e27",
),
(
&NAMESPACE_X500,
"lorem ipsum",
"b11f79a5-1e6d-57ce-a4b5-ba8531ea03d0",
),
];
#[test]
fn test_nil() {
let nil = Uuid::nil();
let not_nil = test_util::new();
assert!(nil.is_nil());
assert!(!not_nil.is_nil());
}
#[test]
fn test_new() {
if cfg!(feature = "v3") {
let u = Uuid::new(UuidVersion::Md5);
assert!(u.is_some(), "{:?}", u);
assert_eq!(u.unwrap().get_version().unwrap(), UuidVersion::Md5);
} else {
assert_eq!(Uuid::new(UuidVersion::Md5), None);
}
if cfg!(feature = "v4") {
let uuid1 = Uuid::new(UuidVersion::Random).unwrap();
let s = uuid1.simple().to_string();
assert_eq!(s.len(), 32);
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
} else {
assert!(Uuid::new(UuidVersion::Random).is_none());
}
if cfg!(feature = "v5") {
let u = Uuid::new(UuidVersion::Sha1);
assert!(u.is_some(), "{:?}", u);
assert_eq!(u.unwrap().get_version().unwrap(), UuidVersion::Sha1);
} else {
assert_eq!(Uuid::new(UuidVersion::Sha1), None);
}
// Test unsupported versions
assert_eq!(Uuid::new(UuidVersion::Mac), None);
assert_eq!(Uuid::new(UuidVersion::Dce), None);
}
#[cfg(feature = "v1")]
#[test]
fn test_new_v1() {
use UuidV1Context;
let time: u64 = 1_496_854_535;
let timefrac: u32 = 812_946_000;
let node = [1, 2, 3, 4, 5, 6];
let ctx = UuidV1Context::new(0);
let uuid = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Mac);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(
uuid.hyphenated().to_string(),
"20616934-4ba2-11e7-8000-010203040506"
);
let uuid2 = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
assert_eq!(
uuid2.hyphenated().to_string(),
"20616934-4ba2-11e7-8001-010203040506"
);
let ts = uuid.to_timestamp().unwrap();
assert_eq!(ts.0 - 0x01B21DD213814000, 1_496_854_535_812_946_0);
assert_eq!(ts.1, 0);
assert_eq!(uuid2.to_timestamp().unwrap().1, 1);
}
#[cfg(feature = "v3")]
#[test]
fn test_new_v3() {
for &(ref ns, ref name, _) in FIXTURE_V3 {
let uuid = Uuid::new_v3(*ns, *name);
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Md5);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
}
}
#[test]
#[cfg(feature = "v4")]
fn test_new_v4() {
let uuid1 = Uuid::new_v4();
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
assert_eq!(uuid1.get_variant().unwrap(), UuidVariant::RFC4122);
}
#[cfg(feature = "v5")]
#[test]
fn test_new_v5() {
for &(ref ns, ref name, _) in FIXTURE_V5 {
let uuid = Uuid::new_v5(*ns, *name);
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Sha1);
assert_eq!(uuid.get_variant().unwrap(), UuidVariant::RFC4122);
}
}
#[test]
fn test_predefined_namespaces() {
assert_eq!(
NAMESPACE_DNS.hyphenated().to_string(),
"6ba7b810-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_URL.hyphenated().to_string(),
"6ba7b811-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_OID.hyphenated().to_string(),
"6ba7b812-9dad-11d1-80b4-00c04fd430c8"
);
assert_eq!(
NAMESPACE_X500.hyphenated().to_string(),
"6ba7b814-9dad-11d1-80b4-00c04fd430c8"
);
}
#[cfg(feature = "v3")]
#[test]
fn test_get_version_v3() {
let uuid = Uuid::new_v3(&NAMESPACE_DNS, "rust-lang.org");
assert_eq!(uuid.get_version().unwrap(), UuidVersion::Md5);
assert_eq!(uuid.get_version_num(), 3);
}
#[test]
#[cfg(feature = "v4")]
fn test_get_version_v4() {
let uuid1 = Uuid::new_v4();
assert_eq!(uuid1.get_version().unwrap(), UuidVersion::Random);
assert_eq!(uuid1.get_version_num(), 4);
}
#[cfg(feature = "v5")]
#[test]
fn test_get_version_v5() {
let uuid2 = Uuid::new_v5(&NAMESPACE_DNS, "rust-lang.org");
assert_eq!(uuid2.get_version().unwrap(), UuidVersion::Sha1);
assert_eq!(uuid2.get_version_num(), 5);
}
#[test]
fn test_get_variant() {
let uuid1 = test_util::new();
let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
let uuid3 = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
let uuid4 = Uuid::parse_str("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
let uuid5 = Uuid::parse_str("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
let uuid6 = Uuid::parse_str("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();
assert_eq!(uuid1.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid2.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid3.get_variant().unwrap(), UuidVariant::RFC4122);
assert_eq!(uuid4.get_variant().unwrap(), UuidVariant::Microsoft);
assert_eq!(uuid5.get_variant().unwrap(), UuidVariant::Microsoft);
assert_eq!(uuid6.get_variant().unwrap(), UuidVariant::NCS);
}
#[test]
fn test_parse_uuid_v4() {
use super::ParseError::*;
// Invalid
assert_eq!(Uuid::parse_str(""), Err(InvalidLength(0)));
assert_eq!(Uuid::parse_str("!"), Err(InvalidLength(1)));
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45"),
Err(InvalidLength(37))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4"),
Err(InvalidLength(35))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4"),
Err(InvalidCharacter('G', 20))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2F4faaFB6BFF329BF39FA1E4"),
Err(InvalidGroups(2))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faaFB6BFF329BF39FA1E4"),
Err(InvalidGroups(3))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4"),
Err(InvalidGroups(4))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa"),
Err(InvalidLength(18))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4"),
Err(InvalidCharacter('X', 18))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4"),
Err(InvalidGroupLength(1, 3, 4))
);
assert_eq!(
Uuid::parse_str("01020304-1112-2122-3132-41424344"),
Err(InvalidGroupLength(4, 8, 12))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
Err(InvalidLength(31))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c88"),
Err(InvalidLength(33))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0cg8"),
Err(InvalidLength(33))
);
assert_eq!(
Uuid::parse_str("67e5504410b1426%9247bb680e5fe0c8"),
Err(InvalidCharacter('%', 15))
);
assert_eq!(
Uuid::parse_str("231231212212423424324323477343246663"),
Err(InvalidLength(36))
);
// Valid
assert!(Uuid::parse_str("00000000000000000000000000000000").is_ok());
assert!(Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
assert!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok());
assert!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8").is_ok());
assert!(Uuid::parse_str("01020304-1112-2122-3132-414243444546").is_ok());
assert!(Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
// Nil
let nil = Uuid::nil();
assert_eq!(
Uuid::parse_str("00000000000000000000000000000000").unwrap(),
nil
);
assert_eq!(
Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(),
nil
);
// Round-trip
let uuid_orig = test_util::new();
let orig_str = uuid_orig.to_string();
let uuid_out = Uuid::parse_str(&orig_str).unwrap();
assert_eq!(uuid_orig, uuid_out);
// Test error reporting
assert_eq!(
Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
Err(InvalidLength(31))
);
assert_eq!(
Uuid::parse_str("67e550X410b1426f9247bb680e5fe0cd"),
Err(InvalidCharacter('X', 6))
);
assert_eq!(
Uuid::parse_str("67e550-4105b1426f9247bb680e5fe0c"),
Err(InvalidGroupLength(0, 6, 8))
);
assert_eq!(
Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4"),
Err(InvalidGroupLength(3, 5, 4))
);
}
#[test]
fn test_to_simple_string() {
let uuid1 = test_util::new();
let s = uuid1.simple().to_string();
assert_eq!(s.len(), 32);
assert!(s.chars().all(|c| c.is_digit(16)));
}
#[test]
fn test_to_hyphenated_string() {
let uuid1 = test_util::new();
let s = uuid1.hyphenated().to_string();
assert!(s.len() == 36);
assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
}
#[test]
fn test_upper_lower_hex() {
use super::fmt::Write;
let mut buf = String::new();
let u = test_util::new();
macro_rules! check {
($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
$buf.clear();
write!($buf, $format, $target).unwrap();
assert!(buf.len() == $len);
assert!($buf.chars().all($cond), "{}", $buf);
};
}
check!(buf, "{:X}", u, 36, |c| c.is_uppercase() || c.is_digit(10)
|| c == '-');
check!(
buf,
"{:X}",
u.hyphenated(),
36,
|c| c.is_uppercase() || c.is_digit(10) || c == '-'
);
check!(buf, "{:X}", u.simple(), 32, |c| c.is_uppercase()
|| c.is_digit(10));
check!(
buf,
"{:x}",
u.hyphenated(),
36,
|c| c.is_lowercase() || c.is_digit(10) || c == '-'
);
check!(buf, "{:x}", u.simple(), 32, |c| c.is_lowercase()
|| c.is_digit(10));
}
#[cfg(feature = "v3")]
#[test]
fn test_v3_to_hypenated_string() {
for &(ref ns, ref name, ref expected) in FIXTURE_V3 {
let uuid = Uuid::new_v3(*ns, *name);
assert_eq!(uuid.hyphenated().to_string(), *expected);
}
}
#[cfg(feature = "v5")]
#[test]
fn test_v5_to_hypenated_string() {
for &(ref ns, ref name, ref expected) in FIXTURE_V5 {
let uuid = Uuid::new_v5(*ns, *name);
assert_eq!(uuid.hyphenated().to_string(), *expected);
}
}
#[test]
fn test_to_urn_string() {
let uuid1 = test_util::new();
let ss = uuid1.urn().to_string();
let s = &ss[9..];
assert!(ss.starts_with("urn:uuid:"));
assert_eq!(s.len(), 36);
assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
}
#[test]
fn test_to_simple_string_matching() {
let uuid1 = test_util::new();
let hs = uuid1.hyphenated().to_string();
let ss = uuid1.simple().to_string();
let hsn = hs.chars().filter(|&c| c != '-').collect::<String>();
assert_eq!(hsn, ss);
}
#[test]
fn test_string_roundtrip() {
let uuid = test_util::new();
let hs = uuid.hyphenated().to_string();
let uuid_hs = Uuid::parse_str(&hs).unwrap();
assert_eq!(uuid_hs, uuid);
let ss = uuid.to_string();
let uuid_ss = Uuid::parse_str(&ss).unwrap();
assert_eq!(uuid_ss, uuid);
}
#[test]
fn test_from_fields() {
let d1: u32 = 0xa1a2a3a4;
let d2: u16 = 0xb1b2;
let d3: u16 = 0xc1c2;
let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
let u = Uuid::from_fields(d1, d2, d3, &d4).unwrap();
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
let result = u.simple().to_string();
assert_eq!(result, expected);
}
#[test]
fn test_as_fields() {
let u = test_util::new();
let (d1, d2, d3, d4) = u.as_fields();
assert_ne!(d1, 0);
assert_ne!(d2, 0);
assert_ne!(d3, 0);
assert_eq!(d4.len(), 8);
assert!(!d4.iter().all(|&b| b == 0));
}
#[test]
fn test_fields_roundtrip() {
let d1_in: u32 = 0xa1a2a3a4;
let d2_in: u16 = 0xb1b2;
let d3_in: u16 = 0xc1c2;
let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in).unwrap();
let (d1_out, d2_out, d3_out, d4_out) = u.as_fields();
assert_eq!(d1_in, d1_out);
assert_eq!(d2_in, d2_out);
assert_eq!(d3_in, d3_out);
assert_eq!(d4_in, d4_out);
}
#[test]
fn test_from_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_bytes(&b).unwrap();
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_from_uuid_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_uuid_bytes(b);
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_as_bytes() {
let u = test_util::new();
let ub = u.as_bytes();
assert_eq!(ub.len(), 16);
assert!(!ub.iter().all(|&b| b == 0));
}
#[test]
fn test_bytes_roundtrip() {
let b_in: [u8; 16] = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_bytes(&b_in).unwrap();
let b_out = u.as_bytes();
assert_eq!(&b_in, b_out);
}
#[test]
fn test_from_random_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_random_bytes(b);
let expected = "a1a2a3a4b1b241c291d2d3d4d5d6d7d8";
assert_eq!(u.simple().to_string(), expected);
}
#[test]
fn test_iterbytes_impl_for_uuid() {
let mut set = std::collections::HashSet::new();
let id1 = test_util::new();
let id2 = test_util::new2();
set.insert(id1.clone());
assert!(set.contains(&id1));
assert!(!set.contains(&id2));
}
}
|
/* Copyright 2015 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
#![feature(coerce_unsized)]
extern crate libc;
extern crate iup_sys;
macro_rules! impl_control_traits {
($control:ident) => {
impl Drop for ::$control {
fn drop(&mut self) {
unsafe {
if IupGetParent(self.handle_mut()) == ptr::null_mut() {
IupDestroy(self.handle_mut());
}
}
}
}
unsafe impl Control for ::$control {
fn handle(&self) -> *const Ihandle { self.0 }
fn handle_mut(&mut self) -> *mut Ihandle { self.0 }
}
};
}
#[macro_use]
mod common_callbacks;
mod dialog;
mod button;
pub use dialog::{Position, Dialog};
pub use button::Button;
pub use common_callbacks::{NonMenuCommonCallbacks, MenuCommonCallbacks, ButtonCallback};
use std::borrow::Cow;
use std::ffi::CStr;
use std::ptr;
use libc::{c_char, c_int};
use iup_sys::*;
pub fn main_loop() {
unsafe {
IupMainLoop();
}
}
fn set_str_attribute(handle: *mut Ihandle, name: &str, value: &str) {
unsafe {
IupSetStrAttribute(handle,
name.as_ptr() as *const c_char,
value.as_ptr() as *const c_char);
}
}
// Unfortunately, the return value has to be copied because its lifetime isn't guarenteed.
// IUP's docs state:
// "The returned pointer can be used safely even if IupGetGlobal or IupGetAttribute are called
// several times. But not too many times, because it is an internal buffer and after IUP may
// reuse it after around 50 calls."
fn get_str_attribute(handle: *const Ihandle, name: &str) -> String {
unsafe {
get_str_attribute_slice(handle, name).into_owned()
}
}
unsafe fn get_str_attribute_slice(handle: *const Ihandle, name: &str) -> Cow<str> {
let value = IupGetAttribute(handle as *mut Ihandle, name.as_ptr() as *const c_char);
CStr::from_ptr(value).to_string_lossy()
}
fn iup_open() {
unsafe { IupOpen(ptr::null_mut(), ptr::null_mut()); }
}
// Part of the contract of implementing this trait is that no invalid handle
// is returned. Either the handle will stay valid for the life of the object or
// the method will panic.
pub unsafe trait Control {
fn handle(&self) -> *const Ihandle;
fn handle_mut(&mut self) -> *mut Ihandle;
}
#[derive(Copy,Clone)]
pub enum MouseButton {
Button1,
Button2,
Button3,
Button4,
Button5,
}
impl MouseButton {
fn from_int(i: c_int) -> MouseButton {
match i {
IUP_BUTTON1 => MouseButton::Button1,
IUP_BUTTON2 => MouseButton::Button2,
IUP_BUTTON3 => MouseButton::Button3,
IUP_BUTTON4 => MouseButton::Button4,
IUP_BUTTON5 => MouseButton::Button5,
_ => panic!("unknown mouse button"),
}
}
// fn to_int(self) -> c_int {
// match self {
// MouseButton::Button1 => IUP_BUTTON1,
// MouseButton::Button2 => IUP_BUTTON2,
// MouseButton::Button3 => IUP_BUTTON3,
// MouseButton::Button4 => IUP_BUTTON4,
// MouseButton::Button5 => IUP_BUTTON5,
// }
// }
}
#[derive(Clone)]
pub struct KeyboardMouseStatus {
shift_pressed: bool,
control_pressed: bool,
alt_pressed: bool,
sys_pressed: bool,
button1_pressed: bool,
button2_pressed: bool,
button3_pressed: bool,
button4_pressed: bool,
button5_pressed: bool,
}
impl KeyboardMouseStatus {
unsafe fn from_cstr(s: *const c_char) -> KeyboardMouseStatus {
KeyboardMouseStatus {
shift_pressed: iup_isshift(s),
control_pressed: iup_iscontrol(s),
alt_pressed: iup_isalt(s),
sys_pressed: iup_issys(s),
button1_pressed: iup_isbutton1(s),
button2_pressed: iup_isbutton2(s),
button3_pressed: iup_isbutton3(s),
button4_pressed: iup_isbutton4(s),
button5_pressed: iup_isbutton5(s),
}
}
}
pub trait CommonAttributes : Control {
fn active(&self) -> bool {
get_str_attribute(self.handle(), "ACTIVE") == "YES"
}
fn set_active(&mut self, active: bool) {
set_str_attribute(self.handle_mut(), "ACTIVE", if active { "YES" } else { "NO" });
}
fn tip(&self) -> String {
get_str_attribute(self.handle(), "TIP")
}
unsafe fn tip_slice(&self) -> Cow<str> {
get_str_attribute_slice(self.handle(), "TIP")
}
fn set_tip(&mut self, tip: &str) {
set_str_attribute(self.handle_mut(), "TIP", tip);
}
fn show(&mut self) -> Result<(), ()> {
unsafe {
if IupShow(self.handle_mut()) == IUP_NOERROR {
Ok(())
} else {
Err(())
}
}
}
fn hide(&mut self) -> Result<(), ()> {
unsafe {
if IupHide(self.handle_mut()) == IUP_NOERROR {
Ok(())
} else {
Err(())
}
}
}
fn set_visible(&mut self, visible: bool) -> Result<(), ()> {
if visible { self.show() } else { self.hide() }
}
}
pub trait TitleAttribute : Control {
fn title(&self) -> String {
get_str_attribute(self.handle(), "TITLE")
}
fn set_title(&mut self, title: &str) {
set_str_attribute(self.handle_mut(), "TITLE", title);
}
}
#[test]
#[should_panic]
fn test_destroyed_control() {
let dialog = Dialog::new();
let button = Button::new();
dialog.append(button);
button.set_title("Hello");
}
#[test]
#[should_panic]
fn test_destroyed_control_with_normalizer() {
panic!("TODO");
}
Make sure IUP is open before calling IupMainLoop()
/* Copyright 2015 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
#![feature(coerce_unsized)]
extern crate libc;
extern crate iup_sys;
macro_rules! impl_control_traits {
($control:ident) => {
impl Drop for ::$control {
fn drop(&mut self) {
unsafe {
if IupGetParent(self.handle_mut()) == ptr::null_mut() {
IupDestroy(self.handle_mut());
}
}
}
}
unsafe impl Control for ::$control {
fn handle(&self) -> *const Ihandle { self.0 }
fn handle_mut(&mut self) -> *mut Ihandle { self.0 }
}
};
}
#[macro_use]
mod common_callbacks;
mod dialog;
mod button;
pub use dialog::{Position, Dialog};
pub use button::Button;
pub use common_callbacks::{NonMenuCommonCallbacks, MenuCommonCallbacks, ButtonCallback};
use std::borrow::Cow;
use std::ffi::CStr;
use std::ptr;
use libc::{c_char, c_int};
use iup_sys::*;
pub fn main_loop() {
unsafe {
iup_open();
IupMainLoop();
}
}
fn set_str_attribute(handle: *mut Ihandle, name: &str, value: &str) {
unsafe {
IupSetStrAttribute(handle,
name.as_ptr() as *const c_char,
value.as_ptr() as *const c_char);
}
}
// Unfortunately, the return value has to be copied because its lifetime isn't guarenteed.
// IUP's docs state:
// "The returned pointer can be used safely even if IupGetGlobal or IupGetAttribute are called
// several times. But not too many times, because it is an internal buffer and after IUP may
// reuse it after around 50 calls."
fn get_str_attribute(handle: *const Ihandle, name: &str) -> String {
unsafe {
get_str_attribute_slice(handle, name).into_owned()
}
}
unsafe fn get_str_attribute_slice(handle: *const Ihandle, name: &str) -> Cow<str> {
let value = IupGetAttribute(handle as *mut Ihandle, name.as_ptr() as *const c_char);
CStr::from_ptr(value).to_string_lossy()
}
fn iup_open() {
unsafe { IupOpen(ptr::null_mut(), ptr::null_mut()); }
}
// Part of the contract of implementing this trait is that no invalid handle
// is returned. Either the handle will stay valid for the life of the object or
// the method will panic.
pub unsafe trait Control {
fn handle(&self) -> *const Ihandle;
fn handle_mut(&mut self) -> *mut Ihandle;
}
#[derive(Copy,Clone)]
pub enum MouseButton {
Button1,
Button2,
Button3,
Button4,
Button5,
}
impl MouseButton {
fn from_int(i: c_int) -> MouseButton {
match i {
IUP_BUTTON1 => MouseButton::Button1,
IUP_BUTTON2 => MouseButton::Button2,
IUP_BUTTON3 => MouseButton::Button3,
IUP_BUTTON4 => MouseButton::Button4,
IUP_BUTTON5 => MouseButton::Button5,
_ => panic!("unknown mouse button"),
}
}
// fn to_int(self) -> c_int {
// match self {
// MouseButton::Button1 => IUP_BUTTON1,
// MouseButton::Button2 => IUP_BUTTON2,
// MouseButton::Button3 => IUP_BUTTON3,
// MouseButton::Button4 => IUP_BUTTON4,
// MouseButton::Button5 => IUP_BUTTON5,
// }
// }
}
#[derive(Clone)]
pub struct KeyboardMouseStatus {
shift_pressed: bool,
control_pressed: bool,
alt_pressed: bool,
sys_pressed: bool,
button1_pressed: bool,
button2_pressed: bool,
button3_pressed: bool,
button4_pressed: bool,
button5_pressed: bool,
}
impl KeyboardMouseStatus {
unsafe fn from_cstr(s: *const c_char) -> KeyboardMouseStatus {
KeyboardMouseStatus {
shift_pressed: iup_isshift(s),
control_pressed: iup_iscontrol(s),
alt_pressed: iup_isalt(s),
sys_pressed: iup_issys(s),
button1_pressed: iup_isbutton1(s),
button2_pressed: iup_isbutton2(s),
button3_pressed: iup_isbutton3(s),
button4_pressed: iup_isbutton4(s),
button5_pressed: iup_isbutton5(s),
}
}
}
pub trait CommonAttributes : Control {
fn active(&self) -> bool {
get_str_attribute(self.handle(), "ACTIVE") == "YES"
}
fn set_active(&mut self, active: bool) {
set_str_attribute(self.handle_mut(), "ACTIVE", if active { "YES" } else { "NO" });
}
fn tip(&self) -> String {
get_str_attribute(self.handle(), "TIP")
}
unsafe fn tip_slice(&self) -> Cow<str> {
get_str_attribute_slice(self.handle(), "TIP")
}
fn set_tip(&mut self, tip: &str) {
set_str_attribute(self.handle_mut(), "TIP", tip);
}
fn show(&mut self) -> Result<(), ()> {
unsafe {
if IupShow(self.handle_mut()) == IUP_NOERROR {
Ok(())
} else {
Err(())
}
}
}
fn hide(&mut self) -> Result<(), ()> {
unsafe {
if IupHide(self.handle_mut()) == IUP_NOERROR {
Ok(())
} else {
Err(())
}
}
}
fn set_visible(&mut self, visible: bool) -> Result<(), ()> {
if visible { self.show() } else { self.hide() }
}
}
pub trait TitleAttribute : Control {
fn title(&self) -> String {
get_str_attribute(self.handle(), "TITLE")
}
fn set_title(&mut self, title: &str) {
set_str_attribute(self.handle_mut(), "TITLE", title);
}
}
#[test]
#[should_panic]
fn test_destroyed_control() {
let dialog = Dialog::new();
let button = Button::new();
dialog.append(button);
button.set_title("Hello");
}
#[test]
#[should_panic]
fn test_destroyed_control_with_normalizer() {
panic!("TODO");
}
|
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! # Chrono 0.4.0
//!
//! Date and time handling for Rust.
//! It aims to be a feature-complete superset of
//! the [time](https://github.com/rust-lang-deprecated/time) library.
//! In particular,
//!
//! * Chrono strictly adheres to ISO 8601.
//! * Chrono is timezone-aware by default, with separate timezone-naive types.
//! * Chrono is space-optimal and (while not being the primary goal) reasonably efficient.
//!
//! There were several previous attempts to bring a good date and time library to Rust,
//! which Chrono builds upon and should acknowledge:
//!
//! * [Initial research on
//! the wiki](https://github.com/rust-lang/rust-wiki-backup/blob/master/Lib-datetime.md)
//! * Dietrich Epp's [datetime-rs](https://github.com/depp/datetime-rs)
//! * Luis de Bethencourt's [rust-datetime](https://github.com/luisbg/rust-datetime)
//!
//! Any significant changes to Chrono are documented in
//! the [`CHANGELOG.md`](https://github.com/chronotope/chrono/blob/master/CHANGELOG.md) file.
//!
//! ## Usage
//!
//! Put this in your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! chrono = "0.4"
//! ```
//!
//! Or, if you want [Serde](https://github.com/serde-rs/serde) or
//! [rustc-serialize](https://github.com/rust-lang-nursery/rustc-serialize) support,
//! include the features like this:
//!
//! ```toml
//! [dependencies]
//! chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
//! ```
//!
//! > Note that Chrono's support for rustc-serialize is now considered deprecated.
//! Starting from 0.4.0 there is no further guarantee that
//! the features available in Serde will be also available to rustc-serialize,
//! and the support can be removed in any future major version.
//! **Rustc-serialize users are strongly recommended to migrate to Serde.**
//!
//! Then put this in your crate root:
//!
//! ```rust
//! extern crate chrono;
//! ```
//!
//! Avoid using `use chrono::*;` as Chrono exports several modules other than types.
//! If you prefer the glob imports, use the following instead:
//!
//! ```rust
//! use chrono::prelude::*;
//! ```
//!
//! ## Overview
//!
//! ### Duration
//!
//! Chrono currently uses
//! the [`time::Duration`](https://doc.rust-lang.org/time/time/struct.Duration.html) type
//! from the `time` crate to represent the magnitude of a time span.
//! Since this has the same name to the newer, standard type for duration,
//! the reference will refer this type as `OldDuration`.
//! Note that this is an "accurate" duration represented as seconds and
//! nanoseconds and does not represent "nominal" components such as days or
//! months.
//!
//! Chrono does not yet natively support
//! the standard [`Duration`](https://doc.rust-lang.org/std/time/struct.Duration.html) type,
//! but it will be supported in the future.
//! Meanwhile you can convert between two types with
//! [`Duration::from_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.from_std)
//! and
//! [`Duration::to_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.to_std)
//! methods.
//!
//! ### Date and Time
//!
//! Chrono provides a
//! [**`DateTime`**](./struct.DateTime.html)
//! type to represent a date and a time in a timezone.
//!
//! For more abstract moment-in-time tracking such as internal timekeeping
//! that is unconcerned with timezones, consider
//! [`time::SystemTime`](https://doc.rust-lang.org/std/time/struct.SystemTime.html),
//! which tracks your system clock, or
//! [`time::Instant`](https://doc.rust-lang.org/std/time/struct.Instant.html), which
//! is an opaque but monotonically-increasing representation of a moment in time.
//!
//! `DateTime` is timezone-aware and must be constructed from
//! the [**`TimeZone`**](./offset/trait.TimeZone.html) object,
//! which defines how the local date is converted to and back from the UTC date.
//! There are three well-known `TimeZone` implementations:
//!
//! * [**`Utc`**](./offset/struct.Utc.html) specifies the UTC time zone. It is most efficient.
//!
//! * [**`Local`**](./offset/struct.Local.html) specifies the system local time zone.
//!
//! * [**`FixedOffset`**](./offset/struct.FixedOffset.html) specifies
//! an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30.
//! This often results from the parsed textual date and time.
//! Since it stores the most information and does not depend on the system environment,
//! you would want to normalize other `TimeZone`s into this type.
//!
//! `DateTime`s with different `TimeZone` types are distinct and do not mix,
//! but can be converted to each other using
//! the [`DateTime::with_timezone`](./struct.DateTime.html#method.with_timezone) method.
//!
//! You can get the current date and time in the UTC time zone
//! ([`Utc::now()`](./offset/struct.Utc.html#method.now))
//! or in the local time zone
//! ([`Local::now()`](./offset/struct.Local.html#method.now)).
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`
//! let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`
//! # let _ = utc; let _ = local;
//! ```
//!
//! Alternatively, you can create your own date and time.
//! This is a bit verbose due to Rust's lack of function and method overloading,
//! but in turn we get a rich combination of initialization methods.
//!
//! ```rust
//! use chrono::prelude::*;
//! use chrono::offset::LocalResult;
//!
//! let dt = Utc.ymd(2014, 7, 8).and_hms(9, 10, 11); // `2014-07-08T09:10:11Z`
//! // July 8 is 188th day of the year 2014 (`o` for "ordinal")
//! assert_eq!(dt, Utc.yo(2014, 189).and_hms(9, 10, 11));
//! // July 8 is Tuesday in ISO week 28 of the year 2014.
//! assert_eq!(dt, Utc.isoywd(2014, 28, Weekday::Tue).and_hms(9, 10, 11));
//!
//! let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); // `2014-07-08T09:10:11.012Z`
//! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_micro(9, 10, 11, 12_000));
//! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_nano(9, 10, 11, 12_000_000));
//!
//! // dynamic verification
//! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(21, 15, 33),
//! LocalResult::Single(Utc.ymd(2014, 7, 8).and_hms(21, 15, 33)));
//! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(80, 15, 33), LocalResult::None);
//! assert_eq!(Utc.ymd_opt(2014, 7, 38).and_hms_opt(21, 15, 33), LocalResult::None);
//!
//! // other time zone objects can be used to construct a local datetime.
//! // obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical.
//! let local_dt = Local.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12);
//! let fixed_dt = FixedOffset::east(9 * 3600).ymd(2014, 7, 8).and_hms_milli(18, 10, 11, 12);
//! assert_eq!(dt, fixed_dt);
//! # let _ = local_dt;
//! ```
//!
//! Various properties are available to the date and time, and can be altered individually.
//! Most of them are defined in the traits [`Datelike`](./trait.Datelike.html) and
//! [`Timelike`](./trait.Timelike.html) which you should `use` before.
//! Addition and subtraction is also supported.
//! The following illustrates most supported operations to the date and time:
//!
//! ```rust
//! # extern crate chrono; extern crate time; fn main() {
//! use chrono::prelude::*;
//! use time::Duration;
//!
//! # /* we intentionally fake the datetime...
//! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
//! let dt = Local::now();
//! # */ // up to here. we now define a fixed datetime for the illustrative purpose.
//! # let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);
//!
//! // property accessors
//! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
//! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
//! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
//! assert_eq!(dt.weekday(), Weekday::Fri);
//! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sat=7
//! assert_eq!(dt.ordinal(), 332); // the day of year
//! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1
//!
//! // time zone accessor and manipulation
//! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
//! assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
//! assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));
//!
//! // a sample of property manipulations (validates dynamically)
//! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
//! assert_eq!(dt.with_day(32), None);
//! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE
//!
//! // arithmetic operations
//! let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
//! let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
//! assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
//! assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
//! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
//! Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
//! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
//! Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));
//! # }
//! ```
//!
//! Formatting is done via the [`format`](./struct.DateTime.html#method.format) method,
//! which format is equivalent to the familiar `strftime` format.
//! (See the [`format::strftime` module documentation](./format/strftime/index.html#specifiers)
//! for full syntax.)
//!
//! The default `to_string` method and `{:?}` specifier also give a reasonable representation.
//! Chrono also provides [`to_rfc2822`](./struct.DateTime.html#method.to_rfc2822) and
//! [`to_rfc3339`](./struct.DateTime.html#method.to_rfc3339) methods
//! for well-known formats.
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
//! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
//! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
//! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
//!
//! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
//! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
//! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
//! assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");
//! ```
//!
//! Parsing can be done with three methods:
//!
//! 1. The standard [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) trait
//! (and [`parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) method
//! on a string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and
//! `DateTime<Local>` values. This parses what the `{:?}`
//! ([`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html))
//! format specifier prints, and requires the offset to be present.
//!
//! 2. [`DateTime::parse_from_str`](./struct.DateTime.html#method.parse_from_str) parses
//! a date and time with offsets and returns `DateTime<FixedOffset>`.
//! This should be used when the offset is a part of input and the caller cannot guess that.
//! It *cannot* be used when the offset can be missing.
//! [`DateTime::parse_from_rfc2822`](./struct.DateTime.html#method.parse_from_rfc2822)
//! and
//! [`DateTime::parse_from_rfc3339`](./struct.DateTime.html#method.parse_from_rfc3339)
//! are similar but for well-known formats.
//!
//! 3. [`Offset::datetime_from_str`](./offset/trait.TimeZone.html#method.datetime_from_str) is
//! similar but returns `DateTime` of given offset.
//! When the explicit offset is missing from the input, it simply uses given offset.
//! It issues an error when the input contains an explicit offset different
//! from the current offset.
//!
//! More detailed control over the parsing process is available via
//! [`format`](./format/index.html) module.
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
//! let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));
//!
//! // method 1
//! assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
//! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
//! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));
//!
//! // method 2
//! assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
//! Ok(fixed_dt.clone()));
//! assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
//! Ok(fixed_dt.clone()));
//! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));
//!
//! // method 3
//! assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
//! assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));
//!
//! // oops, the year is missing!
//! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
//! // oops, the format string does not include the year at all!
//! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
//! // oops, the weekday is incorrect!
//! assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());
//! ```
//!
//! ### Conversion from and to EPOCH timestamps
//!
//! Use [`Utc.timestamp(seconds, nanoseconds)`](./offset/trait.TimeZone.html#method.timestamp)
//! to construct a [`DateTime<Utc>`](./struct.DateTime.html) from a UNIX timestamp
//! (seconds, nanoseconds that passed since January 1st 1970).
//!
//! Use [`DateTime.timestamp`](./struct.DateTime.html#method.timestamp) to get the timestamp (in seconds)
//! from a [`DateTime`](./struct.DateTime.html). Additionally, you can use
//! [`DateTime.timestamp_subsec_nanos`](./struct.DateTime.html#method.timestamp_subsec_nanos)
//! to get the number of additional number of nanoseconds.
//!
//! ```rust
//! # use chrono::DateTime;
//! # use chrono::Utc;
//! // We need the trait in scope to use Utc::timestamp().
//! use chrono::TimeZone;
//!
//! // Construct a datetime from epoch:
//! let dt = Utc.timestamp(1500000000, 0);
//! assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
//!
//! // Get epoch value from a datetime:
//! let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
//! assert_eq!(dt.timestamp(), 1500000000);
//! ```
//! ### Individual date
//!
//! Chrono also provides an individual date type ([**`Date`**](./struct.Date.html)).
//! It also has time zones attached, and have to be constructed via time zones.
//! Most operations available to `DateTime` are also available to `Date` whenever appropriate.
//!
//! ```rust
//! use chrono::prelude::*;
//! use chrono::offset::LocalResult;
//!
//! # // these *may* fail, but only very rarely. just rerun the test if you were that unfortunate ;)
//! assert_eq!(Utc::today(), Utc::now().date());
//! assert_eq!(Local::today(), Local::now().date());
//!
//! assert_eq!(Utc.ymd(2014, 11, 28).weekday(), Weekday::Fri);
//! assert_eq!(Utc.ymd_opt(2014, 11, 31), LocalResult::None);
//! assert_eq!(Utc.ymd(2014, 11, 28).and_hms_milli(7, 8, 9, 10).format("%H%M%S").to_string(),
//! "070809");
//! ```
//!
//! There is no timezone-aware `Time` due to the lack of usefulness and also the complexity.
//!
//! `DateTime` has [`date`](./struct.DateTime.html#method.date) method
//! which returns a `Date` which represents its date component.
//! There is also a [`time`](./struct.DateTime.html#method.time) method,
//! which simply returns a naive local time described below.
//!
//! ### Naive date and time
//!
//! Chrono provides naive counterparts to `Date`, (non-existent) `Time` and `DateTime`
//! as [**`NaiveDate`**](./naive/struct.NaiveDate.html),
//! [**`NaiveTime`**](./naive/struct.NaiveTime.html) and
//! [**`NaiveDateTime`**](./naive/struct.NaiveDateTime.html) respectively.
//!
//! They have almost equivalent interfaces as their timezone-aware twins,
//! but are not associated to time zones obviously and can be quite low-level.
//! They are mostly useful for building blocks for higher-level types.
//!
//! Timezone-aware `DateTime` and `Date` types have two methods returning naive versions:
//! [`naive_local`](./struct.DateTime.html#method.naive_local) returns
//! a view to the naive local time,
//! and [`naive_utc`](./struct.DateTime.html#method.naive_utc) returns
//! a view to the naive UTC time.
//!
//! ## Limitations
//!
//! Only proleptic Gregorian calendar (i.e. extended to support older dates) is supported.
//! Be very careful if you really have to deal with pre-20C dates, they can be in Julian or others.
//!
//! Date types are limited in about +/- 262,000 years from the common epoch.
//! Time types are limited in the nanosecond accuracy.
//!
//! [Leap seconds are supported in the representation but
//! Chrono doesn't try to make use of them](./naive/struct.NaiveTime.html#leap-second-handling).
//! (The main reason is that leap seconds are not really predictable.)
//! Almost *every* operation over the possible leap seconds will ignore them.
//! Consider using `NaiveDateTime` with the implicit TAI (International Atomic Time) scale
//! if you want.
//!
//! Chrono inherently does not support an inaccurate or partial date and time representation.
//! Any operation that can be ambiguous will return `None` in such cases.
//! For example, "a month later" of 2014-01-30 is not well-defined
//! and consequently `Utc.ymd(2014, 1, 30).with_month(2)` returns `None`.
//!
//! Advanced time zone handling is not yet supported.
//! For now you can try the [Chrono-tz](https://github.com/chronotope/chrono-tz/) crate instead.
#![doc(html_root_url = "https://docs.rs/chrono/0.4.0/")]
#![cfg_attr(bench, feature(test))] // lib stability features as per RFC #507
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
extern crate time as oldtime;
extern crate num;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature = "serde")]
extern crate serde as serdelib;
// this reexport is to aid the transition and should not be in the prelude!
pub use oldtime::Duration;
#[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset, Local};
#[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
pub use date::{Date, MIN_DATE, MAX_DATE};
pub use datetime::DateTime;
#[cfg(feature = "rustc-serialize")] pub use datetime::rustc_serialize::TsSeconds;
pub use format::{ParseError, ParseResult};
/// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
pub mod prelude {
#[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
#[doc(no_inline)] pub use {TimeZone, Offset};
#[doc(no_inline)] pub use {Utc, FixedOffset, Local};
#[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
#[doc(no_inline)] pub use Date;
#[doc(no_inline)] pub use DateTime;
}
// useful throughout the codebase
macro_rules! try_opt {
($e:expr) => (match $e { Some(v) => v, None => return None })
}
mod div;
pub mod offset;
pub mod naive {
//! Date and time types which do not concern about the timezones.
//!
//! They are primarily building blocks for other types
//! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
//! but can be also used for the simpler date and time handling.
mod internals;
mod date;
mod isoweek;
mod time;
mod datetime;
pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
pub use self::isoweek::IsoWeek;
pub use self::time::NaiveTime;
pub use self::datetime::NaiveDateTime;
#[cfg(feature = "rustc-serialize")]
pub use self::datetime::rustc_serialize::TsSeconds;
/// Serialization/Deserialization of naive types in alternate formats
///
/// The various modules in here are intended to be used with serde's [`with`
/// annotation][1] to serialize as something other than the default [RFC
/// 3339][2] format.
///
/// [1]: https://serde.rs/attributes.html#field-attributes
/// [2]: https://tools.ietf.org/html/rfc3339
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
}
mod date;
mod datetime;
pub mod format;
/// Serialization/Deserialization in alternate formats
///
/// The various modules in here are intended to be used with serde's [`with`
/// annotation][1] to serialize as something other than the default [RFC
/// 3339][2] format.
///
/// [1]: https://serde.rs/attributes.html#field-attributes
/// [2]: https://tools.ietf.org/html/rfc3339
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
/// The day of week.
///
/// The order of the days of week depends on the context.
/// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
/// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum Weekday {
/// Monday.
Mon = 0,
/// Tuesday.
Tue = 1,
/// Wednesday.
Wed = 2,
/// Thursday.
Thu = 3,
/// Friday.
Fri = 4,
/// Saturday.
Sat = 5,
/// Sunday.
Sun = 6,
}
impl Weekday {
/// The next day in the week.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
#[inline]
pub fn succ(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Tue,
Weekday::Tue => Weekday::Wed,
Weekday::Wed => Weekday::Thu,
Weekday::Thu => Weekday::Fri,
Weekday::Fri => Weekday::Sat,
Weekday::Sat => Weekday::Sun,
Weekday::Sun => Weekday::Mon,
}
}
/// The previous day in the week.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
#[inline]
pub fn pred(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Sun,
Weekday::Tue => Weekday::Mon,
Weekday::Wed => Weekday::Tue,
Weekday::Thu => Weekday::Wed,
Weekday::Fri => Weekday::Thu,
Weekday::Sat => Weekday::Fri,
Weekday::Sun => Weekday::Sat,
}
}
/// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
#[inline]
pub fn number_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 7,
}
}
/// Returns a day-of-week number starting from Sunday = 1.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
#[inline]
pub fn number_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 2,
Weekday::Tue => 3,
Weekday::Wed => 4,
Weekday::Thu => 5,
Weekday::Fri => 6,
Weekday::Sat => 7,
Weekday::Sun => 1,
}
}
/// Returns a day-of-week number starting from Monday = 0.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
#[inline]
pub fn num_days_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 0,
Weekday::Tue => 1,
Weekday::Wed => 2,
Weekday::Thu => 3,
Weekday::Fri => 4,
Weekday::Sat => 5,
Weekday::Sun => 6,
}
}
/// Returns a day-of-week number starting from Sunday = 0.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
#[inline]
pub fn num_days_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 0,
}
}
}
/// Any weekday can be represented as an integer from 0 to 6, which equals to
/// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
/// Do not heavily depend on this though; use explicit methods whenever possible.
impl num::traits::FromPrimitive for Weekday {
#[inline]
fn from_i64(n: i64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
#[inline]
fn from_u64(n: u64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
}
use std::fmt;
/// An error resulting from reading `Weekday` value with `FromStr`.
#[derive(Clone, PartialEq)]
pub struct ParseWeekdayError {
_dummy: (),
}
impl fmt::Debug for ParseWeekdayError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ParseWeekdayError {{ .. }}")
}
}
// the actual `FromStr` implementation is in the `format` module to leverage the existing code
#[cfg(feature = "serde")]
mod weekday_serde {
use super::Weekday;
use std::fmt;
use serdelib::{ser, de};
impl ser::Serialize for Weekday {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.serialize_str(&format!("{:?}", self))
}
}
struct WeekdayVisitor;
impl<'de> de::Visitor<'de> for WeekdayVisitor {
type Value = Weekday;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Weekday")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where E: de::Error
{
value.parse().map_err(|_| E::custom("short or long weekday names expected"))
}
}
impl<'de> de::Deserialize<'de> for Weekday {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: de::Deserializer<'de>
{
deserializer.deserialize_str(WeekdayVisitor)
}
}
#[cfg(test)]
extern crate serde_json;
#[test]
fn test_serde_serialize() {
use self::serde_json::to_string;
use Weekday::*;
let cases: Vec<(Weekday, &str)> = vec![
(Mon, "\"Mon\""),
(Tue, "\"Tue\""),
(Wed, "\"Wed\""),
(Thu, "\"Thu\""),
(Fri, "\"Fri\""),
(Sat, "\"Sat\""),
(Sun, "\"Sun\""),
];
for (weekday, expected_str) in cases {
let string = to_string(&weekday).unwrap();
assert_eq!(string, expected_str);
}
}
#[test]
fn test_serde_deserialize() {
use self::serde_json::from_str;
use Weekday::*;
let cases: Vec<(&str, Weekday)> = vec![
("\"mon\"", Mon),
("\"MONDAY\"", Mon),
("\"MonDay\"", Mon),
("\"mOn\"", Mon),
("\"tue\"", Tue),
("\"tuesday\"", Tue),
("\"wed\"", Wed),
("\"wednesday\"", Wed),
("\"thu\"", Thu),
("\"thursday\"", Thu),
("\"fri\"", Fri),
("\"friday\"", Fri),
("\"sat\"", Sat),
("\"saturday\"", Sat),
("\"sun\"", Sun),
("\"sunday\"", Sun),
];
for (str, expected_weekday) in cases {
let weekday = from_str::<Weekday>(str).unwrap();
assert_eq!(weekday, expected_weekday);
}
let errors: Vec<&str> = vec![
"\"not a weekday\"",
"\"monDAYs\"",
"\"mond\"",
"mon",
"\"thur\"",
"\"thurs\"",
];
for str in errors {
from_str::<Weekday>(str).unwrap_err();
}
}
}
/// The common set of methods for date component.
pub trait Datelike: Sized {
/// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
fn year(&self) -> i32;
/// Returns the absolute year number starting from 1 with a boolean flag,
/// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
#[inline]
fn year_ce(&self) -> (bool, u32) {
let year = self.year();
if year < 1 {
(false, (1 - year) as u32)
} else {
(true, year as u32)
}
}
/// Returns the month number starting from 1.
///
/// The return value ranges from 1 to 12.
fn month(&self) -> u32;
/// Returns the month number starting from 0.
///
/// The return value ranges from 0 to 11.
fn month0(&self) -> u32;
/// Returns the day of month starting from 1.
///
/// The return value ranges from 1 to 31. (The last day of month differs by months.)
fn day(&self) -> u32;
/// Returns the day of month starting from 0.
///
/// The return value ranges from 0 to 30. (The last day of month differs by months.)
fn day0(&self) -> u32;
/// Returns the day of year starting from 1.
///
/// The return value ranges from 1 to 366. (The last day of year differs by years.)
fn ordinal(&self) -> u32;
/// Returns the day of year starting from 0.
///
/// The return value ranges from 0 to 365. (The last day of year differs by years.)
fn ordinal0(&self) -> u32;
/// Returns the day of week.
fn weekday(&self) -> Weekday;
/// Returns the ISO week.
fn iso_week(&self) -> IsoWeek;
/// Makes a new value with the year number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_year(&self, year: i32) -> Option<Self>;
/// Makes a new value with the month number (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_month(&self, month: u32) -> Option<Self>;
/// Makes a new value with the month number (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_month0(&self, month0: u32) -> Option<Self>;
/// Makes a new value with the day of month (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_day(&self, day: u32) -> Option<Self>;
/// Makes a new value with the day of month (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_day0(&self, day0: u32) -> Option<Self>;
/// Makes a new value with the day of year (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
/// Makes a new value with the day of year (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
/// Returns the number of days since January 1, 1 (Day 1) in the proleptic Gregorian calendar.
fn num_days_from_ce(&self) -> i32 {
// we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
let mut year = self.year() - 1;
let mut ndays = 0;
if year < 0 {
let excess = 1 + (-year) / 400;
year += excess * 400;
ndays -= excess * 146097;
}
let div_100 = year / 100;
ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
ndays + self.ordinal() as i32
}
}
/// The common set of methods for time component.
pub trait Timelike: Sized {
/// Returns the hour number from 0 to 23.
fn hour(&self) -> u32;
/// Returns the hour number from 1 to 12 with a boolean flag,
/// which is false for AM and true for PM.
#[inline]
fn hour12(&self) -> (bool, u32) {
let hour = self.hour();
let mut hour12 = hour % 12;
if hour12 == 0 {
hour12 = 12;
}
(hour >= 12, hour12)
}
/// Returns the minute number from 0 to 59.
fn minute(&self) -> u32;
/// Returns the second number from 0 to 59.
fn second(&self) -> u32;
/// Returns the number of nanoseconds since the whole non-leap second.
/// The range from 1,000,000,000 to 1,999,999,999 represents
/// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
fn nanosecond(&self) -> u32;
/// Makes a new value with the hour number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_hour(&self, hour: u32) -> Option<Self>;
/// Makes a new value with the minute number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_minute(&self, min: u32) -> Option<Self>;
/// Makes a new value with the second number changed.
///
/// Returns `None` when the resulting value would be invalid.
/// As with the [`second`](#tymethod.second) method,
/// the input range is restricted to 0 through 59.
fn with_second(&self, sec: u32) -> Option<Self>;
/// Makes a new value with nanoseconds since the whole non-leap second changed.
///
/// Returns `None` when the resulting value would be invalid.
/// As with the [`nanosecond`](#tymethod.nanosecond) method,
/// the input range can exceed 1,000,000,000 for leap seconds.
fn with_nanosecond(&self, nano: u32) -> Option<Self>;
/// Returns the number of non-leap seconds past the last midnight.
#[inline]
fn num_seconds_from_midnight(&self) -> u32 {
self.hour() * 3600 + self.minute() * 60 + self.second()
}
}
#[test]
fn test_readme_doomsday() {
use num::iter::range_inclusive;
for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
// even months
let d4 = NaiveDate::from_ymd(y, 4, 4);
let d6 = NaiveDate::from_ymd(y, 6, 6);
let d8 = NaiveDate::from_ymd(y, 8, 8);
let d10 = NaiveDate::from_ymd(y, 10, 10);
let d12 = NaiveDate::from_ymd(y, 12, 12);
// nine to five, seven-eleven
let d59 = NaiveDate::from_ymd(y, 5, 9);
let d95 = NaiveDate::from_ymd(y, 9, 5);
let d711 = NaiveDate::from_ymd(y, 7, 11);
let d117 = NaiveDate::from_ymd(y, 11, 7);
// "March 0"
let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
let weekday = d30.weekday();
let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
assert!(other_dates.iter().all(|d| d.weekday() == weekday));
}
}
Added underscores on long numbers.
// This is a part of Chrono.
// See README.md and LICENSE.txt for details.
//! # Chrono 0.4.0
//!
//! Date and time handling for Rust.
//! It aims to be a feature-complete superset of
//! the [time](https://github.com/rust-lang-deprecated/time) library.
//! In particular,
//!
//! * Chrono strictly adheres to ISO 8601.
//! * Chrono is timezone-aware by default, with separate timezone-naive types.
//! * Chrono is space-optimal and (while not being the primary goal) reasonably efficient.
//!
//! There were several previous attempts to bring a good date and time library to Rust,
//! which Chrono builds upon and should acknowledge:
//!
//! * [Initial research on
//! the wiki](https://github.com/rust-lang/rust-wiki-backup/blob/master/Lib-datetime.md)
//! * Dietrich Epp's [datetime-rs](https://github.com/depp/datetime-rs)
//! * Luis de Bethencourt's [rust-datetime](https://github.com/luisbg/rust-datetime)
//!
//! Any significant changes to Chrono are documented in
//! the [`CHANGELOG.md`](https://github.com/chronotope/chrono/blob/master/CHANGELOG.md) file.
//!
//! ## Usage
//!
//! Put this in your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! chrono = "0.4"
//! ```
//!
//! Or, if you want [Serde](https://github.com/serde-rs/serde) or
//! [rustc-serialize](https://github.com/rust-lang-nursery/rustc-serialize) support,
//! include the features like this:
//!
//! ```toml
//! [dependencies]
//! chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
//! ```
//!
//! > Note that Chrono's support for rustc-serialize is now considered deprecated.
//! Starting from 0.4.0 there is no further guarantee that
//! the features available in Serde will be also available to rustc-serialize,
//! and the support can be removed in any future major version.
//! **Rustc-serialize users are strongly recommended to migrate to Serde.**
//!
//! Then put this in your crate root:
//!
//! ```rust
//! extern crate chrono;
//! ```
//!
//! Avoid using `use chrono::*;` as Chrono exports several modules other than types.
//! If you prefer the glob imports, use the following instead:
//!
//! ```rust
//! use chrono::prelude::*;
//! ```
//!
//! ## Overview
//!
//! ### Duration
//!
//! Chrono currently uses
//! the [`time::Duration`](https://doc.rust-lang.org/time/time/struct.Duration.html) type
//! from the `time` crate to represent the magnitude of a time span.
//! Since this has the same name to the newer, standard type for duration,
//! the reference will refer this type as `OldDuration`.
//! Note that this is an "accurate" duration represented as seconds and
//! nanoseconds and does not represent "nominal" components such as days or
//! months.
//!
//! Chrono does not yet natively support
//! the standard [`Duration`](https://doc.rust-lang.org/std/time/struct.Duration.html) type,
//! but it will be supported in the future.
//! Meanwhile you can convert between two types with
//! [`Duration::from_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.from_std)
//! and
//! [`Duration::to_std`](https://doc.rust-lang.org/time/time/struct.Duration.html#method.to_std)
//! methods.
//!
//! ### Date and Time
//!
//! Chrono provides a
//! [**`DateTime`**](./struct.DateTime.html)
//! type to represent a date and a time in a timezone.
//!
//! For more abstract moment-in-time tracking such as internal timekeeping
//! that is unconcerned with timezones, consider
//! [`time::SystemTime`](https://doc.rust-lang.org/std/time/struct.SystemTime.html),
//! which tracks your system clock, or
//! [`time::Instant`](https://doc.rust-lang.org/std/time/struct.Instant.html), which
//! is an opaque but monotonically-increasing representation of a moment in time.
//!
//! `DateTime` is timezone-aware and must be constructed from
//! the [**`TimeZone`**](./offset/trait.TimeZone.html) object,
//! which defines how the local date is converted to and back from the UTC date.
//! There are three well-known `TimeZone` implementations:
//!
//! * [**`Utc`**](./offset/struct.Utc.html) specifies the UTC time zone. It is most efficient.
//!
//! * [**`Local`**](./offset/struct.Local.html) specifies the system local time zone.
//!
//! * [**`FixedOffset`**](./offset/struct.FixedOffset.html) specifies
//! an arbitrary, fixed time zone such as UTC+09:00 or UTC-10:30.
//! This often results from the parsed textual date and time.
//! Since it stores the most information and does not depend on the system environment,
//! you would want to normalize other `TimeZone`s into this type.
//!
//! `DateTime`s with different `TimeZone` types are distinct and do not mix,
//! but can be converted to each other using
//! the [`DateTime::with_timezone`](./struct.DateTime.html#method.with_timezone) method.
//!
//! You can get the current date and time in the UTC time zone
//! ([`Utc::now()`](./offset/struct.Utc.html#method.now))
//! or in the local time zone
//! ([`Local::now()`](./offset/struct.Local.html#method.now)).
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`
//! let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`
//! # let _ = utc; let _ = local;
//! ```
//!
//! Alternatively, you can create your own date and time.
//! This is a bit verbose due to Rust's lack of function and method overloading,
//! but in turn we get a rich combination of initialization methods.
//!
//! ```rust
//! use chrono::prelude::*;
//! use chrono::offset::LocalResult;
//!
//! let dt = Utc.ymd(2014, 7, 8).and_hms(9, 10, 11); // `2014-07-08T09:10:11Z`
//! // July 8 is 188th day of the year 2014 (`o` for "ordinal")
//! assert_eq!(dt, Utc.yo(2014, 189).and_hms(9, 10, 11));
//! // July 8 is Tuesday in ISO week 28 of the year 2014.
//! assert_eq!(dt, Utc.isoywd(2014, 28, Weekday::Tue).and_hms(9, 10, 11));
//!
//! let dt = Utc.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12); // `2014-07-08T09:10:11.012Z`
//! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_micro(9, 10, 11, 12_000));
//! assert_eq!(dt, Utc.ymd(2014, 7, 8).and_hms_nano(9, 10, 11, 12_000_000));
//!
//! // dynamic verification
//! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(21, 15, 33),
//! LocalResult::Single(Utc.ymd(2014, 7, 8).and_hms(21, 15, 33)));
//! assert_eq!(Utc.ymd_opt(2014, 7, 8).and_hms_opt(80, 15, 33), LocalResult::None);
//! assert_eq!(Utc.ymd_opt(2014, 7, 38).and_hms_opt(21, 15, 33), LocalResult::None);
//!
//! // other time zone objects can be used to construct a local datetime.
//! // obviously, `local_dt` is normally different from `dt`, but `fixed_dt` should be identical.
//! let local_dt = Local.ymd(2014, 7, 8).and_hms_milli(9, 10, 11, 12);
//! let fixed_dt = FixedOffset::east(9 * 3600).ymd(2014, 7, 8).and_hms_milli(18, 10, 11, 12);
//! assert_eq!(dt, fixed_dt);
//! # let _ = local_dt;
//! ```
//!
//! Various properties are available to the date and time, and can be altered individually.
//! Most of them are defined in the traits [`Datelike`](./trait.Datelike.html) and
//! [`Timelike`](./trait.Timelike.html) which you should `use` before.
//! Addition and subtraction is also supported.
//! The following illustrates most supported operations to the date and time:
//!
//! ```rust
//! # extern crate chrono; extern crate time; fn main() {
//! use chrono::prelude::*;
//! use time::Duration;
//!
//! # /* we intentionally fake the datetime...
//! // assume this returned `2014-11-28T21:45:59.324310806+09:00`:
//! let dt = Local::now();
//! # */ // up to here. we now define a fixed datetime for the illustrative purpose.
//! # let dt = FixedOffset::east(9*3600).ymd(2014, 11, 28).and_hms_nano(21, 45, 59, 324310806);
//!
//! // property accessors
//! assert_eq!((dt.year(), dt.month(), dt.day()), (2014, 11, 28));
//! assert_eq!((dt.month0(), dt.day0()), (10, 27)); // for unfortunate souls
//! assert_eq!((dt.hour(), dt.minute(), dt.second()), (21, 45, 59));
//! assert_eq!(dt.weekday(), Weekday::Fri);
//! assert_eq!(dt.weekday().number_from_monday(), 5); // Mon=1, ..., Sat=7
//! assert_eq!(dt.ordinal(), 332); // the day of year
//! assert_eq!(dt.num_days_from_ce(), 735565); // the number of days from and including Jan 1, 1
//!
//! // time zone accessor and manipulation
//! assert_eq!(dt.offset().fix().local_minus_utc(), 9 * 3600);
//! assert_eq!(dt.timezone(), FixedOffset::east(9 * 3600));
//! assert_eq!(dt.with_timezone(&Utc), Utc.ymd(2014, 11, 28).and_hms_nano(12, 45, 59, 324310806));
//!
//! // a sample of property manipulations (validates dynamically)
//! assert_eq!(dt.with_day(29).unwrap().weekday(), Weekday::Sat); // 2014-11-29 is Saturday
//! assert_eq!(dt.with_day(32), None);
//! assert_eq!(dt.with_year(-300).unwrap().num_days_from_ce(), -109606); // November 29, 301 BCE
//!
//! // arithmetic operations
//! let dt1 = Utc.ymd(2014, 11, 14).and_hms(8, 9, 10);
//! let dt2 = Utc.ymd(2014, 11, 14).and_hms(10, 9, 8);
//! assert_eq!(dt1.signed_duration_since(dt2), Duration::seconds(-2 * 3600 + 2));
//! assert_eq!(dt2.signed_duration_since(dt1), Duration::seconds(2 * 3600 - 2));
//! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + Duration::seconds(1_000_000_000),
//! Utc.ymd(2001, 9, 9).and_hms(1, 46, 40));
//! assert_eq!(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) - Duration::seconds(1_000_000_000),
//! Utc.ymd(1938, 4, 24).and_hms(22, 13, 20));
//! # }
//! ```
//!
//! Formatting is done via the [`format`](./struct.DateTime.html#method.format) method,
//! which format is equivalent to the familiar `strftime` format.
//! (See the [`format::strftime` module documentation](./format/strftime/index.html#specifiers)
//! for full syntax.)
//!
//! The default `to_string` method and `{:?}` specifier also give a reasonable representation.
//! Chrono also provides [`to_rfc2822`](./struct.DateTime.html#method.to_rfc2822) and
//! [`to_rfc3339`](./struct.DateTime.html#method.to_rfc3339) methods
//! for well-known formats.
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
//! assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), "2014-11-28 12:00:09");
//! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), "Fri Nov 28 12:00:09 2014");
//! assert_eq!(dt.format("%a %b %e %T %Y").to_string(), dt.format("%c").to_string());
//!
//! assert_eq!(dt.to_string(), "2014-11-28 12:00:09 UTC");
//! assert_eq!(dt.to_rfc2822(), "Fri, 28 Nov 2014 12:00:09 +0000");
//! assert_eq!(dt.to_rfc3339(), "2014-11-28T12:00:09+00:00");
//! assert_eq!(format!("{:?}", dt), "2014-11-28T12:00:09Z");
//! ```
//!
//! Parsing can be done with three methods:
//!
//! 1. The standard [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) trait
//! (and [`parse`](https://doc.rust-lang.org/std/primitive.str.html#method.parse) method
//! on a string) can be used for parsing `DateTime<FixedOffset>`, `DateTime<Utc>` and
//! `DateTime<Local>` values. This parses what the `{:?}`
//! ([`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html))
//! format specifier prints, and requires the offset to be present.
//!
//! 2. [`DateTime::parse_from_str`](./struct.DateTime.html#method.parse_from_str) parses
//! a date and time with offsets and returns `DateTime<FixedOffset>`.
//! This should be used when the offset is a part of input and the caller cannot guess that.
//! It *cannot* be used when the offset can be missing.
//! [`DateTime::parse_from_rfc2822`](./struct.DateTime.html#method.parse_from_rfc2822)
//! and
//! [`DateTime::parse_from_rfc3339`](./struct.DateTime.html#method.parse_from_rfc3339)
//! are similar but for well-known formats.
//!
//! 3. [`Offset::datetime_from_str`](./offset/trait.TimeZone.html#method.datetime_from_str) is
//! similar but returns `DateTime` of given offset.
//! When the explicit offset is missing from the input, it simply uses given offset.
//! It issues an error when the input contains an explicit offset different
//! from the current offset.
//!
//! More detailed control over the parsing process is available via
//! [`format`](./format/index.html) module.
//!
//! ```rust
//! use chrono::prelude::*;
//!
//! let dt = Utc.ymd(2014, 11, 28).and_hms(12, 0, 9);
//! let fixed_dt = dt.with_timezone(&FixedOffset::east(9*3600));
//!
//! // method 1
//! assert_eq!("2014-11-28T12:00:09Z".parse::<DateTime<Utc>>(), Ok(dt.clone()));
//! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<Utc>>(), Ok(dt.clone()));
//! assert_eq!("2014-11-28T21:00:09+09:00".parse::<DateTime<FixedOffset>>(), Ok(fixed_dt.clone()));
//!
//! // method 2
//! assert_eq!(DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z"),
//! Ok(fixed_dt.clone()));
//! assert_eq!(DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900"),
//! Ok(fixed_dt.clone()));
//! assert_eq!(DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00"), Ok(fixed_dt.clone()));
//!
//! // method 3
//! assert_eq!(Utc.datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S"), Ok(dt.clone()));
//! assert_eq!(Utc.datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y"), Ok(dt.clone()));
//!
//! // oops, the year is missing!
//! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T %Y").is_err());
//! // oops, the format string does not include the year at all!
//! assert!(Utc.datetime_from_str("Fri Nov 28 12:00:09", "%a %b %e %T").is_err());
//! // oops, the weekday is incorrect!
//! assert!(Utc.datetime_from_str("Sat Nov 28 12:00:09 2014", "%a %b %e %T %Y").is_err());
//! ```
//!
//! ### Conversion from and to EPOCH timestamps
//!
//! Use [`Utc.timestamp(seconds, nanoseconds)`](./offset/trait.TimeZone.html#method.timestamp)
//! to construct a [`DateTime<Utc>`](./struct.DateTime.html) from a UNIX timestamp
//! (seconds, nanoseconds that passed since January 1st 1970).
//!
//! Use [`DateTime.timestamp`](./struct.DateTime.html#method.timestamp) to get the timestamp (in seconds)
//! from a [`DateTime`](./struct.DateTime.html). Additionally, you can use
//! [`DateTime.timestamp_subsec_nanos`](./struct.DateTime.html#method.timestamp_subsec_nanos)
//! to get the number of additional number of nanoseconds.
//!
//! ```rust
//! # use chrono::DateTime;
//! # use chrono::Utc;
//! // We need the trait in scope to use Utc::timestamp().
//! use chrono::TimeZone;
//!
//! // Construct a datetime from epoch:
//! let dt = Utc.timestamp(1_500_000_000, 0);
//! assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
//!
//! // Get epoch value from a datetime:
//! let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
//! assert_eq!(dt.timestamp(), 1_500_000_000);
//! ```
//!
//! ### Individual date
//!
//! Chrono also provides an individual date type ([**`Date`**](./struct.Date.html)).
//! It also has time zones attached, and have to be constructed via time zones.
//! Most operations available to `DateTime` are also available to `Date` whenever appropriate.
//!
//! ```rust
//! use chrono::prelude::*;
//! use chrono::offset::LocalResult;
//!
//! # // these *may* fail, but only very rarely. just rerun the test if you were that unfortunate ;)
//! assert_eq!(Utc::today(), Utc::now().date());
//! assert_eq!(Local::today(), Local::now().date());
//!
//! assert_eq!(Utc.ymd(2014, 11, 28).weekday(), Weekday::Fri);
//! assert_eq!(Utc.ymd_opt(2014, 11, 31), LocalResult::None);
//! assert_eq!(Utc.ymd(2014, 11, 28).and_hms_milli(7, 8, 9, 10).format("%H%M%S").to_string(),
//! "070809");
//! ```
//!
//! There is no timezone-aware `Time` due to the lack of usefulness and also the complexity.
//!
//! `DateTime` has [`date`](./struct.DateTime.html#method.date) method
//! which returns a `Date` which represents its date component.
//! There is also a [`time`](./struct.DateTime.html#method.time) method,
//! which simply returns a naive local time described below.
//!
//! ### Naive date and time
//!
//! Chrono provides naive counterparts to `Date`, (non-existent) `Time` and `DateTime`
//! as [**`NaiveDate`**](./naive/struct.NaiveDate.html),
//! [**`NaiveTime`**](./naive/struct.NaiveTime.html) and
//! [**`NaiveDateTime`**](./naive/struct.NaiveDateTime.html) respectively.
//!
//! They have almost equivalent interfaces as their timezone-aware twins,
//! but are not associated to time zones obviously and can be quite low-level.
//! They are mostly useful for building blocks for higher-level types.
//!
//! Timezone-aware `DateTime` and `Date` types have two methods returning naive versions:
//! [`naive_local`](./struct.DateTime.html#method.naive_local) returns
//! a view to the naive local time,
//! and [`naive_utc`](./struct.DateTime.html#method.naive_utc) returns
//! a view to the naive UTC time.
//!
//! ## Limitations
//!
//! Only proleptic Gregorian calendar (i.e. extended to support older dates) is supported.
//! Be very careful if you really have to deal with pre-20C dates, they can be in Julian or others.
//!
//! Date types are limited in about +/- 262,000 years from the common epoch.
//! Time types are limited in the nanosecond accuracy.
//!
//! [Leap seconds are supported in the representation but
//! Chrono doesn't try to make use of them](./naive/struct.NaiveTime.html#leap-second-handling).
//! (The main reason is that leap seconds are not really predictable.)
//! Almost *every* operation over the possible leap seconds will ignore them.
//! Consider using `NaiveDateTime` with the implicit TAI (International Atomic Time) scale
//! if you want.
//!
//! Chrono inherently does not support an inaccurate or partial date and time representation.
//! Any operation that can be ambiguous will return `None` in such cases.
//! For example, "a month later" of 2014-01-30 is not well-defined
//! and consequently `Utc.ymd(2014, 1, 30).with_month(2)` returns `None`.
//!
//! Advanced time zone handling is not yet supported.
//! For now you can try the [Chrono-tz](https://github.com/chronotope/chrono-tz/) crate instead.
#![doc(html_root_url = "https://docs.rs/chrono/0.4.0/")]
#![cfg_attr(bench, feature(test))] // lib stability features as per RFC #507
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
extern crate time as oldtime;
extern crate num;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature = "serde")]
extern crate serde as serdelib;
// this reexport is to aid the transition and should not be in the prelude!
pub use oldtime::Duration;
#[doc(no_inline)] pub use offset::{TimeZone, Offset, LocalResult, Utc, FixedOffset, Local};
#[doc(no_inline)] pub use naive::{NaiveDate, IsoWeek, NaiveTime, NaiveDateTime};
pub use date::{Date, MIN_DATE, MAX_DATE};
pub use datetime::DateTime;
#[cfg(feature = "rustc-serialize")] pub use datetime::rustc_serialize::TsSeconds;
pub use format::{ParseError, ParseResult};
/// A convenience module appropriate for glob imports (`use chrono::prelude::*;`).
pub mod prelude {
#[doc(no_inline)] pub use {Datelike, Timelike, Weekday};
#[doc(no_inline)] pub use {TimeZone, Offset};
#[doc(no_inline)] pub use {Utc, FixedOffset, Local};
#[doc(no_inline)] pub use {NaiveDate, NaiveTime, NaiveDateTime};
#[doc(no_inline)] pub use Date;
#[doc(no_inline)] pub use DateTime;
}
// useful throughout the codebase
macro_rules! try_opt {
($e:expr) => (match $e { Some(v) => v, None => return None })
}
mod div;
pub mod offset;
pub mod naive {
//! Date and time types which do not concern about the timezones.
//!
//! They are primarily building blocks for other types
//! (e.g. [`TimeZone`](../offset/trait.TimeZone.html)),
//! but can be also used for the simpler date and time handling.
mod internals;
mod date;
mod isoweek;
mod time;
mod datetime;
pub use self::date::{NaiveDate, MIN_DATE, MAX_DATE};
pub use self::isoweek::IsoWeek;
pub use self::time::NaiveTime;
pub use self::datetime::NaiveDateTime;
#[cfg(feature = "rustc-serialize")]
pub use self::datetime::rustc_serialize::TsSeconds;
/// Serialization/Deserialization of naive types in alternate formats
///
/// The various modules in here are intended to be used with serde's [`with`
/// annotation][1] to serialize as something other than the default [RFC
/// 3339][2] format.
///
/// [1]: https://serde.rs/attributes.html#field-attributes
/// [2]: https://tools.ietf.org/html/rfc3339
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
}
mod date;
mod datetime;
pub mod format;
/// Serialization/Deserialization in alternate formats
///
/// The various modules in here are intended to be used with serde's [`with`
/// annotation][1] to serialize as something other than the default [RFC
/// 3339][2] format.
///
/// [1]: https://serde.rs/attributes.html#field-attributes
/// [2]: https://tools.ietf.org/html/rfc3339
#[cfg(feature = "serde")]
pub mod serde {
pub use super::datetime::serde::*;
}
/// The day of week.
///
/// The order of the days of week depends on the context.
/// (This is why this type does *not* implement `PartialOrd` or `Ord` traits.)
/// One should prefer `*_from_monday` or `*_from_sunday` methods to get the correct result.
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum Weekday {
/// Monday.
Mon = 0,
/// Tuesday.
Tue = 1,
/// Wednesday.
Wed = 2,
/// Thursday.
Thu = 3,
/// Friday.
Fri = 4,
/// Saturday.
Sat = 5,
/// Sunday.
Sun = 6,
}
impl Weekday {
/// The next day in the week.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.succ()`: | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun` | `Mon`
#[inline]
pub fn succ(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Tue,
Weekday::Tue => Weekday::Wed,
Weekday::Wed => Weekday::Thu,
Weekday::Thu => Weekday::Fri,
Weekday::Fri => Weekday::Sat,
Weekday::Sat => Weekday::Sun,
Weekday::Sun => Weekday::Mon,
}
}
/// The previous day in the week.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ----------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.pred()`: | `Sun` | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat`
#[inline]
pub fn pred(&self) -> Weekday {
match *self {
Weekday::Mon => Weekday::Sun,
Weekday::Tue => Weekday::Mon,
Weekday::Wed => Weekday::Tue,
Weekday::Thu => Weekday::Wed,
Weekday::Fri => Weekday::Thu,
Weekday::Sat => Weekday::Fri,
Weekday::Sun => Weekday::Sat,
}
}
/// Returns a day-of-week number starting from Monday = 1. (ISO 8601 weekday number)
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.number_from_monday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 7
#[inline]
pub fn number_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 7,
}
}
/// Returns a day-of-week number starting from Sunday = 1.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// ------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.number_from_sunday()`: | 2 | 3 | 4 | 5 | 6 | 7 | 1
#[inline]
pub fn number_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 2,
Weekday::Tue => 3,
Weekday::Wed => 4,
Weekday::Thu => 5,
Weekday::Fri => 6,
Weekday::Sat => 7,
Weekday::Sun => 1,
}
}
/// Returns a day-of-week number starting from Monday = 0.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.num_days_from_monday()`: | 0 | 1 | 2 | 3 | 4 | 5 | 6
#[inline]
pub fn num_days_from_monday(&self) -> u32 {
match *self {
Weekday::Mon => 0,
Weekday::Tue => 1,
Weekday::Wed => 2,
Weekday::Thu => 3,
Weekday::Fri => 4,
Weekday::Sat => 5,
Weekday::Sun => 6,
}
}
/// Returns a day-of-week number starting from Sunday = 0.
///
/// `w`: | `Mon` | `Tue` | `Wed` | `Thu` | `Fri` | `Sat` | `Sun`
/// --------------------------- | ----- | ----- | ----- | ----- | ----- | ----- | -----
/// `w.num_days_from_sunday()`: | 1 | 2 | 3 | 4 | 5 | 6 | 0
#[inline]
pub fn num_days_from_sunday(&self) -> u32 {
match *self {
Weekday::Mon => 1,
Weekday::Tue => 2,
Weekday::Wed => 3,
Weekday::Thu => 4,
Weekday::Fri => 5,
Weekday::Sat => 6,
Weekday::Sun => 0,
}
}
}
/// Any weekday can be represented as an integer from 0 to 6, which equals to
/// [`Weekday::num_days_from_monday`](#method.num_days_from_monday) in this implementation.
/// Do not heavily depend on this though; use explicit methods whenever possible.
impl num::traits::FromPrimitive for Weekday {
#[inline]
fn from_i64(n: i64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
#[inline]
fn from_u64(n: u64) -> Option<Weekday> {
match n {
0 => Some(Weekday::Mon),
1 => Some(Weekday::Tue),
2 => Some(Weekday::Wed),
3 => Some(Weekday::Thu),
4 => Some(Weekday::Fri),
5 => Some(Weekday::Sat),
6 => Some(Weekday::Sun),
_ => None,
}
}
}
use std::fmt;
/// An error resulting from reading `Weekday` value with `FromStr`.
#[derive(Clone, PartialEq)]
pub struct ParseWeekdayError {
_dummy: (),
}
impl fmt::Debug for ParseWeekdayError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ParseWeekdayError {{ .. }}")
}
}
// the actual `FromStr` implementation is in the `format` module to leverage the existing code
#[cfg(feature = "serde")]
mod weekday_serde {
use super::Weekday;
use std::fmt;
use serdelib::{ser, de};
impl ser::Serialize for Weekday {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer
{
serializer.serialize_str(&format!("{:?}", self))
}
}
struct WeekdayVisitor;
impl<'de> de::Visitor<'de> for WeekdayVisitor {
type Value = Weekday;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Weekday")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where E: de::Error
{
value.parse().map_err(|_| E::custom("short or long weekday names expected"))
}
}
impl<'de> de::Deserialize<'de> for Weekday {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: de::Deserializer<'de>
{
deserializer.deserialize_str(WeekdayVisitor)
}
}
#[cfg(test)]
extern crate serde_json;
#[test]
fn test_serde_serialize() {
use self::serde_json::to_string;
use Weekday::*;
let cases: Vec<(Weekday, &str)> = vec![
(Mon, "\"Mon\""),
(Tue, "\"Tue\""),
(Wed, "\"Wed\""),
(Thu, "\"Thu\""),
(Fri, "\"Fri\""),
(Sat, "\"Sat\""),
(Sun, "\"Sun\""),
];
for (weekday, expected_str) in cases {
let string = to_string(&weekday).unwrap();
assert_eq!(string, expected_str);
}
}
#[test]
fn test_serde_deserialize() {
use self::serde_json::from_str;
use Weekday::*;
let cases: Vec<(&str, Weekday)> = vec![
("\"mon\"", Mon),
("\"MONDAY\"", Mon),
("\"MonDay\"", Mon),
("\"mOn\"", Mon),
("\"tue\"", Tue),
("\"tuesday\"", Tue),
("\"wed\"", Wed),
("\"wednesday\"", Wed),
("\"thu\"", Thu),
("\"thursday\"", Thu),
("\"fri\"", Fri),
("\"friday\"", Fri),
("\"sat\"", Sat),
("\"saturday\"", Sat),
("\"sun\"", Sun),
("\"sunday\"", Sun),
];
for (str, expected_weekday) in cases {
let weekday = from_str::<Weekday>(str).unwrap();
assert_eq!(weekday, expected_weekday);
}
let errors: Vec<&str> = vec![
"\"not a weekday\"",
"\"monDAYs\"",
"\"mond\"",
"mon",
"\"thur\"",
"\"thurs\"",
];
for str in errors {
from_str::<Weekday>(str).unwrap_err();
}
}
}
/// The common set of methods for date component.
pub trait Datelike: Sized {
/// Returns the year number in the [calendar date](./naive/struct.NaiveDate.html#calendar-date).
fn year(&self) -> i32;
/// Returns the absolute year number starting from 1 with a boolean flag,
/// which is false when the year predates the epoch (BCE/BC) and true otherwise (CE/AD).
#[inline]
fn year_ce(&self) -> (bool, u32) {
let year = self.year();
if year < 1 {
(false, (1 - year) as u32)
} else {
(true, year as u32)
}
}
/// Returns the month number starting from 1.
///
/// The return value ranges from 1 to 12.
fn month(&self) -> u32;
/// Returns the month number starting from 0.
///
/// The return value ranges from 0 to 11.
fn month0(&self) -> u32;
/// Returns the day of month starting from 1.
///
/// The return value ranges from 1 to 31. (The last day of month differs by months.)
fn day(&self) -> u32;
/// Returns the day of month starting from 0.
///
/// The return value ranges from 0 to 30. (The last day of month differs by months.)
fn day0(&self) -> u32;
/// Returns the day of year starting from 1.
///
/// The return value ranges from 1 to 366. (The last day of year differs by years.)
fn ordinal(&self) -> u32;
/// Returns the day of year starting from 0.
///
/// The return value ranges from 0 to 365. (The last day of year differs by years.)
fn ordinal0(&self) -> u32;
/// Returns the day of week.
fn weekday(&self) -> Weekday;
/// Returns the ISO week.
fn iso_week(&self) -> IsoWeek;
/// Makes a new value with the year number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_year(&self, year: i32) -> Option<Self>;
/// Makes a new value with the month number (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_month(&self, month: u32) -> Option<Self>;
/// Makes a new value with the month number (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_month0(&self, month0: u32) -> Option<Self>;
/// Makes a new value with the day of month (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_day(&self, day: u32) -> Option<Self>;
/// Makes a new value with the day of month (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_day0(&self, day0: u32) -> Option<Self>;
/// Makes a new value with the day of year (starting from 1) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_ordinal(&self, ordinal: u32) -> Option<Self>;
/// Makes a new value with the day of year (starting from 0) changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_ordinal0(&self, ordinal0: u32) -> Option<Self>;
/// Returns the number of days since January 1, 1 (Day 1) in the proleptic Gregorian calendar.
fn num_days_from_ce(&self) -> i32 {
// we know this wouldn't overflow since year is limited to 1/2^13 of i32's full range.
let mut year = self.year() - 1;
let mut ndays = 0;
if year < 0 {
let excess = 1 + (-year) / 400;
year += excess * 400;
ndays -= excess * 146097;
}
let div_100 = year / 100;
ndays += ((year * 1461) >> 2) - div_100 + (div_100 >> 2);
ndays + self.ordinal() as i32
}
}
/// The common set of methods for time component.
pub trait Timelike: Sized {
/// Returns the hour number from 0 to 23.
fn hour(&self) -> u32;
/// Returns the hour number from 1 to 12 with a boolean flag,
/// which is false for AM and true for PM.
#[inline]
fn hour12(&self) -> (bool, u32) {
let hour = self.hour();
let mut hour12 = hour % 12;
if hour12 == 0 {
hour12 = 12;
}
(hour >= 12, hour12)
}
/// Returns the minute number from 0 to 59.
fn minute(&self) -> u32;
/// Returns the second number from 0 to 59.
fn second(&self) -> u32;
/// Returns the number of nanoseconds since the whole non-leap second.
/// The range from 1,000,000,000 to 1,999,999,999 represents
/// the [leap second](./naive/struct.NaiveTime.html#leap-second-handling).
fn nanosecond(&self) -> u32;
/// Makes a new value with the hour number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_hour(&self, hour: u32) -> Option<Self>;
/// Makes a new value with the minute number changed.
///
/// Returns `None` when the resulting value would be invalid.
fn with_minute(&self, min: u32) -> Option<Self>;
/// Makes a new value with the second number changed.
///
/// Returns `None` when the resulting value would be invalid.
/// As with the [`second`](#tymethod.second) method,
/// the input range is restricted to 0 through 59.
fn with_second(&self, sec: u32) -> Option<Self>;
/// Makes a new value with nanoseconds since the whole non-leap second changed.
///
/// Returns `None` when the resulting value would be invalid.
/// As with the [`nanosecond`](#tymethod.nanosecond) method,
/// the input range can exceed 1,000,000,000 for leap seconds.
fn with_nanosecond(&self, nano: u32) -> Option<Self>;
/// Returns the number of non-leap seconds past the last midnight.
#[inline]
fn num_seconds_from_midnight(&self) -> u32 {
self.hour() * 3600 + self.minute() * 60 + self.second()
}
}
#[test]
fn test_readme_doomsday() {
use num::iter::range_inclusive;
for y in range_inclusive(naive::MIN_DATE.year(), naive::MAX_DATE.year()) {
// even months
let d4 = NaiveDate::from_ymd(y, 4, 4);
let d6 = NaiveDate::from_ymd(y, 6, 6);
let d8 = NaiveDate::from_ymd(y, 8, 8);
let d10 = NaiveDate::from_ymd(y, 10, 10);
let d12 = NaiveDate::from_ymd(y, 12, 12);
// nine to five, seven-eleven
let d59 = NaiveDate::from_ymd(y, 5, 9);
let d95 = NaiveDate::from_ymd(y, 9, 5);
let d711 = NaiveDate::from_ymd(y, 7, 11);
let d117 = NaiveDate::from_ymd(y, 11, 7);
// "March 0"
let d30 = NaiveDate::from_ymd(y, 3, 1).pred();
let weekday = d30.weekday();
let other_dates = [d4, d6, d8, d10, d12, d59, d95, d711, d117];
assert!(other_dates.iter().all(|d| d.weekday() == weekday));
}
}
|
//! A cross-platform library for running child processes and building
//! pipelines.
//!
//! `duct` wants to make shelling out in Rust as easy and flexible as it is in
//! Bash. It takes care of [gotchas and
//! inconsistencies](https://github.com/oconnor663/duct.py/blob/master/spec.md)
//! in the way different platforms shell out. And it's a cross-language library;
//! the [original implementation](https://github.com/oconnor663/duct.py) is in
//! Python, with an identical API.
//!
//! - [Docs](https://docs.rs/duct)
//! - [Crate](https://crates.io/crates/duct)
//! - [Repo](https://github.com/oconnor663/duct.rs)
//!
//! # Example
//!
//! `duct` tries to be as concise as possible, so that you don't wish you were
//! back writing shell scripts. At the same time, it's explicit about what
//! happens to output, and strict about error codes in child processes.
//!
//! ```rust,no_run
//! #[macro_use]
//! extern crate duct;
//!
//! use duct::{cmd, sh};
//!
//! fn main() {
//! // Read the name of the current git branch. If git exits with an error
//! // code here (because we're not in a git repo, for example), `read` will
//! // return an error too. `sh` commands run under the real system shell,
//! // /bin/sh on Unix or cmd.exe on Windows.
//! let current_branch = sh("git symbolic-ref --short HEAD").read().unwrap();
//!
//! // Log the current branch, with git taking over the terminal as usual.
//! // `cmd!` commands are spawned directly, without going through the
//! // shell, so there aren't any escaping issues with variable arguments.
//! cmd!("git", "log", current_branch).run().unwrap();
//!
//! // More complicated expressions become trees. Here's a pipeline with two
//! // child processes on the left, just because we can. In Bash this would
//! // be: stdout=$((echo -n part one "" && echo part two) | sed s/p/sm/g)
//! let part_one = &["-n", "part", "one", ""];
//! let stdout = cmd("echo", part_one)
//! .then(sh("echo part two"))
//! .pipe(cmd!("sed", "s/p/sm/g"))
//! .read()
//! .unwrap();
//! assert_eq!("smart one smart two", stdout);
//! }
//! ```
//!
//! `duct` uses [`os_pipe`](https://github.com/oconnor663/os_pipe.rs)
//! internally, and the docs for that one include a [big
//! example](https://docs.rs/os_pipe#example) that takes a dozen lines of code
//! to read both stdout and stderr from a child process. `duct` can do that in
//! one line:
//!
//! ```rust
//! use duct::sh;
//!
//! // This works on Windows too!
//! let output = sh("echo foo && echo bar >&2").stderr_to_stdout().read().unwrap();
//!
//! assert!(output.split_whitespace().eq(vec!["foo", "bar"]));
//! ```
extern crate lazycell;
use lazycell::AtomicLazyCell;
// Two utility crates build mainly to work for duct.
extern crate os_pipe;
extern crate shared_child;
use os_pipe::FromFile;
use shared_child::SharedChild;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio, Output, ExitStatus};
use std::thread::JoinHandle;
use std::sync::{Arc, Mutex};
// enums defined below
use ExpressionInner::*;
use IoExpressionInner::*;
/// Create a command given a program name and a collection of arguments. See
/// also the [`cmd!`](macro.cmd.html) macro, which doesn't require a collection.
///
/// # Example
///
/// ```
/// use duct::cmd;
///
/// let args = vec!["foo", "bar", "baz"];
///
/// # // NOTE: Normally this wouldn't work on Windows, but we have an "echo"
/// # // binary that gets built for our main tests, and it's sitting around by
/// # // the time we get here. If this ever stops working, then we can disable
/// # // the tests that depend on it.
/// let output = cmd("echo", &args).read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn cmd<T, U, V>(program: T, args: U) -> Expression
where T: ToExecutable,
U: IntoIterator<Item = V>,
V: Into<OsString>
{
let mut argv_vec = Vec::new();
argv_vec.push(program.to_executable());
argv_vec.extend(args.into_iter().map(Into::<OsString>::into));
Expression::new(Cmd(argv_vec))
}
/// Create a command with any number of of positional arguments, which may be
/// different types (anything that implements
/// [`Into<OsString>`](https://doc.rust-lang.org/std/convert/trait.From.html)).
/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of
/// arguments.
///
/// # Example
///
/// ```
/// #[macro_use]
/// extern crate duct;
/// use std::path::Path;
///
/// fn main() {
/// let arg1 = "foo";
/// let arg2 = "bar".to_owned();
/// let arg3 = Path::new("baz");
///
/// let output = cmd!("echo", arg1, arg2, arg3).read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// }
/// ```
#[macro_export]
macro_rules! cmd {
( $program:expr ) => {
{
use std::ffi::OsString;
use std::iter::empty;
$crate::cmd($program, empty::<OsString>())
}
};
( $program:expr $(, $arg:expr )* ) => {
{
use std::ffi::OsString;
let mut args: Vec<OsString> = Vec::new();
$(
args.push(Into::<OsString>::into($arg));
)*
$crate::cmd($program, args)
}
};
}
/// Create a command from a string of shell code.
///
/// This invokes the operating system's shell to execute the string:
/// `/bin/sh` on Unix-like systems and `cmd.exe` on Windows. This can be
/// very convenient sometimes, especially in small scripts and examples.
/// You don't need to quote each argument, and all the operators like
/// `|` and `>` work as usual.
///
/// However, building shell commands at runtime brings up tricky whitespace and
/// escaping issues, so avoid using `sh` and `format!` together. Prefer
/// [`cmd!`](macro.cmd.html) instead in those cases. Also note that shell
/// commands don't tend to be portable between Unix and Windows.
///
/// # Example
///
/// ```
/// use duct::sh;
///
/// let output = sh("echo foo bar baz").read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn sh<T: ToExecutable>(command: T) -> Expression {
Expression::new(Sh(command.to_executable()))
}
/// The central objects in `duct`, Expressions are created with
/// [`cmd`](fn.cmd.html), [`cmd!`](macro.cmd.html), or [`sh`](fn.sh.html), then
/// combined with [`pipe`](struct.Expression.html#method.pipe) or
/// [`then`](struct.Expression.html#method.then), and finally executed with
/// [`start`](struct.Expression.html#method.start),
/// [`run`](struct.Expression.html#method.run), or
/// [`read`](struct.Expression.html#method.read). They also support several
/// methods to control their execution, like
/// [`input`](struct.Expression.html#method.input),
/// [`env`](struct.Expression.html#method.env), and
/// [`unchecked`](struct.Expression.html#method.unchecked). Expressions are
/// immutable, and they do a lot of
/// [`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) sharing
/// internally, so all of these methods take `&self` and return a new
/// `Expression` cheaply.
#[derive(Clone, Debug)]
#[must_use]
pub struct Expression(Arc<ExpressionInner>);
impl Expression {
/// Execute an expression, wait for it to complete, and return a
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object containing the results. Nothing is captured by default, but if
/// you build the expression with
/// [`stdout_capture`](struct.Expression.html#method.stdout_capture) or
/// [`stderr_capture`](struct.Expression.html#method.stderr_capture) then
/// the `Output` will hold those captured bytes.
///
/// # Errors
///
/// In addition to all the IO errors possible with
/// [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html),
/// `run` will return an
/// [`ErrorKind::Other`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html)
/// IO error if child returns a non-zero exit status. To suppress this error
/// and return an `Output` even when the exit status is non-zero, use the
/// [`unchecked`](struct.Expression.html#method.unchecked) method.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").stdout_capture().run().unwrap();
/// assert_eq!(b"hi\n".to_vec(), output.stdout);
/// # }
/// # }
/// ```
pub fn run(&self) -> io::Result<Output> {
self.start()?.output()
}
/// Execute an expression, capture its standard output, and return the
/// captured output as a `String`. This is a convenience wrapper around
/// [`run`](struct.Expression.html#method.run). Like backticks and `$()` in
/// the shell, `read` trims trailing newlines.
///
/// # Errors
///
/// In addition to all the errors possible with
/// [`run`](struct.Expression.html#method.run), `read` will return an
/// [`ErrorKind::InvalidData`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html)
/// IO error if the captured bytes aren't valid UTF-8.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").stdout_capture().read().unwrap();
/// assert_eq!("hi", output);
/// # }
/// # }
/// ```
pub fn read(&self) -> io::Result<String> {
let output = self.stdout_capture().run()?;
if let Ok(output_str) = std::str::from_utf8(&output.stdout) {
Ok(trim_right_newlines(output_str).to_owned())
} else {
Err(io::Error::new(io::ErrorKind::InvalidData, "stdout is not valid UTF-8"))
}
}
/// Start running an expression, and immediately return a
/// [`Handle`](struct.Handle.html) that represents all the child processes.
/// This is analogous to the
/// [`spawn`](https://doc.rust-lang.org/std/process/struct.Command.html#method.spawn)
/// method in the standard library. The `Handle` may be shared between
/// multiple threads.
///
/// # Errors
///
/// In addition to all the errors prossible with
/// [`std::process::Command::spawn`](https://doc.rust-lang.org/std/process/struct.Command.html#method.spawn),
/// `start` can return errors from opening pipes and files. However, `start`
/// will never return an error if a child process has already started. In
/// particular, if the left side of a pipe expression starts successfully,
/// `start` will always return `Ok`. Any errors that happen on the right
/// side will be saved and returned later by the wait methods. That makes it
/// safe for callers to short circuit on `start` errors without the risk of
/// leaking processes.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let handle = cmd!("echo", "hi").stdout_capture().start().unwrap();
/// let output = handle.wait().unwrap();
/// assert_eq!(b"hi\n".to_vec(), output.stdout);
/// # }
/// # }
/// ```
pub fn start(&self) -> io::Result<Handle> {
// TODO: SUBSTANTIAL COMMENTS ABOUT ERROR BEHAVIOR
let (context, stdout_reader, stderr_reader) = IoContext::new()?;
Ok(Handle {
inner: self.0.start(context)?,
result: AtomicLazyCell::new(),
readers: Mutex::new(Some((stdout_reader, stderr_reader))),
})
}
/// Join two expressions into a pipe, with the standard output of the left
/// hooked up to the standard input of the right, like `|` in the shell. If
/// either side of the pipe returns a non-zero exit status, that becomes the
/// status of the whole pipe, similar to Bash's `pipefail` option. If both
/// sides return non-zero, and one of them is
/// [`unchecked`](struct.Expression.html#method.unchecked), then the checked
/// side wins. Otherwise the right side wins.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").pipe(cmd!("sed", "s/h/p/")).read();
/// assert_eq!("pi", output.unwrap());
/// # }
/// # }
/// ```
pub fn pipe(&self, right: Expression) -> Expression {
Self::new(Pipe(self.clone(), right.clone()))
}
/// Chain two expressions together to run in series, like `&&` in the shell.
/// If the left child returns a non-zero exit status, the right child
/// doesn't run. You can use
/// [`unchecked`](struct.Expression.html#method.unchecked) on the left child
/// to make sure the right child always runs. The exit status of this
/// expression is the status of the last child that ran. Note that
/// [`kill`](struct.Handle.html#method.kill) will prevent the right side
/// from starting if it hasn't already, even if the left side is
/// `unchecked`.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # use duct::sh;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Both echoes share the same stdout, so both go through `sed`.
/// # // NOTE: The shell's builtin echo doesn't support -n on OSX.
/// let output = cmd!("echo", "-n", "bar")
/// .then(sh("echo baz"))
/// .pipe(sh("sed s/b/f/g")).read();
/// assert_eq!("farfaz", output.unwrap());
/// # }
/// # }
/// ```
pub fn then(&self, right: Expression) -> Expression {
Self::new(Then(self.clone(), right.clone()))
}
/// Use bytes or a string as input for an expression, like `<<<` in the
/// shell. A worker thread will be spawned at runtime to write this input.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Many types implement Into<Vec<u8>>. Here's a string.
/// let output = cmd!("cat").input("foo").read().unwrap();
/// assert_eq!("foo", output);
///
/// // And here's a byte slice.
/// let output = cmd!("cat").input(&b"foo"[..]).read().unwrap();
/// assert_eq!("foo", output);
/// # }
/// # }
/// ```
pub fn input<T: Into<Vec<u8>>>(&self, input: T) -> Self {
Self::new(Io(Input(Arc::new(input.into())), self.clone()))
}
/// Open a file at the given path and use it as input for an expression, like
/// `<` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let output = sh("head -c 3").stdin("/dev/zero").read().unwrap();
/// assert_eq!("\0\0\0", output);
/// # }
/// ```
pub fn stdin<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stdin(path.into()), self.clone()))
}
/// Use an already opened file as input for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let input_file = std::fs::File::open("/dev/zero").unwrap();
/// let output = sh("head -c 3").stdin_file(input_file).read().unwrap();
/// assert_eq!("\0\0\0", output);
/// # }
/// ```
pub fn stdin_file(&self, file: File) -> Self {
Self::new(Io(StdinFile(file), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as input for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("cat").stdin_null().read().unwrap();
/// assert_eq!("", output);
/// # }
/// # }
/// ```
pub fn stdin_null(&self) -> Self {
Self::new(Io(StdinNull, self.clone()))
}
/// Open a file at the given path and use it as output for an expression,
/// like `>` in the shell.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let path = cmd!("mktemp").read().unwrap();
/// sh("echo wee").stdout(&path).run().unwrap();
/// let mut output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut output).unwrap();
/// assert_eq!("wee\n", output);
/// # }
/// # }
/// ```
pub fn stdout<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stdout(path.into()), self.clone()))
}
/// Use an already opened file as output for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// let path = cmd!("mktemp").read().unwrap();
/// let file = std::fs::File::create(&path).unwrap();
/// sh("echo wee").stdout_file(file).run().unwrap();
/// let mut output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut output).unwrap();
/// assert_eq!("wee\n", output);
/// # }
/// # }
/// ```
pub fn stdout_file(&self, file: File) -> Self {
Self::new(Io(StdoutFile(file), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as output for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// // This echo command won't print anything.
/// sh("echo foo bar baz").stdout_null().run().unwrap();
///
/// // And you won't get anything even if you try to read its output! The
/// // null redirect happens farther down in the expression tree than the
/// // implicit `stdout_capture`, and so it takes precedence.
/// let output = sh("echo foo bar baz").stdout_null().read().unwrap();
/// assert_eq!("", output);
/// ```
pub fn stdout_null(&self) -> Self {
Self::new(Io(StdoutNull, self.clone()))
}
/// Capture the standard output of an expression. The captured bytes will be
/// available on the `stdout` field of the
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object returned by [`run`](struct.Expression.html#method.run) or
/// [`wait`](struct.Handle.html#method.wait). In the simplest cases,
/// [`read`](struct.Expression.html#method.read) can be more convenient.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// // The most direct way to read stdout bytes is `stdout_capture`.
/// let output1 = sh("echo foo").stdout_capture().run().unwrap().stdout;
/// assert_eq!(&b"foo\n"[..], &output1[..]);
///
/// // The `read` method is a shorthand for `stdout_capture`, and it also
/// // does string parsing and newline trimming.
/// let output2 = sh("echo foo").read().unwrap();
/// assert_eq!("foo", output2)
/// # }
/// ```
pub fn stdout_capture(&self) -> Self {
Self::new(Io(StdoutCapture, self.clone()))
}
/// Join the standard output of an expression to its standard error pipe,
/// similar to `1>&2` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output = sh("echo foo").stdout_to_stderr().stderr_capture().run().unwrap();
/// assert_eq!(&b"foo\n"[..], &output.stderr[..]);
/// # }
/// ```
pub fn stdout_to_stderr(&self) -> Self {
Self::new(Io(StdoutToStderr, self.clone()))
}
/// Open a file at the given path and use it as error output for an
/// expression, like `2>` in the shell.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let path = cmd!("mktemp").read().unwrap();
/// sh("echo wee >&2").stderr(&path).run().unwrap();
/// let mut error_output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut error_output).unwrap();
/// assert_eq!("wee\n", error_output);
/// # }
/// # }
/// ```
pub fn stderr<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stderr(path.into()), self.clone()))
}
/// Use an already opened file as error output for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// let path = cmd!("mktemp").read().unwrap();
/// let file = std::fs::File::create(&path).unwrap();
/// sh("echo wee >&2").stderr_file(file).run().unwrap();
/// let mut error_output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut error_output).unwrap();
/// assert_eq!("wee\n", error_output);
/// # }
/// # }
/// ```
pub fn stderr_file(&self, file: File) -> Self {
Self::new(Io(StderrFile(file.into()), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as error output for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// // This echo-to-stderr command won't print anything.
/// sh("echo foo bar baz >&2").stderr_null().run().unwrap();
/// ```
pub fn stderr_null(&self) -> Self {
Self::new(Io(StderrNull, self.clone()))
}
/// Capture the error output of an expression. The captured bytes will be
/// available on the `stderr` field of the `Output` object returned by
/// [`run`](struct.Expression.html#method.run) or
/// [`wait`](struct.Handle.html#method.wait).
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output_obj = sh("echo foo >&2").stderr_capture().run().unwrap();
/// assert_eq!(&b"foo\n"[..], &output_obj.stderr[..]);
/// # }
/// ```
pub fn stderr_capture(&self) -> Self {
Self::new(Io(StderrCapture, self.clone()))
}
/// Join the standard error of an expression to its standard output pipe,
/// similar to `2>&1` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let error_output = sh("echo foo >&2").stderr_to_stdout().read().unwrap();
/// assert_eq!("foo", error_output);
/// # }
/// ```
pub fn stderr_to_stdout(&self) -> Self {
Self::new(Io(StderrToStdout, self.clone()))
}
/// Set the working directory where the expression will execute.
///
/// Note that in some languages (Rust and Python at least), there are tricky
/// platform differences in the way relative exe paths interact with child
/// working directories. In particular, the exe path will be interpreted
/// relative to the child dir on Unix, but relative to the parent dir on
/// Windows. `duct` considers the Windows behavior correct, so in order to
/// get that behavior consistently it calls
/// [`std::fs::canonicalize`](https://doc.rust-lang.org/std/fs/fn.canonicalize.html)
/// on relative exe paths when `dir` is in use. Paths in this sense are any
/// program name containing a path separator, regardless of the type. (Note
/// also that `Path` and `PathBuf` program names get a `./` prepended to
/// them automatically by the [`ToExecutable`](trait.ToExecutable.html)
/// trait, and so will always contain a separator.)
///
/// # Errors
///
/// Canonicalization can fail on some filesystems, or if the current
/// directory has been removed, and
/// [`run`](struct.Expression.html#method.run) will return those errors
/// rather than trying any sneaky workarounds.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("pwd").dir("/").read().unwrap();
/// assert_eq!("/", output);
/// # }
/// # }
/// ```
pub fn dir<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Dir(path.into()), self.clone()))
}
/// Set a variable in the expression's environment.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output = sh("echo $FOO").env("FOO", "bar").read().unwrap();
/// assert_eq!("bar", output);
/// # }
/// ```
pub fn env<T, U>(&self, name: T, val: U) -> Self
where T: Into<OsString>,
U: Into<OsString>
{
Self::new(Io(Env(name.into(), val.into()), self.clone()))
}
/// Set the expression's entire environment, from a collection of name-value
/// pairs (like a `HashMap`). You can use this method to clear specific
/// variables for example, by collecting the parent's environment, removing
/// some names from the collection, and passing the result to `full_env`.
/// Note that some environment variables are required for normal program
/// execution (like `SystemRoot` on Windows), so copying the parent's
/// environment is usually preferable to starting with an empty one.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # use std::collections::HashMap;
/// # if cfg!(not(windows)) {
/// let mut env_map: HashMap<_, _> = std::env::vars().collect();
/// env_map.insert("FOO".into(), "bar".into());
/// let output = sh("echo $FOO").full_env(env_map).read().unwrap();
/// assert_eq!("bar", output);
///
/// // The IntoIterator/Into<OsString> bounds are pretty flexible. A shared
/// // reference works here too.
/// # let mut env_map: HashMap<_, _> = std::env::vars().collect();
/// # env_map.insert("FOO".into(), "bar".into());
/// let output = sh("echo $FOO").full_env(&env_map).read().unwrap();
/// assert_eq!("bar", output);
/// # }
/// ```
pub fn full_env<T, U, V>(&self, name_vals: T) -> Self
where T: IntoIterator<Item = (U, V)>,
U: Into<OsString>,
V: Into<OsString>
{
let env_map = name_vals.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
Self::new(Io(FullEnv(env_map), self.clone()))
}
/// Prevent a non-zero exit status from short-circuiting a
/// [`then`](struct.Expression.html#method.then) expression or from causing
/// [`run`](struct.Expression.html#method.run) and friends to return an
/// error. The unchecked exit code will still be there on the `Output`
/// returned by `run`; its value doesn't change.
///
/// "Uncheckedness" sticks to an exit code as it bubbles up through
/// complicated expressions, but it doesn't "infect" other exit codes. So
/// for example, if only one sub-expression in a pipe has `unchecked`, then
/// errors returned by the other side will still be checked. That said,
/// most commonly you'll just call `unchecked` right before `run`, and it'll
/// apply to an entire expression. This sub-expression stuff doesn't usually
/// come up unless you have a big pipeline built out of lots of different
/// pieces.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Normally the `false` command (which does nothing but return a
/// // non-zero exit status) would short-circuit the `then` expression and
/// // also make `read` return an error. `unchecked` prevents this.
/// cmd!("false").unchecked().then(cmd!("echo", "hi")).read().unwrap();
/// # }
/// # }
/// ```
pub fn unchecked(&self) -> Self {
Self::new(Io(Unchecked, self.clone()))
}
fn new(inner: ExpressionInner) -> Self {
Expression(Arc::new(inner))
}
}
/// A handle to a running expression, returned by the
/// [`start`](struct.Expression.html#method.start) method. Calling `start`
/// followed by [`output`](struct.Handle.html#method.output) on the handle is
/// equivalent to [`run`](struct.Expression.html#method.run). Note that unlike
/// [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html),
/// most of the methods on `Handle` take `&self` rather than `&mut self`, and a
/// `Handle` may be shared between multiple threads.
///
/// See the [`shared_child`](https://github.com/oconnor663/shared_child.rs)
/// crate for implementation details behind making handles thread safe.
pub struct Handle {
inner: HandleInner,
result: AtomicLazyCell<io::Result<Output>>,
readers: Mutex<Option<(ReaderThread, ReaderThread)>>,
}
impl Handle {
/// Wait for the running expression to finish, and return a reference to its
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html).
/// Multiple threads may wait at the same time.
pub fn wait(&self) -> io::Result<&Output> {
let status = self.inner.wait(WaitMode::Blocking)?.expect("blocking wait can't return None");
// The expression has exited. See if we need to collect its output
// result, or if another caller has already done it. Do this inside the
// readers lock, to avoid racing to fill the result.
let mut readers_lock = self.readers.lock().expect("readers lock poisoned");
if !self.result.filled() {
// We're holding the readers lock, and we're the thread that needs
// to collect the output. Take the reader threads and join them.
let (stdout_reader, stderr_reader) = readers_lock.take()
.expect("readers taken without filling result");
let stdout_result = stdout_reader.join().expect("stdout reader panic");
let stderr_result = stderr_reader.join().expect("stderr reader panic");
let final_result = match (stdout_result, stderr_result) {
// The highest priority result is IO errors in the reader
// threads.
(Err(err), _) | (_, Err(err)) => Err(err),
// Then checked status errors.
_ if status.is_checked_error() => {
Err(io::Error::new(io::ErrorKind::Other, status.message()))
}
// And finally the successful output.
(Ok(stdout), Ok(stderr)) => {
Ok(Output {
status: status.status,
stdout: stdout,
stderr: stderr,
})
}
};
self.result.fill(final_result).expect("result already filled outside the readers lock");
}
// The result has been collected, whether or not we were the caller that
// collected it. Return a reference.
match self.result.borrow().expect("result not filled") {
&Ok(ref output) => Ok(output),
&Err(ref err) => Err(clone_io_error(err)),
}
}
/// Check whether the running expression is finished. If it is, return a
/// reference to its
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html).
/// If it's still running, return `Ok(None)`.
pub fn try_wait(&self) -> io::Result<Option<&Output>> {
if self.inner.wait(WaitMode::Nonblocking)?.is_none() {
Ok(None)
} else {
self.wait().map(Some)
}
}
/// Wait for the running expression to finish, and then return a
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object containing the results, including any captured output. This
/// consumes the `Handle`. Calling
/// [`start`](struct.Expression.html#method.start) followed by `output` is
/// equivalent to [`run`](struct.Expression.html#method.run).
pub fn output(self) -> io::Result<Output> {
self.wait()?;
self.result.into_inner().expect("wait didn't set the result")
}
/// Kill the running expression.
pub fn kill(&self) -> io::Result<()> {
self.inner.kill()
}
}
enum HandleInner {
// Cmd and Sh expressions both yield this guy.
Child(SharedChild, String),
// If the left side of a pipe fails to start, there's nothing to wait for,
// and we return an error immediately. But if the right side fails to start,
// the caller still needs to wait on the left, and we must return a handle.
// Thus the handle preserves the right side's errors here.
Pipe(Box<HandleInner>, Box<io::Result<HandleInner>>),
// Then requires a background thread to wait on the left side and start the
// right side.
Then(Box<ThenState>),
Input(Box<HandleInner>, WriterThread),
Unchecked(Box<HandleInner>),
}
impl HandleInner {
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
match *self {
HandleInner::Child(ref shared_child, ref command_string) => {
wait_child(shared_child, command_string, mode)
}
HandleInner::Pipe(ref left_handle, ref right_start_result) => {
wait_pipe(left_handle, right_start_result, mode)
}
HandleInner::Then(ref then_state) => then_state.wait(mode),
HandleInner::Input(ref inner_handle, ref writer_thread) => {
wait_input(inner_handle, writer_thread, mode)
}
HandleInner::Unchecked(ref inner_handle) => {
Ok(inner_handle.wait(mode)?.map(|mut status| {
status.checked = false;
status
}))
}
}
}
fn kill(&self) -> io::Result<()> {
match *self {
HandleInner::Child(ref shared_child, _) => shared_child.kill(),
HandleInner::Pipe(ref left_handle, ref right_start_result) => {
kill_pipe(left_handle, right_start_result)
}
HandleInner::Then(ref then_state) => then_state.kill(),
HandleInner::Input(ref inner_handle, _) => inner_handle.kill(),
HandleInner::Unchecked(ref inner_handle) => inner_handle.kill(),
}
}
}
#[derive(Debug)]
enum ExpressionInner {
Cmd(Vec<OsString>),
Sh(OsString),
Pipe(Expression, Expression),
Then(Expression, Expression),
Io(IoExpressionInner, Expression),
}
impl ExpressionInner {
fn start(&self, context: IoContext) -> io::Result<HandleInner> {
match *self {
Cmd(ref argv) => start_argv(argv, context),
Sh(ref command) => start_sh(command, context),
Pipe(ref left, ref right) => start_pipe(left, right, context),
Then(ref left, ref right) => {
Ok(HandleInner::Then(Box::new(ThenState::start(left, right.clone(), context)?)))
}
Io(ref io_inner, ref expr) => start_io(io_inner, expr, context),
}
}
}
fn start_argv(argv: &[OsString], context: IoContext) -> io::Result<HandleInner> {
let exe = canonicalize_exe_path_for_dir(&argv[0], &context)?;
let mut command = Command::new(exe);
command.args(&argv[1..]);
// TODO: Avoid unnecessary dup'ing here.
command.stdin(context.stdin.into_stdio()?);
command.stdout(context.stdout.into_stdio()?);
command.stderr(context.stderr.into_stdio()?);
if let Some(dir) = context.dir {
command.current_dir(dir);
}
command.env_clear();
for (name, val) in context.env {
command.env(name, val);
}
let shared_child = SharedChild::spawn(&mut command)?;
let command_string = format!("{:?}", argv);
Ok(HandleInner::Child(shared_child, command_string))
}
#[cfg(unix)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
[OsStr::new("/bin/sh").to_owned(), OsStr::new("-c").to_owned(), command]
}
#[cfg(windows)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
let comspec = std::env::var_os("COMSPEC").unwrap_or(OsStr::new("cmd.exe").to_owned());
[comspec, OsStr::new("/C").to_owned(), command]
}
fn start_sh(command: &OsString, context: IoContext) -> io::Result<HandleInner> {
start_argv(&shell_command_argv(command.clone()), context)
}
fn wait_child(shared_child: &SharedChild,
command_string: &str,
mode: WaitMode)
-> io::Result<Option<ExpressionStatus>> {
let maybe_status = match mode {
WaitMode::Blocking => Some(shared_child.wait()?),
WaitMode::Nonblocking => shared_child.try_wait()?,
};
if let Some(status) = maybe_status {
Ok(Some(ExpressionStatus {
status: status,
checked: true,
command: command_string.to_owned(),
}))
} else {
Ok(None)
}
}
fn start_pipe(left: &Expression,
right: &Expression,
context: IoContext)
-> io::Result<HandleInner> {
let (reader, writer) = os_pipe::pipe()?;
let mut left_context = context.try_clone()?; // dup'ing stdin/stdout isn't strictly necessary, but no big deal
left_context.stdout = IoValue::File(File::from_file(writer));
let mut right_context = context;
right_context.stdin = IoValue::File(File::from_file(reader));
// Errors starting the left side just short-circuit us.
let left_handle = left.0.start(left_context)?;
// Now the left has started, and we *must* return a handle. No more
// short-circuiting.
let right_result = right.0.start(right_context);
Ok(HandleInner::Pipe(Box::new(left_handle), Box::new(right_result)))
}
// Waiting on a pipe expression is tricky. The right side might've failed to
// start before we even got here. Or we might hit an error waiting on the left
// side, before we try to wait on the right. No matter what happens, we must
// call wait on *both* sides (if they're running), to make sure that errors on
// one side don't cause us to leave zombie processes on the other side.
fn wait_pipe(left_handle: &HandleInner,
right_start_result: &io::Result<HandleInner>,
mode: WaitMode)
-> io::Result<Option<ExpressionStatus>> {
// Even if the right side never started, the left side did. Wait for it.
// Don't short circuit until after we wait on the right side though.
let left_wait_result = left_handle.wait(mode);
// Now if the right side never started at all, we just return that error,
// regardless of how the left turned out. (Recall that if the left never
// started, we won't get here at all.)
let right_handle = match *right_start_result {
Ok(ref handle) => handle,
Err(ref err) => return Err(clone_io_error(err)),
};
// The right side did start, so we need to wait on it.
let right_wait_result = right_handle.wait(mode);
// Now we deal with errors from either of those waits. The left wait
// happened first, so that one takes precedence. Note that this is the
// reverse order of exit status precedence.
let left_status = left_wait_result?;
let right_status = right_wait_result?;
// Now return one of the two statuses.
Ok(pipe_status_precedence(left_status, right_status))
}
// The rules of precedence are:
// 1) If either side unfinished, the result is unfinished.
// 2) Checked errors trump unchecked errors.
// 3) Any errors trump success.
// 4) All else equal, the right side wins.
fn pipe_status_precedence(left_maybe_status: Option<ExpressionStatus>,
right_maybe_status: Option<ExpressionStatus>)
-> Option<ExpressionStatus> {
let (left_status, right_status) = match (left_maybe_status, right_maybe_status) {
(Some(left), Some(right)) => (left, right),
_ => return None,
};
Some(if right_status.is_checked_error() {
right_status
} else if left_status.is_checked_error() {
left_status
} else if !right_status.status.success() {
right_status
} else {
left_status
})
}
// As with wait_pipe, we need to call kill on both sides even if the left side
// returns an error. But if the right side never started, we'll ignore it.
fn kill_pipe(left_handle: &HandleInner,
right_start_result: &io::Result<HandleInner>)
-> io::Result<()> {
let left_kill_result = left_handle.kill();
if let Ok(ref right_handle) = *right_start_result {
let right_kill_result = right_handle.kill();
// As with wait, the left side happened first, so its errors take
// precedence.
left_kill_result.and(right_kill_result)
} else {
left_kill_result
}
}
// A "then" expression must start the right side as soon as the left is
// finished, even if the original caller isn't waiting on it yet. We do that
// with a background thread.
struct ThenState {
shared_state: Arc<ThenSharedState>,
background_waiter: SharedThread<io::Result<ExpressionStatus>>,
}
impl ThenState {
fn start(left: &Expression, right: Expression, context: IoContext) -> io::Result<ThenState> {
let left_context = context.try_clone()?;
let left_handle = left.0.start(left_context)?;
let shared = Arc::new(ThenSharedState {
left_handle: left_handle,
right_lock: Mutex::new(Some((right, context))),
right_cell: AtomicLazyCell::new(),
});
let clone = shared.clone();
let background_waiter = std::thread::spawn(move || {
Ok(clone.wait(WaitMode::Blocking)?.expect("blocking wait can't return None"))
});
Ok(ThenState {
shared_state: shared,
background_waiter: SharedThread::new(background_waiter),
})
}
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
// ThenSharedState does most of the heavy lifting. We just need to join
// the background waiter if the expression is finished. Similar to
// wait_input, blocking mode *must* clean up even in the presence of
// errors, but we *must not* do a potentially blocking join if we're in
// nonblocking mode.
let wait_res = self.shared_state.wait(mode);
if mode.should_join_background_thread(&wait_res) {
self.background_waiter.join().as_ref().map_err(clone_io_error)?;
}
wait_res
}
fn kill(&self) -> io::Result<()> {
self.shared_state.kill()
}
}
// This is the state that gets shared with the background waiter thread.
struct ThenSharedState {
left_handle: HandleInner,
right_lock: Mutex<Option<(Expression, IoContext)>>,
right_cell: AtomicLazyCell<io::Result<HandleInner>>,
}
impl ThenSharedState {
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
// Wait for the left side to finish. If the left side hasn't finished
// yet (in nonblocking mode), short-circuit.
let left_status = match self.left_handle.wait(mode)? {
Some(status) => status,
None => return Ok(None),
};
// The left side has finished, so now we *must* try to take ownership of
// the right IoContext. If we get it, and if the left side isn't a
// checked error, then we'll start the right child. But no matter what,
// we can't leave that IoContext alive. There are write pipes in it that
// will deadlock the top level wait otherwise.
//
// We also need to keep holding this lock until we finish starting the
// right side. Kill will take the same lock, and that avoids the race
// condition where one thread gets the right context, kill happens, and
// *then* the first thread starts the right.
let mut right_lock_guard = self.right_lock.lock().unwrap();
let maybe_expression_context = right_lock_guard.take();
// Checked errors on the left side will short-circuit the right. As
// noted above, this will still drop the right IoContext, if any.
if left_status.is_checked_error() {
return Ok(Some(left_status));
}
// Now if we got the right expression above, we're responsible for
// starting it. Otherwise either it's already been started, or this
// expression has been killed.
if let Some((expression, context)) = maybe_expression_context {
let right_start_result = expression.0.start(context);
self.right_cell
.fill(right_start_result)
.map_err(|_| "right_cell unexpectedly filled")
.unwrap();
}
// Release the right lock. Kills may now happen on other threads. It's
// important that we don't hold this lock during waits.
drop(right_lock_guard);
// Wait on the right side, if it was started. There are two ways it
// might not have been started:
// 1) Start might've returned an error. We'll just clone it.
// 2) The expression might've been killed before we started the right
// side. We'll return the left side's result. Note that it's possible
// that the kill happened precisely in between the left exit and the
// right start, in which case the left exit status could actually be
// success.
match self.right_cell.borrow() {
Some(&Ok(ref handle)) => handle.wait(mode),
Some(&Err(ref err)) => Err(clone_io_error(err)),
None => Ok(Some(left_status)),
}
}
fn kill(&self) -> io::Result<()> {
// Lock and clear the right context first, so that it can't be started
// if it hasn't been already. This is important because if the left side
// is unchecked, a waiting thread will ignore its killed exit status and
// try to start the right side anyway.
let mut right_lock_guard = self.right_lock.lock().unwrap();
*right_lock_guard = None;
// Try to kill both sides, even if the first kill fails for some reason.
let left_result = self.left_handle.kill();
if let Some(&Ok(ref handle)) = self.right_cell.borrow() {
let right_result = handle.kill();
left_result.and(right_result)
} else {
left_result
}
}
}
fn start_io(io_inner: &IoExpressionInner,
expr_inner: &Expression,
mut context: IoContext)
-> io::Result<HandleInner> {
match *io_inner {
Input(ref v) => return start_input(expr_inner, context, v.clone()),
Stdin(ref p) => {
context.stdin = IoValue::File(File::open(p)?);
}
StdinFile(ref f) => {
context.stdin = IoValue::File(f.try_clone()?);
}
StdinNull => {
context.stdin = IoValue::Null;
}
Stdout(ref p) => {
context.stdout = IoValue::File(File::create(p)?);
}
StdoutFile(ref f) => {
context.stdout = IoValue::File(f.try_clone()?);
}
StdoutNull => {
context.stdout = IoValue::Null;
}
StdoutCapture => {
context.stdout = IoValue::File(context.stdout_capture.try_clone()?);
}
StdoutToStderr => {
context.stdout = context.stderr.try_clone()?;
}
Stderr(ref p) => {
context.stderr = IoValue::File(File::create(p)?);
}
StderrFile(ref f) => {
context.stderr = IoValue::File(f.try_clone()?);
}
StderrNull => {
context.stderr = IoValue::Null;
}
StderrCapture => context.stderr = IoValue::File(context.stderr_capture.try_clone()?),
StderrToStdout => {
context.stderr = context.stdout.try_clone()?;
}
Dir(ref p) => {
context.dir = Some(p.clone());
}
Env(ref name, ref val) => {
context.env.insert(name.clone(), val.clone());
}
FullEnv(ref map) => {
context.env = map.clone();
}
Unchecked => {
let inner_handle = expr_inner.0.start(context)?;
return Ok(HandleInner::Unchecked(Box::new(inner_handle)));
}
}
expr_inner.0.start(context)
}
fn start_input(expression: &Expression,
mut context: IoContext,
input: Arc<Vec<u8>>)
-> io::Result<HandleInner> {
let (reader, mut writer) = os_pipe::pipe()?;
context.stdin = IoValue::File(File::from_file(reader));
let inner = expression.0.start(context)?;
// We only spawn the writer thread if the expression started successfully,
// so that start errors won't leak a zombie thread.
let thread = std::thread::spawn(move || writer.write_all(&input));
Ok(HandleInner::Input(Box::new(inner), SharedThread::new(thread)))
}
fn wait_input(inner_handle: &HandleInner,
writer_thread: &WriterThread,
mode: WaitMode)
-> io::Result<Option<ExpressionStatus>> {
// We're responsible for joining the writer thread and not leaving a zombie.
// But waiting on the inner child can return an error, and in that case we
// don't know whether the child is still running or not. The rule in
// nonblocking mode is "clean up as much as we can, but never block," so we
// can't wait on the writer thread. But the rule in blocking mode is "clean
// up everything, even if some cleanup returns errors," so we must wait
// regardless of what's going on with the child.
let wait_res = inner_handle.wait(mode);
if mode.should_join_background_thread(&wait_res) {
// Join the writer thread. Broken pipe errors here are expected if
// the child exited without reading all of its input, so we suppress
// them. Return other errors though.
match *writer_thread.join() {
Err(ref err) if err.kind() != io::ErrorKind::BrokenPipe => {
return Err(clone_io_error(err));
}
_ => {}
}
}
wait_res
}
#[derive(Debug)]
enum IoExpressionInner {
Input(Arc<Vec<u8>>),
Stdin(PathBuf),
StdinFile(File),
StdinNull,
Stdout(PathBuf),
StdoutFile(File),
StdoutNull,
StdoutCapture,
StdoutToStderr,
Stderr(PathBuf),
StderrFile(File),
StderrNull,
StderrCapture,
StderrToStdout,
Dir(PathBuf),
Env(OsString, OsString),
FullEnv(HashMap<OsString, OsString>),
Unchecked,
}
// An IoContext represents the file descriptors child processes are talking to at execution time.
// It's initialized in run(), with dups of the stdin/stdout/stderr pipes, and then passed down to
// sub-expressions. Compound expressions will clone() it, and redirections will modify it.
#[derive(Debug)]
struct IoContext {
stdin: IoValue,
stdout: IoValue,
stderr: IoValue,
stdout_capture: File,
stderr_capture: File,
dir: Option<PathBuf>,
env: HashMap<OsString, OsString>,
}
impl IoContext {
// Returns (context, stdout_reader, stderr_reader).
fn new() -> io::Result<(IoContext, ReaderThread, ReaderThread)> {
let (stdout_capture, stdout_reader) = pipe_with_reader_thread()?;
let (stderr_capture, stderr_reader) = pipe_with_reader_thread()?;
let mut env = HashMap::new();
for (name, val) in std::env::vars_os() {
env.insert(name, val);
}
let context = IoContext {
stdin: IoValue::ParentStdin,
stdout: IoValue::ParentStdout,
stderr: IoValue::ParentStderr,
stdout_capture: stdout_capture,
stderr_capture: stderr_capture,
dir: None,
env: env,
};
Ok((context, stdout_reader, stderr_reader))
}
fn try_clone(&self) -> io::Result<IoContext> {
Ok(IoContext {
stdin: self.stdin.try_clone()?,
stdout: self.stdout.try_clone()?,
stderr: self.stderr.try_clone()?,
stdout_capture: self.stdout_capture.try_clone()?,
stderr_capture: self.stderr_capture.try_clone()?,
dir: self.dir.clone(),
env: self.env.clone(),
})
}
}
#[derive(Debug)]
enum IoValue {
ParentStdin,
ParentStdout,
ParentStderr,
Null,
File(File),
}
impl IoValue {
fn try_clone(&self) -> io::Result<IoValue> {
Ok(match self {
&IoValue::ParentStdin => IoValue::ParentStdin,
&IoValue::ParentStdout => IoValue::ParentStdout,
&IoValue::ParentStderr => IoValue::ParentStderr,
&IoValue::Null => IoValue::Null,
&IoValue::File(ref f) => IoValue::File(f.try_clone()?),
})
}
fn into_stdio(self) -> io::Result<Stdio> {
match self {
IoValue::ParentStdin => os_pipe::parent_stdin(),
IoValue::ParentStdout => os_pipe::parent_stdout(),
IoValue::ParentStderr => os_pipe::parent_stderr(),
IoValue::Null => Ok(Stdio::null()),
IoValue::File(f) => Ok(Stdio::from_file(f)),
}
}
}
// This struct keeps track of a child exit status, whether or not it's been
// unchecked(), and what the command was that gave it (for error messages).
#[derive(Clone, Debug)]
struct ExpressionStatus {
status: ExitStatus,
checked: bool,
command: String,
}
impl ExpressionStatus {
fn is_checked_error(&self) -> bool {
self.checked && !self.status.success()
}
fn message(&self) -> String {
format!("command {} exited with code {}",
self.command,
self.exit_code_string())
}
#[cfg(not(windows))]
fn exit_code_string(&self) -> String {
use std::os::unix::process::ExitStatusExt;
if self.status.code().is_none() {
return format!("<signal {}>", self.status.signal().unwrap());
}
self.status.code().unwrap().to_string()
}
#[cfg(windows)]
fn exit_code_string(&self) -> String {
self.status.code().unwrap().to_string()
}
}
fn canonicalize_exe_path_for_dir(exe_name: &OsStr, context: &IoContext) -> io::Result<OsString> {
// There's a tricky interaction between exe paths and `dir`. Exe
// paths can be relative, and so we have to ask: Is an exe path
// interpreted relative to the parent's cwd, or the child's? The
// answer is that it's platform dependent! >.< (Windows uses the
// parent's cwd, but because of the fork-chdir-exec pattern, Unix
// usually uses the child's.)
//
// We want to use the parent's cwd consistently, because that saves
// the caller from having to worry about whether `dir` will have
// side effects, and because it's easy for the caller to use
// Path::join if they want to. That means that when `dir` is in use,
// we need to detect exe names that are relative paths, and
// absolutify them. We want to do that as little as possible though,
// both because canonicalization can fail, and because we prefer to
// let the caller control the child's argv[0].
//
// We never want to absolutify a name like "emacs", because that's
// probably a program in the PATH rather than a local file. So we
// look for slashes in the name to determine what's a filepath and
// what isn't. Note that anything given as a std::path::Path will
// always have a slash by the time we get here, because we
// specialize the ToExecutable trait to prepend a ./ to them when
// they're relative. This leaves the case where Windows users might
// pass a local file like "foo.bat" as a string, which we can't
// distinguish from a global program name. However, because the
// Windows has the preferred "relative to parent's cwd" behavior
// already, this case actually works without our help. (The thing
// Windows users have to watch out for instead is local files
// shadowing global program names, which I don't think we can or
// should prevent.)
let has_separator = exe_name.to_string_lossy().chars().any(std::path::is_separator);
let is_relative = Path::new(exe_name).is_relative();
if context.dir.is_some() && has_separator && is_relative {
Path::new(exe_name).canonicalize().map(Into::into)
} else {
Ok(exe_name.to_owned())
}
}
// We want to allow Path("foo") to refer to the local file "./foo" on
// Unix, and we want to *prevent* Path("echo") from referring to the
// global "echo" command on either Unix or Windows. Prepend a dot to all
// relative paths to accomplish both of those.
fn dotify_relative_exe_path(path: &Path) -> PathBuf {
// This is a no-op if path is absolute or begins with a Windows prefix.
Path::new(".").join(path)
}
/// `duct` provides several impls of this trait to handle the difference between
/// [`Path`](https://doc.rust-lang.org/std/path/struct.Path.html)/[`PathBuf`](https://doc.rust-lang.org/std/path/struct.PathBuf.html)
/// and other types of strings. In particular, `duct` automatically prepends a
/// leading dot to relative paths (though not other string types) before
/// executing them. This is required for single-component relative paths to work
/// at all on Unix, and it prevents aliasing with programs in the global `PATH`
/// on both Unix and Windows. See the trait bounds on [`cmd`](fn.cmd.html) and
/// [`sh`](fn.sh.html).
pub trait ToExecutable {
fn to_executable(self) -> OsString;
}
// TODO: Get rid of most of these impls once specialization lands.
impl<'a> ToExecutable for &'a Path {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(self).into()
}
}
impl ToExecutable for PathBuf {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(&self).into()
}
}
impl<'a> ToExecutable for &'a PathBuf {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(self).into()
}
}
impl<'a> ToExecutable for &'a str {
fn to_executable(self) -> OsString {
self.into()
}
}
impl ToExecutable for String {
fn to_executable(self) -> OsString {
self.into()
}
}
impl<'a> ToExecutable for &'a String {
fn to_executable(self) -> OsString {
self.into()
}
}
impl<'a> ToExecutable for &'a OsStr {
fn to_executable(self) -> OsString {
self.into()
}
}
impl ToExecutable for OsString {
fn to_executable(self) -> OsString {
self
}
}
impl<'a> ToExecutable for &'a OsString {
fn to_executable(self) -> OsString {
self.into()
}
}
type ReaderThread = JoinHandle<io::Result<Vec<u8>>>;
fn pipe_with_reader_thread() -> io::Result<(File, ReaderThread)> {
let (mut reader, writer) = os_pipe::pipe()?;
let thread = std::thread::spawn(move || {
let mut output = Vec::new();
reader.read_to_end(&mut output)?;
Ok(output)
});
Ok((File::from_file(writer), thread))
}
type WriterThread = SharedThread<io::Result<()>>;
fn trim_right_newlines(s: &str) -> &str {
s.trim_right_matches(|c| c == '\n' || c == '\r')
}
// io::Error doesn't implement clone directly, so we kind of hack it together.
fn clone_io_error(error: &io::Error) -> io::Error {
if let Some(code) = error.raw_os_error() {
io::Error::from_raw_os_error(code)
} else {
io::Error::new(error.kind(), error.to_string())
}
}
struct SharedThread<T> {
result: AtomicLazyCell<T>,
handle: Mutex<Option<JoinHandle<T>>>,
}
// A thread that sticks its result in a lazy cell, so that multiple callers can see it.
impl<T> SharedThread<T> {
fn new(handle: JoinHandle<T>) -> Self {
SharedThread {
result: AtomicLazyCell::new(),
handle: Mutex::new(Some(handle)),
}
}
// If the other thread panicked, this will panic.
fn join(&self) -> &T {
let mut handle_lock = self.handle.lock().expect("shared thread handle poisoned");
if let Some(handle) = handle_lock.take() {
let ret = handle.join().expect("panic on shared thread");
self.result.fill(ret).map_err(|_| "result lazycell unexpectedly full").unwrap();
}
self.result.borrow().expect("result lazycell unexpectedly empty")
}
}
#[derive(Clone, Copy, Debug)]
enum WaitMode {
Blocking,
Nonblocking,
}
impl WaitMode {
fn should_join_background_thread(&self,
expression_result: &io::Result<Option<ExpressionStatus>>)
-> bool {
// Nonblocking waits can only join associated background threads if the
// running expression is finished (that is, when the thread is
// guaranteed to finish soon). Blocking waits should always join, even
// in the presence of errors.
match (self, expression_result) {
(&WaitMode::Blocking, _) => true,
(_, &Ok(Some(_))) => true,
_ => false,
}
}
}
#[cfg(test)]
mod test;
move pipe handle code into PipeHandle, also ThenState -> ThenHandle
//! A cross-platform library for running child processes and building
//! pipelines.
//!
//! `duct` wants to make shelling out in Rust as easy and flexible as it is in
//! Bash. It takes care of [gotchas and
//! inconsistencies](https://github.com/oconnor663/duct.py/blob/master/spec.md)
//! in the way different platforms shell out. And it's a cross-language library;
//! the [original implementation](https://github.com/oconnor663/duct.py) is in
//! Python, with an identical API.
//!
//! - [Docs](https://docs.rs/duct)
//! - [Crate](https://crates.io/crates/duct)
//! - [Repo](https://github.com/oconnor663/duct.rs)
//!
//! # Example
//!
//! `duct` tries to be as concise as possible, so that you don't wish you were
//! back writing shell scripts. At the same time, it's explicit about what
//! happens to output, and strict about error codes in child processes.
//!
//! ```rust,no_run
//! #[macro_use]
//! extern crate duct;
//!
//! use duct::{cmd, sh};
//!
//! fn main() {
//! // Read the name of the current git branch. If git exits with an error
//! // code here (because we're not in a git repo, for example), `read` will
//! // return an error too. `sh` commands run under the real system shell,
//! // /bin/sh on Unix or cmd.exe on Windows.
//! let current_branch = sh("git symbolic-ref --short HEAD").read().unwrap();
//!
//! // Log the current branch, with git taking over the terminal as usual.
//! // `cmd!` commands are spawned directly, without going through the
//! // shell, so there aren't any escaping issues with variable arguments.
//! cmd!("git", "log", current_branch).run().unwrap();
//!
//! // More complicated expressions become trees. Here's a pipeline with two
//! // child processes on the left, just because we can. In Bash this would
//! // be: stdout=$((echo -n part one "" && echo part two) | sed s/p/sm/g)
//! let part_one = &["-n", "part", "one", ""];
//! let stdout = cmd("echo", part_one)
//! .then(sh("echo part two"))
//! .pipe(cmd!("sed", "s/p/sm/g"))
//! .read()
//! .unwrap();
//! assert_eq!("smart one smart two", stdout);
//! }
//! ```
//!
//! `duct` uses [`os_pipe`](https://github.com/oconnor663/os_pipe.rs)
//! internally, and the docs for that one include a [big
//! example](https://docs.rs/os_pipe#example) that takes a dozen lines of code
//! to read both stdout and stderr from a child process. `duct` can do that in
//! one line:
//!
//! ```rust
//! use duct::sh;
//!
//! // This works on Windows too!
//! let output = sh("echo foo && echo bar >&2").stderr_to_stdout().read().unwrap();
//!
//! assert!(output.split_whitespace().eq(vec!["foo", "bar"]));
//! ```
extern crate lazycell;
use lazycell::AtomicLazyCell;
// Two utility crates build mainly to work for duct.
extern crate os_pipe;
extern crate shared_child;
use os_pipe::FromFile;
use shared_child::SharedChild;
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio, Output, ExitStatus};
use std::thread::JoinHandle;
use std::sync::{Arc, Mutex};
// enums defined below
use ExpressionInner::*;
use IoExpressionInner::*;
/// Create a command given a program name and a collection of arguments. See
/// also the [`cmd!`](macro.cmd.html) macro, which doesn't require a collection.
///
/// # Example
///
/// ```
/// use duct::cmd;
///
/// let args = vec!["foo", "bar", "baz"];
///
/// # // NOTE: Normally this wouldn't work on Windows, but we have an "echo"
/// # // binary that gets built for our main tests, and it's sitting around by
/// # // the time we get here. If this ever stops working, then we can disable
/// # // the tests that depend on it.
/// let output = cmd("echo", &args).read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn cmd<T, U, V>(program: T, args: U) -> Expression
where T: ToExecutable,
U: IntoIterator<Item = V>,
V: Into<OsString>
{
let mut argv_vec = Vec::new();
argv_vec.push(program.to_executable());
argv_vec.extend(args.into_iter().map(Into::<OsString>::into));
Expression::new(Cmd(argv_vec))
}
/// Create a command with any number of of positional arguments, which may be
/// different types (anything that implements
/// [`Into<OsString>`](https://doc.rust-lang.org/std/convert/trait.From.html)).
/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of
/// arguments.
///
/// # Example
///
/// ```
/// #[macro_use]
/// extern crate duct;
/// use std::path::Path;
///
/// fn main() {
/// let arg1 = "foo";
/// let arg2 = "bar".to_owned();
/// let arg3 = Path::new("baz");
///
/// let output = cmd!("echo", arg1, arg2, arg3).read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// }
/// ```
#[macro_export]
macro_rules! cmd {
( $program:expr ) => {
{
use std::ffi::OsString;
use std::iter::empty;
$crate::cmd($program, empty::<OsString>())
}
};
( $program:expr $(, $arg:expr )* ) => {
{
use std::ffi::OsString;
let mut args: Vec<OsString> = Vec::new();
$(
args.push(Into::<OsString>::into($arg));
)*
$crate::cmd($program, args)
}
};
}
/// Create a command from a string of shell code.
///
/// This invokes the operating system's shell to execute the string:
/// `/bin/sh` on Unix-like systems and `cmd.exe` on Windows. This can be
/// very convenient sometimes, especially in small scripts and examples.
/// You don't need to quote each argument, and all the operators like
/// `|` and `>` work as usual.
///
/// However, building shell commands at runtime brings up tricky whitespace and
/// escaping issues, so avoid using `sh` and `format!` together. Prefer
/// [`cmd!`](macro.cmd.html) instead in those cases. Also note that shell
/// commands don't tend to be portable between Unix and Windows.
///
/// # Example
///
/// ```
/// use duct::sh;
///
/// let output = sh("echo foo bar baz").read();
///
/// assert_eq!("foo bar baz", output.unwrap());
/// ```
pub fn sh<T: ToExecutable>(command: T) -> Expression {
Expression::new(Sh(command.to_executable()))
}
/// The central objects in `duct`, Expressions are created with
/// [`cmd`](fn.cmd.html), [`cmd!`](macro.cmd.html), or [`sh`](fn.sh.html), then
/// combined with [`pipe`](struct.Expression.html#method.pipe) or
/// [`then`](struct.Expression.html#method.then), and finally executed with
/// [`start`](struct.Expression.html#method.start),
/// [`run`](struct.Expression.html#method.run), or
/// [`read`](struct.Expression.html#method.read). They also support several
/// methods to control their execution, like
/// [`input`](struct.Expression.html#method.input),
/// [`env`](struct.Expression.html#method.env), and
/// [`unchecked`](struct.Expression.html#method.unchecked). Expressions are
/// immutable, and they do a lot of
/// [`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) sharing
/// internally, so all of these methods take `&self` and return a new
/// `Expression` cheaply.
#[derive(Clone, Debug)]
#[must_use]
pub struct Expression(Arc<ExpressionInner>);
impl Expression {
/// Execute an expression, wait for it to complete, and return a
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object containing the results. Nothing is captured by default, but if
/// you build the expression with
/// [`stdout_capture`](struct.Expression.html#method.stdout_capture) or
/// [`stderr_capture`](struct.Expression.html#method.stderr_capture) then
/// the `Output` will hold those captured bytes.
///
/// # Errors
///
/// In addition to all the IO errors possible with
/// [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html),
/// `run` will return an
/// [`ErrorKind::Other`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html)
/// IO error if child returns a non-zero exit status. To suppress this error
/// and return an `Output` even when the exit status is non-zero, use the
/// [`unchecked`](struct.Expression.html#method.unchecked) method.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").stdout_capture().run().unwrap();
/// assert_eq!(b"hi\n".to_vec(), output.stdout);
/// # }
/// # }
/// ```
pub fn run(&self) -> io::Result<Output> {
self.start()?.output()
}
/// Execute an expression, capture its standard output, and return the
/// captured output as a `String`. This is a convenience wrapper around
/// [`run`](struct.Expression.html#method.run). Like backticks and `$()` in
/// the shell, `read` trims trailing newlines.
///
/// # Errors
///
/// In addition to all the errors possible with
/// [`run`](struct.Expression.html#method.run), `read` will return an
/// [`ErrorKind::InvalidData`](https://doc.rust-lang.org/std/io/enum.ErrorKind.html)
/// IO error if the captured bytes aren't valid UTF-8.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").stdout_capture().read().unwrap();
/// assert_eq!("hi", output);
/// # }
/// # }
/// ```
pub fn read(&self) -> io::Result<String> {
let output = self.stdout_capture().run()?;
if let Ok(output_str) = std::str::from_utf8(&output.stdout) {
Ok(trim_right_newlines(output_str).to_owned())
} else {
Err(io::Error::new(io::ErrorKind::InvalidData, "stdout is not valid UTF-8"))
}
}
/// Start running an expression, and immediately return a
/// [`Handle`](struct.Handle.html) that represents all the child processes.
/// This is analogous to the
/// [`spawn`](https://doc.rust-lang.org/std/process/struct.Command.html#method.spawn)
/// method in the standard library. The `Handle` may be shared between
/// multiple threads.
///
/// # Errors
///
/// In addition to all the errors prossible with
/// [`std::process::Command::spawn`](https://doc.rust-lang.org/std/process/struct.Command.html#method.spawn),
/// `start` can return errors from opening pipes and files. However, `start`
/// will never return an error if a child process has already started. In
/// particular, if the left side of a pipe expression starts successfully,
/// `start` will always return `Ok`. Any errors that happen on the right
/// side will be saved and returned later by the wait methods. That makes it
/// safe for callers to short circuit on `start` errors without the risk of
/// leaking processes.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let handle = cmd!("echo", "hi").stdout_capture().start().unwrap();
/// let output = handle.wait().unwrap();
/// assert_eq!(b"hi\n".to_vec(), output.stdout);
/// # }
/// # }
/// ```
pub fn start(&self) -> io::Result<Handle> {
// TODO: SUBSTANTIAL COMMENTS ABOUT ERROR BEHAVIOR
let (context, stdout_reader, stderr_reader) = IoContext::new()?;
Ok(Handle {
inner: self.0.start(context)?,
result: AtomicLazyCell::new(),
readers: Mutex::new(Some((stdout_reader, stderr_reader))),
})
}
/// Join two expressions into a pipe, with the standard output of the left
/// hooked up to the standard input of the right, like `|` in the shell. If
/// either side of the pipe returns a non-zero exit status, that becomes the
/// status of the whole pipe, similar to Bash's `pipefail` option. If both
/// sides return non-zero, and one of them is
/// [`unchecked`](struct.Expression.html#method.unchecked), then the checked
/// side wins. Otherwise the right side wins.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("echo", "hi").pipe(cmd!("sed", "s/h/p/")).read();
/// assert_eq!("pi", output.unwrap());
/// # }
/// # }
/// ```
pub fn pipe(&self, right: Expression) -> Expression {
Self::new(Pipe(self.clone(), right.clone()))
}
/// Chain two expressions together to run in series, like `&&` in the shell.
/// If the left child returns a non-zero exit status, the right child
/// doesn't run. You can use
/// [`unchecked`](struct.Expression.html#method.unchecked) on the left child
/// to make sure the right child always runs. The exit status of this
/// expression is the status of the last child that ran. Note that
/// [`kill`](struct.Handle.html#method.kill) will prevent the right side
/// from starting if it hasn't already, even if the left side is
/// `unchecked`.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # use duct::sh;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Both echoes share the same stdout, so both go through `sed`.
/// # // NOTE: The shell's builtin echo doesn't support -n on OSX.
/// let output = cmd!("echo", "-n", "bar")
/// .then(sh("echo baz"))
/// .pipe(sh("sed s/b/f/g")).read();
/// assert_eq!("farfaz", output.unwrap());
/// # }
/// # }
/// ```
pub fn then(&self, right: Expression) -> Expression {
Self::new(Then(self.clone(), right.clone()))
}
/// Use bytes or a string as input for an expression, like `<<<` in the
/// shell. A worker thread will be spawned at runtime to write this input.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Many types implement Into<Vec<u8>>. Here's a string.
/// let output = cmd!("cat").input("foo").read().unwrap();
/// assert_eq!("foo", output);
///
/// // And here's a byte slice.
/// let output = cmd!("cat").input(&b"foo"[..]).read().unwrap();
/// assert_eq!("foo", output);
/// # }
/// # }
/// ```
pub fn input<T: Into<Vec<u8>>>(&self, input: T) -> Self {
Self::new(Io(Input(Arc::new(input.into())), self.clone()))
}
/// Open a file at the given path and use it as input for an expression, like
/// `<` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let output = sh("head -c 3").stdin("/dev/zero").read().unwrap();
/// assert_eq!("\0\0\0", output);
/// # }
/// ```
pub fn stdin<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stdin(path.into()), self.clone()))
}
/// Use an already opened file as input for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let input_file = std::fs::File::open("/dev/zero").unwrap();
/// let output = sh("head -c 3").stdin_file(input_file).read().unwrap();
/// assert_eq!("\0\0\0", output);
/// # }
/// ```
pub fn stdin_file(&self, file: File) -> Self {
Self::new(Io(StdinFile(file), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as input for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("cat").stdin_null().read().unwrap();
/// assert_eq!("", output);
/// # }
/// # }
/// ```
pub fn stdin_null(&self) -> Self {
Self::new(Io(StdinNull, self.clone()))
}
/// Open a file at the given path and use it as output for an expression,
/// like `>` in the shell.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let path = cmd!("mktemp").read().unwrap();
/// sh("echo wee").stdout(&path).run().unwrap();
/// let mut output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut output).unwrap();
/// assert_eq!("wee\n", output);
/// # }
/// # }
/// ```
pub fn stdout<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stdout(path.into()), self.clone()))
}
/// Use an already opened file as output for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// let path = cmd!("mktemp").read().unwrap();
/// let file = std::fs::File::create(&path).unwrap();
/// sh("echo wee").stdout_file(file).run().unwrap();
/// let mut output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut output).unwrap();
/// assert_eq!("wee\n", output);
/// # }
/// # }
/// ```
pub fn stdout_file(&self, file: File) -> Self {
Self::new(Io(StdoutFile(file), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as output for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// // This echo command won't print anything.
/// sh("echo foo bar baz").stdout_null().run().unwrap();
///
/// // And you won't get anything even if you try to read its output! The
/// // null redirect happens farther down in the expression tree than the
/// // implicit `stdout_capture`, and so it takes precedence.
/// let output = sh("echo foo bar baz").stdout_null().read().unwrap();
/// assert_eq!("", output);
/// ```
pub fn stdout_null(&self) -> Self {
Self::new(Io(StdoutNull, self.clone()))
}
/// Capture the standard output of an expression. The captured bytes will be
/// available on the `stdout` field of the
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object returned by [`run`](struct.Expression.html#method.run) or
/// [`wait`](struct.Handle.html#method.wait). In the simplest cases,
/// [`read`](struct.Expression.html#method.read) can be more convenient.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// // The most direct way to read stdout bytes is `stdout_capture`.
/// let output1 = sh("echo foo").stdout_capture().run().unwrap().stdout;
/// assert_eq!(&b"foo\n"[..], &output1[..]);
///
/// // The `read` method is a shorthand for `stdout_capture`, and it also
/// // does string parsing and newline trimming.
/// let output2 = sh("echo foo").read().unwrap();
/// assert_eq!("foo", output2)
/// # }
/// ```
pub fn stdout_capture(&self) -> Self {
Self::new(Io(StdoutCapture, self.clone()))
}
/// Join the standard output of an expression to its standard error pipe,
/// similar to `1>&2` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output = sh("echo foo").stdout_to_stderr().stderr_capture().run().unwrap();
/// assert_eq!(&b"foo\n"[..], &output.stderr[..]);
/// # }
/// ```
pub fn stdout_to_stderr(&self) -> Self {
Self::new(Io(StdoutToStderr, self.clone()))
}
/// Open a file at the given path and use it as error output for an
/// expression, like `2>` in the shell.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// // Many types implement Into<PathBuf>, including &str.
/// let path = cmd!("mktemp").read().unwrap();
/// sh("echo wee >&2").stderr(&path).run().unwrap();
/// let mut error_output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut error_output).unwrap();
/// assert_eq!("wee\n", error_output);
/// # }
/// # }
/// ```
pub fn stderr<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Stderr(path.into()), self.clone()))
}
/// Use an already opened file as error output for an expression.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # use duct::sh;
/// # use std::io::prelude::*;
/// # if cfg!(not(windows)) {
/// let path = cmd!("mktemp").read().unwrap();
/// let file = std::fs::File::create(&path).unwrap();
/// sh("echo wee >&2").stderr_file(file).run().unwrap();
/// let mut error_output = String::new();
/// std::fs::File::open(&path).unwrap().read_to_string(&mut error_output).unwrap();
/// assert_eq!("wee\n", error_output);
/// # }
/// # }
/// ```
pub fn stderr_file(&self, file: File) -> Self {
Self::new(Io(StderrFile(file.into()), self.clone()))
}
/// Use `/dev/null` (or `NUL` on Windows) as error output for an expression.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// // This echo-to-stderr command won't print anything.
/// sh("echo foo bar baz >&2").stderr_null().run().unwrap();
/// ```
pub fn stderr_null(&self) -> Self {
Self::new(Io(StderrNull, self.clone()))
}
/// Capture the error output of an expression. The captured bytes will be
/// available on the `stderr` field of the `Output` object returned by
/// [`run`](struct.Expression.html#method.run) or
/// [`wait`](struct.Handle.html#method.wait).
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output_obj = sh("echo foo >&2").stderr_capture().run().unwrap();
/// assert_eq!(&b"foo\n"[..], &output_obj.stderr[..]);
/// # }
/// ```
pub fn stderr_capture(&self) -> Self {
Self::new(Io(StderrCapture, self.clone()))
}
/// Join the standard error of an expression to its standard output pipe,
/// similar to `2>&1` in the shell.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let error_output = sh("echo foo >&2").stderr_to_stdout().read().unwrap();
/// assert_eq!("foo", error_output);
/// # }
/// ```
pub fn stderr_to_stdout(&self) -> Self {
Self::new(Io(StderrToStdout, self.clone()))
}
/// Set the working directory where the expression will execute.
///
/// Note that in some languages (Rust and Python at least), there are tricky
/// platform differences in the way relative exe paths interact with child
/// working directories. In particular, the exe path will be interpreted
/// relative to the child dir on Unix, but relative to the parent dir on
/// Windows. `duct` considers the Windows behavior correct, so in order to
/// get that behavior consistently it calls
/// [`std::fs::canonicalize`](https://doc.rust-lang.org/std/fs/fn.canonicalize.html)
/// on relative exe paths when `dir` is in use. Paths in this sense are any
/// program name containing a path separator, regardless of the type. (Note
/// also that `Path` and `PathBuf` program names get a `./` prepended to
/// them automatically by the [`ToExecutable`](trait.ToExecutable.html)
/// trait, and so will always contain a separator.)
///
/// # Errors
///
/// Canonicalization can fail on some filesystems, or if the current
/// directory has been removed, and
/// [`run`](struct.Expression.html#method.run) will return those errors
/// rather than trying any sneaky workarounds.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// let output = cmd!("pwd").dir("/").read().unwrap();
/// assert_eq!("/", output);
/// # }
/// # }
/// ```
pub fn dir<T: Into<PathBuf>>(&self, path: T) -> Self {
Self::new(Io(Dir(path.into()), self.clone()))
}
/// Set a variable in the expression's environment.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # if cfg!(not(windows)) {
/// let output = sh("echo $FOO").env("FOO", "bar").read().unwrap();
/// assert_eq!("bar", output);
/// # }
/// ```
pub fn env<T, U>(&self, name: T, val: U) -> Self
where T: Into<OsString>,
U: Into<OsString>
{
Self::new(Io(Env(name.into(), val.into()), self.clone()))
}
/// Set the expression's entire environment, from a collection of name-value
/// pairs (like a `HashMap`). You can use this method to clear specific
/// variables for example, by collecting the parent's environment, removing
/// some names from the collection, and passing the result to `full_env`.
/// Note that some environment variables are required for normal program
/// execution (like `SystemRoot` on Windows), so copying the parent's
/// environment is usually preferable to starting with an empty one.
///
/// # Example
///
/// ```
/// # use duct::sh;
/// # use std::collections::HashMap;
/// # if cfg!(not(windows)) {
/// let mut env_map: HashMap<_, _> = std::env::vars().collect();
/// env_map.insert("FOO".into(), "bar".into());
/// let output = sh("echo $FOO").full_env(env_map).read().unwrap();
/// assert_eq!("bar", output);
///
/// // The IntoIterator/Into<OsString> bounds are pretty flexible. A shared
/// // reference works here too.
/// # let mut env_map: HashMap<_, _> = std::env::vars().collect();
/// # env_map.insert("FOO".into(), "bar".into());
/// let output = sh("echo $FOO").full_env(&env_map).read().unwrap();
/// assert_eq!("bar", output);
/// # }
/// ```
pub fn full_env<T, U, V>(&self, name_vals: T) -> Self
where T: IntoIterator<Item = (U, V)>,
U: Into<OsString>,
V: Into<OsString>
{
let env_map = name_vals.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
Self::new(Io(FullEnv(env_map), self.clone()))
}
/// Prevent a non-zero exit status from short-circuiting a
/// [`then`](struct.Expression.html#method.then) expression or from causing
/// [`run`](struct.Expression.html#method.run) and friends to return an
/// error. The unchecked exit code will still be there on the `Output`
/// returned by `run`; its value doesn't change.
///
/// "Uncheckedness" sticks to an exit code as it bubbles up through
/// complicated expressions, but it doesn't "infect" other exit codes. So
/// for example, if only one sub-expression in a pipe has `unchecked`, then
/// errors returned by the other side will still be checked. That said,
/// most commonly you'll just call `unchecked` right before `run`, and it'll
/// apply to an entire expression. This sub-expression stuff doesn't usually
/// come up unless you have a big pipeline built out of lots of different
/// pieces.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate duct;
/// # fn main() {
/// # if cfg!(not(windows)) {
/// // Normally the `false` command (which does nothing but return a
/// // non-zero exit status) would short-circuit the `then` expression and
/// // also make `read` return an error. `unchecked` prevents this.
/// cmd!("false").unchecked().then(cmd!("echo", "hi")).read().unwrap();
/// # }
/// # }
/// ```
pub fn unchecked(&self) -> Self {
Self::new(Io(Unchecked, self.clone()))
}
fn new(inner: ExpressionInner) -> Self {
Expression(Arc::new(inner))
}
}
/// A handle to a running expression, returned by the
/// [`start`](struct.Expression.html#method.start) method. Calling `start`
/// followed by [`output`](struct.Handle.html#method.output) on the handle is
/// equivalent to [`run`](struct.Expression.html#method.run). Note that unlike
/// [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html),
/// most of the methods on `Handle` take `&self` rather than `&mut self`, and a
/// `Handle` may be shared between multiple threads.
///
/// See the [`shared_child`](https://github.com/oconnor663/shared_child.rs)
/// crate for implementation details behind making handles thread safe.
pub struct Handle {
inner: HandleInner,
result: AtomicLazyCell<io::Result<Output>>,
readers: Mutex<Option<(ReaderThread, ReaderThread)>>,
}
impl Handle {
/// Wait for the running expression to finish, and return a reference to its
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html).
/// Multiple threads may wait at the same time.
pub fn wait(&self) -> io::Result<&Output> {
let status = self.inner.wait(WaitMode::Blocking)?.expect("blocking wait can't return None");
// The expression has exited. See if we need to collect its output
// result, or if another caller has already done it. Do this inside the
// readers lock, to avoid racing to fill the result.
let mut readers_lock = self.readers.lock().expect("readers lock poisoned");
if !self.result.filled() {
// We're holding the readers lock, and we're the thread that needs
// to collect the output. Take the reader threads and join them.
let (stdout_reader, stderr_reader) = readers_lock.take()
.expect("readers taken without filling result");
let stdout_result = stdout_reader.join().expect("stdout reader panic");
let stderr_result = stderr_reader.join().expect("stderr reader panic");
let final_result = match (stdout_result, stderr_result) {
// The highest priority result is IO errors in the reader
// threads.
(Err(err), _) | (_, Err(err)) => Err(err),
// Then checked status errors.
_ if status.is_checked_error() => {
Err(io::Error::new(io::ErrorKind::Other, status.message()))
}
// And finally the successful output.
(Ok(stdout), Ok(stderr)) => {
Ok(Output {
status: status.status,
stdout: stdout,
stderr: stderr,
})
}
};
self.result.fill(final_result).expect("result already filled outside the readers lock");
}
// The result has been collected, whether or not we were the caller that
// collected it. Return a reference.
match self.result.borrow().expect("result not filled") {
&Ok(ref output) => Ok(output),
&Err(ref err) => Err(clone_io_error(err)),
}
}
/// Check whether the running expression is finished. If it is, return a
/// reference to its
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html).
/// If it's still running, return `Ok(None)`.
pub fn try_wait(&self) -> io::Result<Option<&Output>> {
if self.inner.wait(WaitMode::Nonblocking)?.is_none() {
Ok(None)
} else {
self.wait().map(Some)
}
}
/// Wait for the running expression to finish, and then return a
/// [`std::process::Output`](https://doc.rust-lang.org/std/process/struct.Output.html)
/// object containing the results, including any captured output. This
/// consumes the `Handle`. Calling
/// [`start`](struct.Expression.html#method.start) followed by `output` is
/// equivalent to [`run`](struct.Expression.html#method.run).
pub fn output(self) -> io::Result<Output> {
self.wait()?;
self.result.into_inner().expect("wait didn't set the result")
}
/// Kill the running expression.
pub fn kill(&self) -> io::Result<()> {
self.inner.kill()
}
}
enum HandleInner {
// Cmd and Sh expressions both yield this guy.
Child(SharedChild, String),
// If the left side of a pipe fails to start, there's nothing to wait for,
// and we return an error immediately. But if the right side fails to start,
// the caller still needs to wait on the left, and we must return a handle.
// Thus the handle preserves the right side's errors here.
Pipe(Box<PipeHandle>),
// Then requires a background thread to wait on the left side and start the
// right side.
Then(Box<ThenHandle>),
Input(Box<HandleInner>, WriterThread),
Unchecked(Box<HandleInner>),
}
impl HandleInner {
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
match *self {
HandleInner::Child(ref shared_child, ref command_string) => {
wait_child(shared_child, command_string, mode)
}
HandleInner::Pipe(ref pipe_handle) => pipe_handle.wait(mode),
HandleInner::Then(ref then_handle) => then_handle.wait(mode),
HandleInner::Input(ref inner_handle, ref writer_thread) => {
wait_input(inner_handle, writer_thread, mode)
}
HandleInner::Unchecked(ref inner_handle) => {
Ok(inner_handle.wait(mode)?.map(|mut status| {
status.checked = false;
status
}))
}
}
}
fn kill(&self) -> io::Result<()> {
match *self {
HandleInner::Child(ref shared_child, _) => shared_child.kill(),
HandleInner::Pipe(ref pipe_handle) => pipe_handle.kill(),
HandleInner::Then(ref then_handle) => then_handle.kill(),
HandleInner::Input(ref inner_handle, _) => inner_handle.kill(),
HandleInner::Unchecked(ref inner_handle) => inner_handle.kill(),
}
}
}
#[derive(Debug)]
enum ExpressionInner {
Cmd(Vec<OsString>),
Sh(OsString),
Pipe(Expression, Expression),
Then(Expression, Expression),
Io(IoExpressionInner, Expression),
}
impl ExpressionInner {
fn start(&self, context: IoContext) -> io::Result<HandleInner> {
match *self {
Cmd(ref argv) => start_argv(argv, context),
Sh(ref command) => start_sh(command, context),
Pipe(ref left, ref right) => {
Ok(HandleInner::Pipe(Box::new(PipeHandle::start(left, right, context)?)))
}
Then(ref left, ref right) => {
Ok(HandleInner::Then(Box::new(ThenHandle::start(left, right.clone(), context)?)))
}
Io(ref io_inner, ref expr) => start_io(io_inner, expr, context),
}
}
}
fn start_argv(argv: &[OsString], context: IoContext) -> io::Result<HandleInner> {
let exe = canonicalize_exe_path_for_dir(&argv[0], &context)?;
let mut command = Command::new(exe);
command.args(&argv[1..]);
// TODO: Avoid unnecessary dup'ing here.
command.stdin(context.stdin.into_stdio()?);
command.stdout(context.stdout.into_stdio()?);
command.stderr(context.stderr.into_stdio()?);
if let Some(dir) = context.dir {
command.current_dir(dir);
}
command.env_clear();
for (name, val) in context.env {
command.env(name, val);
}
let shared_child = SharedChild::spawn(&mut command)?;
let command_string = format!("{:?}", argv);
Ok(HandleInner::Child(shared_child, command_string))
}
#[cfg(unix)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
[OsStr::new("/bin/sh").to_owned(), OsStr::new("-c").to_owned(), command]
}
#[cfg(windows)]
fn shell_command_argv(command: OsString) -> [OsString; 3] {
let comspec = std::env::var_os("COMSPEC").unwrap_or(OsStr::new("cmd.exe").to_owned());
[comspec, OsStr::new("/C").to_owned(), command]
}
fn start_sh(command: &OsString, context: IoContext) -> io::Result<HandleInner> {
start_argv(&shell_command_argv(command.clone()), context)
}
fn wait_child(shared_child: &SharedChild,
command_string: &str,
mode: WaitMode)
-> io::Result<Option<ExpressionStatus>> {
let maybe_status = match mode {
WaitMode::Blocking => Some(shared_child.wait()?),
WaitMode::Nonblocking => shared_child.try_wait()?,
};
if let Some(status) = maybe_status {
Ok(Some(ExpressionStatus {
status: status,
checked: true,
command: command_string.to_owned(),
}))
} else {
Ok(None)
}
}
struct PipeHandle {
left_handle: HandleInner,
right_start_result: io::Result<HandleInner>,
}
impl PipeHandle {
fn start(left: &Expression, right: &Expression, context: IoContext) -> io::Result<PipeHandle> {
let (reader, writer) = os_pipe::pipe()?;
let mut left_context = context.try_clone()?; // dup'ing stdin/stdout isn't strictly necessary, but no big deal
left_context.stdout = IoValue::File(File::from_file(writer));
let mut right_context = context;
right_context.stdin = IoValue::File(File::from_file(reader));
// Errors starting the left side just short-circuit us.
let left_handle = left.0.start(left_context)?;
// Now the left has started, and we *must* return a handle. No more
// short-circuiting.
let right_result = right.0.start(right_context);
Ok(PipeHandle {
left_handle: left_handle,
right_start_result: right_result,
})
}
// Waiting on a pipe expression is tricky. The right side might've failed to
// start before we even got here. Or we might hit an error waiting on the
// left side, before we try to wait on the right. No matter what happens, we
// must call wait on *both* sides (if they're running), to make sure that
// errors on one side don't cause us to leave zombie processes on the other
// side.
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
// Even if the right side never started, the left side did. Wait for it.
// Don't short circuit until after we wait on the right side though.
let left_wait_result = self.left_handle.wait(mode);
// Now if the right side never started at all, we just return that
// error, regardless of how the left turned out. (Recall that if the
// left never started, we won't get here at all.)
let right_handle = match self.right_start_result {
Ok(ref handle) => handle,
Err(ref err) => return Err(clone_io_error(err)),
};
// The right side did start, so we need to wait on it.
let right_wait_result = right_handle.wait(mode);
// Now we deal with errors from either of those waits. The left wait
// happened first, so that one takes precedence. Note that this is the
// reverse order of exit status precedence.
let left_status = left_wait_result?;
let right_status = right_wait_result?;
// Now return one of the two statuses.
Ok(pipe_status_precedence(left_status, right_status))
}
// As with wait, we need to call kill on both sides even if the left side
// returns an error. But if the right side never started, we'll ignore it.
fn kill(&self) -> io::Result<()> {
let left_kill_result = self.left_handle.kill();
if let Ok(ref right_handle) = self.right_start_result {
let right_kill_result = right_handle.kill();
// As with wait, the left side happened first, so its errors take
// precedence.
left_kill_result.and(right_kill_result)
} else {
left_kill_result
}
}
}
// The rules of precedence are:
// 1) If either side unfinished, the result is unfinished.
// 2) Checked errors trump unchecked errors.
// 3) Any errors trump success.
// 4) All else equal, the right side wins.
fn pipe_status_precedence(left_maybe_status: Option<ExpressionStatus>,
right_maybe_status: Option<ExpressionStatus>)
-> Option<ExpressionStatus> {
let (left_status, right_status) = match (left_maybe_status, right_maybe_status) {
(Some(left), Some(right)) => (left, right),
_ => return None,
};
Some(if right_status.is_checked_error() {
right_status
} else if left_status.is_checked_error() {
left_status
} else if !right_status.status.success() {
right_status
} else {
left_status
})
}
// A "then" expression must start the right side as soon as the left is
// finished, even if the original caller isn't waiting on it yet. We do that
// with a background thread.
struct ThenHandle {
shared_state: Arc<ThenHandleInner>,
background_waiter: SharedThread<io::Result<ExpressionStatus>>,
}
impl ThenHandle {
fn start(left: &Expression, right: Expression, context: IoContext) -> io::Result<ThenHandle> {
let left_context = context.try_clone()?;
let left_handle = left.0.start(left_context)?;
let shared = Arc::new(ThenHandleInner {
left_handle: left_handle,
right_lock: Mutex::new(Some((right, context))),
right_cell: AtomicLazyCell::new(),
});
let clone = shared.clone();
let background_waiter = std::thread::spawn(move || {
Ok(clone.wait(WaitMode::Blocking)?.expect("blocking wait can't return None"))
});
Ok(ThenHandle {
shared_state: shared,
background_waiter: SharedThread::new(background_waiter),
})
}
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
// ThenHandleInner does most of the heavy lifting. We just need to join
// the background waiter if the expression is finished. Similar to
// wait_input, blocking mode *must* clean up even in the presence of
// errors, but we *must not* do a potentially blocking join if we're in
// nonblocking mode.
let wait_res = self.shared_state.wait(mode);
if mode.should_join_background_thread(&wait_res) {
self.background_waiter.join().as_ref().map_err(clone_io_error)?;
}
wait_res
}
fn kill(&self) -> io::Result<()> {
self.shared_state.kill()
}
}
// This is the state that gets shared with the background waiter thread.
struct ThenHandleInner {
left_handle: HandleInner,
right_lock: Mutex<Option<(Expression, IoContext)>>,
right_cell: AtomicLazyCell<io::Result<HandleInner>>,
}
impl ThenHandleInner {
fn wait(&self, mode: WaitMode) -> io::Result<Option<ExpressionStatus>> {
// Wait for the left side to finish. If the left side hasn't finished
// yet (in nonblocking mode), short-circuit.
let left_status = match self.left_handle.wait(mode)? {
Some(status) => status,
None => return Ok(None),
};
// The left side has finished, so now we *must* try to take ownership of
// the right IoContext. If we get it, and if the left side isn't a
// checked error, then we'll start the right child. But no matter what,
// we can't leave that IoContext alive. There are write pipes in it that
// will deadlock the top level wait otherwise.
//
// We also need to keep holding this lock until we finish starting the
// right side. Kill will take the same lock, and that avoids the race
// condition where one thread gets the right context, kill happens, and
// *then* the first thread starts the right.
let mut right_lock_guard = self.right_lock.lock().unwrap();
let maybe_expression_context = right_lock_guard.take();
// Checked errors on the left side will short-circuit the right. As
// noted above, this will still drop the right IoContext, if any.
if left_status.is_checked_error() {
return Ok(Some(left_status));
}
// Now if we got the right expression above, we're responsible for
// starting it. Otherwise either it's already been started, or this
// expression has been killed.
if let Some((expression, context)) = maybe_expression_context {
let right_start_result = expression.0.start(context);
self.right_cell
.fill(right_start_result)
.map_err(|_| "right_cell unexpectedly filled")
.unwrap();
}
// Release the right lock. Kills may now happen on other threads. It's
// important that we don't hold this lock during waits.
drop(right_lock_guard);
// Wait on the right side, if it was started. There are two ways it
// might not have been started:
// 1) Start might've returned an error. We'll just clone it.
// 2) The expression might've been killed before we started the right
// side. We'll return the left side's result. Note that it's possible
// that the kill happened precisely in between the left exit and the
// right start, in which case the left exit status could actually be
// success.
match self.right_cell.borrow() {
Some(&Ok(ref handle)) => handle.wait(mode),
Some(&Err(ref err)) => Err(clone_io_error(err)),
None => Ok(Some(left_status)),
}
}
fn kill(&self) -> io::Result<()> {
// Lock and clear the right context first, so that it can't be started
// if it hasn't been already. This is important because if the left side
// is unchecked, a waiting thread will ignore its killed exit status and
// try to start the right side anyway.
let mut right_lock_guard = self.right_lock.lock().unwrap();
*right_lock_guard = None;
// Try to kill both sides, even if the first kill fails for some reason.
let left_result = self.left_handle.kill();
if let Some(&Ok(ref handle)) = self.right_cell.borrow() {
let right_result = handle.kill();
left_result.and(right_result)
} else {
left_result
}
}
}
fn start_io(io_inner: &IoExpressionInner,
expr_inner: &Expression,
mut context: IoContext)
-> io::Result<HandleInner> {
match *io_inner {
Input(ref v) => return start_input(expr_inner, context, v.clone()),
Stdin(ref p) => {
context.stdin = IoValue::File(File::open(p)?);
}
StdinFile(ref f) => {
context.stdin = IoValue::File(f.try_clone()?);
}
StdinNull => {
context.stdin = IoValue::Null;
}
Stdout(ref p) => {
context.stdout = IoValue::File(File::create(p)?);
}
StdoutFile(ref f) => {
context.stdout = IoValue::File(f.try_clone()?);
}
StdoutNull => {
context.stdout = IoValue::Null;
}
StdoutCapture => {
context.stdout = IoValue::File(context.stdout_capture.try_clone()?);
}
StdoutToStderr => {
context.stdout = context.stderr.try_clone()?;
}
Stderr(ref p) => {
context.stderr = IoValue::File(File::create(p)?);
}
StderrFile(ref f) => {
context.stderr = IoValue::File(f.try_clone()?);
}
StderrNull => {
context.stderr = IoValue::Null;
}
StderrCapture => context.stderr = IoValue::File(context.stderr_capture.try_clone()?),
StderrToStdout => {
context.stderr = context.stdout.try_clone()?;
}
Dir(ref p) => {
context.dir = Some(p.clone());
}
Env(ref name, ref val) => {
context.env.insert(name.clone(), val.clone());
}
FullEnv(ref map) => {
context.env = map.clone();
}
Unchecked => {
let inner_handle = expr_inner.0.start(context)?;
return Ok(HandleInner::Unchecked(Box::new(inner_handle)));
}
}
expr_inner.0.start(context)
}
fn start_input(expression: &Expression,
mut context: IoContext,
input: Arc<Vec<u8>>)
-> io::Result<HandleInner> {
let (reader, mut writer) = os_pipe::pipe()?;
context.stdin = IoValue::File(File::from_file(reader));
let inner = expression.0.start(context)?;
// We only spawn the writer thread if the expression started successfully,
// so that start errors won't leak a zombie thread.
let thread = std::thread::spawn(move || writer.write_all(&input));
Ok(HandleInner::Input(Box::new(inner), SharedThread::new(thread)))
}
fn wait_input(inner_handle: &HandleInner,
writer_thread: &WriterThread,
mode: WaitMode)
-> io::Result<Option<ExpressionStatus>> {
// We're responsible for joining the writer thread and not leaving a zombie.
// But waiting on the inner child can return an error, and in that case we
// don't know whether the child is still running or not. The rule in
// nonblocking mode is "clean up as much as we can, but never block," so we
// can't wait on the writer thread. But the rule in blocking mode is "clean
// up everything, even if some cleanup returns errors," so we must wait
// regardless of what's going on with the child.
let wait_res = inner_handle.wait(mode);
if mode.should_join_background_thread(&wait_res) {
// Join the writer thread. Broken pipe errors here are expected if
// the child exited without reading all of its input, so we suppress
// them. Return other errors though.
match *writer_thread.join() {
Err(ref err) if err.kind() != io::ErrorKind::BrokenPipe => {
return Err(clone_io_error(err));
}
_ => {}
}
}
wait_res
}
#[derive(Debug)]
enum IoExpressionInner {
Input(Arc<Vec<u8>>),
Stdin(PathBuf),
StdinFile(File),
StdinNull,
Stdout(PathBuf),
StdoutFile(File),
StdoutNull,
StdoutCapture,
StdoutToStderr,
Stderr(PathBuf),
StderrFile(File),
StderrNull,
StderrCapture,
StderrToStdout,
Dir(PathBuf),
Env(OsString, OsString),
FullEnv(HashMap<OsString, OsString>),
Unchecked,
}
// An IoContext represents the file descriptors child processes are talking to at execution time.
// It's initialized in run(), with dups of the stdin/stdout/stderr pipes, and then passed down to
// sub-expressions. Compound expressions will clone() it, and redirections will modify it.
#[derive(Debug)]
struct IoContext {
stdin: IoValue,
stdout: IoValue,
stderr: IoValue,
stdout_capture: File,
stderr_capture: File,
dir: Option<PathBuf>,
env: HashMap<OsString, OsString>,
}
impl IoContext {
// Returns (context, stdout_reader, stderr_reader).
fn new() -> io::Result<(IoContext, ReaderThread, ReaderThread)> {
let (stdout_capture, stdout_reader) = pipe_with_reader_thread()?;
let (stderr_capture, stderr_reader) = pipe_with_reader_thread()?;
let mut env = HashMap::new();
for (name, val) in std::env::vars_os() {
env.insert(name, val);
}
let context = IoContext {
stdin: IoValue::ParentStdin,
stdout: IoValue::ParentStdout,
stderr: IoValue::ParentStderr,
stdout_capture: stdout_capture,
stderr_capture: stderr_capture,
dir: None,
env: env,
};
Ok((context, stdout_reader, stderr_reader))
}
fn try_clone(&self) -> io::Result<IoContext> {
Ok(IoContext {
stdin: self.stdin.try_clone()?,
stdout: self.stdout.try_clone()?,
stderr: self.stderr.try_clone()?,
stdout_capture: self.stdout_capture.try_clone()?,
stderr_capture: self.stderr_capture.try_clone()?,
dir: self.dir.clone(),
env: self.env.clone(),
})
}
}
#[derive(Debug)]
enum IoValue {
ParentStdin,
ParentStdout,
ParentStderr,
Null,
File(File),
}
impl IoValue {
fn try_clone(&self) -> io::Result<IoValue> {
Ok(match self {
&IoValue::ParentStdin => IoValue::ParentStdin,
&IoValue::ParentStdout => IoValue::ParentStdout,
&IoValue::ParentStderr => IoValue::ParentStderr,
&IoValue::Null => IoValue::Null,
&IoValue::File(ref f) => IoValue::File(f.try_clone()?),
})
}
fn into_stdio(self) -> io::Result<Stdio> {
match self {
IoValue::ParentStdin => os_pipe::parent_stdin(),
IoValue::ParentStdout => os_pipe::parent_stdout(),
IoValue::ParentStderr => os_pipe::parent_stderr(),
IoValue::Null => Ok(Stdio::null()),
IoValue::File(f) => Ok(Stdio::from_file(f)),
}
}
}
// This struct keeps track of a child exit status, whether or not it's been
// unchecked(), and what the command was that gave it (for error messages).
#[derive(Clone, Debug)]
struct ExpressionStatus {
status: ExitStatus,
checked: bool,
command: String,
}
impl ExpressionStatus {
fn is_checked_error(&self) -> bool {
self.checked && !self.status.success()
}
fn message(&self) -> String {
format!("command {} exited with code {}",
self.command,
self.exit_code_string())
}
#[cfg(not(windows))]
fn exit_code_string(&self) -> String {
use std::os::unix::process::ExitStatusExt;
if self.status.code().is_none() {
return format!("<signal {}>", self.status.signal().unwrap());
}
self.status.code().unwrap().to_string()
}
#[cfg(windows)]
fn exit_code_string(&self) -> String {
self.status.code().unwrap().to_string()
}
}
fn canonicalize_exe_path_for_dir(exe_name: &OsStr, context: &IoContext) -> io::Result<OsString> {
// There's a tricky interaction between exe paths and `dir`. Exe
// paths can be relative, and so we have to ask: Is an exe path
// interpreted relative to the parent's cwd, or the child's? The
// answer is that it's platform dependent! >.< (Windows uses the
// parent's cwd, but because of the fork-chdir-exec pattern, Unix
// usually uses the child's.)
//
// We want to use the parent's cwd consistently, because that saves
// the caller from having to worry about whether `dir` will have
// side effects, and because it's easy for the caller to use
// Path::join if they want to. That means that when `dir` is in use,
// we need to detect exe names that are relative paths, and
// absolutify them. We want to do that as little as possible though,
// both because canonicalization can fail, and because we prefer to
// let the caller control the child's argv[0].
//
// We never want to absolutify a name like "emacs", because that's
// probably a program in the PATH rather than a local file. So we
// look for slashes in the name to determine what's a filepath and
// what isn't. Note that anything given as a std::path::Path will
// always have a slash by the time we get here, because we
// specialize the ToExecutable trait to prepend a ./ to them when
// they're relative. This leaves the case where Windows users might
// pass a local file like "foo.bat" as a string, which we can't
// distinguish from a global program name. However, because the
// Windows has the preferred "relative to parent's cwd" behavior
// already, this case actually works without our help. (The thing
// Windows users have to watch out for instead is local files
// shadowing global program names, which I don't think we can or
// should prevent.)
let has_separator = exe_name.to_string_lossy().chars().any(std::path::is_separator);
let is_relative = Path::new(exe_name).is_relative();
if context.dir.is_some() && has_separator && is_relative {
Path::new(exe_name).canonicalize().map(Into::into)
} else {
Ok(exe_name.to_owned())
}
}
// We want to allow Path("foo") to refer to the local file "./foo" on
// Unix, and we want to *prevent* Path("echo") from referring to the
// global "echo" command on either Unix or Windows. Prepend a dot to all
// relative paths to accomplish both of those.
fn dotify_relative_exe_path(path: &Path) -> PathBuf {
// This is a no-op if path is absolute or begins with a Windows prefix.
Path::new(".").join(path)
}
/// `duct` provides several impls of this trait to handle the difference between
/// [`Path`](https://doc.rust-lang.org/std/path/struct.Path.html)/[`PathBuf`](https://doc.rust-lang.org/std/path/struct.PathBuf.html)
/// and other types of strings. In particular, `duct` automatically prepends a
/// leading dot to relative paths (though not other string types) before
/// executing them. This is required for single-component relative paths to work
/// at all on Unix, and it prevents aliasing with programs in the global `PATH`
/// on both Unix and Windows. See the trait bounds on [`cmd`](fn.cmd.html) and
/// [`sh`](fn.sh.html).
pub trait ToExecutable {
fn to_executable(self) -> OsString;
}
// TODO: Get rid of most of these impls once specialization lands.
impl<'a> ToExecutable for &'a Path {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(self).into()
}
}
impl ToExecutable for PathBuf {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(&self).into()
}
}
impl<'a> ToExecutable for &'a PathBuf {
fn to_executable(self) -> OsString {
dotify_relative_exe_path(self).into()
}
}
impl<'a> ToExecutable for &'a str {
fn to_executable(self) -> OsString {
self.into()
}
}
impl ToExecutable for String {
fn to_executable(self) -> OsString {
self.into()
}
}
impl<'a> ToExecutable for &'a String {
fn to_executable(self) -> OsString {
self.into()
}
}
impl<'a> ToExecutable for &'a OsStr {
fn to_executable(self) -> OsString {
self.into()
}
}
impl ToExecutable for OsString {
fn to_executable(self) -> OsString {
self
}
}
impl<'a> ToExecutable for &'a OsString {
fn to_executable(self) -> OsString {
self.into()
}
}
type ReaderThread = JoinHandle<io::Result<Vec<u8>>>;
fn pipe_with_reader_thread() -> io::Result<(File, ReaderThread)> {
let (mut reader, writer) = os_pipe::pipe()?;
let thread = std::thread::spawn(move || {
let mut output = Vec::new();
reader.read_to_end(&mut output)?;
Ok(output)
});
Ok((File::from_file(writer), thread))
}
type WriterThread = SharedThread<io::Result<()>>;
fn trim_right_newlines(s: &str) -> &str {
s.trim_right_matches(|c| c == '\n' || c == '\r')
}
// io::Error doesn't implement clone directly, so we kind of hack it together.
fn clone_io_error(error: &io::Error) -> io::Error {
if let Some(code) = error.raw_os_error() {
io::Error::from_raw_os_error(code)
} else {
io::Error::new(error.kind(), error.to_string())
}
}
struct SharedThread<T> {
result: AtomicLazyCell<T>,
handle: Mutex<Option<JoinHandle<T>>>,
}
// A thread that sticks its result in a lazy cell, so that multiple callers can see it.
impl<T> SharedThread<T> {
fn new(handle: JoinHandle<T>) -> Self {
SharedThread {
result: AtomicLazyCell::new(),
handle: Mutex::new(Some(handle)),
}
}
// If the other thread panicked, this will panic.
fn join(&self) -> &T {
let mut handle_lock = self.handle.lock().expect("shared thread handle poisoned");
if let Some(handle) = handle_lock.take() {
let ret = handle.join().expect("panic on shared thread");
self.result.fill(ret).map_err(|_| "result lazycell unexpectedly full").unwrap();
}
self.result.borrow().expect("result lazycell unexpectedly empty")
}
}
#[derive(Clone, Copy, Debug)]
enum WaitMode {
Blocking,
Nonblocking,
}
impl WaitMode {
fn should_join_background_thread(&self,
expression_result: &io::Result<Option<ExpressionStatus>>)
-> bool {
// Nonblocking waits can only join associated background threads if the
// running expression is finished (that is, when the thread is
// guaranteed to finish soon). Blocking waits should always join, even
// in the presence of errors.
match (self, expression_result) {
(&WaitMode::Blocking, _) => true,
(_, &Ok(Some(_))) => true,
_ => false,
}
}
}
#[cfg(test)]
mod test;
|
//! ### rust-mysql-simple
//! Mysql client library implemented in rust nightly.
//!
//! #### Install
//! Please use *mysql* crate:
//!
//! ```toml
//! [dependencies]
//! mysql = "*"
//! ```
//!
//! rust-mysql-simple offers support of SSL via `ssl` cargo feature which is enabled by default.
//! If you have no plans to use SSL, then you should disable that feature to not to depend on
//! rust-openssl:
//!
//! ```toml
//! [dependencies.mysql]
//! mysql = "*"
//! default-features = false
//! features = ["socket"]
//! ```
//!
//! #### Windows support (since 0.18.0)
//!
//! Currently rust-mysql-simple has no support for SSL on Windows.
//!
//! ```toml
//! [dependencies.mysql]
//! mysql = "*"
//! default-features = false
//! features = ["pipe"]
//! ```
//!
//! #### Use
//! You should start by creating [`Opts`](conn/struct.Opts.html) struct.
//!
//! Then you can create [`Pool`](conn/pool/struct.Pool.html) which should be
//! enough to work with mysql server.
//!
//! ##### Example
//!
//! ```rust
//! use std::default::Default;
//!
//! use mysql::conn::Opts;
//! use mysql::conn::pool::Pool;
//! use mysql::value::from_row;
//!
//! #[derive(Debug, PartialEq, Eq)]
//! struct Payment {
//! customer_id: i32,
//! amount: i32,
//! account_name: Option<String>,
//! }
//!
//! fn main() {
//! let pool = Pool::new("mysql://root:password@localhost:3307").unwrap();
//! # let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or("password".to_string());
//! # let port: u16 = ::std::env::var("MYSQL_SERVER_PORT").ok()
//! # .map(|my_port| my_port.parse::<u16>().ok().unwrap_or(3307))
//! # .unwrap_or(3307);
//! # let opts = Opts {
//! # user: Some("root".to_string()),
//! # pass: Some(pwd),
//! # ip_or_hostname: Some("127.0.0.1".to_string()),
//! # tcp_port: port,
//! # ..Default::default()
//! # };
//! # let pool = Pool::new(opts).unwrap();
//!
//! // Let's create payment table.
//! // It is temporary so we do not need `tmp` database to exist.
//! // Unwap just to make sure no error happened.
//! pool.prep_exec(r"CREATE TEMPORARY TABLE tmp.payment (
//! customer_id int not null,
//! amount int not null,
//! account_name text
//! )", ()).unwrap();
//!
//! let payments = vec![
//! Payment { customer_id: 1, amount: 2, account_name: None },
//! Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) },
//! Payment { customer_id: 5, amount: 6, account_name: None },
//! Payment { customer_id: 7, amount: 8, account_name: None },
//! Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) },
//! ];
//!
//! // Let's insert payments to the database
//! // We will use into_iter() because we do not need to map Stmt to anything else.
//! // Also we assume that no error happened in `prepare`.
//! for mut stmt in pool.prepare(r"INSERT INTO tmp.payment
//! (customer_id, amount, account_name)
//! VALUES
//! (?, ?, ?)").into_iter() {
//! for p in payments.iter() {
//! // `execute` takes ownership of `params` so we pass account name by reference.
//! // Unwrap each result just to make sure no errors happended.
//! stmt.execute((p.customer_id, p.amount, &p.account_name)).unwrap();
//! }
//! }
//!
//! // Let's select payments from database
//! let selected_payments: Vec<Payment> =
//! pool.prep_exec("SELECT customer_id, amount, account_name from tmp.payment", ())
//! .map(|result| { // In this closure we sill map `QueryResult` to `Vec<Payment>`
//! // `QueryResult` is iterator over `MyResult<row, err>` so first call to `map`
//! // will map each `MyResult` to contained `row` (no proper error handling)
//! // and second call to `map` will map each `row` to `Payment`
//! result.map(|x| x.unwrap()).map(|row| {
//! let (customer_id, amount, account_name) = from_row(row);
//! Payment {
//! customer_id: customer_id,
//! amount: amount,
//! account_name: account_name,
//! }
//! }).collect() // Collect payments so now `QueryResult` is mapped to `Vec<Payment>`
//! }).unwrap(); // Unwrap `Vec<Payment>`
//!
//! // Now make shure that `payments` equals to `selected_payments`.
//! // Mysql gives no guaranties on order of returned rows without `ORDER BY`
//! // so assume we are lukky.
//! assert_eq!(payments, selected_payments);
//! println!("Yay!");
//! }
//! ```
#![crate_name="mysql"]
#![crate_type="rlib"]
#![crate_type="dylib"]
#![cfg_attr(feature = "nightly", feature(test, const_fn))]
#[cfg(feature = "nightly")]
extern crate test;
extern crate time;
#[cfg(feature = "openssl")]
extern crate openssl;
extern crate regex;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;
extern crate byteorder;
#[cfg(feature = "socket")]
extern crate unix_socket;
#[cfg(feature = "pipe")]
extern crate named_pipe;
extern crate url;
mod scramble;
pub mod consts;
pub mod error;
mod packet;
mod io;
pub mod value;
pub mod conn;
Reexport everything meaningful to the upper level
//! ### rust-mysql-simple
//! Mysql client library implemented in rust nightly.
//!
//! #### Install
//! Please use *mysql* crate:
//!
//! ```toml
//! [dependencies]
//! mysql = "*"
//! ```
//!
//! rust-mysql-simple offers support of SSL via `ssl` cargo feature which is enabled by default.
//! If you have no plans to use SSL, then you should disable that feature to not to depend on
//! rust-openssl:
//!
//! ```toml
//! [dependencies.mysql]
//! mysql = "*"
//! default-features = false
//! features = ["socket"]
//! ```
//!
//! #### Windows support (since 0.18.0)
//!
//! Currently rust-mysql-simple has no support for SSL on Windows.
//!
//! ```toml
//! [dependencies.mysql]
//! mysql = "*"
//! default-features = false
//! features = ["pipe"]
//! ```
//!
//! #### Use
//! You should start by creating [`Opts`](conn/struct.Opts.html) struct.
//!
//! Then you can create [`Pool`](conn/pool/struct.Pool.html) which should be
//! enough to work with mysql server.
//!
//! ##### Example
//!
//! ```rust
//! use std::default::Default;
//!
//! use mysql::conn::Opts;
//! use mysql::conn::pool::Pool;
//! use mysql::value::from_row;
//!
//! #[derive(Debug, PartialEq, Eq)]
//! struct Payment {
//! customer_id: i32,
//! amount: i32,
//! account_name: Option<String>,
//! }
//!
//! fn main() {
//! let pool = Pool::new("mysql://root:password@localhost:3307").unwrap();
//! # let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or("password".to_string());
//! # let port: u16 = ::std::env::var("MYSQL_SERVER_PORT").ok()
//! # .map(|my_port| my_port.parse::<u16>().ok().unwrap_or(3307))
//! # .unwrap_or(3307);
//! # let opts = Opts {
//! # user: Some("root".to_string()),
//! # pass: Some(pwd),
//! # ip_or_hostname: Some("127.0.0.1".to_string()),
//! # tcp_port: port,
//! # ..Default::default()
//! # };
//! # let pool = Pool::new(opts).unwrap();
//!
//! // Let's create payment table.
//! // It is temporary so we do not need `tmp` database to exist.
//! // Unwap just to make sure no error happened.
//! pool.prep_exec(r"CREATE TEMPORARY TABLE tmp.payment (
//! customer_id int not null,
//! amount int not null,
//! account_name text
//! )", ()).unwrap();
//!
//! let payments = vec![
//! Payment { customer_id: 1, amount: 2, account_name: None },
//! Payment { customer_id: 3, amount: 4, account_name: Some("foo".into()) },
//! Payment { customer_id: 5, amount: 6, account_name: None },
//! Payment { customer_id: 7, amount: 8, account_name: None },
//! Payment { customer_id: 9, amount: 10, account_name: Some("bar".into()) },
//! ];
//!
//! // Let's insert payments to the database
//! // We will use into_iter() because we do not need to map Stmt to anything else.
//! // Also we assume that no error happened in `prepare`.
//! for mut stmt in pool.prepare(r"INSERT INTO tmp.payment
//! (customer_id, amount, account_name)
//! VALUES
//! (?, ?, ?)").into_iter() {
//! for p in payments.iter() {
//! // `execute` takes ownership of `params` so we pass account name by reference.
//! // Unwrap each result just to make sure no errors happended.
//! stmt.execute((p.customer_id, p.amount, &p.account_name)).unwrap();
//! }
//! }
//!
//! // Let's select payments from database
//! let selected_payments: Vec<Payment> =
//! pool.prep_exec("SELECT customer_id, amount, account_name from tmp.payment", ())
//! .map(|result| { // In this closure we sill map `QueryResult` to `Vec<Payment>`
//! // `QueryResult` is iterator over `MyResult<row, err>` so first call to `map`
//! // will map each `MyResult` to contained `row` (no proper error handling)
//! // and second call to `map` will map each `row` to `Payment`
//! result.map(|x| x.unwrap()).map(|row| {
//! let (customer_id, amount, account_name) = from_row(row);
//! Payment {
//! customer_id: customer_id,
//! amount: amount,
//! account_name: account_name,
//! }
//! }).collect() // Collect payments so now `QueryResult` is mapped to `Vec<Payment>`
//! }).unwrap(); // Unwrap `Vec<Payment>`
//!
//! // Now make shure that `payments` equals to `selected_payments`.
//! // Mysql gives no guaranties on order of returned rows without `ORDER BY`
//! // so assume we are lukky.
//! assert_eq!(payments, selected_payments);
//! println!("Yay!");
//! }
//! ```
#![crate_name="mysql"]
#![crate_type="rlib"]
#![crate_type="dylib"]
#![cfg_attr(feature = "nightly", feature(test, const_fn))]
#[cfg(feature = "nightly")]
extern crate test;
extern crate time;
#[cfg(feature = "openssl")]
extern crate openssl;
extern crate regex;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;
extern crate byteorder;
#[cfg(feature = "socket")]
extern crate unix_socket;
#[cfg(feature = "pipe")]
extern crate named_pipe;
extern crate url;
mod scramble;
pub mod consts;
pub mod error;
mod packet;
mod io;
pub mod value;
pub mod conn;
pub use conn::Column;
pub use conn::Conn;
pub use conn::IsolationLevel;
pub use conn::Opts;
pub use conn::QueryResult;
pub use conn::Row;
pub use conn::Stmt;
pub use conn::Transaction;
pub use conn::pool::Pool;
pub use conn::pool::PooledConn;
pub use error::DriverError;
pub use error::Error;
pub use error::ErrPacket;
pub use error::Result;
pub use error::ServerError;
pub use value::ConvIr;
pub use value::FromRow;
pub use value::FromValue;
pub use value::Params;
pub use value::ToValue;
pub use value::Value;
pub use value::from_row;
pub use value::from_row_opt;
pub use value::from_value;
pub use value::from_value_opt;
|
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![recursion_limit="1000"]
extern crate libc;
use libc::size_t;
use std::os::raw::{c_void, c_int, c_uint, c_char};
pub mod placeholders {
include!(concat!(env!("OUT_DIR"), "/placeholders.rs"));
}
#[macro_use]
mod macros;
pub mod arm;
pub mod arm64;
pub mod mips;
pub mod ppc;
pub mod sparc;
pub mod sysz;
pub mod x86;
pub mod xcore;
// automatically generated by rust-bindgen
// then heavily modified
pub type csh = size_t;
fake_enum! {
/// Architecture type
pub enum cs_arch {
/// ARM architecture (including Thumb, Thumb-2)
CS_ARCH_ARM = 0,
/// ARM-64, also called AArch64
CS_ARCH_ARM64 = 1,
/// Mips architecture
CS_ARCH_MIPS = 2,
/// X86 architecture (including x86 & x86-64)
CS_ARCH_X86 = 3,
/// PowerPC architecture
CS_ARCH_PPC = 4,
/// Sparc architecture
CS_ARCH_SPARC = 5,
/// SystemZ architecture
CS_ARCH_SYSZ = 6,
/// XCore architecture
CS_ARCH_XCORE = 7,
CS_ARCH_MAX = 8,
/// All architecture for `cs_support`
CS_ARCH_ALL = 0xFFFF,
}
}
fake_enum! {
/// Mode type (architecture variant, not all combination are possible)
pub enum cs_mode {
/// Little-endian mode (default mode)
CS_MODE_LITTLE_ENDIAN = 0,
/// 32-bit ARM
CS_MODE_ARM = 0,
/// 16-bit mode X86
CS_MODE_16 = 1 << 1,
/// 32-bit mode X86
CS_MODE_32 = 1 << 2,
/// 64-bit mode X86
CS_MODE_64 = 1 << 3,
/// ARM's Thumb mode, including Thumb-2
CS_MODE_THUMB = 1 << 4,
/// ARM's Cortex-M series
CS_MODE_MCLASS = 1 << 5,
/// ARMv8 A32 encodings for ARM
CS_MODE_V8 = 1 << 6,
/// MicroMips mode (MIPS)
CS_MODE_MICRO = 1 << 4,
/// Mips III ISA
CS_MODE_MIPS3 = 1 << 5,
/// Mips32r6 ISA
CS_MODE_MIPS32R6 = 1 << 6,
/// General Purpose Registers are 64-bit wide (MIPS)
CS_MODE_MIPSGP64 = 1 << 7,
/// SparcV9 mode (Sparc)
CS_MODE_V9 = 1 << 31,
/// big-endian mode
CS_MODE_BIG_ENDIAN = 1 << 31,
/// Mips32 ISA (Mips)
CS_MODE_MIPS32 = CS_MODE_32,
/// Mips64 ISA (Mips)
CS_MODE_MIPS64 = CS_MODE_64,
}
}
pub type cs_malloc_t = Option<extern "C" fn(size: size_t) -> *mut c_void>;
pub type cs_calloc_t = Option<extern "C" fn(nmemb: size_t, size: size_t) -> *mut c_void>;
pub type cs_realloc_t = Option<unsafe extern "C" fn(ptr: *mut c_void, size: size_t) -> *mut c_void>;
pub type cs_free_t = Option<unsafe extern "C" fn(ptr: *mut c_void)>;
pub type cs_vsnprintf_t = Option<unsafe extern "C" fn()>;
// pub type cs_vsnprintf_t = Option<unsafe extern "C" fn(str: *mut c_char,
// size: size_t,
// format: *const c_char,
// ap: va_list)
// -> c_int>;
#[repr(C)]
pub struct cs_opt_mem {
pub malloc: cs_malloc_t,
pub calloc: cs_calloc_t,
pub realloc: cs_realloc_t,
pub free: cs_free_t,
pub vsnprintf: cs_vsnprintf_t,
}
impl ::std::default::Default for cs_opt_mem {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
fake_enum! {
/// Runtime option for the disassembled engine
pub enum cs_opt_type {
/// Assembly output syntax
CS_OPT_SYNTAX = 1,
/// Break down instruction structure into details
CS_OPT_DETAIL,
/// Change engine's mode at run-time
CS_OPT_MODE,
/// User-defined dynamic memory related functions
CS_OPT_MEM,
/// Skip data when disassembling. Then engine is in SKIPDATA mode.
CS_OPT_SKIPDATA,
/// Setup user-defined function for SKIPDATA option
CS_OPT_SKIPDATA_SETUP,
}
}
fake_enum! {
/// Runtime option value (associated with option type above)
pub enum cs_opt_value {
/// Turn OFF an option - default option of CS_OPT_DETAIL, CS_OPT_SKIPDATA.
CS_OPT_OFF = 0,
/// Turn ON an option (CS_OPT_DETAIL, CS_OPT_SKIPDATA).
CS_OPT_ON = 3,
/// Default asm syntax (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_DEFAULT = 0,
/// X86 Intel asm syntax - default on X86 (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_INTEL,
/// X86 ATT asm syntax (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_ATT,
/// Prints register name with only number (CS_OPT_SYNTAX)
CS_OPT_SYNTAX_NOREGNAME,
}
}
fake_enum! {
/// Common instruction operand types - to be consistent across all architectures.
pub enum cs_op_type {
/// Uninitialized/invalid operand.
CS_OP_INVALID = 0,
/// Register operand.
CS_OP_REG = 1,
/// Immediate operand.
CS_OP_IMM = 2,
/// Memory operand.
CS_OP_MEM = 3,
/// Floating-Point operand.
CS_OP_FP = 4,
}
}
fake_enum! {
/// Common instruction groups - to be consistent across all architectures.
pub enum cs_group_type {
/// uninitialized/invalid group.
CS_GRP_INVALID = 0,
/// all jump instructions (conditional+direct+indirect jumps)
CS_GRP_JUMP,
/// all call instructions
CS_GRP_CALL,
/// all return instructions
CS_GRP_RET,
/// all interrupt instructions (int+syscall)
CS_GRP_INT,
/// all interrupt return instructions
CS_GRP_IRET,
}
}
pub type cs_skipdata_cb_t = Option<unsafe extern "C" fn(code: *const u8,
code_size: size_t,
offset: size_t,
user_data: *mut c_void)
-> size_t>;
#[repr(C)]
pub struct cs_opt_skipdata {
pub mnemonic: *const c_char,
pub callback: cs_skipdata_cb_t,
pub user_data: *mut c_void,
}
impl ::std::default::Default for cs_opt_skipdata {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
pub struct cs_detail {
pub regs_read: [u8; 12usize],
pub regs_read_count: u8,
pub regs_write: [u8; 20usize],
pub regs_write_count: u8,
pub groups: [u8; 8usize],
pub groups_count: u8,
data: placeholders::detail_data,
}
impl cs_detail {
pub unsafe fn x86(&self) -> &x86::cs_x86 {
::std::mem::transmute(&self.data)
}
pub unsafe fn arm64(&self) -> &arm64::cs_arm64 {
::std::mem::transmute(&self.data)
}
pub unsafe fn arm(&self) -> &arm::cs_arm {
::std::mem::transmute(&self.data)
}
pub unsafe fn mips(&self) -> &mips::cs_mips {
::std::mem::transmute(&self.data)
}
pub unsafe fn ppc(&self) -> &ppc::cs_ppc {
::std::mem::transmute(&self.data)
}
pub unsafe fn sparc(&self) -> &sparc::cs_sparc {
::std::mem::transmute(&self.data)
}
pub unsafe fn sysz(&self) -> &sysz::cs_sysz {
::std::mem::transmute(&self.data)
}
pub unsafe fn xcore(&self) -> &xcore::cs_xcore {
::std::mem::transmute(&self.data)
}
}
#[repr(C)]
pub struct cs_insn {
pub id: c_uint,
pub address: u64,
pub size: u16,
pub bytes: [u8; 16usize],
pub mnemonic: [c_char; 32usize],
pub op_str: [c_char; 160usize],
pub detail: *mut cs_detail,
}
fake_enum! {
/// All type of errors encountered by Capstone API.
/// These are values returned by cs_errno()
pub enum cs_err {
/// No error: everything was fine
CS_ERR_OK = 0,
/// Out-Of-Memory error: cs_open(), cs_disasm(), cs_disasm_iter()
CS_ERR_MEM,
/// Unsupported architecture: cs_open()
CS_ERR_ARCH,
/// Invalid handle: cs_op_count(), cs_op_index()
CS_ERR_HANDLE,
/// Invalid csh argument: cs_close(), cs_errno(), cs_option()
CS_ERR_CSH,
/// Invalid/unsupported mode: cs_open()
CS_ERR_MODE,
/// Invalid/unsupported option: cs_option()
CS_ERR_OPTION,
/// Information is unavailable because detail option is OFF
CS_ERR_DETAIL,
/// Dynamic memory management uninitialized (see CS_OPT_MEM)
CS_ERR_MEMSETUP,
/// Unsupported version (bindings)
CS_ERR_VERSION,
/// Access irrelevant data in "diet" engine
CS_ERR_DIET,
/// Access irrelevant data for "data" instruction in SKIPDATA mode
CS_ERR_SKIPDATA,
/// X86 AT&T syntax is unsupported (opt-out at compile time)
CS_ERR_X86_ATT,
/// X86 Intel syntax is unsupported (opt-out at compile time)
CS_ERR_X86_INTEL,
}
}
#[link(name = "capstone", kind = "dylib")]
extern "C" {
pub fn cs_version(major: *mut c_int, minor: *mut c_int) -> c_uint;
pub fn cs_support(query: c_int) -> u8;
pub fn cs_open(arch: cs_arch, mode: cs_mode, handle: *mut csh) -> cs_err;
pub fn cs_close(handle: *mut csh) -> cs_err;
pub fn cs_option(handle: csh, _type: cs_opt_type, value: size_t) -> cs_err;
pub fn cs_errno(handle: csh) -> cs_err;
pub fn cs_strerror(code: cs_err) -> *const c_char;
pub fn cs_disasm(handle: csh,
code: *const u8,
code_size: size_t,
address: u64,
count: size_t,
insn: *mut *mut cs_insn)
-> size_t;
pub fn cs_free(insn: *mut cs_insn, count: size_t);
pub fn cs_malloc(handle: csh) -> *mut cs_insn;
pub fn cs_disasm_iter(handle: csh,
code: *mut *const u8,
size: *mut size_t,
address: *mut u64,
insn: *mut cs_insn)
-> u8;
pub fn cs_reg_name(handle: csh, reg_id: c_uint) -> *const c_char;
pub fn cs_insn_name(handle: csh, insn_id: c_uint) -> *const c_char;
pub fn cs_group_name(handle: csh, group_id: c_uint) -> *const c_char;
pub fn cs_insn_group(handle: csh, insn: *const cs_insn, group_id: c_uint) -> u8;
pub fn cs_reg_read(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8;
pub fn cs_reg_write(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8;
pub fn cs_op_count(handle: csh, insn: *const cs_insn, op_type: c_uint) -> c_int;
pub fn cs_op_index(handle: csh,
insn: *const cs_insn,
op_type: c_uint,
position: c_uint)
-> c_int;
}
Add CS_SUPPORT_ flags
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![recursion_limit="1000"]
extern crate libc;
use libc::size_t;
use std::os::raw::{c_void, c_int, c_uint, c_char};
pub mod placeholders {
include!(concat!(env!("OUT_DIR"), "/placeholders.rs"));
}
#[macro_use]
mod macros;
pub mod arm;
pub mod arm64;
pub mod mips;
pub mod ppc;
pub mod sparc;
pub mod sysz;
pub mod x86;
pub mod xcore;
// automatically generated by rust-bindgen
// then heavily modified
pub type csh = size_t;
fake_enum! {
/// Architecture type
pub enum cs_arch {
/// ARM architecture (including Thumb, Thumb-2)
CS_ARCH_ARM = 0,
/// ARM-64, also called AArch64
CS_ARCH_ARM64 = 1,
/// Mips architecture
CS_ARCH_MIPS = 2,
/// X86 architecture (including x86 & x86-64)
CS_ARCH_X86 = 3,
/// PowerPC architecture
CS_ARCH_PPC = 4,
/// Sparc architecture
CS_ARCH_SPARC = 5,
/// SystemZ architecture
CS_ARCH_SYSZ = 6,
/// XCore architecture
CS_ARCH_XCORE = 7,
CS_ARCH_MAX = 8,
/// All architecture for `cs_support`
CS_ARCH_ALL = 0xFFFF,
/// Support value to verify diet mode of the engine.
CS_SUPPORT_DIET = CS_ARCH_ALL+1,
/// Support value to verify X86 reduce mode of the engine.
CS_SUPPORT_X86_REDUCE = CS_ARCH_ALL+2,
}
}
fake_enum! {
/// Mode type (architecture variant, not all combination are possible)
pub enum cs_mode {
/// Little-endian mode (default mode)
CS_MODE_LITTLE_ENDIAN = 0,
/// 32-bit ARM
CS_MODE_ARM = 0,
/// 16-bit mode X86
CS_MODE_16 = 1 << 1,
/// 32-bit mode X86
CS_MODE_32 = 1 << 2,
/// 64-bit mode X86
CS_MODE_64 = 1 << 3,
/// ARM's Thumb mode, including Thumb-2
CS_MODE_THUMB = 1 << 4,
/// ARM's Cortex-M series
CS_MODE_MCLASS = 1 << 5,
/// ARMv8 A32 encodings for ARM
CS_MODE_V8 = 1 << 6,
/// MicroMips mode (MIPS)
CS_MODE_MICRO = 1 << 4,
/// Mips III ISA
CS_MODE_MIPS3 = 1 << 5,
/// Mips32r6 ISA
CS_MODE_MIPS32R6 = 1 << 6,
/// General Purpose Registers are 64-bit wide (MIPS)
CS_MODE_MIPSGP64 = 1 << 7,
/// SparcV9 mode (Sparc)
CS_MODE_V9 = 1 << 31,
/// big-endian mode
CS_MODE_BIG_ENDIAN = 1 << 31,
/// Mips32 ISA (Mips)
CS_MODE_MIPS32 = CS_MODE_32,
/// Mips64 ISA (Mips)
CS_MODE_MIPS64 = CS_MODE_64,
}
}
pub type cs_malloc_t = Option<extern "C" fn(size: size_t) -> *mut c_void>;
pub type cs_calloc_t = Option<extern "C" fn(nmemb: size_t, size: size_t) -> *mut c_void>;
pub type cs_realloc_t = Option<unsafe extern "C" fn(ptr: *mut c_void, size: size_t) -> *mut c_void>;
pub type cs_free_t = Option<unsafe extern "C" fn(ptr: *mut c_void)>;
pub type cs_vsnprintf_t = Option<unsafe extern "C" fn()>;
// pub type cs_vsnprintf_t = Option<unsafe extern "C" fn(str: *mut c_char,
// size: size_t,
// format: *const c_char,
// ap: va_list)
// -> c_int>;
#[repr(C)]
pub struct cs_opt_mem {
pub malloc: cs_malloc_t,
pub calloc: cs_calloc_t,
pub realloc: cs_realloc_t,
pub free: cs_free_t,
pub vsnprintf: cs_vsnprintf_t,
}
impl ::std::default::Default for cs_opt_mem {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
fake_enum! {
/// Runtime option for the disassembled engine
pub enum cs_opt_type {
/// Assembly output syntax
CS_OPT_SYNTAX = 1,
/// Break down instruction structure into details
CS_OPT_DETAIL,
/// Change engine's mode at run-time
CS_OPT_MODE,
/// User-defined dynamic memory related functions
CS_OPT_MEM,
/// Skip data when disassembling. Then engine is in SKIPDATA mode.
CS_OPT_SKIPDATA,
/// Setup user-defined function for SKIPDATA option
CS_OPT_SKIPDATA_SETUP,
}
}
fake_enum! {
/// Runtime option value (associated with option type above)
pub enum cs_opt_value {
/// Turn OFF an option - default option of CS_OPT_DETAIL, CS_OPT_SKIPDATA.
CS_OPT_OFF = 0,
/// Turn ON an option (CS_OPT_DETAIL, CS_OPT_SKIPDATA).
CS_OPT_ON = 3,
/// Default asm syntax (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_DEFAULT = 0,
/// X86 Intel asm syntax - default on X86 (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_INTEL,
/// X86 ATT asm syntax (CS_OPT_SYNTAX).
CS_OPT_SYNTAX_ATT,
/// Prints register name with only number (CS_OPT_SYNTAX)
CS_OPT_SYNTAX_NOREGNAME,
}
}
fake_enum! {
/// Common instruction operand types - to be consistent across all architectures.
pub enum cs_op_type {
/// Uninitialized/invalid operand.
CS_OP_INVALID = 0,
/// Register operand.
CS_OP_REG = 1,
/// Immediate operand.
CS_OP_IMM = 2,
/// Memory operand.
CS_OP_MEM = 3,
/// Floating-Point operand.
CS_OP_FP = 4,
}
}
fake_enum! {
/// Common instruction groups - to be consistent across all architectures.
pub enum cs_group_type {
/// uninitialized/invalid group.
CS_GRP_INVALID = 0,
/// all jump instructions (conditional+direct+indirect jumps)
CS_GRP_JUMP,
/// all call instructions
CS_GRP_CALL,
/// all return instructions
CS_GRP_RET,
/// all interrupt instructions (int+syscall)
CS_GRP_INT,
/// all interrupt return instructions
CS_GRP_IRET,
}
}
pub type cs_skipdata_cb_t = Option<unsafe extern "C" fn(code: *const u8,
code_size: size_t,
offset: size_t,
user_data: *mut c_void)
-> size_t>;
#[repr(C)]
pub struct cs_opt_skipdata {
pub mnemonic: *const c_char,
pub callback: cs_skipdata_cb_t,
pub user_data: *mut c_void,
}
impl ::std::default::Default for cs_opt_skipdata {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
pub struct cs_detail {
pub regs_read: [u8; 12usize],
pub regs_read_count: u8,
pub regs_write: [u8; 20usize],
pub regs_write_count: u8,
pub groups: [u8; 8usize],
pub groups_count: u8,
data: placeholders::detail_data,
}
impl cs_detail {
pub unsafe fn x86(&self) -> &x86::cs_x86 {
::std::mem::transmute(&self.data)
}
pub unsafe fn arm64(&self) -> &arm64::cs_arm64 {
::std::mem::transmute(&self.data)
}
pub unsafe fn arm(&self) -> &arm::cs_arm {
::std::mem::transmute(&self.data)
}
pub unsafe fn mips(&self) -> &mips::cs_mips {
::std::mem::transmute(&self.data)
}
pub unsafe fn ppc(&self) -> &ppc::cs_ppc {
::std::mem::transmute(&self.data)
}
pub unsafe fn sparc(&self) -> &sparc::cs_sparc {
::std::mem::transmute(&self.data)
}
pub unsafe fn sysz(&self) -> &sysz::cs_sysz {
::std::mem::transmute(&self.data)
}
pub unsafe fn xcore(&self) -> &xcore::cs_xcore {
::std::mem::transmute(&self.data)
}
}
#[repr(C)]
pub struct cs_insn {
pub id: c_uint,
pub address: u64,
pub size: u16,
pub bytes: [u8; 16usize],
pub mnemonic: [c_char; 32usize],
pub op_str: [c_char; 160usize],
pub detail: *mut cs_detail,
}
fake_enum! {
/// All type of errors encountered by Capstone API.
/// These are values returned by cs_errno()
pub enum cs_err {
/// No error: everything was fine
CS_ERR_OK = 0,
/// Out-Of-Memory error: cs_open(), cs_disasm(), cs_disasm_iter()
CS_ERR_MEM,
/// Unsupported architecture: cs_open()
CS_ERR_ARCH,
/// Invalid handle: cs_op_count(), cs_op_index()
CS_ERR_HANDLE,
/// Invalid csh argument: cs_close(), cs_errno(), cs_option()
CS_ERR_CSH,
/// Invalid/unsupported mode: cs_open()
CS_ERR_MODE,
/// Invalid/unsupported option: cs_option()
CS_ERR_OPTION,
/// Information is unavailable because detail option is OFF
CS_ERR_DETAIL,
/// Dynamic memory management uninitialized (see CS_OPT_MEM)
CS_ERR_MEMSETUP,
/// Unsupported version (bindings)
CS_ERR_VERSION,
/// Access irrelevant data in "diet" engine
CS_ERR_DIET,
/// Access irrelevant data for "data" instruction in SKIPDATA mode
CS_ERR_SKIPDATA,
/// X86 AT&T syntax is unsupported (opt-out at compile time)
CS_ERR_X86_ATT,
/// X86 Intel syntax is unsupported (opt-out at compile time)
CS_ERR_X86_INTEL,
}
}
#[link(name = "capstone", kind = "dylib")]
extern "C" {
pub fn cs_version(major: *mut c_int, minor: *mut c_int) -> c_uint;
pub fn cs_support(query: c_int) -> u8;
pub fn cs_open(arch: cs_arch, mode: cs_mode, handle: *mut csh) -> cs_err;
pub fn cs_close(handle: *mut csh) -> cs_err;
pub fn cs_option(handle: csh, _type: cs_opt_type, value: size_t) -> cs_err;
pub fn cs_errno(handle: csh) -> cs_err;
pub fn cs_strerror(code: cs_err) -> *const c_char;
pub fn cs_disasm(handle: csh,
code: *const u8,
code_size: size_t,
address: u64,
count: size_t,
insn: *mut *mut cs_insn)
-> size_t;
pub fn cs_free(insn: *mut cs_insn, count: size_t);
pub fn cs_malloc(handle: csh) -> *mut cs_insn;
pub fn cs_disasm_iter(handle: csh,
code: *mut *const u8,
size: *mut size_t,
address: *mut u64,
insn: *mut cs_insn)
-> u8;
pub fn cs_reg_name(handle: csh, reg_id: c_uint) -> *const c_char;
pub fn cs_insn_name(handle: csh, insn_id: c_uint) -> *const c_char;
pub fn cs_group_name(handle: csh, group_id: c_uint) -> *const c_char;
pub fn cs_insn_group(handle: csh, insn: *const cs_insn, group_id: c_uint) -> u8;
pub fn cs_reg_read(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8;
pub fn cs_reg_write(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8;
pub fn cs_op_count(handle: csh, insn: *const cs_insn, op_type: c_uint) -> c_int;
pub fn cs_op_index(handle: csh,
insn: *const cs_insn,
op_type: c_uint,
position: c_uint)
-> c_int;
}
|
#[macro_use] extern crate log;
extern crate env_logger;
extern crate glutin;
pub mod constants;
pub mod controls;
pub mod network;
pub mod video;
pub mod window_manager;
use glutin::{ElementState, VirtualKeyCode};
use window_manager::WindowManager;
use video::Video;
use std::sync::mpsc::*;
pub fn connect(listener: video::VideoListener) {
env_logger::init().unwrap();
let (keypress_tx, keypress_rx): (Sender<(ElementState, VirtualKeyCode)>, Receiver<(ElementState, VirtualKeyCode)>) = channel();
let window_manager = WindowManager::new(keypress_tx);
let video = Video::new(&window_manager);
network::start(keypress_rx);
video.render_video();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_connect_valid() {
connect(video::VideoListener::new(cb));
}
fn cb(data: &mut [u8], width: u32, height: u32) {
}
}
Fix parameter
#[macro_use] extern crate log;
extern crate env_logger;
extern crate glutin;
pub mod constants;
pub mod controls;
pub mod network;
pub mod video;
pub mod window_manager;
use glutin::{ElementState, VirtualKeyCode};
use window_manager::WindowManager;
use video::Video;
use std::sync::mpsc::*;
pub fn connect(listener: video::VideoListener) {
env_logger::init().unwrap();
let (keypress_tx, keypress_rx): (Sender<(ElementState, VirtualKeyCode)>, Receiver<(ElementState, VirtualKeyCode)>) = channel();
let window_manager = WindowManager::new(keypress_tx);
let video = Video::new(&window_manager);
network::start(keypress_rx);
video.render_video(listener);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_connect_valid() {
connect(video::VideoListener::new(cb));
}
fn cb(data: &mut [u8], width: u32, height: u32) {
}
}
|
//! Rust-Postgres is a pure-Rust frontend for the popular PostgreSQL database. It
//! exposes a high level interface in the vein of JDBC or Go's `database/sql`
//! package.
//!
//! ```rust,no_run
//! extern crate postgres;
//!
//! use postgres::{Connection, SslMode};
//!
//! struct Person {
//! id: i32,
//! name: String,
//! data: Option<Vec<u8>>
//! }
//!
//! fn main() {
//! let conn = Connection::connect("postgresql://postgres@localhost", &SslMode::None)
//! .unwrap();
//!
//! conn.execute("CREATE TABLE person (
//! id SERIAL PRIMARY KEY,
//! name VARCHAR NOT NULL,
//! data BYTEA
//! )", &[]).unwrap();
//! let me = Person {
//! id: 0,
//! name: "Steven".to_string(),
//! data: None
//! };
//! conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
//! &[&me.name, &me.data]).unwrap();
//!
//! let stmt = conn.prepare("SELECT id, name, data FROM person").unwrap();
//! for row in stmt.query(&[]).unwrap() {
//! let person = Person {
//! id: row.get(0),
//! name: row.get(1),
//! data: row.get(2)
//! };
//! println!("Found person {}", person.name);
//! }
//! }
//! ```
#![doc(html_root_url="https://sfackler.github.io/rust-postgres/doc/v0.9.3")]
#![warn(missing_docs)]
extern crate bufstream;
extern crate byteorder;
#[macro_use]
extern crate log;
extern crate phf;
extern crate rustc_serialize as serialize;
#[cfg(feature = "unix_socket")]
extern crate unix_socket;
extern crate debug_builders;
use bufstream::BufStream;
use md5::Md5;
use debug_builders::DebugStruct;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell};
use std::collections::{VecDeque, HashMap};
use std::fmt;
use std::iter::IntoIterator;
use std::io as std_io;
use std::io::prelude::*;
use std::mem;
use std::result;
#[cfg(feature = "unix_socket")]
use std::path::PathBuf;
use error::{Error, ConnectError, SqlState, DbError};
use types::{ToSql, FromSql};
use io::{StreamWrapper, NegotiateSsl};
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, ReadWithInfo};
use message::BackendMessage::*;
use message::FrontendMessage::*;
use message::{FrontendMessage, BackendMessage, RowDescriptionEntry};
use message::{WriteMessage, ReadMessage};
use url::Url;
use rows::{Rows, LazyRows};
#[macro_use]
mod macros;
pub mod error;
pub mod io;
mod message;
mod priv_io;
mod url;
mod util;
pub mod types;
pub mod rows;
mod md5;
const TYPEINFO_QUERY: &'static str = "t";
/// A type alias of the result returned by many methods.
pub type Result<T> = result::Result<T, Error>;
/// Specifies the target server to connect to.
#[derive(Clone, Debug)]
pub enum ConnectTarget {
/// Connect via TCP to the specified host.
Tcp(String),
/// Connect via a Unix domain socket in the specified directory.
///
/// Only available on Unix platforms with the `unix_socket` feature.
#[cfg(feature = "unix_socket")]
Unix(PathBuf)
}
/// Authentication information.
#[derive(Clone, Debug)]
pub struct UserInfo {
/// The username
pub user: String,
/// An optional password
pub password: Option<String>,
}
/// Information necessary to open a new connection to a Postgres server.
#[derive(Clone, Debug)]
pub struct ConnectParams {
/// The target server
pub target: ConnectTarget,
/// The target port.
///
/// Defaults to 5432 if not specified.
pub port: Option<u16>,
/// The user to login as.
///
/// `Connection::connect` requires a user but `cancel_query` does not.
pub user: Option<UserInfo>,
/// The database to connect to. Defaults the value of `user`.
pub database: Option<String>,
/// Runtime parameters to be passed to the Postgres backend.
pub options: Vec<(String, String)>,
}
/// A trait implemented by types that can be converted into a `ConnectParams`.
pub trait IntoConnectParams {
/// Converts the value of `self` into a `ConnectParams`.
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => return Err(ConnectError::InvalidUrl(err)),
}
}
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
let Url {
host,
port,
user,
path: url::Path { mut path, query: options, .. },
..
} = self;
#[cfg(feature = "unix_socket")]
fn make_unix(maybe_path: String) -> result::Result<ConnectTarget, ConnectError> {
Ok(ConnectTarget::Unix(PathBuf::from(maybe_path)))
}
#[cfg(not(feature = "unix_socket"))]
fn make_unix(_: String) -> result::Result<ConnectTarget, ConnectError> {
Err(ConnectError::InvalidUrl("unix socket support requires the `unix_socket` feature"
.to_string()))
}
let maybe_path = try!(url::decode_component(&host).map_err(ConnectError::InvalidUrl));
let target = if maybe_path.starts_with("/") {
try!(make_unix(maybe_path))
} else {
ConnectTarget::Tcp(host)
};
let user = user.map(|url::UserInfo { user, pass }| {
UserInfo { user: user, password: pass }
});
let database = if path.is_empty() {
None
} else {
// path contains the leading /
path.remove(0);
Some(path)
};
Ok(ConnectParams {
target: target,
port: port,
user: user,
database: database,
options: options,
})
}
}
/// Trait for types that can handle Postgres notice messages
pub trait HandleNotice: Send {
/// Handle a Postgres notice message
fn handle_notice(&mut self, notice: DbError);
}
/// A notice handler which logs at the `info` level.
///
/// This is the default handler used by a `Connection`.
#[derive(Copy, Clone, Debug)]
pub struct LoggingNoticeHandler;
impl HandleNotice for LoggingNoticeHandler {
fn handle_notice(&mut self, notice: DbError) {
info!("{}: {}", notice.severity(), notice.message());
}
}
/// An asynchronous notification.
#[derive(Clone, Debug)]
pub struct Notification {
/// The process ID of the notifying backend process.
pub pid: u32,
/// The name of the channel that the notify has been raised on.
pub channel: String,
/// The "payload" string passed from the notifying process.
pub payload: String,
}
/// An iterator over asynchronous notifications.
pub struct Notifications<'conn> {
conn: &'conn Connection
}
impl<'a> fmt::Debug for Notifications<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Notifications")
.field("pending", &self.conn.conn.borrow().notifications.len())
.finish()
}
}
impl<'conn> Iterator for Notifications<'conn> {
type Item = Notification;
/// Returns the oldest pending notification or `None` if there are none.
///
/// ## Note
///
/// `next` may return `Some` notification after returning `None` if a new
/// notification was received.
fn next(&mut self) -> Option<Notification> {
self.conn.conn.borrow_mut().notifications.pop_front()
}
}
impl<'conn> Notifications<'conn> {
/// Returns the oldest pending notification.
///
/// If no notifications are pending, blocks until one arrives.
pub fn next_block(&mut self) -> Result<Notification> {
if let Some(notification) = self.next() {
return Ok(notification);
}
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
match try!(conn.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
Ok(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
_ => unreachable!()
}
}
}
/// Contains information necessary to cancel queries for a session.
#[derive(Copy, Clone, Debug)]
pub struct CancelData {
/// The process ID of the session.
pub process_id: u32,
/// The secret key for the session.
pub secret_key: u32,
}
/// Attempts to cancel an in-progress query.
///
/// The backend provides no information about whether a cancellation attempt
/// was successful or not. An error will only be returned if the driver was
/// unable to connect to the database.
///
/// A `CancelData` object can be created via `Connection::cancel_data`. The
/// object can cancel any query made on that connection.
///
/// Only the host and port of the connection info are used. See
/// `Connection::connect` for details of the `params` argument.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # use std::thread;
/// # let url = "";
/// let conn = Connection::connect(url, &SslMode::None).unwrap();
/// let cancel_data = conn.cancel_data();
/// thread::spawn(move || {
/// conn.execute("SOME EXPENSIVE QUERY", &[]).unwrap();
/// });
/// # let _ =
/// postgres::cancel_query(url, &SslMode::None, cancel_data);
/// ```
pub fn cancel_query<T>(params: T, ssl: &SslMode, data: CancelData)
-> result::Result<(), ConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let mut socket = try!(priv_io::initialize_stream(¶ms, ssl));
try!(socket.write_message(&CancelRequest {
code: message::CANCEL_CODE,
process_id: data.process_id,
secret_key: data.secret_key
}));
try!(socket.flush());
Ok(())
}
fn bad_response() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::InvalidInput,
"the server returned an unexpected response")
}
fn desynchronized() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::Other,
"communication with the server has desynchronized due to an earlier IO error")
}
/// An enumeration of transaction isolation levels.
///
/// See the [Postgres documentation](http://www.postgresql.org/docs/9.4/static/transaction-iso.html)
/// for full details on the semantics of each level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
/// The "read uncommitted" level.
///
/// In current versions of Postgres, this behaves identically to
/// `ReadCommitted`.
ReadUncommitted,
/// The "read committed" level.
///
/// This is the default isolation level in Postgres.
ReadCommitted,
/// The "repeatable read" level.
RepeatableRead,
/// The "serializable" level.
Serializable,
}
impl IsolationLevel {
fn to_set_query(&self) -> &'static str {
match *self {
IsolationLevel::ReadUncommitted => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"
}
IsolationLevel::ReadCommitted => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED"
}
IsolationLevel::RepeatableRead => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ"
}
IsolationLevel::Serializable => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE"
}
}
}
fn parse(raw: &str) -> Result<IsolationLevel> {
if raw.eq_ignore_ascii_case("READ UNCOMMITTED") {
Ok(IsolationLevel::ReadUncommitted)
} else if raw.eq_ignore_ascii_case("READ COMMITTED") {
Ok(IsolationLevel::ReadCommitted)
} else if raw.eq_ignore_ascii_case("REPEATABLE READ") {
Ok(IsolationLevel::RepeatableRead)
} else if raw.eq_ignore_ascii_case("SERIALIZABLE") {
Ok(IsolationLevel::Serializable)
} else {
Err(Error::IoError(bad_response()))
}
}
}
/// Specifies the SSL support requested for a new connection.
pub enum SslMode {
/// The connection will not use SSL.
None,
/// The connection will use SSL if the backend supports it.
Prefer(Box<NegotiateSsl+std::marker::Sync+Send>),
/// The connection must use SSL.
Require(Box<NegotiateSsl+std::marker::Sync+Send>),
}
impl fmt::Debug for SslMode {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
SslMode::None => fmt.write_str("None"),
SslMode::Prefer(..) => fmt.write_str("Prefer"),
SslMode::Require(..) => fmt.write_str("Require"),
}
}
}
#[derive(Clone)]
struct CachedStatement {
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
}
struct InnerConnection {
stream: BufStream<Box<StreamWrapper>>,
notice_handler: Box<HandleNotice>,
notifications: VecDeque<Notification>,
cancel_data: CancelData,
unknown_types: HashMap<Oid, Type>,
cached_statements: HashMap<String, CachedStatement>,
parameters: HashMap<String, String>,
next_stmt_id: u32,
trans_depth: u32,
desynchronized: bool,
finished: bool,
}
impl Drop for InnerConnection {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl InnerConnection {
fn connect<T>(params: T, ssl: &SslMode) -> result::Result<InnerConnection, ConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let stream = try!(priv_io::initialize_stream(¶ms, ssl));
let ConnectParams { user, database, mut options, .. } = params;
let user = try!(user.ok_or(ConnectError::MissingUser));
let mut conn = InnerConnection {
stream: BufStream::new(stream),
next_stmt_id: 0,
notice_handler: Box::new(LoggingNoticeHandler),
notifications: VecDeque::new(),
cancel_data: CancelData { process_id: 0, secret_key: 0 },
unknown_types: HashMap::new(),
cached_statements: HashMap::new(),
parameters: HashMap::new(),
desynchronized: false,
finished: false,
trans_depth: 0,
};
options.push(("client_encoding".to_owned(), "UTF8".to_owned()));
// Postgres uses the value of TimeZone as the time zone for TIMESTAMP
// WITH TIME ZONE values. Timespec converts to GMT internally.
options.push(("timezone".to_owned(), "GMT".to_owned()));
// We have to clone here since we need the user again for auth
options.push(("user".to_owned(), user.user.clone()));
if let Some(database) = database {
options.push(("database".to_owned(), database));
}
try!(conn.write_messages(&[StartupMessage {
version: message::PROTOCOL_VERSION,
parameters: &options
}]));
try!(conn.handle_auth(user));
loop {
match try!(conn.read_message()) {
BackendKeyData { process_id, secret_key } => {
conn.cancel_data.process_id = process_id;
conn.cancel_data.secret_key = secret_key;
}
ReadyForQuery { .. } => break,
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response())),
}
}
try!(conn.setup_typeinfo_query());
Ok(conn)
}
fn setup_typeinfo_query(&mut self) -> result::Result<(), ConnectError> {
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT t.typname, t.typelem, r.rngsubtype \
FROM pg_catalog.pg_type t \
LEFT OUTER JOIN pg_catalog.pg_range r \
ON r.rngtypid = t.oid \
WHERE t.oid = $1") {
Ok(..) => return Ok(()),
Err(Error::IoError(e)) => return Err(ConnectError::IoError(e)),
// Range types weren't added until Postgres 9.2, so pg_range may not exist
Err(Error::DbError(ref e)) if e.code() == &SqlState::UndefinedTable => {}
Err(Error::DbError(e)) => return Err(ConnectError::DbError(e)),
_ => unreachable!()
}
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT typname, typelem, NULL::OID \
FROM pg_catalog.pg_type \
WHERE oid = $1") {
Ok(..) => Ok(()),
Err(Error::IoError(e)) => Err(ConnectError::IoError(e)),
Err(Error::DbError(e)) => Err(ConnectError::DbError(e)),
_ => unreachable!()
}
}
fn write_messages(&mut self, messages: &[FrontendMessage]) -> std_io::Result<()> {
debug_assert!(!self.desynchronized);
for message in messages {
try_desync!(self, self.stream.write_message(message));
}
Ok(try_desync!(self, self.stream.flush()))
}
fn read_message_with_notification(&mut self) -> std_io::Result<BackendMessage> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message()) {
NoticeResponse { fields } => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
ParameterStatus { parameter, value } => {
self.parameters.insert(parameter, value);
}
val => return Ok(val)
}
}
}
fn read_message(&mut self) -> std_io::Result<BackendMessage> {
loop {
match try!(self.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
self.notifications.push_back(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
val => return Ok(val)
}
}
}
fn handle_auth(&mut self, user: UserInfo) -> result::Result<(), ConnectError> {
match try!(self.read_message()) {
AuthenticationOk => return Ok(()),
AuthenticationCleartextPassword => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
try!(self.write_messages(&[PasswordMessage {
password: &pass,
}]));
}
AuthenticationMD5Password { salt } => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
let mut hasher = Md5::new();
let _ = hasher.input(pass.as_bytes());
let _ = hasher.input(user.user.as_bytes());
let output = hasher.result_str();
hasher.reset();
let _ = hasher.input(output.as_bytes());
let _ = hasher.input(&salt);
let output = format!("md5{}", hasher.result_str());
try!(self.write_messages(&[PasswordMessage {
password: &output
}]));
}
AuthenticationKerberosV5
| AuthenticationSCMCredential
| AuthenticationGSS
| AuthenticationSSPI => return Err(ConnectError::UnsupportedAuthentication),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response()))
}
match try!(self.read_message()) {
AuthenticationOk => Ok(()),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response()))
}
}
fn set_notice_handler(&mut self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
mem::replace(&mut self.notice_handler, handler)
}
fn raw_prepare(&mut self, stmt_name: &str, query: &str) -> Result<(Vec<Type>, Vec<Column>)> {
debug!("preparing query with name `{}`: {}", stmt_name, query);
try!(self.write_messages(&[
Parse {
name: stmt_name,
query: query,
param_types: &[]
},
Describe {
variant: b'S',
name: stmt_name,
},
Sync]));
match try!(self.read_message()) {
ParseComplete => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self),
}
let raw_param_types = match try!(self.read_message()) {
ParameterDescription { types } => types,
_ => bad_response!(self),
};
let raw_columns = match try!(self.read_message()) {
RowDescription { descriptions } => descriptions,
NoData => vec![],
_ => bad_response!(self)
};
try!(self.wait_for_ready());
let mut param_types = vec![];
for oid in raw_param_types {
param_types.push(try!(self.get_type(oid)));
}
let mut columns = vec![];
for RowDescriptionEntry { name, type_oid, .. } in raw_columns {
columns.push(Column {
name: name,
type_: try!(self.get_type(type_oid)),
});
}
Ok((param_types, columns))
}
fn make_stmt_name(&mut self) -> String {
let stmt_name = format!("s{}", self.next_stmt_id);
self.next_stmt_id += 1;
stmt_name
}
fn prepare<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
Ok(Statement {
conn: conn,
name: stmt_name,
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: false,
})
}
fn prepare_cached<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let stmt = self.cached_statements.get(query).cloned();
let CachedStatement { name, param_types, columns } = match stmt {
Some(stmt) => stmt,
None => {
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
let stmt = CachedStatement {
name: stmt_name,
param_types: param_types,
columns: columns,
};
self.cached_statements.insert(query.to_owned(), stmt.clone());
stmt
}
};
Ok(Statement {
conn: conn,
name: name,
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: true, // << !
})
}
fn close_statement(&mut self, name: &str, type_: u8) -> Result<()> {
try!(self.write_messages(&[
Close {
variant: type_,
name: name,
},
Sync]));
let resp = match try!(self.read_message()) {
CloseComplete => Ok(()),
ErrorResponse { fields } => DbError::new(fields),
_ => bad_response!(self)
};
try!(self.wait_for_ready());
resp
}
fn get_type(&mut self, oid: Oid) -> Result<Type> {
if let Some(ty) = Type::new(oid) {
return Ok(ty);
}
if let Some(ty) = self.unknown_types.get(&oid) {
return Ok(ty.clone());
}
// Ew @ doing this manually :(
let mut buf = vec![];
let value = match try!(oid.to_sql_checked(&Type::Oid, &mut buf, &SessionInfo::new(self))) {
IsNull::Yes => None,
IsNull::No => Some(buf),
};
try!(self.write_messages(&[
Bind {
portal: "",
statement: TYPEINFO_QUERY,
formats: &[1],
values: &[value],
result_formats: &[1]
},
Execute {
portal: "",
max_rows: 0,
},
Sync]));
match try!(self.read_message()) {
BindComplete => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
}
let (name, elem_oid, rngsubtype): (String, Oid, Option<Oid>) =
match try!(self.read_message()) {
DataRow { row } => {
let ctx = SessionInfo::new(self);
(try!(FromSql::from_sql_nullable(&Type::Name,
row[0].as_ref().map(|r| &**r).as_mut(),
&ctx)),
try!(FromSql::from_sql_nullable(&Type::Oid,
row[1].as_ref().map(|r| &**r).as_mut(),
&ctx)),
try!(FromSql::from_sql_nullable(&Type::Oid,
row[2].as_ref().map(|r| &**r).as_mut(),
&ctx)))
}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
};
match try!(self.read_message()) {
CommandComplete { .. } => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
}
try!(self.wait_for_ready());
let kind = if elem_oid != 0 {
Kind::Array(try!(self.get_type(elem_oid)))
} else {
match rngsubtype {
Some(oid) => Kind::Range(try!(self.get_type(oid))),
None => Kind::Simple
}
};
let type_ = Type::Other(Box::new(Other::new(name, oid, kind)));
self.unknown_types.insert(oid, type_.clone());
Ok(type_)
}
fn is_desynchronized(&self) -> bool {
self.desynchronized
}
fn wait_for_ready(&mut self) -> Result<()> {
match try!(self.read_message()) {
ReadyForQuery { .. } => Ok(()),
_ => bad_response!(self)
}
}
fn quick_query(&mut self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
check_desync!(self);
debug!("executing query: {}", query);
try!(self.write_messages(&[Query { query: query }]));
let mut result = vec![];
loop {
match try!(self.read_message()) {
ReadyForQuery { .. } => break,
DataRow { row } => {
result.push(row.into_iter().map(|opt| {
opt.map(|b| String::from_utf8_lossy(&b).into_owned())
}).collect());
}
CopyInResponse { .. } => {
try!(self.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => {}
}
}
Ok(result)
}
fn finish_inner(&mut self) -> Result<()> {
check_desync!(self);
try!(self.write_messages(&[Terminate]));
Ok(())
}
}
/// A connection to a Postgres database.
pub struct Connection {
conn: RefCell<InnerConnection>
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let conn = self.conn.borrow();
DebugStruct::new(fmt, "Connection")
.field("cancel_data", &conn.cancel_data)
.field("notifications", &conn.notifications.len())
.field("transaction_depth", &conn.trans_depth)
.field("desynchronized", &conn.desynchronized)
.field("cached_statements", &conn.cached_statements.len())
.finish()
}
}
impl Connection {
/// Creates a new connection to a Postgres database.
///
/// Most applications can use a URL string in the normal format:
///
/// ```notrust
/// postgresql://user[:password]@host[:port][/database][?param1=val1[[¶m2=val2]...]]
/// ```
///
/// The password may be omitted if not required. The default Postgres port
/// (5432) is used if none is specified. The database name defaults to the
/// username if not specified.
///
/// Connection via Unix sockets is supported with the `unix_socket`
/// feature. To connect to the server via Unix sockets, `host` should be
/// set to the absolute path of the directory containing the socket file.
/// Since `/` is a reserved character in URLs, the path should be URL
/// encoded. If the path contains non-UTF 8 characters, a `ConnectParams`
/// struct should be created manually and passed in. Note that Postgres
/// does not support SSL over Unix sockets.
///
/// ## Examples
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// let url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, UserInfo, ConnectParams, SslMode, ConnectTarget};
/// # #[cfg(feature = "unix_socket")]
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// # let some_crazy_path = Path::new("");
/// let params = ConnectParams {
/// target: ConnectTarget::Unix(some_crazy_path),
/// port: None,
/// user: Some(UserInfo {
/// user: "postgres".to_string(),
/// password: None
/// }),
/// database: None,
/// options: vec![],
/// };
/// let conn = try!(Connection::connect(params, &SslMode::None));
/// # Ok(()) };
/// ```
pub fn connect<T>(params: T, ssl: &SslMode) -> result::Result<Connection, ConnectError>
where T: IntoConnectParams {
InnerConnection::connect(params, ssl).map(|conn| {
Connection { conn: RefCell::new(conn) }
})
}
/// Sets the notice handler for the connection, returning the old handler.
pub fn set_notice_handler(&self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
self.conn.borrow_mut().set_notice_handler(handler)
}
/// Returns an iterator over asynchronous notification messages.
///
/// Use the `LISTEN` command to register this connection for notifications.
pub fn notifications<'a>(&'a self) -> Notifications<'a> {
Notifications { conn: self }
}
/// Creates a new prepared statement.
///
/// A statement may contain parameters, specified by `$n` where `n` is the
/// index of the parameter in the list provided at execution time,
/// 1-indexed.
///
/// The statement is associated with the connection that created it and may
/// not outlive that connection.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let maybe_stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1");
/// let stmt = match maybe_stmt {
/// Ok(stmt) => stmt,
/// Err(err) => panic!("Error preparing statement: {:?}", err)
/// };
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare(query, self)
}
/// Creates cached prepared statement.
///
/// Like `prepare`, except that the statement is only prepared once over
/// the lifetime of the connection and then cached. If the same statement
/// is going to be used frequently, caching it can improve performance by
/// reducing the number of round trips to the Postgres backend.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> postgres::Result<()> {
/// # let x = 10i32;
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let stmt = try!(conn.prepare_cached("SELECT foo FROM bar WHERE baz = $1"));
/// for row in try!(stmt.query(&[&x])) {
/// println!("foo: {}", row.get::<_, String>(0));
/// }
/// # Ok(()) };
/// ```
pub fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare_cached(query, self)
}
/// Begins a new transaction.
///
/// Returns a `Transaction` object which should be used instead of
/// the connection for the duration of the transaction. The transaction
/// is active until the `Transaction` object falls out of scope.
///
/// ## Note
/// A transaction will roll back by default. The `set_commit`,
/// `set_rollback`, and `commit` methods alter this behavior.
///
/// ## Panics
///
/// Panics if a transaction is already active.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn foo() -> Result<(), postgres::error::Error> {
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let trans = try!(conn.transaction());
/// try!(trans.execute("UPDATE foo SET bar = 10", &[]));
/// // ...
///
/// try!(trans.commit());
/// # Ok(())
/// # }
/// ```
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
assert!(conn.trans_depth == 0, "`transaction` must be called on the active transaction");
try!(conn.quick_query("BEGIN"));
conn.trans_depth += 1;
Ok(Transaction {
conn: self,
commit: Cell::new(false),
depth: 1,
finished: false,
})
}
/// Sets the isolation level which will be used for future transactions.
///
/// ## Note
///
/// This will not change the behavior of an active transaction.
pub fn set_transaction_isolation(&self, level: IsolationLevel) -> Result<()> {
self.batch_execute(level.to_set_query())
}
/// Returns the isolation level which will be used for future transactions.
pub fn transaction_isolation(&self) -> Result<IsolationLevel> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
let result = try!(conn.quick_query("SHOW TRANSACTION ISOLATION LEVEL"));
IsolationLevel::parse(result[0][0].as_ref().unwrap())
}
/// A convenience function for queries that are only run once.
///
/// If an error is returned, it could have come from either the preparation
/// or execution of the statement.
///
/// On success, returns the number of rows modified or 0 if not applicable.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
let stmt = Statement {
conn: self,
name: "".to_owned(),
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: true, // << !!
};
stmt.execute(params)
}
/// Execute a sequence of SQL statements.
///
/// Statements should be separated by `;` characters. If an error occurs,
/// execution of the sequence will stop at that point. This is intended for
/// execution of batches of non-dynamic statements - for example, creation
/// of a schema for a fresh database.
///
/// ## Warning
///
/// Prepared statements should be used for any SQL statement which contains
/// user-specified data, as it provides functionality to safely embed that
/// data in the statement. Do not form statements via string concatenation
/// and feed them into this method.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, Result};
/// fn init_db(conn: &Connection) -> Result<()> {
/// conn.batch_execute("
/// CREATE TABLE person (
/// id SERIAL PRIMARY KEY,
/// name NOT NULL
/// );
///
/// CREATE TABLE purchase (
/// id SERIAL PRIMARY KEY,
/// person INT NOT NULL REFERENCES person (id),
/// time TIMESTAMPTZ NOT NULL,
/// );
///
/// CREATE INDEX ON purchase (time);
/// ")
/// }
/// ```
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.borrow_mut().quick_query(query).map(|_| ())
}
/// Returns information used to cancel pending queries.
///
/// Used with the `cancel_query` function. The object returned can be used
/// to cancel any query executed by the connection it was created from.
pub fn cancel_data(&self) -> CancelData {
self.conn.borrow().cancel_data
}
/// Returns the value of the specified Postgres backend parameter, such as
/// `timezone` or `server_version`.
pub fn parameter(&self, param: &str) -> Option<String> {
self.conn.borrow().parameters.get(param).cloned()
}
/// Returns whether or not the stream has been desynchronized due to an
/// error in the communication channel with the server.
///
/// If this has occurred, all further queries will immediately return an
/// error.
pub fn is_desynchronized(&self) -> bool {
self.conn.borrow().is_desynchronized()
}
/// Determines if the `Connection` is currently "active", that is, if there
/// are no active transactions.
///
/// The `transaction` method can only be called on the active `Connection`
/// or `Transaction`.
pub fn is_active(&self) -> bool {
self.conn.borrow().trans_depth == 0
}
/// Consumes the connection, closing it.
///
/// Functionally equivalent to the `Drop` implementation for `Connection`
/// except that it returns any error encountered to the caller.
pub fn finish(self) -> Result<()> {
let mut conn = self.conn.borrow_mut();
conn.finished = true;
conn.finish_inner()
}
}
/// Represents a transaction on a database connection.
///
/// The transaction will roll back by default.
pub struct Transaction<'conn> {
conn: &'conn Connection,
depth: u32,
commit: Cell<bool>,
finished: bool,
}
impl<'a> fmt::Debug for Transaction<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Transaction")
.field("commit", &self.commit.get())
.field("depth", &self.depth)
.finish()
}
}
impl<'conn> Drop for Transaction<'conn> {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl<'conn> Transaction<'conn> {
fn finish_inner(&mut self) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut();
debug_assert!(self.depth == conn.trans_depth);
let query = match (self.commit.get(), self.depth != 1) {
(false, true) => "ROLLBACK TO sp",
(false, false) => "ROLLBACK",
(true, true) => "RELEASE sp",
(true, false) => "COMMIT",
};
conn.trans_depth -= 1;
conn.quick_query(query).map(|_| ())
}
/// Like `Connection::prepare`.
pub fn prepare(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare(query)
}
/// Like `Connection::prepare_cached`.
///
/// Note that the statement will be cached for the duration of the
/// connection, not just the duration of this transaction.
pub fn prepare_cached(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare_cached(query)
}
/// Like `Connection::execute`.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.conn.execute(query, params)
}
/// Like `Connection::batch_execute`.
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.batch_execute(query)
}
/// Like `Connection::transaction`.
///
/// ## Panics
///
/// Panics if there is an active nested transaction.
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
assert!(conn.trans_depth == self.depth,
"`transaction` may only be called on the active transaction");
try!(conn.quick_query("SAVEPOINT sp"));
conn.trans_depth += 1;
Ok(Transaction {
conn: self.conn,
commit: Cell::new(false),
depth: self.depth + 1,
finished: false,
})
}
/// Returns a reference to the `Transaction`'s `Connection`.
pub fn connection(&self) -> &'conn Connection {
self.conn
}
/// Like `Connection::is_active`.
pub fn is_active(&self) -> bool {
self.conn.conn.borrow().trans_depth == self.depth
}
/// Determines if the transaction is currently set to commit or roll back.
pub fn will_commit(&self) -> bool {
self.commit.get()
}
/// Sets the transaction to commit at its completion.
pub fn set_commit(&self) {
self.commit.set(true);
}
/// Sets the transaction to roll back at its completion.
pub fn set_rollback(&self) {
self.commit.set(false);
}
/// A convenience method which consumes and commits a transaction.
pub fn commit(self) -> Result<()> {
self.set_commit();
self.finish()
}
/// Consumes the transaction, commiting or rolling it back as appropriate.
///
/// Functionally equivalent to the `Drop` implementation of `Transaction`
/// except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
self.finished = true;
self.finish_inner()
}
}
/// A prepared statement.
pub struct Statement<'conn> {
conn: &'conn Connection,
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
next_portal_id: Cell<u32>,
finished: bool,
}
impl<'a> fmt::Debug for Statement<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Statement")
.field("name", &self.name)
.field("parameter_types", &self.param_types)
.field("columns", &self.columns)
.finish()
}
}
impl<'conn> Drop for Statement<'conn> {
fn drop(&mut self) {
let _ = self.finish_inner();
}
}
impl<'conn> Statement<'conn> {
fn finish_inner(&mut self) -> Result<()> {
if !self.finished {
self.finished = true;
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
conn.close_statement(&self.name, b'S')
} else {
Ok(())
}
}
fn inner_execute(&self, portal_name: &str, row_limit: i32, params: &[&ToSql]) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut();
assert!(self.param_types().len() == params.len(),
"expected {} parameters but got {}",
self.param_types.len(),
params.len());
debug!("executing statement {} with parameters: {:?}", self.name, params);
let mut values = vec![];
for (param, ty) in params.iter().zip(self.param_types.iter()) {
let mut buf = vec![];
match try!(param.to_sql_checked(ty, &mut buf, &SessionInfo::new(&*conn))) {
IsNull::Yes => values.push(None),
IsNull::No => values.push(Some(buf)),
}
};
try!(conn.write_messages(&[
Bind {
portal: portal_name,
statement: &self.name,
formats: &[1],
values: &values,
result_formats: &[1]
},
Execute {
portal: portal_name,
max_rows: row_limit
},
Sync]));
match try!(conn.read_message()) {
BindComplete => Ok(()),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
DbError::new(fields)
}
_ => {
conn.desynchronized = true;
Err(Error::IoError(bad_response()))
}
}
}
fn inner_query<'a>(&'a self, portal_name: &str, row_limit: i32, params: &[&ToSql])
-> Result<(VecDeque<Vec<Option<Vec<u8>>>>, bool)> {
try!(self.inner_execute(portal_name, row_limit, params));
let mut buf = VecDeque::new();
let more_rows = try!(read_rows(&mut self.conn.conn.borrow_mut(), &mut buf));
Ok((buf, more_rows))
}
/// Returns a slice containing the expected parameter types.
pub fn param_types(&self) -> &[Type] {
&self.param_types
}
/// Returns a slice describing the columns of the result of the query.
pub fn columns(&self) -> &[Column] {
&self.columns
}
/// Executes the prepared statement, returning the number of rows modified.
///
/// If the statement does not modify any rows (e.g. SELECT), 0 is returned.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// # let bar = 1i32;
/// # let baz = true;
/// let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();
/// match stmt.execute(&[&bar, &baz]) {
/// Ok(count) => println!("{} row(s) updated", count),
/// Err(err) => println!("Error executing query: {:?}", err)
/// }
/// ```
pub fn execute(&self, params: &[&ToSql]) -> Result<u64> {
check_desync!(self.conn);
try!(self.inner_execute("", 0, params));
let mut conn = self.conn.conn.borrow_mut();
let num;
loop {
match try!(conn.read_message()) {
DataRow { .. } => {}
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
CommandComplete { tag } => {
num = util::parse_update_count(tag);
break;
}
EmptyQueryResponse => {
num = 0;
break;
}
CopyInResponse { .. } => {
try!(conn.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
}
try!(conn.wait_for_ready());
Ok(num)
}
/// Executes the prepared statement, returning the resulting rows.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1").unwrap();
/// # let baz = true;
/// let rows = match stmt.query(&[&baz]) {
/// Ok(rows) => rows,
/// Err(err) => panic!("Error running query: {:?}", err)
/// };
/// for row in &rows {
/// let foo: i32 = row.get("foo");
/// println!("foo: {}", foo);
/// }
/// ```
pub fn query<'a>(&'a self, params: &[&ToSql]) -> Result<Rows<'a>> {
check_desync!(self.conn);
self.inner_query("", 0, params).map(|(buf, _)| {
Rows::new(self, buf.into_iter().collect())
})
}
/// Executes the prepared statement, returning a lazily loaded iterator
/// over the resulting rows.
///
/// No more than `row_limit` rows will be stored in memory at a time. Rows
/// will be pulled from the database in batches of `row_limit` as needed.
/// If `row_limit` is less than or equal to 0, `lazy_query` is equivalent
/// to `query`.
///
/// This can only be called inside of a transaction, and the `Transaction`
/// object representing the active transaction must be passed to
/// `lazy_query`.
///
/// ## Panics
///
/// Panics if the provided `Transaction` is not associated with the same
/// `Connection` as this `Statement`, if the `Transaction` is not
/// active, or if the number of parameters provided does not match the
/// number of parameters expected.
pub fn lazy_query<'trans, 'stmt>(&'stmt self,
trans: &'trans Transaction,
params: &[&ToSql],
row_limit: i32)
-> Result<LazyRows<'trans, 'stmt>> {
assert!(self.conn as *const _ == trans.conn as *const _,
"the `Transaction` passed to `lazy_query` must be associated with the same \
`Connection` as the `Statement`");
let conn = self.conn.conn.borrow();
check_desync!(conn);
assert!(conn.trans_depth == trans.depth,
"`lazy_query` must be passed the active transaction");
drop(conn);
let id = self.next_portal_id.get();
self.next_portal_id.set(id + 1);
let portal_name = format!("{}p{}", self.name, id);
self.inner_query(&portal_name, row_limit, params).map(move |(data, more_rows)| {
LazyRows::new(self, data, portal_name, row_limit, more_rows, false, trans)
})
}
/// Executes a `COPY FROM STDIN` statement, returning the number of rows
/// added.
///
/// The contents of the provided reader are passed to the Postgres server
/// verbatim; it is the caller's responsibility to ensure it uses the
/// proper format. See the
/// [Postgres documentation](http://www.postgresql.org/docs/9.4/static/sql-copy.html)
/// for details.
///
/// If the statement is not a `COPY FROM STDIN` statement it will still be
/// executed and this method will return an error.
///
/// # Examples
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// conn.batch_execute("CREATE TABLE people (id INT PRIMARY KEY, name VARCHAR)").unwrap();
/// let stmt = conn.prepare("COPY people FROM STDIN").unwrap();
/// stmt.copy_in(&[], &mut "1\tjohn\n2\tjane\n".as_bytes()).unwrap();
/// ```
pub fn copy_in<R: ReadWithInfo>(&self, params: &[&ToSql], r: &mut R) -> Result<u64> {
try!(self.inner_execute("", 0, params));
let mut conn = self.conn.conn.borrow_mut();
match try!(conn.read_message()) {
CopyInResponse { .. } => {}
_ => {
loop {
match try!(conn.read_message()) {
ReadyForQuery { .. } => {
return Err(Error::IoError(std_io::Error::new(
std_io::ErrorKind::InvalidInput,
"called `copy_in` on a non-`COPY FROM STDIN` statement")));
}
_ => {}
}
}
}
}
let mut buf = [0; 16 * 1024];
loop {
match fill_copy_buf(&mut buf, r, &SessionInfo::new(&conn)) {
Ok(0) => break,
Ok(len) => {
try_desync!(conn, conn.stream.write_message(
&CopyData {
data: &buf[..len],
}));
}
Err(err) => {
try!(conn.write_messages(&[
CopyFail {
message: "",
},
CopyDone,
Sync]));
match try!(conn.read_message()) {
ErrorResponse { .. } => { /* expected from the CopyFail */ }
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
try!(conn.wait_for_ready());
return Err(Error::IoError(err));
}
}
}
try!(conn.write_messages(&[CopyDone, Sync]));
let num = match try!(conn.read_message()) {
CommandComplete { tag } => util::parse_update_count(tag),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
};
try!(conn.wait_for_ready());
Ok(num)
}
/// Consumes the statement, clearing it from the Postgres session.
///
/// If this statement was created via the `prepare_cached` method, `finish`
/// does nothing.
///
/// Functionally identical to the `Drop` implementation of the
/// `Statement` except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
self.finish_inner()
}
}
fn fill_copy_buf<R: ReadWithInfo>(buf: &mut [u8], r: &mut R, info: &SessionInfo)
-> std_io::Result<usize> {
let mut nread = 0;
while nread < buf.len() {
match r.read_with_info(&mut buf[nread..], info) {
Ok(0) => break,
Ok(n) => nread += n,
Err(ref e) if e.kind() == std_io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(nread)
}
/// Information about a column of the result of a query.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Column {
name: String,
type_: Type
}
impl Column {
/// The name of the column.
pub fn name(&self) -> &str {
&self.name
}
/// The type of the data in the column.
pub fn type_(&self) -> &Type {
&self.type_
}
}
fn read_rows(conn: &mut InnerConnection, buf: &mut VecDeque<Vec<Option<Vec<u8>>>>) -> Result<bool> {
let more_rows;
loop {
match try!(conn.read_message()) {
EmptyQueryResponse | CommandComplete { .. } => {
more_rows = false;
break;
}
PortalSuspended => {
more_rows = true;
break;
}
DataRow { row } => buf.push_back(row),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
CopyInResponse { .. } => {
try!(conn.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
}
try!(conn.wait_for_ready());
Ok(more_rows)
}
/// A trait allowing abstraction over connections and transactions
pub trait GenericConnection {
/// Like `Connection::prepare`.
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
/// Like `Connection::prepare_cached`.
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
/// Like `Connection::execute`.
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64>;
/// Like `Connection::transaction`.
fn transaction<'a>(&'a self) -> Result<Transaction<'a>>;
/// Like `Connection::batch_execute`.
fn batch_execute(&self, query: &str) -> Result<()>;
/// Like `Connection::is_active`.
fn is_active(&self) -> bool;
}
impl GenericConnection for Connection {
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare(query)
}
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare_cached(query)
}
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
self.transaction()
}
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
impl<'a> GenericConnection for Transaction<'a> {
fn prepare<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare(query)
}
fn prepare_cached<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare_cached(query)
}
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn transaction<'b>(&'b self) -> Result<Transaction<'b>> {
self.transaction()
}
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
trait OtherNew {
fn new(name: String, oid: Oid, kind: Kind) -> Other;
}
trait DbErrorNew {
fn new_raw(fields: Vec<(u8, String)>) -> result::Result<DbError, ()>;
fn new_connect<T>(fields: Vec<(u8, String)>) -> result::Result<T, ConnectError>;
fn new<T>(fields: Vec<(u8, String)>) -> Result<T>;
}
trait TypeNew {
fn new(oid: Oid) -> Option<Type>;
}
trait RowsNew<'a> {
fn new(stmt: &'a Statement<'a>, data: Vec<Vec<Option<Vec<u8>>>>) -> Rows<'a>;
}
trait LazyRowsNew<'trans, 'stmt> {
fn new(stmt: &'stmt Statement<'stmt>,
data: VecDeque<Vec<Option<Vec<u8>>>>,
name: String,
row_limit: i32,
more_rows: bool,
finished: bool,
trans: &'trans Transaction<'trans>) -> LazyRows<'trans, 'stmt>;
}
trait SessionInfoNew<'a> {
fn new(conn: &'a InnerConnection) -> SessionInfo<'a>;
}
Ensure Connection is always Send
//! Rust-Postgres is a pure-Rust frontend for the popular PostgreSQL database. It
//! exposes a high level interface in the vein of JDBC or Go's `database/sql`
//! package.
//!
//! ```rust,no_run
//! extern crate postgres;
//!
//! use postgres::{Connection, SslMode};
//!
//! struct Person {
//! id: i32,
//! name: String,
//! data: Option<Vec<u8>>
//! }
//!
//! fn main() {
//! let conn = Connection::connect("postgresql://postgres@localhost", &SslMode::None)
//! .unwrap();
//!
//! conn.execute("CREATE TABLE person (
//! id SERIAL PRIMARY KEY,
//! name VARCHAR NOT NULL,
//! data BYTEA
//! )", &[]).unwrap();
//! let me = Person {
//! id: 0,
//! name: "Steven".to_string(),
//! data: None
//! };
//! conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
//! &[&me.name, &me.data]).unwrap();
//!
//! let stmt = conn.prepare("SELECT id, name, data FROM person").unwrap();
//! for row in stmt.query(&[]).unwrap() {
//! let person = Person {
//! id: row.get(0),
//! name: row.get(1),
//! data: row.get(2)
//! };
//! println!("Found person {}", person.name);
//! }
//! }
//! ```
#![doc(html_root_url="https://sfackler.github.io/rust-postgres/doc/v0.9.3")]
#![warn(missing_docs)]
extern crate bufstream;
extern crate byteorder;
#[macro_use]
extern crate log;
extern crate phf;
extern crate rustc_serialize as serialize;
#[cfg(feature = "unix_socket")]
extern crate unix_socket;
extern crate debug_builders;
use bufstream::BufStream;
use md5::Md5;
use debug_builders::DebugStruct;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell};
use std::collections::{VecDeque, HashMap};
use std::fmt;
use std::iter::IntoIterator;
use std::io as std_io;
use std::io::prelude::*;
use std::mem;
use std::result;
#[cfg(feature = "unix_socket")]
use std::path::PathBuf;
use error::{Error, ConnectError, SqlState, DbError};
use types::{ToSql, FromSql};
use io::{StreamWrapper, NegotiateSsl};
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, ReadWithInfo};
use message::BackendMessage::*;
use message::FrontendMessage::*;
use message::{FrontendMessage, BackendMessage, RowDescriptionEntry};
use message::{WriteMessage, ReadMessage};
use url::Url;
use rows::{Rows, LazyRows};
#[macro_use]
mod macros;
pub mod error;
pub mod io;
mod message;
mod priv_io;
mod url;
mod util;
pub mod types;
pub mod rows;
mod md5;
const TYPEINFO_QUERY: &'static str = "t";
/// A type alias of the result returned by many methods.
pub type Result<T> = result::Result<T, Error>;
/// Specifies the target server to connect to.
#[derive(Clone, Debug)]
pub enum ConnectTarget {
/// Connect via TCP to the specified host.
Tcp(String),
/// Connect via a Unix domain socket in the specified directory.
///
/// Only available on Unix platforms with the `unix_socket` feature.
#[cfg(feature = "unix_socket")]
Unix(PathBuf)
}
/// Authentication information.
#[derive(Clone, Debug)]
pub struct UserInfo {
/// The username
pub user: String,
/// An optional password
pub password: Option<String>,
}
/// Information necessary to open a new connection to a Postgres server.
#[derive(Clone, Debug)]
pub struct ConnectParams {
/// The target server
pub target: ConnectTarget,
/// The target port.
///
/// Defaults to 5432 if not specified.
pub port: Option<u16>,
/// The user to login as.
///
/// `Connection::connect` requires a user but `cancel_query` does not.
pub user: Option<UserInfo>,
/// The database to connect to. Defaults the value of `user`.
pub database: Option<String>,
/// Runtime parameters to be passed to the Postgres backend.
pub options: Vec<(String, String)>,
}
/// A trait implemented by types that can be converted into a `ConnectParams`.
pub trait IntoConnectParams {
/// Converts the value of `self` into a `ConnectParams`.
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => return Err(ConnectError::InvalidUrl(err)),
}
}
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
let Url {
host,
port,
user,
path: url::Path { mut path, query: options, .. },
..
} = self;
#[cfg(feature = "unix_socket")]
fn make_unix(maybe_path: String) -> result::Result<ConnectTarget, ConnectError> {
Ok(ConnectTarget::Unix(PathBuf::from(maybe_path)))
}
#[cfg(not(feature = "unix_socket"))]
fn make_unix(_: String) -> result::Result<ConnectTarget, ConnectError> {
Err(ConnectError::InvalidUrl("unix socket support requires the `unix_socket` feature"
.to_string()))
}
let maybe_path = try!(url::decode_component(&host).map_err(ConnectError::InvalidUrl));
let target = if maybe_path.starts_with("/") {
try!(make_unix(maybe_path))
} else {
ConnectTarget::Tcp(host)
};
let user = user.map(|url::UserInfo { user, pass }| {
UserInfo { user: user, password: pass }
});
let database = if path.is_empty() {
None
} else {
// path contains the leading /
path.remove(0);
Some(path)
};
Ok(ConnectParams {
target: target,
port: port,
user: user,
database: database,
options: options,
})
}
}
/// Trait for types that can handle Postgres notice messages
pub trait HandleNotice: Send {
/// Handle a Postgres notice message
fn handle_notice(&mut self, notice: DbError);
}
/// A notice handler which logs at the `info` level.
///
/// This is the default handler used by a `Connection`.
#[derive(Copy, Clone, Debug)]
pub struct LoggingNoticeHandler;
impl HandleNotice for LoggingNoticeHandler {
fn handle_notice(&mut self, notice: DbError) {
info!("{}: {}", notice.severity(), notice.message());
}
}
/// An asynchronous notification.
#[derive(Clone, Debug)]
pub struct Notification {
/// The process ID of the notifying backend process.
pub pid: u32,
/// The name of the channel that the notify has been raised on.
pub channel: String,
/// The "payload" string passed from the notifying process.
pub payload: String,
}
/// An iterator over asynchronous notifications.
pub struct Notifications<'conn> {
conn: &'conn Connection
}
impl<'a> fmt::Debug for Notifications<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Notifications")
.field("pending", &self.conn.conn.borrow().notifications.len())
.finish()
}
}
impl<'conn> Iterator for Notifications<'conn> {
type Item = Notification;
/// Returns the oldest pending notification or `None` if there are none.
///
/// ## Note
///
/// `next` may return `Some` notification after returning `None` if a new
/// notification was received.
fn next(&mut self) -> Option<Notification> {
self.conn.conn.borrow_mut().notifications.pop_front()
}
}
impl<'conn> Notifications<'conn> {
/// Returns the oldest pending notification.
///
/// If no notifications are pending, blocks until one arrives.
pub fn next_block(&mut self) -> Result<Notification> {
if let Some(notification) = self.next() {
return Ok(notification);
}
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
match try!(conn.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
Ok(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
_ => unreachable!()
}
}
}
/// Contains information necessary to cancel queries for a session.
#[derive(Copy, Clone, Debug)]
pub struct CancelData {
/// The process ID of the session.
pub process_id: u32,
/// The secret key for the session.
pub secret_key: u32,
}
/// Attempts to cancel an in-progress query.
///
/// The backend provides no information about whether a cancellation attempt
/// was successful or not. An error will only be returned if the driver was
/// unable to connect to the database.
///
/// A `CancelData` object can be created via `Connection::cancel_data`. The
/// object can cancel any query made on that connection.
///
/// Only the host and port of the connection info are used. See
/// `Connection::connect` for details of the `params` argument.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # use std::thread;
/// # let url = "";
/// let conn = Connection::connect(url, &SslMode::None).unwrap();
/// let cancel_data = conn.cancel_data();
/// thread::spawn(move || {
/// conn.execute("SOME EXPENSIVE QUERY", &[]).unwrap();
/// });
/// # let _ =
/// postgres::cancel_query(url, &SslMode::None, cancel_data);
/// ```
pub fn cancel_query<T>(params: T, ssl: &SslMode, data: CancelData)
-> result::Result<(), ConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let mut socket = try!(priv_io::initialize_stream(¶ms, ssl));
try!(socket.write_message(&CancelRequest {
code: message::CANCEL_CODE,
process_id: data.process_id,
secret_key: data.secret_key
}));
try!(socket.flush());
Ok(())
}
fn bad_response() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::InvalidInput,
"the server returned an unexpected response")
}
fn desynchronized() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::Other,
"communication with the server has desynchronized due to an earlier IO error")
}
/// An enumeration of transaction isolation levels.
///
/// See the [Postgres documentation](http://www.postgresql.org/docs/9.4/static/transaction-iso.html)
/// for full details on the semantics of each level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
/// The "read uncommitted" level.
///
/// In current versions of Postgres, this behaves identically to
/// `ReadCommitted`.
ReadUncommitted,
/// The "read committed" level.
///
/// This is the default isolation level in Postgres.
ReadCommitted,
/// The "repeatable read" level.
RepeatableRead,
/// The "serializable" level.
Serializable,
}
impl IsolationLevel {
fn to_set_query(&self) -> &'static str {
match *self {
IsolationLevel::ReadUncommitted => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"
}
IsolationLevel::ReadCommitted => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED"
}
IsolationLevel::RepeatableRead => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ"
}
IsolationLevel::Serializable => {
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE"
}
}
}
fn parse(raw: &str) -> Result<IsolationLevel> {
if raw.eq_ignore_ascii_case("READ UNCOMMITTED") {
Ok(IsolationLevel::ReadUncommitted)
} else if raw.eq_ignore_ascii_case("READ COMMITTED") {
Ok(IsolationLevel::ReadCommitted)
} else if raw.eq_ignore_ascii_case("REPEATABLE READ") {
Ok(IsolationLevel::RepeatableRead)
} else if raw.eq_ignore_ascii_case("SERIALIZABLE") {
Ok(IsolationLevel::Serializable)
} else {
Err(Error::IoError(bad_response()))
}
}
}
/// Specifies the SSL support requested for a new connection.
pub enum SslMode {
/// The connection will not use SSL.
None,
/// The connection will use SSL if the backend supports it.
Prefer(Box<NegotiateSsl+std::marker::Sync+Send>),
/// The connection must use SSL.
Require(Box<NegotiateSsl+std::marker::Sync+Send>),
}
impl fmt::Debug for SslMode {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
SslMode::None => fmt.write_str("None"),
SslMode::Prefer(..) => fmt.write_str("Prefer"),
SslMode::Require(..) => fmt.write_str("Require"),
}
}
}
#[derive(Clone)]
struct CachedStatement {
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
}
struct InnerConnection {
stream: BufStream<Box<StreamWrapper>>,
notice_handler: Box<HandleNotice>,
notifications: VecDeque<Notification>,
cancel_data: CancelData,
unknown_types: HashMap<Oid, Type>,
cached_statements: HashMap<String, CachedStatement>,
parameters: HashMap<String, String>,
next_stmt_id: u32,
trans_depth: u32,
desynchronized: bool,
finished: bool,
}
impl Drop for InnerConnection {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl InnerConnection {
fn connect<T>(params: T, ssl: &SslMode) -> result::Result<InnerConnection, ConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let stream = try!(priv_io::initialize_stream(¶ms, ssl));
let ConnectParams { user, database, mut options, .. } = params;
let user = try!(user.ok_or(ConnectError::MissingUser));
let mut conn = InnerConnection {
stream: BufStream::new(stream),
next_stmt_id: 0,
notice_handler: Box::new(LoggingNoticeHandler),
notifications: VecDeque::new(),
cancel_data: CancelData { process_id: 0, secret_key: 0 },
unknown_types: HashMap::new(),
cached_statements: HashMap::new(),
parameters: HashMap::new(),
desynchronized: false,
finished: false,
trans_depth: 0,
};
options.push(("client_encoding".to_owned(), "UTF8".to_owned()));
// Postgres uses the value of TimeZone as the time zone for TIMESTAMP
// WITH TIME ZONE values. Timespec converts to GMT internally.
options.push(("timezone".to_owned(), "GMT".to_owned()));
// We have to clone here since we need the user again for auth
options.push(("user".to_owned(), user.user.clone()));
if let Some(database) = database {
options.push(("database".to_owned(), database));
}
try!(conn.write_messages(&[StartupMessage {
version: message::PROTOCOL_VERSION,
parameters: &options
}]));
try!(conn.handle_auth(user));
loop {
match try!(conn.read_message()) {
BackendKeyData { process_id, secret_key } => {
conn.cancel_data.process_id = process_id;
conn.cancel_data.secret_key = secret_key;
}
ReadyForQuery { .. } => break,
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response())),
}
}
try!(conn.setup_typeinfo_query());
Ok(conn)
}
fn setup_typeinfo_query(&mut self) -> result::Result<(), ConnectError> {
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT t.typname, t.typelem, r.rngsubtype \
FROM pg_catalog.pg_type t \
LEFT OUTER JOIN pg_catalog.pg_range r \
ON r.rngtypid = t.oid \
WHERE t.oid = $1") {
Ok(..) => return Ok(()),
Err(Error::IoError(e)) => return Err(ConnectError::IoError(e)),
// Range types weren't added until Postgres 9.2, so pg_range may not exist
Err(Error::DbError(ref e)) if e.code() == &SqlState::UndefinedTable => {}
Err(Error::DbError(e)) => return Err(ConnectError::DbError(e)),
_ => unreachable!()
}
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT typname, typelem, NULL::OID \
FROM pg_catalog.pg_type \
WHERE oid = $1") {
Ok(..) => Ok(()),
Err(Error::IoError(e)) => Err(ConnectError::IoError(e)),
Err(Error::DbError(e)) => Err(ConnectError::DbError(e)),
_ => unreachable!()
}
}
fn write_messages(&mut self, messages: &[FrontendMessage]) -> std_io::Result<()> {
debug_assert!(!self.desynchronized);
for message in messages {
try_desync!(self, self.stream.write_message(message));
}
Ok(try_desync!(self, self.stream.flush()))
}
fn read_message_with_notification(&mut self) -> std_io::Result<BackendMessage> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message()) {
NoticeResponse { fields } => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
ParameterStatus { parameter, value } => {
self.parameters.insert(parameter, value);
}
val => return Ok(val)
}
}
}
fn read_message(&mut self) -> std_io::Result<BackendMessage> {
loop {
match try!(self.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
self.notifications.push_back(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
val => return Ok(val)
}
}
}
fn handle_auth(&mut self, user: UserInfo) -> result::Result<(), ConnectError> {
match try!(self.read_message()) {
AuthenticationOk => return Ok(()),
AuthenticationCleartextPassword => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
try!(self.write_messages(&[PasswordMessage {
password: &pass,
}]));
}
AuthenticationMD5Password { salt } => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
let mut hasher = Md5::new();
let _ = hasher.input(pass.as_bytes());
let _ = hasher.input(user.user.as_bytes());
let output = hasher.result_str();
hasher.reset();
let _ = hasher.input(output.as_bytes());
let _ = hasher.input(&salt);
let output = format!("md5{}", hasher.result_str());
try!(self.write_messages(&[PasswordMessage {
password: &output
}]));
}
AuthenticationKerberosV5
| AuthenticationSCMCredential
| AuthenticationGSS
| AuthenticationSSPI => return Err(ConnectError::UnsupportedAuthentication),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response()))
}
match try!(self.read_message()) {
AuthenticationOk => Ok(()),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::IoError(bad_response()))
}
}
fn set_notice_handler(&mut self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
mem::replace(&mut self.notice_handler, handler)
}
fn raw_prepare(&mut self, stmt_name: &str, query: &str) -> Result<(Vec<Type>, Vec<Column>)> {
debug!("preparing query with name `{}`: {}", stmt_name, query);
try!(self.write_messages(&[
Parse {
name: stmt_name,
query: query,
param_types: &[]
},
Describe {
variant: b'S',
name: stmt_name,
},
Sync]));
match try!(self.read_message()) {
ParseComplete => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self),
}
let raw_param_types = match try!(self.read_message()) {
ParameterDescription { types } => types,
_ => bad_response!(self),
};
let raw_columns = match try!(self.read_message()) {
RowDescription { descriptions } => descriptions,
NoData => vec![],
_ => bad_response!(self)
};
try!(self.wait_for_ready());
let mut param_types = vec![];
for oid in raw_param_types {
param_types.push(try!(self.get_type(oid)));
}
let mut columns = vec![];
for RowDescriptionEntry { name, type_oid, .. } in raw_columns {
columns.push(Column {
name: name,
type_: try!(self.get_type(type_oid)),
});
}
Ok((param_types, columns))
}
fn make_stmt_name(&mut self) -> String {
let stmt_name = format!("s{}", self.next_stmt_id);
self.next_stmt_id += 1;
stmt_name
}
fn prepare<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
Ok(Statement {
conn: conn,
name: stmt_name,
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: false,
})
}
fn prepare_cached<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let stmt = self.cached_statements.get(query).cloned();
let CachedStatement { name, param_types, columns } = match stmt {
Some(stmt) => stmt,
None => {
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
let stmt = CachedStatement {
name: stmt_name,
param_types: param_types,
columns: columns,
};
self.cached_statements.insert(query.to_owned(), stmt.clone());
stmt
}
};
Ok(Statement {
conn: conn,
name: name,
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: true, // << !
})
}
fn close_statement(&mut self, name: &str, type_: u8) -> Result<()> {
try!(self.write_messages(&[
Close {
variant: type_,
name: name,
},
Sync]));
let resp = match try!(self.read_message()) {
CloseComplete => Ok(()),
ErrorResponse { fields } => DbError::new(fields),
_ => bad_response!(self)
};
try!(self.wait_for_ready());
resp
}
fn get_type(&mut self, oid: Oid) -> Result<Type> {
if let Some(ty) = Type::new(oid) {
return Ok(ty);
}
if let Some(ty) = self.unknown_types.get(&oid) {
return Ok(ty.clone());
}
// Ew @ doing this manually :(
let mut buf = vec![];
let value = match try!(oid.to_sql_checked(&Type::Oid, &mut buf, &SessionInfo::new(self))) {
IsNull::Yes => None,
IsNull::No => Some(buf),
};
try!(self.write_messages(&[
Bind {
portal: "",
statement: TYPEINFO_QUERY,
formats: &[1],
values: &[value],
result_formats: &[1]
},
Execute {
portal: "",
max_rows: 0,
},
Sync]));
match try!(self.read_message()) {
BindComplete => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
}
let (name, elem_oid, rngsubtype): (String, Oid, Option<Oid>) =
match try!(self.read_message()) {
DataRow { row } => {
let ctx = SessionInfo::new(self);
(try!(FromSql::from_sql_nullable(&Type::Name,
row[0].as_ref().map(|r| &**r).as_mut(),
&ctx)),
try!(FromSql::from_sql_nullable(&Type::Oid,
row[1].as_ref().map(|r| &**r).as_mut(),
&ctx)),
try!(FromSql::from_sql_nullable(&Type::Oid,
row[2].as_ref().map(|r| &**r).as_mut(),
&ctx)))
}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
};
match try!(self.read_message()) {
CommandComplete { .. } => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self)
}
try!(self.wait_for_ready());
let kind = if elem_oid != 0 {
Kind::Array(try!(self.get_type(elem_oid)))
} else {
match rngsubtype {
Some(oid) => Kind::Range(try!(self.get_type(oid))),
None => Kind::Simple
}
};
let type_ = Type::Other(Box::new(Other::new(name, oid, kind)));
self.unknown_types.insert(oid, type_.clone());
Ok(type_)
}
fn is_desynchronized(&self) -> bool {
self.desynchronized
}
fn wait_for_ready(&mut self) -> Result<()> {
match try!(self.read_message()) {
ReadyForQuery { .. } => Ok(()),
_ => bad_response!(self)
}
}
fn quick_query(&mut self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
check_desync!(self);
debug!("executing query: {}", query);
try!(self.write_messages(&[Query { query: query }]));
let mut result = vec![];
loop {
match try!(self.read_message()) {
ReadyForQuery { .. } => break,
DataRow { row } => {
result.push(row.into_iter().map(|opt| {
opt.map(|b| String::from_utf8_lossy(&b).into_owned())
}).collect());
}
CopyInResponse { .. } => {
try!(self.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => {}
}
}
Ok(result)
}
fn finish_inner(&mut self) -> Result<()> {
check_desync!(self);
try!(self.write_messages(&[Terminate]));
Ok(())
}
}
fn _ensure_send() {
fn _is_send<T: Send>() {}
_is_send::<Connection>();
}
/// A connection to a Postgres database.
pub struct Connection {
conn: RefCell<InnerConnection>
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let conn = self.conn.borrow();
DebugStruct::new(fmt, "Connection")
.field("cancel_data", &conn.cancel_data)
.field("notifications", &conn.notifications.len())
.field("transaction_depth", &conn.trans_depth)
.field("desynchronized", &conn.desynchronized)
.field("cached_statements", &conn.cached_statements.len())
.finish()
}
}
impl Connection {
/// Creates a new connection to a Postgres database.
///
/// Most applications can use a URL string in the normal format:
///
/// ```notrust
/// postgresql://user[:password]@host[:port][/database][?param1=val1[[¶m2=val2]...]]
/// ```
///
/// The password may be omitted if not required. The default Postgres port
/// (5432) is used if none is specified. The database name defaults to the
/// username if not specified.
///
/// Connection via Unix sockets is supported with the `unix_socket`
/// feature. To connect to the server via Unix sockets, `host` should be
/// set to the absolute path of the directory containing the socket file.
/// Since `/` is a reserved character in URLs, the path should be URL
/// encoded. If the path contains non-UTF 8 characters, a `ConnectParams`
/// struct should be created manually and passed in. Note that Postgres
/// does not support SSL over Unix sockets.
///
/// ## Examples
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// let url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, UserInfo, ConnectParams, SslMode, ConnectTarget};
/// # #[cfg(feature = "unix_socket")]
/// # fn f() -> Result<(), ::postgres::error::ConnectError> {
/// # let some_crazy_path = Path::new("");
/// let params = ConnectParams {
/// target: ConnectTarget::Unix(some_crazy_path),
/// port: None,
/// user: Some(UserInfo {
/// user: "postgres".to_string(),
/// password: None
/// }),
/// database: None,
/// options: vec![],
/// };
/// let conn = try!(Connection::connect(params, &SslMode::None));
/// # Ok(()) };
/// ```
pub fn connect<T>(params: T, ssl: &SslMode) -> result::Result<Connection, ConnectError>
where T: IntoConnectParams {
InnerConnection::connect(params, ssl).map(|conn| {
Connection { conn: RefCell::new(conn) }
})
}
/// Sets the notice handler for the connection, returning the old handler.
pub fn set_notice_handler(&self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
self.conn.borrow_mut().set_notice_handler(handler)
}
/// Returns an iterator over asynchronous notification messages.
///
/// Use the `LISTEN` command to register this connection for notifications.
pub fn notifications<'a>(&'a self) -> Notifications<'a> {
Notifications { conn: self }
}
/// Creates a new prepared statement.
///
/// A statement may contain parameters, specified by `$n` where `n` is the
/// index of the parameter in the list provided at execution time,
/// 1-indexed.
///
/// The statement is associated with the connection that created it and may
/// not outlive that connection.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let maybe_stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1");
/// let stmt = match maybe_stmt {
/// Ok(stmt) => stmt,
/// Err(err) => panic!("Error preparing statement: {:?}", err)
/// };
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare(query, self)
}
/// Creates cached prepared statement.
///
/// Like `prepare`, except that the statement is only prepared once over
/// the lifetime of the connection and then cached. If the same statement
/// is going to be used frequently, caching it can improve performance by
/// reducing the number of round trips to the Postgres backend.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn f() -> postgres::Result<()> {
/// # let x = 10i32;
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let stmt = try!(conn.prepare_cached("SELECT foo FROM bar WHERE baz = $1"));
/// for row in try!(stmt.query(&[&x])) {
/// println!("foo: {}", row.get::<_, String>(0));
/// }
/// # Ok(()) };
/// ```
pub fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare_cached(query, self)
}
/// Begins a new transaction.
///
/// Returns a `Transaction` object which should be used instead of
/// the connection for the duration of the transaction. The transaction
/// is active until the `Transaction` object falls out of scope.
///
/// ## Note
/// A transaction will roll back by default. The `set_commit`,
/// `set_rollback`, and `commit` methods alter this behavior.
///
/// ## Panics
///
/// Panics if a transaction is already active.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn foo() -> Result<(), postgres::error::Error> {
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let trans = try!(conn.transaction());
/// try!(trans.execute("UPDATE foo SET bar = 10", &[]));
/// // ...
///
/// try!(trans.commit());
/// # Ok(())
/// # }
/// ```
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
assert!(conn.trans_depth == 0, "`transaction` must be called on the active transaction");
try!(conn.quick_query("BEGIN"));
conn.trans_depth += 1;
Ok(Transaction {
conn: self,
commit: Cell::new(false),
depth: 1,
finished: false,
})
}
/// Sets the isolation level which will be used for future transactions.
///
/// ## Note
///
/// This will not change the behavior of an active transaction.
pub fn set_transaction_isolation(&self, level: IsolationLevel) -> Result<()> {
self.batch_execute(level.to_set_query())
}
/// Returns the isolation level which will be used for future transactions.
pub fn transaction_isolation(&self) -> Result<IsolationLevel> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
let result = try!(conn.quick_query("SHOW TRANSACTION ISOLATION LEVEL"));
IsolationLevel::parse(result[0][0].as_ref().unwrap())
}
/// A convenience function for queries that are only run once.
///
/// If an error is returned, it could have come from either the preparation
/// or execution of the statement.
///
/// On success, returns the number of rows modified or 0 if not applicable.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
let stmt = Statement {
conn: self,
name: "".to_owned(),
param_types: param_types,
columns: columns,
next_portal_id: Cell::new(0),
finished: true, // << !!
};
stmt.execute(params)
}
/// Execute a sequence of SQL statements.
///
/// Statements should be separated by `;` characters. If an error occurs,
/// execution of the sequence will stop at that point. This is intended for
/// execution of batches of non-dynamic statements - for example, creation
/// of a schema for a fresh database.
///
/// ## Warning
///
/// Prepared statements should be used for any SQL statement which contains
/// user-specified data, as it provides functionality to safely embed that
/// data in the statement. Do not form statements via string concatenation
/// and feed them into this method.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, Result};
/// fn init_db(conn: &Connection) -> Result<()> {
/// conn.batch_execute("
/// CREATE TABLE person (
/// id SERIAL PRIMARY KEY,
/// name NOT NULL
/// );
///
/// CREATE TABLE purchase (
/// id SERIAL PRIMARY KEY,
/// person INT NOT NULL REFERENCES person (id),
/// time TIMESTAMPTZ NOT NULL,
/// );
///
/// CREATE INDEX ON purchase (time);
/// ")
/// }
/// ```
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.borrow_mut().quick_query(query).map(|_| ())
}
/// Returns information used to cancel pending queries.
///
/// Used with the `cancel_query` function. The object returned can be used
/// to cancel any query executed by the connection it was created from.
pub fn cancel_data(&self) -> CancelData {
self.conn.borrow().cancel_data
}
/// Returns the value of the specified Postgres backend parameter, such as
/// `timezone` or `server_version`.
pub fn parameter(&self, param: &str) -> Option<String> {
self.conn.borrow().parameters.get(param).cloned()
}
/// Returns whether or not the stream has been desynchronized due to an
/// error in the communication channel with the server.
///
/// If this has occurred, all further queries will immediately return an
/// error.
pub fn is_desynchronized(&self) -> bool {
self.conn.borrow().is_desynchronized()
}
/// Determines if the `Connection` is currently "active", that is, if there
/// are no active transactions.
///
/// The `transaction` method can only be called on the active `Connection`
/// or `Transaction`.
pub fn is_active(&self) -> bool {
self.conn.borrow().trans_depth == 0
}
/// Consumes the connection, closing it.
///
/// Functionally equivalent to the `Drop` implementation for `Connection`
/// except that it returns any error encountered to the caller.
pub fn finish(self) -> Result<()> {
let mut conn = self.conn.borrow_mut();
conn.finished = true;
conn.finish_inner()
}
}
/// Represents a transaction on a database connection.
///
/// The transaction will roll back by default.
pub struct Transaction<'conn> {
conn: &'conn Connection,
depth: u32,
commit: Cell<bool>,
finished: bool,
}
impl<'a> fmt::Debug for Transaction<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Transaction")
.field("commit", &self.commit.get())
.field("depth", &self.depth)
.finish()
}
}
impl<'conn> Drop for Transaction<'conn> {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl<'conn> Transaction<'conn> {
fn finish_inner(&mut self) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut();
debug_assert!(self.depth == conn.trans_depth);
let query = match (self.commit.get(), self.depth != 1) {
(false, true) => "ROLLBACK TO sp",
(false, false) => "ROLLBACK",
(true, true) => "RELEASE sp",
(true, false) => "COMMIT",
};
conn.trans_depth -= 1;
conn.quick_query(query).map(|_| ())
}
/// Like `Connection::prepare`.
pub fn prepare(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare(query)
}
/// Like `Connection::prepare_cached`.
///
/// Note that the statement will be cached for the duration of the
/// connection, not just the duration of this transaction.
pub fn prepare_cached(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare_cached(query)
}
/// Like `Connection::execute`.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.conn.execute(query, params)
}
/// Like `Connection::batch_execute`.
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.batch_execute(query)
}
/// Like `Connection::transaction`.
///
/// ## Panics
///
/// Panics if there is an active nested transaction.
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
assert!(conn.trans_depth == self.depth,
"`transaction` may only be called on the active transaction");
try!(conn.quick_query("SAVEPOINT sp"));
conn.trans_depth += 1;
Ok(Transaction {
conn: self.conn,
commit: Cell::new(false),
depth: self.depth + 1,
finished: false,
})
}
/// Returns a reference to the `Transaction`'s `Connection`.
pub fn connection(&self) -> &'conn Connection {
self.conn
}
/// Like `Connection::is_active`.
pub fn is_active(&self) -> bool {
self.conn.conn.borrow().trans_depth == self.depth
}
/// Determines if the transaction is currently set to commit or roll back.
pub fn will_commit(&self) -> bool {
self.commit.get()
}
/// Sets the transaction to commit at its completion.
pub fn set_commit(&self) {
self.commit.set(true);
}
/// Sets the transaction to roll back at its completion.
pub fn set_rollback(&self) {
self.commit.set(false);
}
/// A convenience method which consumes and commits a transaction.
pub fn commit(self) -> Result<()> {
self.set_commit();
self.finish()
}
/// Consumes the transaction, commiting or rolling it back as appropriate.
///
/// Functionally equivalent to the `Drop` implementation of `Transaction`
/// except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
self.finished = true;
self.finish_inner()
}
}
/// A prepared statement.
pub struct Statement<'conn> {
conn: &'conn Connection,
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
next_portal_id: Cell<u32>,
finished: bool,
}
impl<'a> fmt::Debug for Statement<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
DebugStruct::new(fmt, "Statement")
.field("name", &self.name)
.field("parameter_types", &self.param_types)
.field("columns", &self.columns)
.finish()
}
}
impl<'conn> Drop for Statement<'conn> {
fn drop(&mut self) {
let _ = self.finish_inner();
}
}
impl<'conn> Statement<'conn> {
fn finish_inner(&mut self) -> Result<()> {
if !self.finished {
self.finished = true;
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
conn.close_statement(&self.name, b'S')
} else {
Ok(())
}
}
fn inner_execute(&self, portal_name: &str, row_limit: i32, params: &[&ToSql]) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut();
assert!(self.param_types().len() == params.len(),
"expected {} parameters but got {}",
self.param_types.len(),
params.len());
debug!("executing statement {} with parameters: {:?}", self.name, params);
let mut values = vec![];
for (param, ty) in params.iter().zip(self.param_types.iter()) {
let mut buf = vec![];
match try!(param.to_sql_checked(ty, &mut buf, &SessionInfo::new(&*conn))) {
IsNull::Yes => values.push(None),
IsNull::No => values.push(Some(buf)),
}
};
try!(conn.write_messages(&[
Bind {
portal: portal_name,
statement: &self.name,
formats: &[1],
values: &values,
result_formats: &[1]
},
Execute {
portal: portal_name,
max_rows: row_limit
},
Sync]));
match try!(conn.read_message()) {
BindComplete => Ok(()),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
DbError::new(fields)
}
_ => {
conn.desynchronized = true;
Err(Error::IoError(bad_response()))
}
}
}
fn inner_query<'a>(&'a self, portal_name: &str, row_limit: i32, params: &[&ToSql])
-> Result<(VecDeque<Vec<Option<Vec<u8>>>>, bool)> {
try!(self.inner_execute(portal_name, row_limit, params));
let mut buf = VecDeque::new();
let more_rows = try!(read_rows(&mut self.conn.conn.borrow_mut(), &mut buf));
Ok((buf, more_rows))
}
/// Returns a slice containing the expected parameter types.
pub fn param_types(&self) -> &[Type] {
&self.param_types
}
/// Returns a slice describing the columns of the result of the query.
pub fn columns(&self) -> &[Column] {
&self.columns
}
/// Executes the prepared statement, returning the number of rows modified.
///
/// If the statement does not modify any rows (e.g. SELECT), 0 is returned.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// # let bar = 1i32;
/// # let baz = true;
/// let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();
/// match stmt.execute(&[&bar, &baz]) {
/// Ok(count) => println!("{} row(s) updated", count),
/// Err(err) => println!("Error executing query: {:?}", err)
/// }
/// ```
pub fn execute(&self, params: &[&ToSql]) -> Result<u64> {
check_desync!(self.conn);
try!(self.inner_execute("", 0, params));
let mut conn = self.conn.conn.borrow_mut();
let num;
loop {
match try!(conn.read_message()) {
DataRow { .. } => {}
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
CommandComplete { tag } => {
num = util::parse_update_count(tag);
break;
}
EmptyQueryResponse => {
num = 0;
break;
}
CopyInResponse { .. } => {
try!(conn.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
}
try!(conn.wait_for_ready());
Ok(num)
}
/// Executes the prepared statement, returning the resulting rows.
///
/// ## Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1").unwrap();
/// # let baz = true;
/// let rows = match stmt.query(&[&baz]) {
/// Ok(rows) => rows,
/// Err(err) => panic!("Error running query: {:?}", err)
/// };
/// for row in &rows {
/// let foo: i32 = row.get("foo");
/// println!("foo: {}", foo);
/// }
/// ```
pub fn query<'a>(&'a self, params: &[&ToSql]) -> Result<Rows<'a>> {
check_desync!(self.conn);
self.inner_query("", 0, params).map(|(buf, _)| {
Rows::new(self, buf.into_iter().collect())
})
}
/// Executes the prepared statement, returning a lazily loaded iterator
/// over the resulting rows.
///
/// No more than `row_limit` rows will be stored in memory at a time. Rows
/// will be pulled from the database in batches of `row_limit` as needed.
/// If `row_limit` is less than or equal to 0, `lazy_query` is equivalent
/// to `query`.
///
/// This can only be called inside of a transaction, and the `Transaction`
/// object representing the active transaction must be passed to
/// `lazy_query`.
///
/// ## Panics
///
/// Panics if the provided `Transaction` is not associated with the same
/// `Connection` as this `Statement`, if the `Transaction` is not
/// active, or if the number of parameters provided does not match the
/// number of parameters expected.
pub fn lazy_query<'trans, 'stmt>(&'stmt self,
trans: &'trans Transaction,
params: &[&ToSql],
row_limit: i32)
-> Result<LazyRows<'trans, 'stmt>> {
assert!(self.conn as *const _ == trans.conn as *const _,
"the `Transaction` passed to `lazy_query` must be associated with the same \
`Connection` as the `Statement`");
let conn = self.conn.conn.borrow();
check_desync!(conn);
assert!(conn.trans_depth == trans.depth,
"`lazy_query` must be passed the active transaction");
drop(conn);
let id = self.next_portal_id.get();
self.next_portal_id.set(id + 1);
let portal_name = format!("{}p{}", self.name, id);
self.inner_query(&portal_name, row_limit, params).map(move |(data, more_rows)| {
LazyRows::new(self, data, portal_name, row_limit, more_rows, false, trans)
})
}
/// Executes a `COPY FROM STDIN` statement, returning the number of rows
/// added.
///
/// The contents of the provided reader are passed to the Postgres server
/// verbatim; it is the caller's responsibility to ensure it uses the
/// proper format. See the
/// [Postgres documentation](http://www.postgresql.org/docs/9.4/static/sql-copy.html)
/// for details.
///
/// If the statement is not a `COPY FROM STDIN` statement it will still be
/// executed and this method will return an error.
///
/// # Examples
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// conn.batch_execute("CREATE TABLE people (id INT PRIMARY KEY, name VARCHAR)").unwrap();
/// let stmt = conn.prepare("COPY people FROM STDIN").unwrap();
/// stmt.copy_in(&[], &mut "1\tjohn\n2\tjane\n".as_bytes()).unwrap();
/// ```
pub fn copy_in<R: ReadWithInfo>(&self, params: &[&ToSql], r: &mut R) -> Result<u64> {
try!(self.inner_execute("", 0, params));
let mut conn = self.conn.conn.borrow_mut();
match try!(conn.read_message()) {
CopyInResponse { .. } => {}
_ => {
loop {
match try!(conn.read_message()) {
ReadyForQuery { .. } => {
return Err(Error::IoError(std_io::Error::new(
std_io::ErrorKind::InvalidInput,
"called `copy_in` on a non-`COPY FROM STDIN` statement")));
}
_ => {}
}
}
}
}
let mut buf = [0; 16 * 1024];
loop {
match fill_copy_buf(&mut buf, r, &SessionInfo::new(&conn)) {
Ok(0) => break,
Ok(len) => {
try_desync!(conn, conn.stream.write_message(
&CopyData {
data: &buf[..len],
}));
}
Err(err) => {
try!(conn.write_messages(&[
CopyFail {
message: "",
},
CopyDone,
Sync]));
match try!(conn.read_message()) {
ErrorResponse { .. } => { /* expected from the CopyFail */ }
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
try!(conn.wait_for_ready());
return Err(Error::IoError(err));
}
}
}
try!(conn.write_messages(&[CopyDone, Sync]));
let num = match try!(conn.read_message()) {
CommandComplete { tag } => util::parse_update_count(tag),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
};
try!(conn.wait_for_ready());
Ok(num)
}
/// Consumes the statement, clearing it from the Postgres session.
///
/// If this statement was created via the `prepare_cached` method, `finish`
/// does nothing.
///
/// Functionally identical to the `Drop` implementation of the
/// `Statement` except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
self.finish_inner()
}
}
fn fill_copy_buf<R: ReadWithInfo>(buf: &mut [u8], r: &mut R, info: &SessionInfo)
-> std_io::Result<usize> {
let mut nread = 0;
while nread < buf.len() {
match r.read_with_info(&mut buf[nread..], info) {
Ok(0) => break,
Ok(n) => nread += n,
Err(ref e) if e.kind() == std_io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(nread)
}
/// Information about a column of the result of a query.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Column {
name: String,
type_: Type
}
impl Column {
/// The name of the column.
pub fn name(&self) -> &str {
&self.name
}
/// The type of the data in the column.
pub fn type_(&self) -> &Type {
&self.type_
}
}
fn read_rows(conn: &mut InnerConnection, buf: &mut VecDeque<Vec<Option<Vec<u8>>>>) -> Result<bool> {
let more_rows;
loop {
match try!(conn.read_message()) {
EmptyQueryResponse | CommandComplete { .. } => {
more_rows = false;
break;
}
PortalSuspended => {
more_rows = true;
break;
}
DataRow { row } => buf.push_back(row),
ErrorResponse { fields } => {
try!(conn.wait_for_ready());
return DbError::new(fields);
}
CopyInResponse { .. } => {
try!(conn.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
_ => {
conn.desynchronized = true;
return Err(Error::IoError(bad_response()));
}
}
}
try!(conn.wait_for_ready());
Ok(more_rows)
}
/// A trait allowing abstraction over connections and transactions
pub trait GenericConnection {
/// Like `Connection::prepare`.
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
/// Like `Connection::prepare_cached`.
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
/// Like `Connection::execute`.
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64>;
/// Like `Connection::transaction`.
fn transaction<'a>(&'a self) -> Result<Transaction<'a>>;
/// Like `Connection::batch_execute`.
fn batch_execute(&self, query: &str) -> Result<()>;
/// Like `Connection::is_active`.
fn is_active(&self) -> bool;
}
impl GenericConnection for Connection {
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare(query)
}
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare_cached(query)
}
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
self.transaction()
}
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
impl<'a> GenericConnection for Transaction<'a> {
fn prepare<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare(query)
}
fn prepare_cached<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare_cached(query)
}
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn transaction<'b>(&'b self) -> Result<Transaction<'b>> {
self.transaction()
}
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
trait OtherNew {
fn new(name: String, oid: Oid, kind: Kind) -> Other;
}
trait DbErrorNew {
fn new_raw(fields: Vec<(u8, String)>) -> result::Result<DbError, ()>;
fn new_connect<T>(fields: Vec<(u8, String)>) -> result::Result<T, ConnectError>;
fn new<T>(fields: Vec<(u8, String)>) -> Result<T>;
}
trait TypeNew {
fn new(oid: Oid) -> Option<Type>;
}
trait RowsNew<'a> {
fn new(stmt: &'a Statement<'a>, data: Vec<Vec<Option<Vec<u8>>>>) -> Rows<'a>;
}
trait LazyRowsNew<'trans, 'stmt> {
fn new(stmt: &'stmt Statement<'stmt>,
data: VecDeque<Vec<Option<Vec<u8>>>>,
name: String,
row_limit: i32,
more_rows: bool,
finished: bool,
trans: &'trans Transaction<'trans>) -> LazyRows<'trans, 'stmt>;
}
trait SessionInfoNew<'a> {
fn new(conn: &'a InnerConnection) -> SessionInfo<'a>;
}
|
extern crate libc;
extern crate winapi;
extern crate kernel32;
/// Allocates `size` Bytes aligned to `align` Bytes. Returns a null pointer on allocation failure.
///
/// The returned pointer must be deallocated by using `aligned_free`.
///
/// Note: This function is meant to be used for infrequent large allocations (as `malloc` already
/// guarantees suitable alignment for all native datatypes) and might be quite slow when used
/// heavily.
///
/// # Parameters
///
/// * `size`: The size of the allocation in bytes.
/// * `align`: The alignment of the allocation (at least the size of `usize` on the current
/// platform). Must also be a power of two.
#[inline]
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
imp::aligned_alloc(size, align)
}
/// Deallocates aligned memory that was allocated with `aligned_alloc`. Unsafe because calling this
/// with a pointer that was not allocated with `aligned_alloc` (or already released) causes
/// undefined behavior.
#[inline]
pub unsafe fn aligned_free(ptr: *mut ()) {
imp::aligned_free(ptr)
}
#[cfg(unix)]
mod imp {
use libc::{c_void, c_int, size_t, EINVAL, ENOMEM, free};
use std::{mem, ptr};
extern "C" {
fn posix_memalign(memptr: *mut *mut c_void, alignment: size_t, size: size_t) -> c_int;
}
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
let mut memptr: *mut c_void = ptr::null_mut();
let result = unsafe { posix_memalign(&mut memptr, align as size_t, size as size_t) };
match result {
0 => return memptr as *mut (),
EINVAL => {
if align < mem::size_of::<usize>() {
panic!("EINVAL: invalid alignment: {} (minimum is {})", align,
mem::size_of::<usize>());
}
if !align.is_power_of_two() {
panic!("EINVAL: invalid alignment: {} (must be a power of two)", align)
}
panic!("EINVAL: invalid alignment: {}", align);
}
ENOMEM => return ptr::null_mut(),
_ => unreachable!(),
}
}
#[inline]
pub unsafe fn aligned_free(ptr: *mut ()) {
free(ptr as *mut c_void)
}
}
#[cfg(windows)]
mod imp {
use kernel32::{GetLastError, GetSystemInfo, VirtualAlloc, VirtualFree};
use winapi::{MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PAGE_NOACCESS, PAGE_READWRITE, SIZE_T,
LPVOID, DWORD, SYSTEM_INFO};
use std::mem;
use std::ptr;
static mut PAGE_SIZE: DWORD = 0;
#[cold]
fn get_page_size() {
let mut info: SYSTEM_INFO = unsafe { mem::uninitialized() };
unsafe { GetSystemInfo(&mut info); }
unsafe {
PAGE_SIZE = info.dwPageSize;
}
}
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
assert!(align.is_power_of_two(), "align must be a power of two");
if unsafe { PAGE_SIZE } == 0 { get_page_size() }
unsafe {
if align <= PAGE_SIZE as usize {
// Page alignment is guaranteed by `VirtualAlloc`
let ptr = VirtualAlloc(ptr::null_mut(), size as SIZE_T, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
return ptr as *mut ()
}
// Step 1: Reserve `size+align-1` Bytes of address space to find a suitable address
let ptr = VirtualAlloc(ptr::null_mut(), (size + align - 1) as SIZE_T, MEM_RESERVE,
PAGE_NOACCESS);
if ptr.is_null() { return ptr::null_mut() }
// Step 2: Calculate an aligned address within the reserved range
// (this works because `align` must be a power of two)
let aligned_ptr = (ptr as usize + align - 1) & !(align - 1);
// Step 3: Actually allocate (commit) the memory
let res = VirtualFree(ptr as LPVOID, 0, MEM_RELEASE);
if res == 0 {
panic!("WINAPI error {} while freeing reserved memory", GetLastError());
}
let ptr = VirtualAlloc(aligned_ptr as LPVOID, size as SIZE_T, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
ptr as *mut ()
}
}
pub unsafe fn aligned_free(ptr: *mut ()) {
let res = VirtualFree(ptr as LPVOID, 0, MEM_RELEASE);
if res == 0 {
panic!("WINAPI error {} while releasing memory", GetLastError());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_low_align() {
let ptr = aligned_alloc(1, 128);
assert!(!ptr.is_null());
assert!(ptr as usize % 128 == 0);
unsafe { aligned_free(ptr) }
}
#[test]
fn test_high_align() {
let ptr = aligned_alloc(1, 1024 * 1024);
assert!(!ptr.is_null());
assert!(ptr as usize % (1024 * 1024) == 0);
unsafe { aligned_free(ptr) }
}
}
Add more tests
Closes #3
extern crate libc;
extern crate winapi;
extern crate kernel32;
/// Allocates `size` Bytes aligned to `align` Bytes. Returns a null pointer on allocation failure.
///
/// The returned pointer must be deallocated by using `aligned_free`.
///
/// Note: This function is meant to be used for infrequent large allocations (as `malloc` already
/// guarantees suitable alignment for all native datatypes) and might be quite slow when used
/// heavily.
///
/// # Parameters
///
/// * `size`: The size of the allocation in bytes.
/// * `align`: The alignment of the allocation (at least the size of `usize` on the current
/// platform). Must also be a power of two.
#[inline]
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
imp::aligned_alloc(size, align)
}
/// Deallocates aligned memory that was allocated with `aligned_alloc`. Unsafe because calling this
/// with a pointer that was not allocated with `aligned_alloc` (or already released) causes
/// undefined behavior.
#[inline]
pub unsafe fn aligned_free(ptr: *mut ()) {
imp::aligned_free(ptr)
}
#[cfg(unix)]
mod imp {
use libc::{c_void, c_int, size_t, EINVAL, ENOMEM, free};
use std::{mem, ptr};
extern "C" {
fn posix_memalign(memptr: *mut *mut c_void, alignment: size_t, size: size_t) -> c_int;
}
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
let mut memptr: *mut c_void = ptr::null_mut();
let result = unsafe { posix_memalign(&mut memptr, align as size_t, size as size_t) };
match result {
0 => return memptr as *mut (),
EINVAL => {
if align < mem::size_of::<usize>() {
panic!("EINVAL: invalid alignment: {} (minimum is {})", align,
mem::size_of::<usize>());
}
if !align.is_power_of_two() {
panic!("EINVAL: invalid alignment: {} (must be a power of two)", align)
}
panic!("EINVAL: invalid alignment: {}", align);
}
ENOMEM => return ptr::null_mut(),
_ => unreachable!(),
}
}
#[inline]
pub unsafe fn aligned_free(ptr: *mut ()) {
free(ptr as *mut c_void)
}
}
#[cfg(windows)]
mod imp {
use kernel32::{GetLastError, GetSystemInfo, VirtualAlloc, VirtualFree};
use winapi::{MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PAGE_NOACCESS, PAGE_READWRITE, SIZE_T,
LPVOID, DWORD, SYSTEM_INFO};
use std::mem;
use std::ptr;
static mut PAGE_SIZE: DWORD = 0;
#[cold]
fn get_page_size() {
let mut info: SYSTEM_INFO = unsafe { mem::uninitialized() };
unsafe { GetSystemInfo(&mut info); }
unsafe {
PAGE_SIZE = info.dwPageSize;
}
}
pub fn aligned_alloc(size: usize, align: usize) -> *mut () {
assert!(align.is_power_of_two(), "align must be a power of two");
if unsafe { PAGE_SIZE } == 0 { get_page_size() }
unsafe {
if align <= PAGE_SIZE as usize {
// Page alignment is guaranteed by `VirtualAlloc`
let ptr = VirtualAlloc(ptr::null_mut(), size as SIZE_T, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
return ptr as *mut ()
}
// Step 1: Reserve `size+align-1` Bytes of address space to find a suitable address
let ptr = VirtualAlloc(ptr::null_mut(), (size + align - 1) as SIZE_T, MEM_RESERVE,
PAGE_NOACCESS);
if ptr.is_null() { return ptr::null_mut() }
// Step 2: Calculate an aligned address within the reserved range
// (this works because `align` must be a power of two)
let aligned_ptr = (ptr as usize + align - 1) & !(align - 1);
// Step 3: Actually allocate (commit) the memory
let res = VirtualFree(ptr as LPVOID, 0, MEM_RELEASE);
if res == 0 {
panic!("WINAPI error {} while freeing reserved memory", GetLastError());
}
let ptr = VirtualAlloc(aligned_ptr as LPVOID, size as SIZE_T, MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
ptr as *mut ()
}
}
pub unsafe fn aligned_free(ptr: *mut ()) {
let res = VirtualFree(ptr as LPVOID, 0, MEM_RELEASE);
if res == 0 {
panic!("WINAPI error {} while releasing memory", GetLastError());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_low_align() {
let ptr = aligned_alloc(1, 128);
assert!(!ptr.is_null());
assert!(ptr as usize % 128 == 0);
unsafe { aligned_free(ptr) }
}
#[test]
fn small_high_align() {
let ptr = aligned_alloc(1, 1024 * 1024);
assert!(!ptr.is_null());
assert!(ptr as usize % (1024 * 1024) == 0);
unsafe { aligned_free(ptr) }
}
#[test]
fn large_high_align() {
// allocate 1 MiB aligned to 1 MiB
let ptr = aligned_alloc(1024 * 1024, 1024 * 1024);
assert!(!ptr.is_null());
assert!(ptr as usize % (1024 * 1024) == 0);
unsafe { aligned_free(ptr) }
}
#[test]
#[should_panic]
fn align_less_than_sizeof_usize() {
// alignment of less than sizeof(usize)
aligned_alloc(1, 3);
}
#[test]
#[should_panic]
fn align_not_power_of_two() {
aligned_alloc(1, 27);
}
}
|
//! This crate provides x86_64 specific functions and data structures,
//! and access to various system registers.
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "const_fn", feature(const_fn))]
#![cfg_attr(feature = "const_fn", feature(const_mut_refs))]
#![cfg_attr(feature = "const_fn", feature(const_in_array_repeat_expressions))]
#![cfg_attr(feature = "inline_asm", feature(llvm_asm))]
#![cfg_attr(feature = "abi_x86_interrupt", feature(abi_x86_interrupt))]
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![cfg_attr(feature = "deny-warnings", deny(missing_docs))]
#![cfg_attr(not(feature = "deny-warnings"), warn(missing_docs))]
#![deny(missing_debug_implementations)]
pub use crate::addr::{align_down, align_up, PhysAddr, VirtAddr};
/// Makes a function const only when `feature = "const_fn"` is enabled.
///
/// This is needed for const functions with bounds on their generic parameters,
/// such as those in `Page` and `PhysFrame` and many more.
macro_rules! const_fn {
(
$(#[$attr:meta])*
pub $($fn:tt)*
) => {
$(#[$attr])*
#[cfg(feature = "const_fn")]
pub const $($fn)*
$(#[$attr])*
#[cfg(not(feature = "const_fn"))]
pub $($fn)*
}
}
#[cfg(all(feature = "instructions", feature = "external_asm"))]
pub(crate) mod asm;
pub mod addr;
pub mod instructions;
pub mod registers;
pub mod structures;
/// Represents a protection ring level.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum PrivilegeLevel {
/// Privilege-level 0 (most privilege): This level is used by critical system-software
/// components that require direct access to, and control over, all processor and system
/// resources. This can include BIOS, memory-management functions, and interrupt handlers.
Ring0 = 0,
/// Privilege-level 1 (moderate privilege): This level is used by less-critical system-
/// software services that can access and control a limited scope of processor and system
/// resources. Software running at these privilege levels might include some device drivers
/// and library routines. The actual privileges of this level are defined by the
/// operating system.
Ring1 = 1,
/// Privilege-level 2 (moderate privilege): Like level 1, this level is used by
/// less-critical system-software services that can access and control a limited scope of
/// processor and system resources. The actual privileges of this level are defined by the
/// operating system.
Ring2 = 2,
/// Privilege-level 3 (least privilege): This level is used by application software.
/// Software running at privilege-level 3 is normally prevented from directly accessing
/// most processor and system resources. Instead, applications request access to the
/// protected processor and system resources by calling more-privileged service routines
/// to perform the accesses.
Ring3 = 3,
}
impl PrivilegeLevel {
/// Creates a `PrivilegeLevel` from a numeric value. The value must be in the range 0..4.
///
/// This function panics if the passed value is >3.
#[inline]
pub fn from_u16(value: u16) -> PrivilegeLevel {
match value {
0 => PrivilegeLevel::Ring0,
1 => PrivilegeLevel::Ring1,
2 => PrivilegeLevel::Ring2,
3 => PrivilegeLevel::Ring3,
i => panic!("{} is not a valid privilege level", i),
}
}
}
Fix build error on latest nightly
//! This crate provides x86_64 specific functions and data structures,
//! and access to various system registers.
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "const_fn", feature(const_fn))]
#![cfg_attr(feature = "const_fn", feature(const_mut_refs))]
#![cfg_attr(feature = "const_fn", feature(const_fn_fn_ptr_basics))]
#![cfg_attr(feature = "const_fn", feature(const_in_array_repeat_expressions))]
#![cfg_attr(feature = "inline_asm", feature(llvm_asm))]
#![cfg_attr(feature = "abi_x86_interrupt", feature(abi_x86_interrupt))]
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![cfg_attr(feature = "deny-warnings", deny(missing_docs))]
#![cfg_attr(not(feature = "deny-warnings"), warn(missing_docs))]
#![deny(missing_debug_implementations)]
pub use crate::addr::{align_down, align_up, PhysAddr, VirtAddr};
/// Makes a function const only when `feature = "const_fn"` is enabled.
///
/// This is needed for const functions with bounds on their generic parameters,
/// such as those in `Page` and `PhysFrame` and many more.
macro_rules! const_fn {
(
$(#[$attr:meta])*
pub $($fn:tt)*
) => {
$(#[$attr])*
#[cfg(feature = "const_fn")]
pub const $($fn)*
$(#[$attr])*
#[cfg(not(feature = "const_fn"))]
pub $($fn)*
}
}
#[cfg(all(feature = "instructions", feature = "external_asm"))]
pub(crate) mod asm;
pub mod addr;
pub mod instructions;
pub mod registers;
pub mod structures;
/// Represents a protection ring level.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum PrivilegeLevel {
/// Privilege-level 0 (most privilege): This level is used by critical system-software
/// components that require direct access to, and control over, all processor and system
/// resources. This can include BIOS, memory-management functions, and interrupt handlers.
Ring0 = 0,
/// Privilege-level 1 (moderate privilege): This level is used by less-critical system-
/// software services that can access and control a limited scope of processor and system
/// resources. Software running at these privilege levels might include some device drivers
/// and library routines. The actual privileges of this level are defined by the
/// operating system.
Ring1 = 1,
/// Privilege-level 2 (moderate privilege): Like level 1, this level is used by
/// less-critical system-software services that can access and control a limited scope of
/// processor and system resources. The actual privileges of this level are defined by the
/// operating system.
Ring2 = 2,
/// Privilege-level 3 (least privilege): This level is used by application software.
/// Software running at privilege-level 3 is normally prevented from directly accessing
/// most processor and system resources. Instead, applications request access to the
/// protected processor and system resources by calling more-privileged service routines
/// to perform the accesses.
Ring3 = 3,
}
impl PrivilegeLevel {
/// Creates a `PrivilegeLevel` from a numeric value. The value must be in the range 0..4.
///
/// This function panics if the passed value is >3.
#[inline]
pub fn from_u16(value: u16) -> PrivilegeLevel {
match value {
0 => PrivilegeLevel::Ring0,
1 => PrivilegeLevel::Ring1,
2 => PrivilegeLevel::Ring2,
3 => PrivilegeLevel::Ring3,
i => panic!("{} is not a valid privilege level", i),
}
}
}
|
#![deny(missing_docs)]
#![warn(dead_code)]
//! A user friendly game engine written in Rust.
#[cfg(feature = "include_gfx")]
extern crate libc;
#[cfg(feature = "include_gfx")]
extern crate gfx;
#[cfg(feature = "include_gfx")]
extern crate gfx_device_gl;
#[cfg(feature = "include_gfx")]
extern crate gfx_graphics;
#[cfg(feature = "include_opengl")]
extern crate opengl_graphics;
#[cfg(feature = "include_sdl2")]
extern crate sdl2;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
extern crate graphics;
extern crate fps_counter;
extern crate current;
extern crate shader_version;
extern crate piston;
#[cfg(feature = "include_sdl2")]
pub use sdl2_window::Sdl2Window as WindowBackEnd;
#[cfg(feature = "include_glfw")]
pub use glfw_window::GlfwWindow as WindowBackEnd;
#[cfg(feature = "include_glutin")]
pub use glutin_window::GlutinWindow as WindowBackEnd;
#[cfg(feature = "include_gfx")]
use gfx_graphics::Gfx2d;
#[cfg(feature = "include_gfx")]
use gfx_device_gl::{ Device, Resources };
#[cfg(feature = "include_gfx")]
use gfx_device_gl::CommandBuffer;
#[cfg(feature = "include_opengl")]
use opengl_graphics::GlGraphics;
use fps_counter::FPSCounter;
use std::rc::Rc;
use std::cell::RefCell;
use piston::window::WindowSettings;
use current::{ Current, CurrentGuard };
fn start_window<F>(
opengl: shader_version::OpenGL,
window_settings: WindowSettings,
mut f: F
)
where
F: FnMut()
{
let mut window = Rc::new(RefCell::new(WindowBackEnd::new(
opengl,
window_settings,
)));
let mut fps_counter = Rc::new(RefCell::new(FPSCounter::new()));
#[cfg(feature = "include_sdl2")]
fn disable_vsync() { sdl2::video::gl_set_swap_interval(0); }
#[cfg(not(feature = "include_sdl2"))]
fn disable_vsync() {}
disable_vsync();
let window_guard = CurrentGuard::new(&mut window);
let fps_counter_guard = CurrentGuard::new(&mut fps_counter);
f();
drop(window_guard);
drop(fps_counter_guard);
}
#[cfg(feature = "include_opengl")]
fn start_opengl<F>(opengl: shader_version::OpenGL, mut f: F)
where
F: FnMut()
{
let mut gl = Rc::new(RefCell::new(GlGraphics::new(opengl)));
let gl_guard = CurrentGuard::new(&mut gl);
f();
drop(gl_guard);
}
#[cfg(not(feature = "include_opengl"))]
fn start_opengl<F>(_opengl: shader_version::OpenGL, mut f: F)
where
F: FnMut()
{
f();
}
#[cfg(feature = "include_gfx")]
fn start_gfx<F>(mut f: F)
where
F: FnMut()
{
use piston::window::Window;
use gfx::render::ext::factory::RenderFactory;
let window = current_window();
let (device, mut factory) = gfx_device_gl::create(|s| {
#[cfg(feature = "include_sdl2")]
fn get_proc_address(_: &WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
unsafe { std::mem::transmute(sdl2::video::gl_get_proc_address(s)) }
}
#[cfg(feature = "include_glfw")]
fn get_proc_address(window: &mut WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
window.window.get_proc_address(s)
}
#[cfg(feature = "include_glutin")]
fn get_proc_address(window: &WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
window.window.get_proc_address(s)
}
get_proc_address(&mut *window.borrow_mut(), s)
});
let mut renderer: Rc<RefCell<
gfx::Renderer<gfx_device_gl::Resources,
<gfx_device_gl::Device as gfx::Device>::CommandBuffer
>>> =
Rc::new(RefCell::new(factory.create_renderer()));
let mut device = Rc::new(RefCell::new(device));
let factory = Rc::new(RefCell::new(factory));
let mut g2d = Rc::new(RefCell::new(Gfx2d::new(&mut *device.borrow_mut(), &mut *factory.borrow_mut())));
let size = window.borrow().size();
let mut frame = Rc::new(RefCell::new(gfx::Frame::<Resources>::new(
size.width as u16, size.height as u16)));
let device_guard = CurrentGuard::new(&mut device);
let g2d_guard = CurrentGuard::new(&mut g2d);
let renderer_guard = CurrentGuard::new(&mut renderer);
let frame_guard = CurrentGuard::new(&mut frame);
f();
drop(g2d_guard);
drop(renderer_guard);
drop(frame_guard);
drop(device_guard);
}
#[cfg(not(feature = "include_gfx"))]
fn start_gfx<F>(mut f: F)
where
F: FnMut()
{
f();
}
/// Initializes window and sets up current objects.
pub fn start<F>(
opengl: shader_version::OpenGL,
window_settings: WindowSettings,
mut f: F
)
where
F: FnMut()
{
start_window(opengl, window_settings, || {
start_opengl(opengl, || {
if cfg!(feature = "include_gfx") {
start_gfx(|| f());
} else {
f();
}
})
});
}
/// The current window
pub fn current_window() -> Rc<RefCell<WindowBackEnd>> {
unsafe {
Current::<Rc<RefCell<WindowBackEnd>>>::new().clone()
}
}
/// The current Gfx device
#[cfg(feature = "include_gfx")]
pub fn current_gfx_device() -> Rc<RefCell<Device>> {
unsafe {
Current::<Rc<RefCell<Device>>>::new().clone()
}
}
/// The current opengl_graphics back-end
#[cfg(feature = "include_opengl")]
pub fn current_gl() -> Rc<RefCell<GlGraphics>> {
unsafe {
Current::<Rc<RefCell<GlGraphics>>>::new().clone()
}
}
/// The current gfx_graphics back-end
#[cfg(feature = "include_gfx")]
pub fn current_g2d() -> Rc<RefCell<Gfx2d<Resources>>> {
unsafe {
Current::<Rc<RefCell<Gfx2d<Resources>>>>::new().clone()
}
}
/// The current Gfx renderer
#[cfg(feature = "include_gfx")]
pub fn current_renderer() -> Rc<RefCell<gfx::Renderer<Resources, CommandBuffer>>> {
unsafe {
Current::<Rc<RefCell<gfx::Renderer<Resources, CommandBuffer>>>>::new().clone()
}
}
/// The current Gfx frame
#[cfg(feature = "include_gfx")]
pub fn current_frame() -> Rc<RefCell<gfx::Frame<Resources>>> {
unsafe {
Current::<Rc<RefCell<gfx::Frame<Resources>>>>::new().clone()
}
}
/// The current FPS counter
pub fn current_fps_counter() -> Rc<RefCell<FPSCounter>> {
unsafe {
Current::<Rc<RefCell<FPSCounter>>>::new().clone()
}
}
/// Returns an event iterator for the event loop
pub fn events() -> piston::event::events::Events<WindowBackEnd, piston::event::Event> {
use piston::event::Events;
current_window().events()
}
/// Updates the FPS counter and gets the frames per second.
pub fn fps_tick() -> usize {
let fps_counter = current_fps_counter();
let mut fps_counter = fps_counter.borrow_mut();
fps_counter.tick()
}
/// Sets title of the current window.
pub fn set_title(text: String) {
use piston::window::AdvancedWindow;
let window = current_window();
let mut window = window.borrow_mut();
window.set_title(text);
}
/// Returns true if the current window should be closed.
pub fn should_close() -> bool {
use piston::window::Window;
let window = current_window();
let window = window.borrow();
window.should_close()
}
/// Renders 2D graphics using Gfx.
#[cfg(feature = "include_gfx")]
pub fn render_2d_gfx<F>(
bg_color: Option<[f32; 4]>,
mut f: F
)
where
F: FnMut(graphics::Context,
&mut gfx_graphics::GfxGraphics<Resources, CommandBuffer>)
{
use gfx::Device;
let renderer = current_renderer();
let mut renderer = renderer.borrow_mut();
let renderer = &mut *renderer;
let gfx = current_g2d();
let mut gfx = gfx.borrow_mut();
let frame = current_frame();
let frame = frame.borrow();
gfx.draw(
renderer,
&*frame,
|c, g| {
if let Some(bg_color) = bg_color {
graphics::clear(bg_color, g);
}
f(c, g);
});
let gfx_device = current_gfx_device();
let mut gfx_device = gfx_device.borrow_mut();
gfx_device.submit(renderer.as_buffer());
renderer.reset();
}
/// Renders 2D graphics using OpenGL.
///
/// Panics if called nested within the closure
/// to prevent mutable aliases to the graphics back-end.
#[cfg(feature = "include_opengl")]
pub fn render_2d_opengl<F>(
bg_color: Option<[f32; 4]>,
mut f: F
)
where
F: FnMut(graphics::Context, &mut opengl_graphics::Gl)
{
use piston::window::Window;
use graphics::Viewport;
let window = current_window();
let window = window.borrow();
let size = window.size();
let draw_size = window.draw_size();
let gl = current_gl();
let mut gl = gl.borrow_mut();
gl.draw(Viewport {
rect: [0, 0, draw_size.width as i32, draw_size.height as i32],
draw_size: [draw_size.width, draw_size.height],
window_size: [size.width, size.height]
}, |c, g| {
use graphics::*;
if let Some(bg_color) = bg_color {
graphics::clear(bg_color, g);
}
f(c, g);
});
}
Computing `Viewport` for Gfx
#![deny(missing_docs)]
#![warn(dead_code)]
//! A user friendly game engine written in Rust.
#[cfg(feature = "include_gfx")]
extern crate libc;
#[cfg(feature = "include_gfx")]
extern crate gfx;
#[cfg(feature = "include_gfx")]
extern crate gfx_device_gl;
#[cfg(feature = "include_gfx")]
extern crate gfx_graphics;
#[cfg(feature = "include_opengl")]
extern crate opengl_graphics;
#[cfg(feature = "include_sdl2")]
extern crate sdl2;
#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;
#[cfg(feature = "include_glfw")]
extern crate glfw;
#[cfg(feature = "include_glfw")]
extern crate glfw_window;
#[cfg(feature = "include_glutin")]
extern crate glutin;
#[cfg(feature = "include_glutin")]
extern crate glutin_window;
extern crate graphics;
extern crate fps_counter;
extern crate current;
extern crate shader_version;
extern crate piston;
#[cfg(feature = "include_sdl2")]
pub use sdl2_window::Sdl2Window as WindowBackEnd;
#[cfg(feature = "include_glfw")]
pub use glfw_window::GlfwWindow as WindowBackEnd;
#[cfg(feature = "include_glutin")]
pub use glutin_window::GlutinWindow as WindowBackEnd;
#[cfg(feature = "include_gfx")]
use gfx_graphics::Gfx2d;
#[cfg(feature = "include_gfx")]
use gfx_device_gl::{ Device, Resources };
#[cfg(feature = "include_gfx")]
use gfx_device_gl::CommandBuffer;
#[cfg(feature = "include_opengl")]
use opengl_graphics::GlGraphics;
use fps_counter::FPSCounter;
use std::rc::Rc;
use std::cell::RefCell;
use piston::window::WindowSettings;
use current::{ Current, CurrentGuard };
fn start_window<F>(
opengl: shader_version::OpenGL,
window_settings: WindowSettings,
mut f: F
)
where
F: FnMut()
{
let mut window = Rc::new(RefCell::new(WindowBackEnd::new(
opengl,
window_settings,
)));
let mut fps_counter = Rc::new(RefCell::new(FPSCounter::new()));
#[cfg(feature = "include_sdl2")]
fn disable_vsync() { sdl2::video::gl_set_swap_interval(0); }
#[cfg(not(feature = "include_sdl2"))]
fn disable_vsync() {}
disable_vsync();
let window_guard = CurrentGuard::new(&mut window);
let fps_counter_guard = CurrentGuard::new(&mut fps_counter);
f();
drop(window_guard);
drop(fps_counter_guard);
}
#[cfg(feature = "include_opengl")]
fn start_opengl<F>(opengl: shader_version::OpenGL, mut f: F)
where
F: FnMut()
{
let mut gl = Rc::new(RefCell::new(GlGraphics::new(opengl)));
let gl_guard = CurrentGuard::new(&mut gl);
f();
drop(gl_guard);
}
#[cfg(not(feature = "include_opengl"))]
fn start_opengl<F>(_opengl: shader_version::OpenGL, mut f: F)
where
F: FnMut()
{
f();
}
#[cfg(feature = "include_gfx")]
fn start_gfx<F>(mut f: F)
where
F: FnMut()
{
use piston::window::Window;
use gfx::render::ext::factory::RenderFactory;
let window = current_window();
let (device, mut factory) = gfx_device_gl::create(|s| {
#[cfg(feature = "include_sdl2")]
fn get_proc_address(_: &WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
unsafe { std::mem::transmute(sdl2::video::gl_get_proc_address(s)) }
}
#[cfg(feature = "include_glfw")]
fn get_proc_address(window: &mut WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
window.window.get_proc_address(s)
}
#[cfg(feature = "include_glutin")]
fn get_proc_address(window: &WindowBackEnd, s: &str) ->
*const libc::types::common::c95::c_void {
window.window.get_proc_address(s)
}
get_proc_address(&mut *window.borrow_mut(), s)
});
let mut renderer: Rc<RefCell<
gfx::Renderer<gfx_device_gl::Resources,
<gfx_device_gl::Device as gfx::Device>::CommandBuffer
>>> =
Rc::new(RefCell::new(factory.create_renderer()));
let mut device = Rc::new(RefCell::new(device));
let factory = Rc::new(RefCell::new(factory));
let mut g2d = Rc::new(RefCell::new(Gfx2d::new(&mut *device.borrow_mut(), &mut *factory.borrow_mut())));
let size = window.borrow().size();
let mut frame = Rc::new(RefCell::new(gfx::Frame::<Resources>::new(
size.width as u16, size.height as u16)));
let device_guard = CurrentGuard::new(&mut device);
let g2d_guard = CurrentGuard::new(&mut g2d);
let renderer_guard = CurrentGuard::new(&mut renderer);
let frame_guard = CurrentGuard::new(&mut frame);
f();
drop(g2d_guard);
drop(renderer_guard);
drop(frame_guard);
drop(device_guard);
}
#[cfg(not(feature = "include_gfx"))]
fn start_gfx<F>(mut f: F)
where
F: FnMut()
{
f();
}
/// Initializes window and sets up current objects.
pub fn start<F>(
opengl: shader_version::OpenGL,
window_settings: WindowSettings,
mut f: F
)
where
F: FnMut()
{
start_window(opengl, window_settings, || {
start_opengl(opengl, || {
if cfg!(feature = "include_gfx") {
start_gfx(|| f());
} else {
f();
}
})
});
}
/// The current window
pub fn current_window() -> Rc<RefCell<WindowBackEnd>> {
unsafe {
Current::<Rc<RefCell<WindowBackEnd>>>::new().clone()
}
}
/// The current Gfx device
#[cfg(feature = "include_gfx")]
pub fn current_gfx_device() -> Rc<RefCell<Device>> {
unsafe {
Current::<Rc<RefCell<Device>>>::new().clone()
}
}
/// The current opengl_graphics back-end
#[cfg(feature = "include_opengl")]
pub fn current_gl() -> Rc<RefCell<GlGraphics>> {
unsafe {
Current::<Rc<RefCell<GlGraphics>>>::new().clone()
}
}
/// The current gfx_graphics back-end
#[cfg(feature = "include_gfx")]
pub fn current_g2d() -> Rc<RefCell<Gfx2d<Resources>>> {
unsafe {
Current::<Rc<RefCell<Gfx2d<Resources>>>>::new().clone()
}
}
/// The current Gfx renderer
#[cfg(feature = "include_gfx")]
pub fn current_renderer() -> Rc<RefCell<gfx::Renderer<Resources, CommandBuffer>>> {
unsafe {
Current::<Rc<RefCell<gfx::Renderer<Resources, CommandBuffer>>>>::new().clone()
}
}
/// The current Gfx frame
#[cfg(feature = "include_gfx")]
pub fn current_frame() -> Rc<RefCell<gfx::Frame<Resources>>> {
unsafe {
Current::<Rc<RefCell<gfx::Frame<Resources>>>>::new().clone()
}
}
/// The current FPS counter
pub fn current_fps_counter() -> Rc<RefCell<FPSCounter>> {
unsafe {
Current::<Rc<RefCell<FPSCounter>>>::new().clone()
}
}
/// Returns an event iterator for the event loop
pub fn events() -> piston::event::events::Events<WindowBackEnd, piston::event::Event> {
use piston::event::Events;
current_window().events()
}
/// Updates the FPS counter and gets the frames per second.
pub fn fps_tick() -> usize {
let fps_counter = current_fps_counter();
let mut fps_counter = fps_counter.borrow_mut();
fps_counter.tick()
}
/// Sets title of the current window.
pub fn set_title(text: String) {
use piston::window::AdvancedWindow;
let window = current_window();
let mut window = window.borrow_mut();
window.set_title(text);
}
/// Returns true if the current window should be closed.
pub fn should_close() -> bool {
use piston::window::Window;
let window = current_window();
let window = window.borrow();
window.should_close()
}
/// Renders 2D graphics using Gfx.
#[cfg(feature = "include_gfx")]
pub fn render_2d_gfx<F>(
bg_color: Option<[f32; 4]>,
mut f: F
)
where
F: FnMut(graphics::Context,
&mut gfx_graphics::GfxGraphics<Resources, CommandBuffer>)
{
use gfx::Device;
use piston::window::Window;
use graphics::Viewport;
let window = current_window();
let window = window.borrow();
let size = window.size();
let draw_size = window.draw_size();
let renderer = current_renderer();
let mut renderer = renderer.borrow_mut();
let renderer = &mut *renderer;
let gfx = current_g2d();
let mut gfx = gfx.borrow_mut();
let frame = current_frame();
let frame = frame.borrow();
gfx.draw(
renderer,
&*frame,
Viewport {
rect: [0, 0, draw_size.width as i32, draw_size.height as i32],
draw_size: [draw_size.width, draw_size.height],
window_size: [size.width, size.height],
},
|c, g| {
if let Some(bg_color) = bg_color {
graphics::clear(bg_color, g);
}
f(c, g);
});
let gfx_device = current_gfx_device();
let mut gfx_device = gfx_device.borrow_mut();
gfx_device.submit(renderer.as_buffer());
renderer.reset();
}
/// Renders 2D graphics using OpenGL.
///
/// Panics if called nested within the closure
/// to prevent mutable aliases to the graphics back-end.
#[cfg(feature = "include_opengl")]
pub fn render_2d_opengl<F>(
bg_color: Option<[f32; 4]>,
mut f: F
)
where
F: FnMut(graphics::Context, &mut opengl_graphics::Gl)
{
use piston::window::Window;
use graphics::Viewport;
let window = current_window();
let window = window.borrow();
let size = window.size();
let draw_size = window.draw_size();
let gl = current_gl();
let mut gl = gl.borrow_mut();
gl.draw(Viewport {
rect: [0, 0, draw_size.width as i32, draw_size.height as i32],
draw_size: [draw_size.width, draw_size.height],
window_size: [size.width, size.height]
}, |c, g| {
use graphics::*;
if let Some(bg_color) = bg_color {
graphics::clear(bg_color, g);
}
f(c, g);
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.