text stringlengths 8 4.13M |
|---|
extern crate json;
use std::collections::HashMap;
use std::collections::HashSet;
/*use std::cell::RefCell;
use std::fmt;*/
use std::mem;
use algo_tools;
/*struct Vertex<'a> {
word: String,
distance: RefCell<i32>,
neighbors: RefCell<Vec<&'a Vertex<'a>>>,
}
impl<'a> Vertex<'a> {
pub fn new(word: &String) -> Vertex {
Vertex {
word : word.clone(),
distance : RefCell::new(-1),
neighbors : RefCell::new(Vec::new())
}
}
pub fn newd(word: &String, distance: i32) -> Vertex {
Vertex {
word : word.clone(),
distance: RefCell::new(distance),
neighbors : RefCell::new(Vec::new())
}
}
}
impl<'a> fmt::Debug for Vertex<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}, [", self.word, self.distance.borrow())?;
for neighbor in self.neighbors.borrow().iter() {
write!(f, "{}, ", neighbor.word) ?;
}
write!(f, "]")
}
}
impl<'a> fmt::Display for Vertex<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}*/
struct Solution;
impl<'a> Solution {
/*fn dist1(w0: &String, w1: &String) -> bool {
let w0_iter = w0.chars();
let mut w1_iter = w1.chars();
let mut delta = 0;
for c0 in w0_iter {
// No risk here to unwrap because lengths are checked equal
let c1 = w1_iter.next().unwrap();
if c0 != c1 {
delta += 1;
if delta > 1 {
return false;
}
}
}
true
}
fn build_map(map: &'a HashMap<&'a String, Vertex<'a>>) {
let mut idx = 0;
for (w0, v0) in map.iter() {
for (w1, v1) in map.iter().skip(idx+1) {
//println!("w0: {}, skip {} => w1 {}, v1 {:?}", &w0, idx+1, &w1, &v1);
if Solution::dist1(w0, w1) {
v0.neighbors.borrow_mut().push(&v1);
v1.neighbors.borrow_mut().push(&v0);
}
}
idx += 1;
}
}
pub fn find_ladders_slow(begin_word: String, end_word: String, word_list: Vec<String>) ->
Vec<Vec<String>> {
let mut res : Vec<Vec<String>> = Vec::new();
let base_len = begin_word.len();
if base_len != end_word.len() {
return res
}
println!("new test (begin_word: {}, end_word: {}, word_list: {:?}",
&begin_word, &end_word, &word_list);
let mut map: HashMap<&String, Vertex> = HashMap::new();
let mut found = false;
for word in &word_list {
if base_len != word.len() {
return res
}
if !found && word == &end_word { found = true; }
map.insert(&word, Vertex::new(&word));
}
if !found { return res; }
map.remove(&begin_word);
map.insert(&begin_word, Vertex::newd(&begin_word, 0));
println!("Unbuilt map {:#?}", &map);
Solution::build_map(&map);
println!("Built map {:#?}", &map);
let mut nodes = &mut map[&begin_word].neighbors.borrow_mut().clone();
let mut next_nodes = &mut Vec::new();
let mut distance = 0;
while !nodes.is_empty() {
distance += 1;
for node in nodes.iter() {
println!("Check {} at distance {}", node, distance);
// check all the nodes at this distance
if *node.distance.borrow() == -1 {
for next_node in node.neighbors.borrow_mut().iter() {
next_nodes.push(*next_node);
}
}
println!("Update distance to {} to {}", node, distance);
*node.distance.borrow_mut() = distance;
}
nodes.clear();
mem::swap(&mut nodes, &mut next_nodes);
let end_distance : i32 = *map[&end_word].distance.borrow();
if end_distance != -1 {
break;
}
}
println!("Final map {:#?}", &map);
println!("Distance from {} to {}: {}", &begin_word, &end_word, distance);
//let r0 : Vec<String> = ["hello".to_string(), "hollo".to_string(), "wollo".to_string(), "worlo".to_string(), "world".to_string()].to_vec();
//res.push(r0);
res
}
fn test() {
let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
// Can be seen as `a - b`.
for x in a.difference(&b) {
println!("{}", x); // Print 1
}
let diff: HashSet<_> = a.difference(&b).collect();
assert_eq!(diff, [1].iter().collect());
// Note that difference is not symmetric,
// and `b - a` means something else:
let diff: HashSet<_> = b.difference(&a).collect();
assert_eq!(diff, [4].iter().collect());
}
pub fn find_ladders_dbg(begin_word: String, end_word: String, word_list: Vec<String>) ->
Vec<Vec<String>> {
let mut res : Vec<Vec<String>> = Vec::new();
let base_len = begin_word.len();
if base_len != end_word.len() {
return res
}
let mut s: HashSet<&String> = word_list.iter().collect();
if !s.contains(&end_word) {
return res;
}
let mut idx2w: HashMap<i32, &String> = HashMap::new();
let mut w2idx: HashMap<&String, i32> = HashMap::new();
for (idx, w) in word_list.iter().enumerate() {
idx2w.insert(idx as i32, w);
w2idx.insert(&w, idx as i32);
}
if !s.contains(&begin_word) {
idx2w.insert(-1, &begin_word);
w2idx.insert(&begin_word, -1);
}
let mut directed_neighbors: HashMap<i32, Vec<i32>> = HashMap::new();
let mut towards_end = true;
let (mut tovisit, mut tovisit_otherdir) = (HashSet::new(), HashSet::new());
tovisit.insert(w2idx[&begin_word]);
tovisit_otherdir.insert(w2idx[&end_word]);
println!("new test (begin_word: {}, end_word: {}, word_list: {:?}",
&begin_word, &end_word, &word_list);
println!("w2idx: {:?}, idx2w: {:?}", &w2idx, &idx2w);
println!("tovisit: {:?}, tovisit_otherdir: {:?}", &tovisit, &tovisit_otherdir);
while !tovisit.is_empty() && !tovisit_otherdir.is_empty() {
if tovisit.len() > tovisit_otherdir.len() {
// Always visit in the direction with the least nodes to visit
println!("swap tovisit: {:?} and tovisit_otherdir: {:?}", &tovisit, &tovisit_otherdir);
mem::swap(&mut tovisit, &mut tovisit_otherdir);
println!("swapped tovisit: {:?} and tovisit_otherdir: {:?}", &tovisit, &tovisit_otherdir);
towards_end = !towards_end;
}
for widx in tovisit.iter() {
s.remove(idx2w[widx]);
}
println!("s - tovisit: {:?}", &s);
let mut next_tovisit : HashSet<i32> = HashSet::new();
for widx in tovisit.iter() {
let w = idx2w[widx];
for idx in 0..base_len {
//let c0 = b'a' + &neighborb[idx];
let mut neighborb = w.clone().into_bytes();
for i in 0..26 {
let c = b'a' + i;
//if c == c0 { continue; }
neighborb[idx] = c;
let neighbor = String::from_utf8(neighborb.clone()).unwrap();
//println!("checks {} is in s {:?}", neighbor, s);
if s.contains(&neighbor) {
let nidx = w2idx[&neighbor];
println!("adds {} to next_tovisit", nidx);
next_tovisit.insert(nidx);
if towards_end {
if ! directed_neighbors.contains_key(&nidx) {
directed_neighbors.insert(nidx, Vec::new());
}
directed_neighbors.get_mut(&nidx).unwrap().push(*widx);
}
else {
if ! directed_neighbors.contains_key(&widx) {
directed_neighbors.insert(*widx, Vec::new());
}
directed_neighbors.get_mut(&widx).unwrap().push(nidx);
}
println!("directed_neighbors arc added");
}
}
}
}
tovisit.clear();
mem::swap(&mut tovisit, &mut next_tovisit);
println!("tovisit is now {:?}", &tovisit);
if ! tovisit_otherdir.is_disjoint(&tovisit) {
println!("Exploration done: directed_neighbors {:?}", &directed_neighbors);
res.push([end_word].to_vec());
while res[0].last().unwrap() != &begin_word {
let mut r0 : Vec<Vec<String>> = Vec::new();
for path in res.iter() {
let pidx = w2idx[&path.last().unwrap()];
//println!("Look at neighbors of {}: {}", &path.last().unwrap(), pidx);
if directed_neighbors.contains_key(&pidx) {
for nidx in directed_neighbors[&pidx].iter() {
let neighbor = idx2w[&nidx];
let mut new_path = path.clone();
new_path.push(neighbor.clone());
r0.push(new_path);
}
}
}
mem::swap(&mut res, &mut r0);
}
for path in res.iter_mut() {
path.reverse();
}
break;
}
}
res
}
pub fn find_ladders_idx(begin_word: String, end_word: String, word_list: Vec<String>) ->
Vec<Vec<String>> {
let mut res : Vec<Vec<String>> = Vec::new();
let base_len = begin_word.len();
if base_len != end_word.len() {
return res
}
let mut s: HashSet<&String> = word_list.iter().collect();
if !s.contains(&end_word) {
return res;
}
let mut idx2w: HashMap<i32, &String> = HashMap::new();
let mut w2idx: HashMap<&String, i32> = HashMap::new();
for (idx, w) in word_list.iter().enumerate() {
idx2w.insert(idx as i32, w);
w2idx.insert(&w, idx as i32);
}
if !s.contains(&begin_word) {
idx2w.insert(-1, &begin_word);
w2idx.insert(&begin_word, -1);
}
let mut directed_neighbors: HashMap<i32, Vec<i32>> = HashMap::new();
let mut towards_end = true;
let (mut tovisit, mut tovisit_otherdir) = (HashSet::new(), HashSet::new());
tovisit.insert(w2idx[&begin_word]);
tovisit_otherdir.insert(w2idx[&end_word]);
while !tovisit.is_empty() && !tovisit_otherdir.is_empty() {
if tovisit.len() > tovisit_otherdir.len() {
// Always visit in the direction with the least nodes to visit
mem::swap(&mut tovisit, &mut tovisit_otherdir);
towards_end = !towards_end;
}
for widx in tovisit.iter() {
s.remove(idx2w[widx]);
}
let mut next_tovisit : HashSet<i32> = HashSet::new();
for widx in tovisit.iter() {
let w = idx2w[widx];
for idx in 0..base_len {
let mut neighborb = w.clone().into_bytes();
for i in 0..26 {
let c = b'a' + i;
neighborb[idx] = c;
let neighbor = String::from_utf8(neighborb.clone()).unwrap();
if s.contains(&neighbor) {
let nidx = w2idx[&neighbor];
next_tovisit.insert(nidx);
if towards_end {
if ! directed_neighbors.contains_key(&nidx) {
directed_neighbors.insert(nidx, Vec::new());
}
directed_neighbors.get_mut(&nidx).unwrap().push(*widx);
}
else {
if ! directed_neighbors.contains_key(&widx) {
directed_neighbors.insert(*widx, Vec::new());
}
directed_neighbors.get_mut(&widx).unwrap().push(nidx);
}
}
}
}
}
tovisit.clear();
mem::swap(&mut tovisit, &mut next_tovisit);
if ! tovisit_otherdir.is_disjoint(&tovisit) {
res.push([end_word].to_vec());
while res[0].last().unwrap() != &begin_word {
let mut r0 : Vec<Vec<String>> = Vec::new();
for path in res.iter() {
let pidx = w2idx[&path.last().unwrap()];
if directed_neighbors.contains_key(&pidx) {
for nidx in directed_neighbors[&pidx].iter() {
let neighbor = idx2w[&nidx];
let mut new_path = path.clone();
new_path.push(neighbor.clone());
r0.push(new_path);
}
}
}
mem::swap(&mut res, &mut r0);
}
for path in res.iter_mut() {
path.reverse();
}
break;
}
}
res
}*/
pub fn find_ladders(begin_word: String, end_word: String, word_list: Vec<String>) ->
Vec<Vec<String>> {
let mut res : Vec<Vec<String>> = Vec::new();
let base_len = begin_word.len();
if base_len != end_word.len() {
return res
}
let mut s: HashSet<&String> = word_list.iter().collect();
if !s.contains(&end_word) {
return res;
}
let mut directed_neighbors: HashMap<&String, Vec<&String>> = HashMap::new();
let mut towards_end = true;
let (mut tovisit, mut tovisit_otherdir) = (HashSet::new(), HashSet::new());
tovisit.insert(&begin_word);
tovisit_otherdir.insert(&end_word);
while !tovisit.is_empty() && !tovisit_otherdir.is_empty() {
if tovisit.len() > tovisit_otherdir.len() {
// Always visit in the direction with the least nodes to visit
mem::swap(&mut tovisit, &mut tovisit_otherdir);
towards_end = !towards_end;
}
for w in tovisit.iter() {
s.remove(w);
}
let mut next_tovisit : HashSet<&String> = HashSet::new();
for w in tovisit.iter() {
for idx in 0..base_len {
let mut neighborb = (*w).clone().into_bytes();
for i in 0..26 {
let c = b'a' + i;
neighborb[idx] = c;
let key = s.get(&String::from_utf8(neighborb.clone()).unwrap());
if let Some(neighbor) = key {
next_tovisit.insert(neighbor);
if towards_end {
directed_neighbors.entry(neighbor).or_insert(Vec::new()).push(w);
}
else {
directed_neighbors.entry(w).or_insert(Vec::new()).push(neighbor);
}
}
}
}
}
tovisit.clear();
mem::swap(&mut tovisit, &mut next_tovisit);
if ! tovisit_otherdir.is_disjoint(&tovisit) {
res.push([end_word.clone()].to_vec());
while res[0].last().unwrap() != &begin_word {
let mut r0 : Vec<Vec<String>> = Vec::new();
res.retain(|path| { directed_neighbors.contains_key(path.last().unwrap()) });
for path in res.iter() {
let w = path.last().unwrap();
for neighbor in directed_neighbors[w].iter() {
let mut new_path = path.clone();
new_path.push((*neighbor).clone());
r0.push(new_path);
}
}
mem::swap(&mut res, &mut r0);
}
for path in res.iter_mut() {
path.reverse();
}
break;
}
}
res
}
}
fn compare_vectors(v0: &Vec<Vec<String>>, v1: &Vec<Vec<String>>) -> bool {
if v0.len() != v1.len() { return false; }
let mut found = vec!(0; v0.len());
for v in v0.iter() {
for (i, w) in v1.iter().enumerate() {
if found[i] > 0 { continue; }
if w == v {
found[i] = 1;
break;
}
}
}
found.iter().sum::<u32>() == v0.len() as u32
}
fn run_test_case(test_case: &json::JsonValue) -> i32 {
let begin_word = &test_case["in"]["begin_word"];
let end_word = &test_case["in"]["end_word"];
let dictionnary = &test_case["in"]["dictionnary"];
let expected = &test_case["expected"];
let mut word_list = Vec::new();
for word in dictionnary.members() {
word_list.push(word.as_str().unwrap().to_string());
}
let mut exp = Vec::new();
for solution in expected.members() {
let mut s = Vec::new();
for word in solution.members() {
s.push(word.as_str().unwrap().to_string());
}
exp.push(s);
}
let result = Solution::find_ladders(begin_word.to_string(), end_word.to_string(), word_list);
if compare_vectors(&result, &exp) {
return 0;
}
println!("result.len {}, expected.len {}\n", result.len(), expected.len());
println!("find_ladders({}, {}, {}) returned {:?} but expected {:?}\n",
begin_word, end_word, dictionnary, result, expected);
1
}
fn main() {
let (tests, test_idx) = algo_tools::load_json_tests();
let (mut successes, mut failures) = (0, 0);
if test_idx >= tests.len() as i32 {
println!("Wrong index {}, only {} tests available!!", test_idx, tests.len());
return
}
if test_idx != -1 {
let rc = run_test_case(&tests[test_idx as usize]);
if rc == 0 { successes += 1; }
else { failures += 1; }
} else {
println!("{} tests specified", tests.len());
for i in 0..tests.len() {
let rc = run_test_case(&tests[i]);
if rc == 0 { successes += 1; }
else { failures += 1; }
}
}
if failures > 0 {
println!("{} tests succeeded and {} tests failed!!", successes, failures);
} else {
println!("All {} tests succeeded!!", successes);
}
}
|
use super::schema::{
ConnectionRequest, ConnectionRequest_Type, ConnectionResponse, ConnectionResponse_Status,
StreamUpdate,
};
use super::{
convert_procedure_result, recv_msg, send_msg, Connection, ConnectionError, KrpcResult,
ResponseError, StreamError,
};
use crate::codec::{Decode, Encode};
use std::io;
use std::thread;
use failure::Error;
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::net::TcpStream;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
/// An event is a KRPC object that allows clients to wait for an Event to occur. This is
/// essentially just a wrapper around a Stream with a `bool` return type that indicates whether
/// the event has triggered/occurred.
pub struct Event<'a> {
stream: Stream<'a, bool>,
}
impl<'a> Event<'a> {
pub(super) fn new(stream: Stream<'a, bool>) -> Self {
Event { stream }
}
/// Returns the backing stream for this event
pub fn stream(&self) -> &Stream<bool> {
&self.stream
}
/// Wait until the event is in the expected state.
///
/// # Arguments
/// * `triggered` - If `true`, waits until the event is triggered; otherwise, wait until
/// it's not triggered.
pub fn wait(&self, triggered: bool) -> KrpcResult<()> {
if !self.stream.is_started() {
self.stream.start()?;
}
while self.stream.value()? != triggered {
self.stream.wait()?;
}
Ok(())
}
/// Wait for the specified amount of time until the event has occurred.
///
/// # Arguments
/// * `triggered` - If `true`, waits until the event is triggered; otherwise, wait until
/// it's not triggered.
/// * `dur` - The maximum amount of time to wait.
///
/// # Returns
/// Returns `true` if the event matches the desired triggered state; `false` if it timed-out.
pub fn wait_timeout(&self, triggered: bool, dur: Duration) -> KrpcResult<bool> {
if !self.stream.is_started() {
self.stream.start()?;
}
let start = Instant::now();
loop {
if self.stream.value()? == triggered {
return Ok(true);
}
let timeout = match dur.checked_sub(start.elapsed()) {
Some(timeout) => timeout,
None => return Ok(false),
};
self.stream.wait_timeout(timeout)?;
}
}
/// Returns whether or not the event has occurred.
pub fn is_triggered(&self) -> KrpcResult<bool> {
self.stream.value()
}
/// Starts the backing stream for this event.
pub fn start(&self) -> KrpcResult<()> {
self.stream.start()
}
/// Returns whether the backing stream has been started.
pub fn is_started(&self) -> bool {
self.stream.is_started()
}
/// Removes the backing stream so it no longer receives updates from the KRPC server.
pub fn remove(&mut self) -> KrpcResult<()> {
self.stream.remove()
}
}
/// An object representing a KRPC streams. Streams allow the KRPC server to push updates to the
/// stream value instead of the client having to continuously poll for them.
pub struct Stream<'a, T: Decode<'a>> {
connection: &'a Connection,
value: Arc<StreamRaw>,
removed: bool,
phantom: PhantomData<T>,
}
impl<'a, T: Decode<'a>> Stream<'a, T> {
pub(super) fn new(connection: &'a Connection, value: Arc<StreamRaw>) -> Self {
Stream {
connection,
value,
removed: false,
phantom: PhantomData,
}
}
/// Returns the id of this stream.
pub fn id(&self) -> u64 {
self.value.id()
}
/// Returns the current value for the stream. If the stream is not started, this will
/// start it and wait for the stream to be updated.
pub fn value(&self) -> KrpcResult<T> {
if !self.value.is_started() {
self.start()?;
self.wait()?;
}
self.value
.value_map(|bytes, _version| Ok(T::decode(bytes, self.connection)?))
}
/// Returns whether or not the stream has started.
pub fn is_started(&self) -> bool {
self.value.is_started()
}
/// Starts this stream value if it hs not already been started. This will cause the stream
/// to start receiving updates from the KRPC server.
pub fn start(&self) -> KrpcResult<()> {
if self.is_started() {
return Ok(());
}
let args = &vec![self.value.id().encode()?];
self.connection.invoke("KRPC", "StartStream", &args)?;
self.value.set_started();
Ok(())
}
/// Returns the current update frequency in hertz.
pub fn rate(&self) -> f32 {
self.value.rate()
}
/// Sets the update frequency for this stream in hertz.
///
/// # Arguments
/// * `rate` - The new update in hertz.
pub fn set_rate(&self, rate: f32) -> KrpcResult<()> {
if !self.is_started() {
return Err(Error::from(StreamError::NotStarted));
}
if self.removed {
return Err(Error::from(StreamError::Removed));
}
let args = vec![self.value.id().encode()?, rate.encode()?];
self.connection.invoke("KRPC", "SetStreamRate", &args)?;
self.value.set_rate(rate);
Ok(())
}
/// Removes the stream so it no longer receives updates from the KRPC server. The last
/// received value for this stream can still be obtained by calling `value()`.
pub fn remove(&mut self) -> KrpcResult<()> {
if !self.removed {
// There could be multiple copies of this stream out there, so only do the remove
// once there are two or fewer copies of the raw stream value left.
// One copy is the stream manager, and the other copy is ourself.
if Arc::strong_count(&self.value) <= 2 {
let args = vec![self.id().encode()?];
self.connection.invoke("KRPC", "RemoveStream", &args)?;
self.connection.deregister_stream(self.id());
}
self.removed = true;
}
Ok(())
}
/// Returns whether or not the stream has been removed. The last received value for this
/// can still be obtained by calling `value()`.
pub fn is_removed(&self) -> bool {
self.removed
}
/// Waits for the stream value to be updated.
pub fn wait(&self) -> KrpcResult<()> {
if self.removed {
return Err(Error::from(StreamError::Removed));
}
self.value.wait()
}
/// Waits for the stream value to be updated for the given amount of time. Returns whether or
/// not the timeout was reached before the stream was updated.
///
/// # Arguments
/// * `timeout` - The maximum amount on time to wait for the stream value to be updated.
pub fn wait_timeout(&self, timeout: Duration) -> KrpcResult<bool> {
if self.removed {
return Err(Error::from(StreamError::Removed));
}
self.value.wait_timeout(timeout)
}
}
impl<'a, T: Decode<'a>> Drop for Stream<'a, T> {
fn drop(&mut self) {
use std::io::{stderr, Write};
use std::thread::panicking;
if !self.removed {
if let Err(e) = self.remove() {
if panicking() {
write!(stderr(), "Error removing stream value: {:?}", e)
.expect("Error writing to `stderr`");
} else {
panic!("Error removing stream value: {:?}", e);
}
}
}
}
}
pub(super) struct StreamRaw {
id: u64,
state: Mutex<StreamState>,
update_cvar: Condvar,
}
impl StreamRaw {
pub(super) fn new(id: u64) -> StreamRaw {
StreamRaw {
id,
state: Mutex::new(StreamState::new()),
update_cvar: Condvar::new(),
}
}
fn wait(&self) -> KrpcResult<()> {
let mut state = self.state.lock().unwrap();
if !state.started {
return Err(Error::from(StreamError::NotStarted));
}
let initial_version = state.version;
// keep waiting until the state version has been incremented
while state.version <= initial_version {
state = self.update_cvar.wait(state).unwrap();
}
Ok(())
}
fn wait_timeout(&self, dur: Duration) -> KrpcResult<bool> {
let mut state = self.state.lock().unwrap();
if !state.started {
return Err(Error::from(StreamError::NotStarted));
}
let initial_version = state.version;
let start = Instant::now();
loop {
if state.version > initial_version {
return Ok(false);
}
let timeout = match dur.checked_sub(start.elapsed()) {
Some(timeout) => timeout,
None => return Ok(true),
};
state = self.update_cvar.wait_timeout(state, timeout).unwrap().0;
}
}
pub(super) fn id(&self) -> u64 {
self.id
}
fn value_map<F, R>(&self, map: F) -> KrpcResult<R>
where
F: FnOnce(&Vec<u8>, u64) -> KrpcResult<R>,
{
let state = self.state.lock().unwrap();
if !state.started {
return Err(Error::from(StreamError::NotStarted));
}
let bytes = state.value.as_ref().map_err(Clone::clone)?;
map(bytes, state.version)
}
fn is_started(&self) -> bool {
let state = self.state.lock().unwrap();
state.started
}
fn rate(&self) -> f32 {
let state = self.state.lock().unwrap();
state.rate
}
fn set_value(&self, bytes: Vec<u8>) {
let mut state = self.state.lock().unwrap();
state.version += 1;
state.value = Ok(bytes);
self.update_cvar.notify_all();
}
fn set_error(&self, err: ResponseError) {
let mut state = self.state.lock().unwrap();
state.version += 1;
state.value = Err(err);
self.update_cvar.notify_all();
}
fn set_rate(&self, rate: f32) {
let mut state = self.state.lock().unwrap();
state.rate = rate;
}
fn set_started(&self) {
let mut state = self.state.lock().unwrap();
state.started = true;
}
}
struct StreamState {
started: bool,
version: u64,
rate: f32,
value: Result<Vec<u8>, ResponseError>,
}
impl StreamState {
fn new() -> Self {
StreamState {
started: false,
version: 0,
rate: 0.0,
value: Err(ResponseError::MissingResult),
}
}
}
pub struct StreamManager {
active_streams: Arc<Mutex<BTreeMap<u64, Arc<StreamRaw>>>>,
stop_flag: Arc<AtomicBool>,
}
impl StreamManager {
pub(super) fn connect(client_id: &[u8], host: &str, port: u16) -> KrpcResult<StreamManager> {
let mut stream_socket = TcpStream::connect((host, port))?;
let mut request = ConnectionRequest::new();
request.set_field_type(ConnectionRequest_Type::STREAM);
request.set_client_identifier(Vec::from(client_id));
send_msg(&mut stream_socket, &request)?;
let response: ConnectionResponse = recv_msg(&mut stream_socket)?;
match response.status {
ConnectionResponse_Status::OK => {
let active_streams = Arc::new(Mutex::new(BTreeMap::new()));
let stop_flag = Arc::new(AtomicBool::new(false));
Self::start_updater(stream_socket, active_streams.clone(), stop_flag.clone());
Ok(StreamManager {
active_streams,
stop_flag,
})
}
ConnectionResponse_Status::TIMEOUT => Err(ConnectionError::Timeout(response.message))?,
ConnectionResponse_Status::MALFORMED_MESSAGE => {
Err(ConnectionError::MalformedMessage(response.message))?
}
ConnectionResponse_Status::WRONG_TYPE => {
Err(ConnectionError::WrongType(response.message))?
}
}
}
fn start_updater(
socket: TcpStream,
active_streams: Arc<Mutex<BTreeMap<u64, Arc<StreamRaw>>>>,
stop_flag: Arc<AtomicBool>,
) {
let mut stream_socket = socket;
thread::spawn(move || {
stream_socket
.set_read_timeout(Some(Duration::from_secs(1)))
.expect("Unable to set read timeout");
while !(*stop_flag).load(Ordering::Relaxed) {
let msg: KrpcResult<StreamUpdate> = recv_msg(&mut stream_socket);
match msg {
Ok(stream_update) => {
Self::process_stream_update(stream_update, &active_streams)
}
Err(ref e) if Self::is_timeout_error(e) => (),
Err(ref e) => panic!("Failed to retrieve stream update: {:?}", e),
}
}
});
}
fn process_stream_update(
stream_update: StreamUpdate,
active_streams: &Mutex<BTreeMap<u64, Arc<StreamRaw>>>,
) {
let streams = active_streams.lock().unwrap();
for stream_result in stream_update.results.iter() {
if let Some(stream_value) = streams.get(&stream_result.id) {
if stream_result.has_result() {
match convert_procedure_result(stream_result.get_result()) {
Ok(bytes) => stream_value.set_value(bytes),
Err(response_err) => stream_value.set_error(response_err),
}
}
}
}
}
fn is_timeout_error(err: &Error) -> bool {
if let Some(ref ioe) = err.downcast_ref::<io::Error>() {
ioe.kind() == io::ErrorKind::TimedOut || ioe.kind() == io::ErrorKind::WouldBlock
} else {
false
}
}
pub(super) fn register(&self, id: u64) -> Arc<StreamRaw> {
let mut active_streams = self.active_streams.lock().unwrap();
// Calling add_stream multiple times for the same method will return the same stream id.
if let Some(stream) = active_streams.get(&id) {
stream.clone()
} else {
let stream = Arc::new(StreamRaw::new(id));
(*active_streams).insert(id, stream.clone());
stream
}
}
pub(super) fn deregister(&self, stream_id: u64) {
let mut active_streams = self.active_streams.lock().unwrap();
(*active_streams).remove(&stream_id);
}
}
impl Drop for StreamManager {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Relaxed);
}
}
|
fn main(){
proconio::input!{mut n:u64};
let mut s=String::new();
while n>0{
n-=1;
s.insert(0,((n%26)as u8+b'a') as char);
n/=26
}
println!("{}",s)
} |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qfontdatabase.h
// dst-file: /src/gui/qfontdatabase.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::super::core::qstring::*; // 771
// use super::qlist::*; // 775
use super::qfont::*; // 773
use super::super::core::qstringlist::*; // 771
use super::super::core::qbytearray::*; // 771
use super::qfontinfo::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QFontDatabase_Class_Size() -> c_int;
// proto: QList<int> QFontDatabase::pointSizes(const QString & family, const QString & style);
fn C_ZN13QFontDatabase10pointSizesERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QString QFontDatabase::styleString(const QFont & font);
fn C_ZN13QFontDatabase11styleStringERK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QList<int> QFontDatabase::smoothSizes(const QString & family, const QString & style);
fn C_ZN13QFontDatabase11smoothSizesERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QStringList QFontDatabase::styles(const QString & family);
fn C_ZNK13QFontDatabase6stylesERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: bool QFontDatabase::italic(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase6italicERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: void QFontDatabase::QFontDatabase();
fn C_ZN13QFontDatabaseC2Ev() -> u64;
// proto: static QStringList QFontDatabase::applicationFontFamilies(int id);
fn C_ZN13QFontDatabase23applicationFontFamiliesEi(arg0: c_int) -> *mut c_void;
// proto: bool QFontDatabase::hasFamily(const QString & family);
fn C_ZNK13QFontDatabase9hasFamilyERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: bool QFontDatabase::isFixedPitch(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase12isFixedPitchERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: QFont QFontDatabase::font(const QString & family, const QString & style, int pointSize);
fn C_ZNK13QFontDatabase4fontERK7QStringS2_i(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: c_int) -> *mut c_void;
// proto: int QFontDatabase::weight(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase6weightERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_int;
// proto: static bool QFontDatabase::removeAllApplicationFonts();
fn C_ZN13QFontDatabase25removeAllApplicationFontsEv() -> c_char;
// proto: static int QFontDatabase::addApplicationFontFromData(const QByteArray & fontData);
fn C_ZN13QFontDatabase26addApplicationFontFromDataERK10QByteArray(arg0: *mut c_void) -> c_int;
// proto: static bool QFontDatabase::supportsThreadedFontRendering();
fn C_ZN13QFontDatabase29supportsThreadedFontRenderingEv() -> c_char;
// proto: bool QFontDatabase::isPrivateFamily(const QString & family);
fn C_ZNK13QFontDatabase15isPrivateFamilyERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_char;
// proto: bool QFontDatabase::isScalable(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase10isScalableERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: static bool QFontDatabase::removeApplicationFont(int id);
fn C_ZN13QFontDatabase21removeApplicationFontEi(arg0: c_int) -> c_char;
// proto: QString QFontDatabase::styleString(const QFontInfo & fontInfo);
fn C_ZN13QFontDatabase11styleStringERK9QFontInfo(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: bool QFontDatabase::isBitmapScalable(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase16isBitmapScalableERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: bool QFontDatabase::isSmoothlyScalable(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase18isSmoothlyScalableERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: bool QFontDatabase::bold(const QString & family, const QString & style);
fn C_ZNK13QFontDatabase4boldERK7QStringS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: static int QFontDatabase::addApplicationFont(const QString & fileName);
fn C_ZN13QFontDatabase18addApplicationFontERK7QString(arg0: *mut c_void) -> c_int;
// proto: static QList<int> QFontDatabase::standardSizes();
fn C_ZN13QFontDatabase13standardSizesEv() -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QFontDatabase)=8
#[derive(Default)]
pub struct QFontDatabase {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QFontDatabase {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QFontDatabase {
return QFontDatabase{qclsinst: qthis, ..Default::default()};
}
}
// proto: QList<int> QFontDatabase::pointSizes(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn pointSizes<RetType, T: QFontDatabase_pointSizes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.pointSizes(self);
// return 1;
}
}
pub trait QFontDatabase_pointSizes<RetType> {
fn pointSizes(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: QList<int> QFontDatabase::pointSizes(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_pointSizes<u64> for (&'a QString, Option<&'a QString>) {
fn pointSizes(self , rsthis: & QFontDatabase) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase10pointSizesERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase10pointSizesERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as u64; // 5
// return 1;
}
}
// proto: QString QFontDatabase::styleString(const QFont & font);
impl /*struct*/ QFontDatabase {
pub fn styleString<RetType, T: QFontDatabase_styleString<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.styleString(self);
// return 1;
}
}
pub trait QFontDatabase_styleString<RetType> {
fn styleString(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: QString QFontDatabase::styleString(const QFont & font);
impl<'a> /*trait*/ QFontDatabase_styleString<QString> for (&'a QFont) {
fn styleString(self , rsthis: & QFontDatabase) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase11styleStringERK5QFont()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase11styleStringERK5QFont(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QList<int> QFontDatabase::smoothSizes(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn smoothSizes<RetType, T: QFontDatabase_smoothSizes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.smoothSizes(self);
// return 1;
}
}
pub trait QFontDatabase_smoothSizes<RetType> {
fn smoothSizes(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: QList<int> QFontDatabase::smoothSizes(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_smoothSizes<u64> for (&'a QString, &'a QString) {
fn smoothSizes(self , rsthis: & QFontDatabase) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase11smoothSizesERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase11smoothSizesERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as u64; // 5
// return 1;
}
}
// proto: QStringList QFontDatabase::styles(const QString & family);
impl /*struct*/ QFontDatabase {
pub fn styles<RetType, T: QFontDatabase_styles<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.styles(self);
// return 1;
}
}
pub trait QFontDatabase_styles<RetType> {
fn styles(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: QStringList QFontDatabase::styles(const QString & family);
impl<'a> /*trait*/ QFontDatabase_styles<QStringList> for (&'a QString) {
fn styles(self , rsthis: & QFontDatabase) -> QStringList {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase6stylesERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase6stylesERK7QString(rsthis.qclsinst, arg0)};
let mut ret1 = QStringList::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QFontDatabase::italic(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn italic<RetType, T: QFontDatabase_italic<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.italic(self);
// return 1;
}
}
pub trait QFontDatabase_italic<RetType> {
fn italic(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::italic(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_italic<i8> for (&'a QString, &'a QString) {
fn italic(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase6italicERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase6italicERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QFontDatabase::QFontDatabase();
impl /*struct*/ QFontDatabase {
pub fn new<T: QFontDatabase_new>(value: T) -> QFontDatabase {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QFontDatabase_new {
fn new(self) -> QFontDatabase;
}
// proto: void QFontDatabase::QFontDatabase();
impl<'a> /*trait*/ QFontDatabase_new for () {
fn new(self) -> QFontDatabase {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabaseC2Ev()};
let ctysz: c_int = unsafe{QFontDatabase_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN13QFontDatabaseC2Ev()};
let rsthis = QFontDatabase{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QStringList QFontDatabase::applicationFontFamilies(int id);
impl /*struct*/ QFontDatabase {
pub fn applicationFontFamilies_s<RetType, T: QFontDatabase_applicationFontFamilies_s<RetType>>( overload_args: T) -> RetType {
return overload_args.applicationFontFamilies_s();
// return 1;
}
}
pub trait QFontDatabase_applicationFontFamilies_s<RetType> {
fn applicationFontFamilies_s(self ) -> RetType;
}
// proto: static QStringList QFontDatabase::applicationFontFamilies(int id);
impl<'a> /*trait*/ QFontDatabase_applicationFontFamilies_s<QStringList> for (i32) {
fn applicationFontFamilies_s(self ) -> QStringList {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase23applicationFontFamiliesEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN13QFontDatabase23applicationFontFamiliesEi(arg0)};
let mut ret1 = QStringList::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QFontDatabase::hasFamily(const QString & family);
impl /*struct*/ QFontDatabase {
pub fn hasFamily<RetType, T: QFontDatabase_hasFamily<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasFamily(self);
// return 1;
}
}
pub trait QFontDatabase_hasFamily<RetType> {
fn hasFamily(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::hasFamily(const QString & family);
impl<'a> /*trait*/ QFontDatabase_hasFamily<i8> for (&'a QString) {
fn hasFamily(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase9hasFamilyERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase9hasFamilyERK7QString(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QFontDatabase::isFixedPitch(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn isFixedPitch<RetType, T: QFontDatabase_isFixedPitch<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isFixedPitch(self);
// return 1;
}
}
pub trait QFontDatabase_isFixedPitch<RetType> {
fn isFixedPitch(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::isFixedPitch(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_isFixedPitch<i8> for (&'a QString, Option<&'a QString>) {
fn isFixedPitch(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase12isFixedPitchERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase12isFixedPitchERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: QFont QFontDatabase::font(const QString & family, const QString & style, int pointSize);
impl /*struct*/ QFontDatabase {
pub fn font<RetType, T: QFontDatabase_font<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.font(self);
// return 1;
}
}
pub trait QFontDatabase_font<RetType> {
fn font(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: QFont QFontDatabase::font(const QString & family, const QString & style, int pointSize);
impl<'a> /*trait*/ QFontDatabase_font<QFont> for (&'a QString, &'a QString, i32) {
fn font(self , rsthis: & QFontDatabase) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase4fontERK7QStringS2_i()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2 as c_int;
let mut ret = unsafe {C_ZNK13QFontDatabase4fontERK7QStringS2_i(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QFontDatabase::weight(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn weight<RetType, T: QFontDatabase_weight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.weight(self);
// return 1;
}
}
pub trait QFontDatabase_weight<RetType> {
fn weight(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: int QFontDatabase::weight(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_weight<i32> for (&'a QString, &'a QString) {
fn weight(self , rsthis: & QFontDatabase) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase6weightERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase6weightERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i32; // 1
// return 1;
}
}
// proto: static bool QFontDatabase::removeAllApplicationFonts();
impl /*struct*/ QFontDatabase {
pub fn removeAllApplicationFonts_s<RetType, T: QFontDatabase_removeAllApplicationFonts_s<RetType>>( overload_args: T) -> RetType {
return overload_args.removeAllApplicationFonts_s();
// return 1;
}
}
pub trait QFontDatabase_removeAllApplicationFonts_s<RetType> {
fn removeAllApplicationFonts_s(self ) -> RetType;
}
// proto: static bool QFontDatabase::removeAllApplicationFonts();
impl<'a> /*trait*/ QFontDatabase_removeAllApplicationFonts_s<i8> for () {
fn removeAllApplicationFonts_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase25removeAllApplicationFontsEv()};
let mut ret = unsafe {C_ZN13QFontDatabase25removeAllApplicationFontsEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static int QFontDatabase::addApplicationFontFromData(const QByteArray & fontData);
impl /*struct*/ QFontDatabase {
pub fn addApplicationFontFromData_s<RetType, T: QFontDatabase_addApplicationFontFromData_s<RetType>>( overload_args: T) -> RetType {
return overload_args.addApplicationFontFromData_s();
// return 1;
}
}
pub trait QFontDatabase_addApplicationFontFromData_s<RetType> {
fn addApplicationFontFromData_s(self ) -> RetType;
}
// proto: static int QFontDatabase::addApplicationFontFromData(const QByteArray & fontData);
impl<'a> /*trait*/ QFontDatabase_addApplicationFontFromData_s<i32> for (&'a QByteArray) {
fn addApplicationFontFromData_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase26addApplicationFontFromDataERK10QByteArray()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase26addApplicationFontFromDataERK10QByteArray(arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: static bool QFontDatabase::supportsThreadedFontRendering();
impl /*struct*/ QFontDatabase {
pub fn supportsThreadedFontRendering_s<RetType, T: QFontDatabase_supportsThreadedFontRendering_s<RetType>>( overload_args: T) -> RetType {
return overload_args.supportsThreadedFontRendering_s();
// return 1;
}
}
pub trait QFontDatabase_supportsThreadedFontRendering_s<RetType> {
fn supportsThreadedFontRendering_s(self ) -> RetType;
}
// proto: static bool QFontDatabase::supportsThreadedFontRendering();
impl<'a> /*trait*/ QFontDatabase_supportsThreadedFontRendering_s<i8> for () {
fn supportsThreadedFontRendering_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase29supportsThreadedFontRenderingEv()};
let mut ret = unsafe {C_ZN13QFontDatabase29supportsThreadedFontRenderingEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QFontDatabase::isPrivateFamily(const QString & family);
impl /*struct*/ QFontDatabase {
pub fn isPrivateFamily<RetType, T: QFontDatabase_isPrivateFamily<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isPrivateFamily(self);
// return 1;
}
}
pub trait QFontDatabase_isPrivateFamily<RetType> {
fn isPrivateFamily(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::isPrivateFamily(const QString & family);
impl<'a> /*trait*/ QFontDatabase_isPrivateFamily<i8> for (&'a QString) {
fn isPrivateFamily(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase15isPrivateFamilyERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase15isPrivateFamilyERK7QString(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QFontDatabase::isScalable(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn isScalable<RetType, T: QFontDatabase_isScalable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isScalable(self);
// return 1;
}
}
pub trait QFontDatabase_isScalable<RetType> {
fn isScalable(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::isScalable(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_isScalable<i8> for (&'a QString, Option<&'a QString>) {
fn isScalable(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase10isScalableERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase10isScalableERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: static bool QFontDatabase::removeApplicationFont(int id);
impl /*struct*/ QFontDatabase {
pub fn removeApplicationFont_s<RetType, T: QFontDatabase_removeApplicationFont_s<RetType>>( overload_args: T) -> RetType {
return overload_args.removeApplicationFont_s();
// return 1;
}
}
pub trait QFontDatabase_removeApplicationFont_s<RetType> {
fn removeApplicationFont_s(self ) -> RetType;
}
// proto: static bool QFontDatabase::removeApplicationFont(int id);
impl<'a> /*trait*/ QFontDatabase_removeApplicationFont_s<i8> for (i32) {
fn removeApplicationFont_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase21removeApplicationFontEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN13QFontDatabase21removeApplicationFontEi(arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: QString QFontDatabase::styleString(const QFontInfo & fontInfo);
impl<'a> /*trait*/ QFontDatabase_styleString<QString> for (&'a QFontInfo) {
fn styleString(self , rsthis: & QFontDatabase) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase11styleStringERK9QFontInfo()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase11styleStringERK9QFontInfo(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QFontDatabase::isBitmapScalable(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn isBitmapScalable<RetType, T: QFontDatabase_isBitmapScalable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isBitmapScalable(self);
// return 1;
}
}
pub trait QFontDatabase_isBitmapScalable<RetType> {
fn isBitmapScalable(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::isBitmapScalable(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_isBitmapScalable<i8> for (&'a QString, Option<&'a QString>) {
fn isBitmapScalable(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase16isBitmapScalableERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase16isBitmapScalableERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QFontDatabase::isSmoothlyScalable(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn isSmoothlyScalable<RetType, T: QFontDatabase_isSmoothlyScalable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSmoothlyScalable(self);
// return 1;
}
}
pub trait QFontDatabase_isSmoothlyScalable<RetType> {
fn isSmoothlyScalable(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::isSmoothlyScalable(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_isSmoothlyScalable<i8> for (&'a QString, Option<&'a QString>) {
fn isSmoothlyScalable(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase18isSmoothlyScalableERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QString::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase18isSmoothlyScalableERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QFontDatabase::bold(const QString & family, const QString & style);
impl /*struct*/ QFontDatabase {
pub fn bold<RetType, T: QFontDatabase_bold<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bold(self);
// return 1;
}
}
pub trait QFontDatabase_bold<RetType> {
fn bold(self , rsthis: & QFontDatabase) -> RetType;
}
// proto: bool QFontDatabase::bold(const QString & family, const QString & style);
impl<'a> /*trait*/ QFontDatabase_bold<i8> for (&'a QString, &'a QString) {
fn bold(self , rsthis: & QFontDatabase) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK13QFontDatabase4boldERK7QStringS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK13QFontDatabase4boldERK7QStringS2_(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: static int QFontDatabase::addApplicationFont(const QString & fileName);
impl /*struct*/ QFontDatabase {
pub fn addApplicationFont_s<RetType, T: QFontDatabase_addApplicationFont_s<RetType>>( overload_args: T) -> RetType {
return overload_args.addApplicationFont_s();
// return 1;
}
}
pub trait QFontDatabase_addApplicationFont_s<RetType> {
fn addApplicationFont_s(self ) -> RetType;
}
// proto: static int QFontDatabase::addApplicationFont(const QString & fileName);
impl<'a> /*trait*/ QFontDatabase_addApplicationFont_s<i32> for (&'a QString) {
fn addApplicationFont_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase18addApplicationFontERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN13QFontDatabase18addApplicationFontERK7QString(arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: static QList<int> QFontDatabase::standardSizes();
impl /*struct*/ QFontDatabase {
pub fn standardSizes_s<RetType, T: QFontDatabase_standardSizes_s<RetType>>( overload_args: T) -> RetType {
return overload_args.standardSizes_s();
// return 1;
}
}
pub trait QFontDatabase_standardSizes_s<RetType> {
fn standardSizes_s(self ) -> RetType;
}
// proto: static QList<int> QFontDatabase::standardSizes();
impl<'a> /*trait*/ QFontDatabase_standardSizes_s<u64> for () {
fn standardSizes_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN13QFontDatabase13standardSizesEv()};
let mut ret = unsafe {C_ZN13QFontDatabase13standardSizesEv()};
return ret as u64; // 5
// return 1;
}
}
// <= body block end
|
extern crate clap;
extern crate reqwest;
extern crate serde;
use std::error::Error;
use std::process::exit;
use clap::{App, Arg, SubCommand};
use vocajeux::*;
#[derive(serde::Deserialize)]
struct Index {
names: Vec<String>
}
fn index(url: &str) -> Result<Index, reqwest::Error> {
let json: Index = reqwest::get(url)?.json()?;
Ok(json)
}
fn pick(url: &str, dataset: &str, accesskey: Option<&str>, seen: bool) -> Result<VocaItem, reqwest::Error> {
let seen = match seen {
true => "yes",
false => "no",
};
let url = if let Some(accesskey) = accesskey {
format!("{}/pick/{}/{}/?seen={}", url, dataset, accesskey, seen)
} else {
format!("{}/pick/{}/?seen={}", url, dataset, seen)
};
let json: VocaItem = reqwest::get(url.as_str())?.json()?;
Ok(json)
}
fn find(url: &str, dataset: &str, word: &str, accesskey: Option<&str>, seen: bool) -> Result<VocaItem, reqwest::Error> {
let seen = match seen {
true => "yes",
false => "no",
};
let url = if let Some(accesskey) = accesskey {
format!("{}/find/{}/{}/{}/?seen={}", url, dataset, word, accesskey, seen)
} else {
format!("{}/find/{}/{}/?seen={}", url, dataset, word, seen)
};
let json: VocaItem = reqwest::get(url.as_str())?.json()?;
Ok(json)
}
fn show(url: &str, dataset: &str) -> Result<VocaList, reqwest::Error> {
let url = format!("{}/show/{}/", url, dataset);
let json: VocaList = reqwest::get(url.as_str())?.json()?;
Ok(json)
}
fn main() {
let mut success = true; //determines the exit code
let arg_dataset = Arg::with_name("dataset")
.help("Name of the vocabulary set to load")
.long("dataset")
.short("s");
let arg_tags = Arg::with_name("tags")
.help("Filter on tags, comma separated list")
.long("tags")
.short("T");
let arg_phon = Arg::with_name("phon")
.help("Show phonetic transcription")
.long("phon")
.short("p");
let arg_translations = Arg::with_name("translations")
.help("Show translations")
.long("translations")
.short("t");
let arg_examples = Arg::with_name("examples")
.help("Show examples")
.long("examples")
.short("x");
let arg_comments = Arg::with_name("comments")
.help("Show comments")
.long("comments")
.short("C");
let argmatches = App::new("Vocajeux Client")
.version("0.1")
.author("Maarten van Gompel (proycon) <proycon@anaproy.nl>")
.about("Games for learning vocabulary - client")
.arg(Arg::with_name("url")
.help("URL")
.long("url")
.takes_value(true)
.short("u")
.required(true)
)
.arg(Arg::with_name("accesskey")
.help("Access key")
.long("accesskey")
.takes_value(true)
.short("K")
.required(true)
)
.arg(Arg::with_name("debug")
.help("Debug")
.long("debug")
.short("D")
)
.subcommand(SubCommand::with_name("ls")
.about("Lists all available datasets")
)
.subcommand(SubCommand::with_name("show")
.about("Show the entire vocabulary list")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(arg_translations.clone())
.arg(arg_examples.clone())
.arg(arg_comments.clone())
.arg(Arg::with_name("showtags")
.help("Show tags")
.long("showtags")
)
.arg(arg_phon.clone()))
.subcommand(SubCommand::with_name("flashcards")
.about("Flashcards")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(arg_phon.clone()))
.subcommand(SubCommand::with_name("pick")
.about("Pick and display a random word")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(arg_phon.clone())
.arg(arg_translations.clone())
.arg(arg_examples.clone())
.arg(arg_comments.clone()))
.subcommand(SubCommand::with_name("find")
.about("Find and display a specific word")
.arg(Arg::with_name("word")
.help("The word")
.index(2)
.required(true))
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(arg_phon.clone())
.arg(arg_translations.clone())
.arg(arg_examples.clone())
.arg(arg_comments.clone()))
.subcommand(SubCommand::with_name("quiz")
.about("Simple open quiz")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(arg_phon.clone()))
.subcommand(SubCommand::with_name("choicequiz")
.about("Simple multiple-choice quiz")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(Arg::with_name("multiplechoice")
.help("Multiple choice (number of choices)")
.long("multiplechoice")
.short("m")
.takes_value(true)
.default_value("6")
)
.arg(arg_phon.clone()))
.subcommand(SubCommand::with_name("matchquiz")
.arg(arg_dataset.clone())
.arg(arg_tags.clone())
.arg(Arg::with_name("number")
.help("Number of pairs to match")
.long("number")
.short("n")
.takes_value(true)
.default_value("6")
)
.arg(arg_phon.clone()))
.get_matches();
let debug = argmatches.is_present("debug");
let url = argmatches.value_of("url").expect("no url specified");
match argmatches.subcommand_name() {
None => {
eprintln!("No command given, see --help for syntax");
std::process::exit(1);
},
Some(command) => {
let submatches = argmatches.subcommand_matches(argmatches.subcommand_name().unwrap()).unwrap();
match command {
"ls" => {
match index(url) {
Ok(dataindex) => {
for name in dataindex.names.iter() {
println!("{}", name);
}
}
Err(err) => {
eprintln!("ERROR: {}", err);
success = false;
}
}
},
"pick" => {
match pick(url, argmatches.value_of("dataset").expect("No dataset specified"), argmatches.value_of("accesskey"), true) {
Ok(vocaitem) => vocaitem.print(submatches.is_present("phon"), submatches.is_present("translation"), submatches.is_present("example")),
Err(err) => println!("ERROR: {}", err),
}
},
"find" => {
match find(url, argmatches.value_of("dataset").expect("No dataset specified"), argmatches.value_of("word").expect("Word not provided") ,argmatches.value_of("accesskey"), true) {
Ok(vocaitem) => vocaitem.print(submatches.is_present("phon"), submatches.is_present("translation"), submatches.is_present("example")),
Err(err) => println!("ERROR: {}", err),
}
},
"show" => {
match show(url, argmatches.value_of("dataset").expect("No dataset specified")) {
Ok(vocalist) => {
vocalist.show(submatches.is_present("translation"), submatches.is_present("phon"), None, false, submatches.is_present("example"), false);
}
Err(err) => println!("ERROR: {}", err),
}
},
_ => {
eprintln!("Not implemented yet");
}
}
}
}
exit(match success {
true => 0,
false => 1,
});
}
|
mod with_arity;
use std::convert::TryInto;
use proptest::strategy::{Just, Strategy};
use proptest::test_runner::{Config, TestRunner};
use proptest::{prop_assert, prop_assert_eq};
use liblumen_alloc::erts::term::prelude::*;
use liblumen_alloc::fixnum;
use crate::erlang::make_tuple_3::result;
use crate::test::strategy;
#[test]
fn without_arity_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_arity(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, arity, default_value)| {
let init_list = Term::NIL;
prop_assert_is_not_arity!(result(&arc_process, arity, default_value, init_list), arity);
Ok(())
},
);
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type INDClosedCaptionDataReceivedEventArgs = *mut ::core::ffi::c_void;
pub type INDCustomData = *mut ::core::ffi::c_void;
pub type INDDownloadEngine = *mut ::core::ffi::c_void;
pub type INDDownloadEngineNotifier = *mut ::core::ffi::c_void;
pub type INDLicenseFetchCompletedEventArgs = *mut ::core::ffi::c_void;
pub type INDLicenseFetchDescriptor = *mut ::core::ffi::c_void;
pub type INDLicenseFetchResult = *mut ::core::ffi::c_void;
pub type INDMessenger = *mut ::core::ffi::c_void;
pub type INDProximityDetectionCompletedEventArgs = *mut ::core::ffi::c_void;
pub type INDRegistrationCompletedEventArgs = *mut ::core::ffi::c_void;
pub type INDSendResult = *mut ::core::ffi::c_void;
pub type INDStartResult = *mut ::core::ffi::c_void;
pub type INDStorageFileHelper = *mut ::core::ffi::c_void;
pub type INDStreamParser = *mut ::core::ffi::c_void;
pub type INDStreamParserNotifier = *mut ::core::ffi::c_void;
pub type INDTransmitterProperties = *mut ::core::ffi::c_void;
pub type IPlayReadyDomain = *mut ::core::ffi::c_void;
pub type IPlayReadyLicense = *mut ::core::ffi::c_void;
pub type IPlayReadyLicenseAcquisitionServiceRequest = *mut ::core::ffi::c_void;
pub type IPlayReadyLicenseSession = *mut ::core::ffi::c_void;
pub type IPlayReadyLicenseSession2 = *mut ::core::ffi::c_void;
pub type IPlayReadySecureStopServiceRequest = *mut ::core::ffi::c_void;
pub type IPlayReadyServiceRequest = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NDCertificateFeature(pub i32);
impl NDCertificateFeature {
pub const Transmitter: Self = Self(1i32);
pub const Receiver: Self = Self(2i32);
pub const SharedCertificate: Self = Self(3i32);
pub const SecureClock: Self = Self(4i32);
pub const AntiRollBackClock: Self = Self(5i32);
pub const CRLS: Self = Self(9i32);
pub const PlayReady3Features: Self = Self(13i32);
}
impl ::core::marker::Copy for NDCertificateFeature {}
impl ::core::clone::Clone for NDCertificateFeature {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NDCertificatePlatformID(pub i32);
impl NDCertificatePlatformID {
pub const Windows: Self = Self(0i32);
pub const OSX: Self = Self(1i32);
pub const WindowsOnARM: Self = Self(2i32);
pub const WindowsMobile7: Self = Self(5i32);
pub const iOSOnARM: Self = Self(6i32);
pub const XBoxOnPPC: Self = Self(7i32);
pub const WindowsPhone8OnARM: Self = Self(8i32);
pub const WindowsPhone8OnX86: Self = Self(9i32);
pub const XboxOne: Self = Self(10i32);
pub const AndroidOnARM: Self = Self(11i32);
pub const WindowsPhone81OnARM: Self = Self(12i32);
pub const WindowsPhone81OnX86: Self = Self(13i32);
}
impl ::core::marker::Copy for NDCertificatePlatformID {}
impl ::core::clone::Clone for NDCertificatePlatformID {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NDCertificateType(pub i32);
impl NDCertificateType {
pub const Unknown: Self = Self(0i32);
pub const PC: Self = Self(1i32);
pub const Device: Self = Self(2i32);
pub const Domain: Self = Self(3i32);
pub const Issuer: Self = Self(4i32);
pub const CrlSigner: Self = Self(5i32);
pub const Service: Self = Self(6i32);
pub const Silverlight: Self = Self(7i32);
pub const Application: Self = Self(8i32);
pub const Metering: Self = Self(9i32);
pub const KeyFileSigner: Self = Self(10i32);
pub const Server: Self = Self(11i32);
pub const LicenseSigner: Self = Self(12i32);
}
impl ::core::marker::Copy for NDCertificateType {}
impl ::core::clone::Clone for NDCertificateType {
fn clone(&self) -> Self {
*self
}
}
pub type NDClient = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NDClosedCaptionFormat(pub i32);
impl NDClosedCaptionFormat {
pub const ATSC: Self = Self(0i32);
pub const SCTE20: Self = Self(1i32);
pub const Unknown: Self = Self(2i32);
}
impl ::core::marker::Copy for NDClosedCaptionFormat {}
impl ::core::clone::Clone for NDClosedCaptionFormat {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NDContentIDType(pub i32);
impl NDContentIDType {
pub const KeyID: Self = Self(1i32);
pub const PlayReadyObject: Self = Self(2i32);
pub const Custom: Self = Self(3i32);
}
impl ::core::marker::Copy for NDContentIDType {}
impl ::core::clone::Clone for NDContentIDType {
fn clone(&self) -> Self {
*self
}
}
pub type NDCustomData = *mut ::core::ffi::c_void;
pub type NDDownloadEngineNotifier = *mut ::core::ffi::c_void;
pub type NDLicenseFetchDescriptor = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct NDMediaStreamType(pub i32);
impl NDMediaStreamType {
pub const Audio: Self = Self(1i32);
pub const Video: Self = Self(2i32);
}
impl ::core::marker::Copy for NDMediaStreamType {}
impl ::core::clone::Clone for NDMediaStreamType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NDProximityDetectionType(pub i32);
impl NDProximityDetectionType {
pub const UDP: Self = Self(1i32);
pub const TCP: Self = Self(2i32);
pub const TransportAgnostic: Self = Self(4i32);
}
impl ::core::marker::Copy for NDProximityDetectionType {}
impl ::core::clone::Clone for NDProximityDetectionType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct NDStartAsyncOptions(pub i32);
impl NDStartAsyncOptions {
pub const MutualAuthentication: Self = Self(1i32);
pub const WaitForLicenseDescriptor: Self = Self(2i32);
}
impl ::core::marker::Copy for NDStartAsyncOptions {}
impl ::core::clone::Clone for NDStartAsyncOptions {
fn clone(&self) -> Self {
*self
}
}
pub type NDStorageFileHelper = *mut ::core::ffi::c_void;
pub type NDStreamParserNotifier = *mut ::core::ffi::c_void;
pub type NDTCPMessenger = *mut ::core::ffi::c_void;
pub type PlayReadyContentHeader = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PlayReadyDecryptorSetup(pub i32);
impl PlayReadyDecryptorSetup {
pub const Uninitialized: Self = Self(0i32);
pub const OnDemand: Self = Self(1i32);
}
impl ::core::marker::Copy for PlayReadyDecryptorSetup {}
impl ::core::clone::Clone for PlayReadyDecryptorSetup {
fn clone(&self) -> Self {
*self
}
}
pub type PlayReadyDomain = *mut ::core::ffi::c_void;
pub type PlayReadyDomainIterable = *mut ::core::ffi::c_void;
pub type PlayReadyDomainIterator = *mut ::core::ffi::c_void;
pub type PlayReadyDomainJoinServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadyDomainLeaveServiceRequest = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PlayReadyEncryptionAlgorithm(pub i32);
impl PlayReadyEncryptionAlgorithm {
pub const Unprotected: Self = Self(0i32);
pub const Aes128Ctr: Self = Self(1i32);
pub const Cocktail: Self = Self(4i32);
pub const Aes128Cbc: Self = Self(5i32);
pub const Unspecified: Self = Self(65535i32);
pub const Uninitialized: Self = Self(2147483647i32);
}
impl ::core::marker::Copy for PlayReadyEncryptionAlgorithm {}
impl ::core::clone::Clone for PlayReadyEncryptionAlgorithm {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PlayReadyHardwareDRMFeatures(pub i32);
impl PlayReadyHardwareDRMFeatures {
pub const HardwareDRM: Self = Self(1i32);
pub const HEVC: Self = Self(2i32);
pub const Aes128Cbc: Self = Self(3i32);
}
impl ::core::marker::Copy for PlayReadyHardwareDRMFeatures {}
impl ::core::clone::Clone for PlayReadyHardwareDRMFeatures {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PlayReadyITADataFormat(pub i32);
impl PlayReadyITADataFormat {
pub const SerializedProperties: Self = Self(0i32);
pub const SerializedProperties_WithContentProtectionWrapper: Self = Self(1i32);
}
impl ::core::marker::Copy for PlayReadyITADataFormat {}
impl ::core::clone::Clone for PlayReadyITADataFormat {
fn clone(&self) -> Self {
*self
}
}
pub type PlayReadyITADataGenerator = *mut ::core::ffi::c_void;
pub type PlayReadyIndividualizationServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadyLicense = *mut ::core::ffi::c_void;
pub type PlayReadyLicenseAcquisitionServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadyLicenseIterable = *mut ::core::ffi::c_void;
pub type PlayReadyLicenseIterator = *mut ::core::ffi::c_void;
pub type PlayReadyLicenseSession = *mut ::core::ffi::c_void;
pub type PlayReadyMeteringReportServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadyRevocationServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadySecureStopIterable = *mut ::core::ffi::c_void;
pub type PlayReadySecureStopIterator = *mut ::core::ffi::c_void;
pub type PlayReadySecureStopServiceRequest = *mut ::core::ffi::c_void;
pub type PlayReadySoapMessage = *mut ::core::ffi::c_void;
|
use crate::config::Config;
use crate::jre::Jre;
use crate::util::OsType;
use anyhow::Result;
use sha1::{Digest, Sha1};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
pub struct LibericaJre {
os_type: OsType,
jre_version: String,
}
impl LibericaJre {
pub fn new(os_type: OsType, config: &Config) -> Self {
LibericaJre {
os_type,
jre_version: config.jre_version.clone(),
}
}
}
impl Jre for LibericaJre {
fn check_jre_archive<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let os_type = &self.os_type;
let get_sha = format!("https://api.bell-sw.com/v1/liberica/releases?version={}&version-feature=8&fx=true&bitness={}&os={}&arch=x86&installation-type=archive&bundle-type=jre&output=text&fields=sha1", self.jre_version, os_type.get_bitness(), os_type.get_os_type());
let sha = minreq::get(get_sha).send()?.as_str()?.to_string();
let mut hasher: Sha1 = Sha1::new();
hasher.update(fs::read(path)?);
let result = hasher.finalize();
if format!("{:x}", result) == sha {
Ok(())
} else {
Err(anyhow::anyhow!("Files don't equal"))
}
}
#[cfg(not(target_os = "linux"))]
fn check_jre_folder<P: AsRef<Path>>(&self, folder: P, zip: P) -> Result<()> {
let file = fs::File::open(zip)?;
let mut archive = zip::ZipArchive::new(file)?;
for i in 0..archive.len() {
let file = archive.by_index(i)?;
if file.is_file() {
if let Some(path) = file.enclosed_name() {
let path = path.iter().skip(1).collect::<PathBuf>();
let mut hasher = crc32fast::Hasher::new();
hasher.update(&fs::read(folder.as_ref().join(&path))?);
let crc = hasher.finalize();
if crc != file.crc32() {
return Err(anyhow::anyhow!("File {:?} has invalid hash", &path));
}
}
}
}
Ok(())
}
#[cfg(target_os = "linux")]
fn check_jre_folder<P: AsRef<Path>>(&self, folder: P, zip: P) -> Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
let file = fs::File::open(zip)?;
let tar = GzDecoder::new(file);
let mut archive = Archive::new(tar);
for entry in archive.entries()?.filter_map(|e| e.ok()) {
let path = entry.path()?.iter().skip(1).collect::<PathBuf>();
let mut hasher = crc32fast::Hasher::new();
hasher.update(&fs::read(folder.as_ref().join(&path))?);
let crc = hasher.finalize();
if crc != entry.header().cksum()? {
return Err(anyhow::anyhow!("File {:?} has invalid hash", &path));
}
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
fn extract_jre<P: AsRef<Path>>(&self, folder: P, zip: P) -> Result<()> {
use zip::result::ZipError;
if !folder.as_ref().exists() {
fs::create_dir_all(&folder)?;
}
let file = fs::File::open(&zip)?;
let mut archive = zip::ZipArchive::new(file)?;
use std::io;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
let filepath = file
.enclosed_name()
.ok_or(ZipError::InvalidArchive("Invalid file path"))?;
let filepath = filepath.iter().skip(1).collect::<PathBuf>();
let outpath = folder.as_ref().join(filepath);
if file.name().ends_with('/') {
fs::create_dir_all(&outpath)?;
} else {
if let Some(p) = outpath.parent() {
if !p.exists() {
fs::create_dir_all(&p)?;
}
}
let mut outfile = fs::File::create(&outpath)?;
io::copy(&mut file, &mut outfile)?;
}
}
fs::remove_file(zip.as_ref())?;
Ok(())
}
#[cfg(target_os = "linux")]
fn extract_jre<P: AsRef<Path>>(&self, folder: P, zip: P) -> Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
if !folder.as_ref().exists() {
fs::create_dir_all(&folder)?;
}
let file = fs::File::open(&zip)?;
let tar = GzDecoder::new(file);
let mut archive = Archive::new(tar);
for mut entry in archive.entries()?.filter_map(|e| e.ok()) {
let path = entry.path()?.iter().skip(1).collect::<PathBuf>();
entry.unpack(folder.as_ref().join(path))?;
}
fs::remove_file(zip.as_ref())?;
Ok(())
}
fn download_jre<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let os_type = &self.os_type;
let get_download_url = format!("https://api.bell-sw.com/v1/liberica/releases?version={}&version-feature=8&fx=true&bitness={}&os={}&arch=x86&installation-type=archive&bundle-type=jre&output=text&fields=downloadUrl", self.jre_version, os_type.get_bitness(), os_type.get_os_type());
let download_url = minreq::get(get_download_url).send()?.as_str()?.to_string();
let response = minreq::get(download_url).send()?.as_bytes().to_vec();
if let Some(parent) = path.as_ref().parent() {
fs::create_dir_all(parent)?;
}
let mut file = fs::OpenOptions::new().create(true).write(true).open(path)?;
file.write(&response)?;
Ok(())
}
}
|
use crate::lib::{default_sub_command, file_to_string, parse_isize, Command};
use anyhow::Error;
use clap::{value_t_or_exit, App, ArgMatches, SubCommand};
use nom::{
branch::alt,
bytes::complete::tag,
combinator::map,
multi::separated_list1,
sequence::{terminated, tuple},
};
use simple_error::SimpleError;
pub const SHUTTLE_SEARCH: Command = Command::new(sub_command, "shuttle-search", run);
#[derive(Debug)]
struct ShuttleSearchArgs {
file: String,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum BusRoute {
Bus(isize),
// I'm *sure* this will come up later
X,
}
#[derive(Debug, Clone)]
struct BusSchedule {
depart_time: isize,
routes: Vec<BusRoute>,
}
fn sub_command() -> App<'static, 'static> {
default_sub_command(
&SHUTTLE_SEARCH,
"Takes a file with a target time and bus schedule then finds the next bus and multiplies that by \
the wait time.",
"Path to the input file. First line contains the target time. Next line contains the comma \
delimited bus schedule.",
)
.subcommand(
SubCommand::with_name("part1")
.about(
"Finds the next bus information with the default input.",
)
.version("1.0.0"),
)
}
fn run(arguments: &ArgMatches) -> Result<(), Error> {
let shuttle_search_arguments = match arguments.subcommand_name() {
Some("part1") => ShuttleSearchArgs {
file: "day13/input.txt".to_string(),
},
_ => ShuttleSearchArgs {
file: value_t_or_exit!(arguments.value_of("file"), String),
},
};
process_schedule(&shuttle_search_arguments)
.map(|result| {
println!("{:#?}", result);
})
.map(|_| ())
}
fn process_schedule(shuttle_search_arguments: &ShuttleSearchArgs) -> Result<isize, Error> {
file_to_string(&shuttle_search_arguments.file)
.and_then(|file| parse_schedule(&file))
.map(|schedule| {
let (bus_number, depart_time) = find_next_bus(&schedule);
(depart_time - schedule.depart_time) * bus_number
})
}
fn find_next_bus(schedule: &BusSchedule) -> (isize, isize) {
schedule
.routes
.clone()
.into_iter()
.filter_map(|bus_route| match bus_route {
BusRoute::Bus(x) => Some(x),
BusRoute::X => None,
})
.map(|bus_number| {
let depart_time =
schedule.depart_time - ((schedule.depart_time % bus_number) - bus_number);
(bus_number, depart_time)
})
.fold_first(|low, new| if new.1 < low.1 { new } else { low })
.unwrap()
}
fn parse_schedule(file: &String) -> Result<BusSchedule, Error> {
map(
tuple((
terminated(parse_isize, tag("\n")),
terminated(
separated_list1(
tag(","),
alt((
map(parse_isize, |bus_number| BusRoute::Bus(bus_number)),
map(tag("x"), |_| BusRoute::X),
)),
),
tag("\n"),
),
)),
|(depart_time, routes)| BusSchedule {
depart_time: depart_time,
routes: routes,
},
)(file)
.map_err(|_| SimpleError::new("Parse failure").into())
.map(|(_, bus_schedule)| bus_schedule)
}
|
use std::sync::Arc;
use datafusion::execution::context::SessionState;
use self::{
handle_gapfill::HandleGapFill, influx_regex_to_datafusion_regex::InfluxRegexToDataFusionRegex,
};
mod handle_gapfill;
mod influx_regex_to_datafusion_regex;
pub use handle_gapfill::range_predicate;
/// Register IOx-specific logical [`OptimizerRule`]s with the SessionContext
///
/// [`OptimizerRule`]: datafusion::optimizer::OptimizerRule
pub fn register_iox_logical_optimizers(state: SessionState) -> SessionState {
state
.add_optimizer_rule(Arc::new(InfluxRegexToDataFusionRegex::new()))
.add_optimizer_rule(Arc::new(HandleGapFill::new()))
}
|
//! Typestate [line protocol] builder.
//!
//! [line protocol]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol
//! [special characters]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#special-characters
use bytes::BufMut;
use std::{
fmt::{self},
marker::PhantomData,
};
// https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#special-characters
const COMMA_EQ_SPACE: [char; 3] = [',', '=', ' '];
const COMMA_SPACE: [char; 2] = [',', ' '];
const DOUBLE_QUOTE: [char; 1] = ['"'];
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default)]
pub struct BeforeMeasurement;
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct AfterMeasurement;
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct AfterTag;
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct AfterField;
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct AfterTimestamp;
/// Implements a [line protocol] builder.
///
/// A [`LineProtocolBuilder`] is a statically-typed InfluxDB [line protocol] builder.
/// It writes one or more lines of [line protocol] to a [`bytes::BufMut`].
///
/// ```
/// use influxdb_line_protocol::LineProtocolBuilder;
/// let lp = LineProtocolBuilder::new()
/// .measurement("foo")
/// .tag("bar", "baz")
/// .field("qux", 42.0)
/// .close_line();
///
/// assert_eq!(lp.build(), b"foo,bar=baz qux=42\n");
/// ```
///
/// [`LineProtocolBuilder`] never returns runtime errors. Instead, it employs a type-level state machine
/// to guarantee that users can't build a syntactically-malformed line protocol batch.
///
/// This builder does not check for semantic errors. In particular, it does not check for duplicate tag and field
/// names, nor it does enforce [naming restrictions] on keys.
///
/// Attempts to consume the line protocol before closing a line yield
/// compile-time errors:
///
/// ```compile_fail
/// # use influxdb_line_protocol::LineProtocolBuilder;
/// let lp = LineProtocolBuilder::new()
/// .measurement("foo")
/// .tag("bar", "baz")
///
/// assert_eq!(lp.build(), b"foo,bar=baz qux=42\n");
/// ```
///
/// and attempts to `close_line` the line without at least one field also yield
/// compile-time errors:
///
/// ```compile_fail
/// # use influxdb_line_protocol::LineProtocolBuilder;
/// let lp = LineProtocolBuilder::new()
/// .measurement("foo")
/// .tag("bar", "baz")
/// .close_line();
/// ```
///
/// Tags, if any, must be emitted before fields. This will fail to compile:
///
/// ```compile_fail
/// # use influxdb_line_protocol::LineProtocolBuilder;
/// let lp = LineProtocolBuilder::new()
/// .measurement("foo")
/// .field("qux", 42.0);
/// .tag("bar", "baz")
/// .close_line();
/// ```
///
/// and timestamps, if any, must be specified last before closing the line:
///
/// ```compile_fail
/// # use influxdb_line_protocol::LineProtocolBuilder;
/// let lp = LineProtocolBuilder::new()
/// .measurement("foo")
/// .timestamp(1234)
/// .field("qux", 42.0);
/// .close_line();
/// ```
///
/// (the negative examples part of the documentation is so verbose because it's the only way to test compilation failures)
///
/// [line protocol]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol
/// [special characters]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#special-characters
/// [naming restrictions]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#naming-restrictions
#[derive(Debug, Default)]
pub struct LineProtocolBuilder<B, S = BeforeMeasurement>
where
B: BufMut,
{
buf: B,
_marker: PhantomData<S>,
}
impl LineProtocolBuilder<Vec<u8>, BeforeMeasurement> {
/// Creates a new [`LineProtocolBuilder`] with an empty buffer.
pub fn new() -> Self {
Self::new_with(vec![])
}
}
impl<B> LineProtocolBuilder<B, BeforeMeasurement>
where
B: BufMut,
{
/// Like `new` but appending to an existing `BufMut`.
pub fn new_with(buf: B) -> Self {
Self {
buf,
_marker: PhantomData,
}
}
/// Provide the measurement name.
///
/// It returns a new builder whose type allows only setting tags and fields.
pub fn measurement(self, measurement: &str) -> LineProtocolBuilder<B, AfterMeasurement> {
let measurement = escape(measurement, COMMA_SPACE);
self.write(format_args!("{measurement}"))
}
/// Finish building the line protocol and return the inner buffer.
pub fn build(self) -> B {
self.buf
}
}
impl<B> LineProtocolBuilder<B, AfterMeasurement>
where
B: BufMut,
{
/// Add a tag (key + value).
///
/// Tag keys and tag values will be escaped according to the rules defined in [the special characters documentation].
///
/// [special characters]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#special-characters
pub fn tag(self, tag_key: &str, tag_value: &str) -> Self {
let tag_key = escape(tag_key, COMMA_EQ_SPACE);
let tag_value = escape(tag_value, COMMA_EQ_SPACE);
self.write(format_args!(",{tag_key}={tag_value}"))
}
/// Add a field (key + value).
///
/// Field keys will be escaped according to the rules defined in [the special characters documentation].
///
/// Field values will encoded according to the rules defined in [the data types and formats documentation].
///
/// This function is called for the first field only. It returns a new builder whose type no longer allows adding tags.
///
/// [special characters]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#special-characters
/// [data types and formats]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#data-types-and-format
pub fn field<F>(self, field_key: &str, field_value: F) -> LineProtocolBuilder<B, AfterField>
where
F: FieldValue,
{
self.write(format_args!(" {}", format_field(field_key, &field_value)))
}
}
impl<B> LineProtocolBuilder<B, AfterField>
where
B: BufMut,
{
/// Add a field (key + value).
///
/// This function is called for the second and subsequent fields.
pub fn field<F: FieldValue>(self, field_key: &str, field_value: F) -> Self {
self.write(format_args!(",{}", format_field(field_key, &field_value)))
}
/// Provide a timestamp.
///
/// It returns a builder whose type allows only closing the line.
///
/// The precision of the timestamp is by default nanoseconds (ns) but the unit
/// can be changed when performing the request that carries the line protocol body.
/// Setting the unit is outside of the scope of a line protocol builder.
pub fn timestamp(self, ts: i64) -> LineProtocolBuilder<B, AfterTimestamp> {
self.write(format_args!(" {ts}"))
}
/// Closing a line is required before starting a new one or finishing building the batch.
pub fn close_line(self) -> LineProtocolBuilder<B, BeforeMeasurement> {
self.close()
}
}
impl<B> LineProtocolBuilder<B, AfterTimestamp>
where
B: BufMut,
{
/// Closing a line is required before starting a new one or finishing building the batch.
pub fn close_line(self) -> LineProtocolBuilder<B, BeforeMeasurement> {
self.close()
}
}
impl<B, S> LineProtocolBuilder<B, S>
where
B: BufMut,
{
fn close(self) -> LineProtocolBuilder<B, BeforeMeasurement> {
self.write(format_args!("\n"))
}
fn write<S2>(self, args: fmt::Arguments<'_>) -> LineProtocolBuilder<B, S2> {
use std::io::Write;
// MutBuf's Write adapter is infallible.
let mut writer = self.buf.writer();
write!(&mut writer, "{args}").unwrap();
LineProtocolBuilder {
buf: writer.into_inner(),
_marker: PhantomData,
}
}
}
// Return a [`fmt::Display`] that renders string while escaping any characters in the `special_characters` array
// with a `\`
fn escape<const N: usize>(src: &str, special_characters: [char; N]) -> Escaped<'_, N> {
Escaped {
src,
special_characters,
}
}
struct Escaped<'a, const N: usize> {
src: &'a str,
special_characters: [char; N],
}
impl<'a, const N: usize> fmt::Display for Escaped<'a, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for ch in self.src.chars() {
if self.special_characters.contains(&ch) || ch == '\\' {
write!(f, "\\")?;
}
write!(f, "{ch}")?;
}
Ok(())
}
}
// This method is used by the two [`LineProtocolBuilder::field`] variants in order to render the
// `key=value` encoding of a field.
fn format_field<'a, F>(field_key: &'a str, field_value: &'a F) -> impl fmt::Display + 'a
where
F: FieldValue,
{
FormattedField {
field_key,
field_value,
}
}
struct FormattedField<'a, F>
where
F: FieldValue,
{
field_key: &'a str,
field_value: &'a F,
}
impl<'a, F> fmt::Display for FormattedField<'a, F>
where
F: FieldValue,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}=", escape(self.field_key, COMMA_EQ_SPACE))?;
self.field_value.fmt(f)
}
}
/// The [`FieldValue`] trait is implemented by the legal [line protocol types].
///
/// [line protocol types]: https://docs.influxdata.com/influxdb/cloud/reference/syntax/line-protocol/#data-types-and-format
pub trait FieldValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
}
impl FieldValue for &str {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}\"", escape(self, DOUBLE_QUOTE))
}
}
impl FieldValue for f64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl FieldValue for bool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl FieldValue for i64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}i")
}
}
impl FieldValue for u64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}u")
}
}
#[cfg(test)]
mod tests {
use crate::{parse_lines, FieldSet, ParsedLine};
use super::*;
#[test]
fn test_string_escape() {
assert_eq!(
format!("\"{}\"", escape(r#"foo"#, DOUBLE_QUOTE)),
r#""foo""#
);
assert_eq!(
format!("\"{}\"", escape(r#"foo \ bar"#, DOUBLE_QUOTE)),
r#""foo \\ bar""#
);
assert_eq!(
format!("\"{}\"", escape(r#"foo " bar"#, DOUBLE_QUOTE)),
r#""foo \" bar""#
);
assert_eq!(
format!("\"{}\"", escape(r#"foo \" bar"#, DOUBLE_QUOTE)),
r#""foo \\\" bar""#
);
}
#[test]
fn test_lp_builder() {
const PLAIN: &str = "plain";
const WITH_SPACE: &str = "with space";
const WITH_COMMA: &str = "with,comma";
const WITH_EQ: &str = "with=eq";
const WITH_DOUBLE_QUOTE: &str = r#"with"doublequote"#;
const WITH_SINGLE_QUOTE: &str = "with'singlequote";
const WITH_BACKSLASH: &str = r#"with\ backslash"#;
let builder = LineProtocolBuilder::new()
// line 0
.measurement("tag_keys")
.tag(PLAIN, "dummy")
.tag(WITH_SPACE, "dummy")
.tag(WITH_COMMA, "dummy")
.tag(WITH_EQ, "dummy")
.tag(WITH_DOUBLE_QUOTE, "dummy")
.tag(WITH_SINGLE_QUOTE, "dummy")
.tag(WITH_BACKSLASH, "dummy")
.field("dummy", true)
.close_line()
// line 1
.measurement("tag_values")
.tag("plain", PLAIN)
.tag("withspace", WITH_SPACE)
.tag("withcomma", WITH_COMMA)
.tag("witheq", WITH_EQ)
.tag("withdoublequote", WITH_DOUBLE_QUOTE)
.tag("withsinglaquote", WITH_SINGLE_QUOTE)
.tag("withbackslash", WITH_BACKSLASH)
.field("dummy", true)
.close_line()
// line 2
.measurement("field keys")
.field(PLAIN, true)
.field(WITH_SPACE, true)
.field(WITH_COMMA, true)
.field(WITH_EQ, true)
.field(WITH_DOUBLE_QUOTE, true)
.field(WITH_SINGLE_QUOTE, true)
.field(WITH_BACKSLASH, true)
.close_line()
// line3
.measurement("field values")
.field("mybool", false)
.field("mysigned", 51_i64)
.field("myunsigned", 51_u64)
.field("myfloat", 51.0)
.field("mystring", "some value")
.field("mystringwithquotes", "some \" value")
.close_line()
// line 4
.measurement(PLAIN)
.field("dummy", true)
.close_line()
// line 5
.measurement(WITH_SPACE)
.field("dummy", true)
.close_line()
// line 6
.measurement(WITH_COMMA)
.field("dummy", true)
.close_line()
// line 7
.measurement(WITH_EQ)
.field("dummy", true)
.close_line()
// line 8
.measurement(WITH_DOUBLE_QUOTE)
.field("dummy", true)
.close_line()
// line 9
.measurement(WITH_SINGLE_QUOTE)
.field("dummy", true)
.close_line()
// line 10
.measurement(WITH_BACKSLASH)
.field("dummy", true)
.close_line()
// line 11
.measurement("without timestamp")
.field("dummy", true)
.close_line()
// line 12
.measurement("with timestamp")
.field("dummy", true)
.timestamp(1234)
.close_line();
let lp = String::from_utf8(builder.build()).unwrap();
println!("-----\n{lp}-----");
let parsed_lines = parse_lines(&lp)
.collect::<Result<Vec<ParsedLine<'_>>, _>>()
.unwrap();
let get_tag_key = |n: usize, f: usize| {
format!("{}", parsed_lines[n].series.tag_set.as_ref().unwrap()[f].0)
};
let row = 0;
assert_eq!(get_tag_key(row, 0), PLAIN);
assert_eq!(get_tag_key(row, 1), WITH_SPACE);
assert_eq!(get_tag_key(row, 2), WITH_COMMA);
assert_eq!(get_tag_key(row, 3), WITH_EQ);
assert_eq!(get_tag_key(row, 4), WITH_DOUBLE_QUOTE);
assert_eq!(get_tag_key(row, 5), WITH_SINGLE_QUOTE);
assert_eq!(get_tag_key(row, 6), WITH_BACKSLASH);
let get_tag_value = |n: usize, f: usize| {
format!("{}", parsed_lines[n].series.tag_set.as_ref().unwrap()[f].1)
};
let row = 1;
assert_eq!(get_tag_value(row, 0), PLAIN);
assert_eq!(get_tag_value(row, 1), WITH_SPACE);
assert_eq!(get_tag_value(row, 2), WITH_COMMA);
assert_eq!(get_tag_value(row, 3), WITH_EQ);
assert_eq!(get_tag_value(row, 4), WITH_DOUBLE_QUOTE);
assert_eq!(get_tag_value(row, 5), WITH_SINGLE_QUOTE);
assert_eq!(get_tag_value(row, 6), WITH_BACKSLASH);
let get_field_key = |n: usize, f: usize| format!("{}", parsed_lines[n].field_set[f].0);
let row = 2;
assert_eq!(get_field_key(row, 0), PLAIN);
assert_eq!(get_field_key(row, 1), WITH_SPACE);
assert_eq!(get_field_key(row, 2), WITH_COMMA);
assert_eq!(get_field_key(row, 3), WITH_EQ);
assert_eq!(get_field_key(row, 4), WITH_DOUBLE_QUOTE);
assert_eq!(get_field_key(row, 5), WITH_SINGLE_QUOTE);
assert_eq!(get_field_key(row, 6), WITH_BACKSLASH);
let get_field_value = |n: usize, f: usize| format!("{}", parsed_lines[n].field_set[f].1);
let row = 3;
assert_eq!(get_field_value(row, 0), "false");
assert_eq!(get_field_value(row, 1), "51i");
assert_eq!(get_field_value(row, 2), "51u");
assert_eq!(get_field_value(row, 3), "51");
assert_eq!(get_field_value(row, 4), "some value");
// TODO(mkm): file an issue for the parser since it incorrectly decodes an escaped double quote (possibly also the Go version).
// assert_eq!(get_field_value(row, 5), "some \" value");
let get_measurement = |n: usize| format!("{}", parsed_lines[n].series.measurement);
assert_eq!(get_measurement(4), PLAIN);
assert_eq!(get_measurement(5), WITH_SPACE);
assert_eq!(get_measurement(6), WITH_COMMA);
assert_eq!(get_measurement(7), WITH_EQ);
assert_eq!(get_measurement(8), WITH_DOUBLE_QUOTE);
assert_eq!(get_measurement(9), WITH_SINGLE_QUOTE);
assert_eq!(get_measurement(10), WITH_BACKSLASH);
let get_timestamp = |n: usize| parsed_lines[n].timestamp;
assert_eq!(get_timestamp(11), None);
assert_eq!(get_timestamp(12), Some(1234));
}
#[test]
fn test_float_formatting() {
// ensure that my_float is printed in a way that it is parsed
// as a float (not an int)
let builder = LineProtocolBuilder::new()
.measurement("tag_keys")
.tag("foo", "bar")
.field("my_float", 3.0)
.close_line();
let lp = String::from_utf8(builder.build()).unwrap();
println!("-----\n{lp}-----");
let parsed_lines = parse_lines(&lp)
.collect::<Result<Vec<ParsedLine<'_>>, _>>()
.unwrap();
assert_eq!(parsed_lines.len(), 1);
let parsed_line = &parsed_lines[0];
let expected_fields = vec![("my_float".into(), crate::FieldValue::F64(3.0))]
.into_iter()
.collect::<FieldSet<'_>>();
assert_eq!(parsed_line.field_set, expected_fields)
}
}
|
//! The following is derived from Rust's
//! library/std/src/os/windows/raw.rs,
//! library/std/src/os/windows/io/raw.rs and
//! library/std/src/os/windows/io/socket.rs
//! at revision
//! 4f9b394c8a24803e57ba892fa00e539742ebafc0.
//!
//! All code in this file is licensed MIT or Apache 2.0 at your option.
mod raw {
#[cfg(target_pointer_width = "32")]
#[cfg_attr(staged_api, stable(feature = "raw_ext", since = "1.1.0"))]
pub type SOCKET = u32;
#[cfg(target_pointer_width = "64")]
#[cfg_attr(staged_api, stable(feature = "raw_ext", since = "1.1.0"))]
pub type SOCKET = u64;
}
pub mod io;
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::constants::FIREBASE_TOKEN_URI;
use crate::error::{AuthProviderError, ResultExt};
use crate::http::{HttpRequest, HttpRequestBuilder};
use crate::openid::IdToken;
use fidl_fuchsia_auth::{AuthProviderStatus, FirebaseToken};
use hyper::StatusCode;
use log::warn;
use serde_derive::{Deserialize, Serialize};
use serde_json::{from_str, to_string};
use std::str::FromStr;
use url::{form_urlencoded, Url};
type AuthProviderResult<T> = Result<T, AuthProviderError>;
/// Representation of the JSON body for a Firebase token request.
#[derive(Serialize)]
struct FirebaseTokenRequestBody {
#[serde(rename = "postBody")]
post_body: String,
#[serde(rename = "returnIdpCredential")]
return_idp_credential: bool,
#[serde(rename = "returnSecureToken")]
return_secure_token: bool,
#[serde(rename = "requestUri")]
request_uri: String,
}
/// Successful response type for Firebase requests.
#[derive(Deserialize)]
struct FirebaseTokenResponse {
#[serde(rename = "idToken")]
id_token: String,
email: String,
#[serde(rename = "localId")]
local_id: String,
#[serde(rename = "expiresIn")]
expires_in_sec: String,
}
/// Error response type for Firebase requests.
#[derive(Deserialize)]
struct FirebaseErrorResponse {
message: String,
}
/// Constructs a Firebase token request.
pub fn build_firebase_token_request(
id_token: IdToken,
firebase_api_key: String,
) -> AuthProviderResult<HttpRequest> {
let params = vec![("key", firebase_api_key.as_str())];
let url = Url::parse_with_params(FIREBASE_TOKEN_URI.as_str(), ¶ms)
.auth_provider_status(AuthProviderStatus::InternalError)?;
let token_request_body = FirebaseTokenRequestBody {
post_body: form_urlencoded::Serializer::new(String::new())
.append_pair("id_token", id_token.0.as_str())
.append_pair("providerId", "google.com")
.finish(),
return_idp_credential: true,
return_secure_token: true,
request_uri: "http://localhost".to_string(),
};
let request_body =
to_string(&token_request_body).auth_provider_status(AuthProviderStatus::InternalError)?;
HttpRequestBuilder::new(url.as_str(), "POST")
.with_header("key", firebase_api_key.as_str())
.with_header("accept", "application/json")
.with_header("content-type", "application/json")
.set_body(&request_body)
.finish()
}
/// Parses a response for a Firebase token request.
pub fn parse_firebase_token_response(
response_body: Option<String>,
status: StatusCode,
) -> AuthProviderResult<FirebaseToken> {
match (response_body.as_ref(), status) {
(Some(response), StatusCode::OK) => {
let FirebaseTokenResponse { id_token, email, local_id, expires_in_sec } =
from_str::<FirebaseTokenResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
let parsed_expiry_seconds = u64::from_str(&expires_in_sec)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
Ok(FirebaseToken {
id_token,
email: Some(email),
local_id: Some(local_id),
expires_in: parsed_expiry_seconds,
})
}
(Some(response), status) if status.is_client_error() => {
let FirebaseErrorResponse { message } = from_str::<FirebaseErrorResponse>(&response)
.auth_provider_status(AuthProviderStatus::OauthServerError)?;
warn!("Got unexpected error while retrieving Firebase token: {}", message);
Err(AuthProviderError::new(AuthProviderStatus::OauthServerError))
}
_ => Err(AuthProviderError::new(AuthProviderStatus::OauthServerError)),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_firebase_token_response_success() {
let response_body = "{\"idToken\": \"test-firebase-token\", \"localId\": \"test-id\",\
\"email\": \"test@example.com\", \"expiresIn\": \"3600\"}"
.to_string();
assert_eq!(
parse_firebase_token_response(Some(response_body), StatusCode::OK).unwrap(),
FirebaseToken {
id_token: "test-firebase-token".to_string(),
email: Some("test@example.com".to_string()),
local_id: Some("test-id".to_string()),
expires_in: 3600,
}
);
}
#[test]
fn test_parse_firebase_token_response_failures() {
// Client error
let response_body = "{\"message\": \"invalid API key\"}".to_string();
let result = parse_firebase_token_response(Some(response_body), StatusCode::BAD_REQUEST);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Server error
let result = parse_firebase_token_response(None, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
// Malformed response
let response_body = "\\malformed\\".to_string();
let result = parse_firebase_token_response(Some(response_body), StatusCode::OK);
assert_eq!(result.unwrap_err().status, AuthProviderStatus::OauthServerError);
}
}
|
use futures::{Future, Poll};
use rustls::ClientSession;
use std::sync::Arc;
use tokio::executor::DefaultExecutor;
use tokio::net::tcp::TcpStream;
use tokio_rustls::{rustls::ClientConfig, Connect, TlsConnector, TlsStream};
use tower_grpc::Request;
use tower_h2::client;
use tower_service::Service;
use tower_util::MakeService;
use webpki::DNSNameRef;
pub mod spike_proto {
include!(concat!(env!("OUT_DIR"), "/spike.rs"));
}
pub fn main() {
let _ = ::env_logger::init();
let uri: http::Uri = format!("https://0.0.0.0:10011").parse().unwrap();
let h2_settings = h2::client::Builder::new();
let mut make_client = client::Connect::new(Dst, h2_settings, DefaultExecutor::current());
let do_send = make_client
.make_service(())
.map(move |conn| {
use spike_proto::client::Spike;
let conn = tower_request_modifier::Builder::new()
.set_origin(uri)
.build(conn)
.unwrap();
Spike::new(conn)
})
.and_then(|mut client| {
use spike_proto::SendRequest;
client
.send(Request::new(SendRequest {
room: "ninety-two".into(),
msg: "not cheap, but costly".into(),
}))
.map_err(|e| panic!("gRPC request failed; err={:?}", e))
})
.and_then(|response| {
println!("RESPONSE = {:?}", response);
Ok(())
})
.map_err(|e| {
println!("ERR = {:?}", e);
});
tokio::run(do_send);
}
struct Dst;
impl Service<()> for Dst {
type Response = TlsStream<TcpStream, ClientSession>;
type Error = ::std::io::Error;
type Future = Connect<TcpStream>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(().into())
}
fn call(&mut self, _: ()) -> Self::Future {
let mut config = ClientConfig::new();
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
config.alpn_protocols.push(b"h2".to_vec());
let tls_connector = TlsConnector::from(Arc::new(config));
let domain = DNSNameRef::try_from_ascii_str("0.0.0.0:10011").unwrap();
let addr = "0.0.0.0:10011".parse().unwrap();
TcpStream::connect(&addr).and_then(move |sock| {
sock.set_nodelay(true).unwrap();
tls_connector.connect(domain, sock)
})
}
}
|
use {Uri, Result};
use convert::{HttpTryFrom, HttpTryInto};
use super::{Authority, Scheme, Parts, PathAndQuery};
/// A builder for `Uri`s.
///
/// This type can be used to construct an instance of `Uri`
/// through a builder pattern.
#[derive(Debug)]
pub struct Builder {
parts: Option<Result<Parts>>,
}
impl Builder {
/// Creates a new default instance of `Builder` to construct a `Uri`.
///
/// # Examples
///
/// ```
/// # use http::*;
///
/// let uri = uri::Builder::new()
/// .scheme("https")
/// .authority("hyper.rs")
/// .path_and_query("/")
/// .build()
/// .unwrap();
/// ```
#[inline]
pub fn new() -> Builder {
Builder::default()
}
/// Set the `Scheme` for this URI.
///
/// # Examples
///
/// ```
/// # use http::*;
///
/// let mut builder = uri::Builder::new();
/// builder.scheme("https");
/// ```
pub fn scheme<T>(&mut self, scheme: T) -> &mut Self
where
Scheme: HttpTryFrom<T>,
{
self.map(|parts| {
parts.scheme = Some(scheme.http_try_into()?);
Ok(())
})
}
/// Set the `Authority` for this URI.
///
/// # Examples
///
/// ```
/// # use http::*;
///
/// let uri = uri::Builder::new()
/// .authority("tokio.rs")
/// .build()
/// .unwrap();
/// ```
pub fn authority<T>(&mut self, auth: T) -> &mut Self
where
Authority: HttpTryFrom<T>,
{
self.map(|parts| {
parts.authority = Some(auth.http_try_into()?);
Ok(())
})
}
/// Set the `PathAndQuery` for this URI.
///
/// # Examples
///
/// ```
/// # use http::*;
///
/// let uri = uri::Builder::new()
/// .path_and_query("/hello?foo=bar")
/// .build()
/// .unwrap();
/// ```
pub fn path_and_query<T>(&mut self, p_and_q: T) -> &mut Self
where
PathAndQuery: HttpTryFrom<T>,
{
self.map(|parts| {
parts.path_and_query = Some(p_and_q.http_try_into()?);
Ok(())
})
}
/// Consumes this builder, and tries to construct a valid `Uri` from
/// the configured pieces.
///
/// # Errors
///
/// This function may return an error if any previously configured argument
/// failed to parse or get converted to the internal representation. For
/// example if an invalid `scheme` was specified via `scheme("!@#%/^")`
/// the error will be returned when this function is called rather than
/// when `scheme` was called.
///
/// Additionally, the various forms of URI require certain combinations of
/// parts to be set to be valid. If the parts don't fit into any of the
/// valid forms of URI, a new error is returned.
///
/// # Examples
///
/// ```
/// # use http::*;
///
/// let uri = Uri::builder()
/// .build()
/// .unwrap();
/// ```
pub fn build(&mut self) -> Result<Uri> {
self
.parts
.take()
.expect("cannot reuse Uri builder")
.and_then(|parts| parts.http_try_into())
}
fn map<F>(&mut self, f: F) -> &mut Self
where
F: FnOnce(&mut Parts) -> Result<()>,
{
let res = if let Some(Ok(ref mut parts)) = self.parts {
f(parts)
} else {
return self;
};
if let Err(err) = res {
self.parts = Some(Err(err));
}
self
}
}
impl Default for Builder {
#[inline]
fn default() -> Builder {
Builder {
parts: Some(Ok(Parts::default())),
}
}
}
|
#![deny(warnings)]
#![feature(box_patterns)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_def_site)]
extern crate proc_macro;
use proc_macro2::Ident;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseBuffer};
use syn::spanned::Spanned;
use syn::{
parse_macro_input, AngleBracketedGenericArguments, Error, FnArg, GenericArgument, ItemFn,
LitInt, Pat, PatIdent, PatType, Path, PathArguments, PathSegment, Token, Type, TypePath,
TypeReference,
};
#[proc_macro_attribute]
pub fn label(_: TokenStream, result_token_stream: TokenStream) -> TokenStream {
let result_item_fn = parse_macro_input!(result_token_stream as ItemFn);
match Signatures::label(&result_item_fn) {
Ok(signatures) => {
let frame = frame_for_label();
let const_native = signatures.const_native();
let native_fn = signatures.native_fn();
let all_tokens = quote! {
#frame
#const_native
#native_fn
#result_item_fn
};
all_tokens.into()
}
Err(error) => error.to_compile_error().into(),
}
}
#[proc_macro_attribute]
pub fn function(
module_function_arity_token_stream: TokenStream,
result_token_stream: TokenStream,
) -> TokenStream {
let module_function_arity =
parse_macro_input!(module_function_arity_token_stream as ModuleFunctionArity);
let result_item_fn = parse_macro_input!(result_token_stream as ItemFn);
match Signatures::entry_point(&result_item_fn, module_function_arity.arity) {
Ok(signatures) => {
let const_arity = signatures.const_arity();
let const_native = signatures.const_native();
let const_closure_native = signatures.const_closure_native();
let frame = frame_for_entry_point();
let frame_for_native = frame_for_native();
let function = module_function_arity.function();
let function_symbol = function_symbol();
let module_function_arity_fn = module_function_arity_fn();
let export_name = module_function_arity.export_name();
let native_fn = signatures.native_fn();
let all_tokens = quote! {
#const_arity
#const_native
#const_closure_native
#frame
#frame_for_native
#function
#function_symbol
#module_function_arity_fn
#[export_name = #export_name]
#native_fn
#result_item_fn
};
all_tokens.into()
}
Err(error) => error.to_compile_error().into(),
}
}
fn fn_arg_to_ident(fn_arg: &FnArg) -> Ident {
match fn_arg {
FnArg::Typed(PatType {
pat: box Pat::Ident(PatIdent { ident, .. }),
..
}) => ident.clone(),
_ => unimplemented!(
"result function is not expected to have argument like {:?}",
fn_arg
),
}
}
fn frame_for_entry_point() -> proc_macro2::TokenStream {
quote! {
pub fn frame() -> liblumen_alloc::erts::process::Frame {
frame_for_native(NATIVE)
}
}
}
fn frame_for_label() -> proc_macro2::TokenStream {
quote! {
pub fn frame() -> liblumen_alloc::erts::process::Frame {
super::frame_for_native(NATIVE)
}
}
}
fn frame_for_native() -> proc_macro2::TokenStream {
quote! {
pub fn frame_for_native(native: liblumen_alloc::erts::process::Native) -> liblumen_alloc::erts::process::Frame {
liblumen_alloc::erts::process::Frame::new(module_function_arity(), native)
}
}
}
fn function_symbol() -> proc_macro2::TokenStream {
quote! {
pub fn function_symbol() -> liblumen_core::symbols::FunctionSymbol {
liblumen_core::symbols::FunctionSymbol {
module: super::module().name().as_ptr(),
function: function().name().as_ptr(),
arity: ARITY,
ptr: native as *const std::ffi::c_void
}
}
}
}
fn module_function_arity_fn() -> proc_macro2::TokenStream {
quote! {
pub fn module_function_arity() -> liblumen_alloc::erts::ModuleFunctionArity {
liblumen_alloc::erts::ModuleFunctionArity {
module: super::module(),
function: function(),
arity: ARITY,
}
}
}
}
#[derive(Debug)]
struct ModuleFunctionArity {
module: String,
function: String,
arity: u8,
}
impl ModuleFunctionArity {
fn export_name(&self) -> String {
format!("{}:{}/{}", self.module, self.function, self.arity)
}
fn function(&self) -> proc_macro2::TokenStream {
let function = &self.function;
quote! {
pub fn function() -> liblumen_alloc::erts::term::prelude::Atom {
liblumen_alloc::erts::term::prelude::Atom::from_str(#function)
}
}
}
fn parse_arity(input: &ParseBuffer) -> syn::parse::Result<u8> {
let arity_lit_int = input.parse::<LitInt>()?;
arity_lit_int.base10_parse()
}
fn parse_function(input: &ParseBuffer) -> syn::parse::Result<String> {
let function = if let Ok(ident) = input.parse::<syn::Ident>() {
ident.to_string()
} else if let Ok(_) = input.parse::<Token![loop]>() {
"loop".to_string()
} else if let Ok(_) = input.parse::<Token![self]>() {
"self".to_string()
} else if let Ok(_) = input.parse::<Token![*]>() {
"*".to_string()
} else if let Ok(_) = input.parse::<Token![+]>() {
if let Ok(_) = input.parse::<Token![+]>() {
"++".to_string()
} else {
"+".to_string()
}
} else if let Ok(_) = input.parse::<Token![-]>() {
if let Ok(_) = input.parse::<Token![-]>() {
"--".to_string()
} else {
"-".to_string()
}
} else if let Ok(_) = input.parse::<Token![/]>() {
if let Ok(_) = input.parse::<Token![=]>() {
"/=".to_string()
} else {
"/".to_string()
}
} else if let Ok(_) = input.parse::<Token![<]>() {
"<".to_string()
} else if let Ok(_) = input.parse::<Token![=]>() {
if let Ok(_) = input.parse::<Token![/]>() {
if let Ok(_) = input.parse::<Token![=]>() {
"=/=".to_string()
} else {
unimplemented!("parse function name from {:?}", input);
}
} else if let Ok(_) = input.parse::<Token![:]>() {
if let Ok(_) = input.parse::<Token![=]>() {
"=:=".to_string()
} else {
unimplemented!("parse function name from {:?}", input);
}
} else if let Ok(_) = input.parse::<Token![<]>() {
"=<".to_string()
} else if let Ok(_) = input.parse::<Token![=]>() {
"==".to_string()
} else {
unimplemented!("parse function name from {:?}", input);
}
} else if let Ok(_) = input.parse::<Token![>]>() {
if let Ok(_) = input.parse::<Token![=]>() {
">=".to_string()
} else {
">".to_string()
}
// anonymous functions
} else if let Ok(index) = input.parse::<LitInt>() {
if let Ok(_) = input.parse::<Token![-]>() {
if let Ok(old_unique) = input.parse::<LitInt>() {
if let Ok(_) = input.parse::<Token![-]>() {
if let Ok(unique) = input.parse::<LitInt>() {
let span = unique.span();
let start = span.start();
let end = span.end();
if start.line == end.line {
let len = end.column - start.column;
if len == 32 {
format!("{}-{}-{}", index, old_unique, unique)
} else {
return Err(Error::new(span, format!("UNIQUE should be a 32-digit hexadecimal integer, but is {} digits long", len)));
}
} else {
return Err(Error::new(span, "UNIQUE should be on one line"));
}
} else {
return Err(input.error(
"Missing UNIQUE in anonymous function (INDEX-OLD_UNIQUE-UNIQUE",
));
}
} else {
return Err(input.error("Missing `-` after OLD_UNIQUE in anonymous function (INDEX-OLD_UNIQUE-UNIQUE)"));
}
} else {
return Err(input.error(
"Missing OLD_UNIQUE in anonymous function (INDEX-OLD_UNIQUE-UNIQUE",
));
}
} else {
return Err(input.error(
"Missing `-` after INDEX in anonymous function (INDEX-OLD_UNIQUE-UNIQUE",
));
}
} else {
unimplemented!("parse function name from {:?}", input);
};
Ok(function)
}
fn parse_module(input: &ParseBuffer) -> syn::parse::Result<String> {
let mut module = if let Ok(ident) = input.parse::<syn::Ident>() {
ident.to_string()
} else {
unimplemented!("parse module name from {:?}", input);
};
loop {
// End of module name.
// This separates module name and function name
if input.peek(Token![:]) {
break;
} else {
if let Ok(_) = input.parse::<Token![.]>() {
module.push('.');
if let Ok(relative) = input.parse::<syn::Ident>() {
module.push_str(&relative.to_string());
} else {
return Err(input.error(
"Relative module names must follow Elixir namespace separator (`.`)",
));
}
} else {
return Err(input.error("Elixir namespace operator (`.`) must follow qualifier. Use `:` separate module from function name."));
}
}
}
Ok(module)
}
}
impl Parse for ModuleFunctionArity {
fn parse(input: &ParseBuffer) -> syn::parse::Result<Self> {
if input.is_empty() {
Err(input.error("MODULE:FUNCTION/ARITY required"))
} else {
let module = Self::parse_module(input)?;
input.parse::<Token![:]>()?;
let function = Self::parse_function(input)?;
input.parse::<Token![/]>()?;
let arity = Self::parse_arity(input)?;
Ok(ModuleFunctionArity {
module,
function,
arity,
})
}
}
}
struct Native {
fn_arg_vec: Vec<FnArg>,
}
impl Native {
pub fn arity(&self) -> u8 {
self.fn_arg_vec.len() as u8
}
}
enum Process {
Arc,
Ref,
None,
}
struct Result {
process: Process,
return_type: ReturnType,
}
enum ReturnType {
Result,
Term,
}
struct Signatures {
native: Native,
result: Result,
}
impl Signatures {
pub fn entry_point(result_item_fn: &ItemFn, arity: u8) -> std::result::Result<Self, Error> {
if result_item_fn.sig.ident != "result" {
return Err(Error::new(
result_item_fn.sig.ident.span(),
format!(
"`{}` should be called `result` when using native_implemented::function macro",
result_item_fn.sig.ident
),
));
}
let result_fn_arg_vec: Vec<FnArg> = result_item_fn
.sig
.inputs
.iter()
.map(|input| match input {
FnArg::Typed(PatType {
pat: box Pat::Ident(PatIdent { .. }),
..
}) => input.clone(),
_ => unimplemented!(
"result function is not expected to have argument like {:?}",
input
),
})
.collect();
let result_arity = result_fn_arg_vec.len();
let (process, native_fn_arg_vec) = if result_arity == ((arity + 1) as usize) {
let process = match result_item_fn.sig.inputs.first().unwrap() {
FnArg::Typed(PatType { ty, .. }) => match **ty {
Type::Reference(TypeReference {
elem:
box Type::Path(TypePath {
path: Path { ref segments, .. },
..
}),
..
}) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Process" => Process::Ref,
s => unimplemented!(
"Extracting result function process from reference ident like {:?}",
s
),
}
}
Type::Path(TypePath {
path: Path { ref segments, .. },
..
}) => {
let PathSegment { ident, arguments } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Arc" => match arguments {
PathArguments::AngleBracketed(AngleBracketedGenericArguments { args: punctuated_generic_arguments, .. }) => {
match punctuated_generic_arguments.len() {
1 => {
match punctuated_generic_arguments.first().unwrap() {
GenericArgument::Type(Type::Path(TypePath { path: Path { segments, .. }, .. })) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Process" => Process::Arc,
s => unimplemented!(
"Extracting result function process from reference ident like {:?}",
s
),
}
}
generic_argument => unimplemented!("Extracting result function process from argument to Arc like {:?}", generic_argument)
}
}
n => unimplemented!("Extracting result function process from {:?} arguments to Arc like {:?}", n, punctuated_generic_arguments)
}
}
_ => unimplemented!("Extracting result function process from arguments to Arc like {:?}", arguments),
}
s => unimplemented!(
"Extracting result function process from path ident like {:?}",
s
),
}
}
_ => {
unimplemented!("Extracting result function process from type like {:?}", ty)
}
},
input => unimplemented!(
"Extracting result function process from argument like {:?}",
input
),
};
(process, result_fn_arg_vec[1..].to_vec())
} else if result_arity == (arity as usize) {
(Process::None, result_fn_arg_vec)
} else {
unreachable!(
"The Erlang arity of a function should not include the Process argument. For this result function, an arity of {} is expected if Process is not used or {} if the Process is the first argument",
arity,
arity + 1
);
};
let return_type = match result_item_fn.sig.output {
syn::ReturnType::Type(
_,
box Type::Path(TypePath {
path: Path { ref segments, .. },
..
}),
) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Result" => ReturnType::Result,
"Term" => ReturnType::Term,
_ => return Err(Error::new(ident.span(), "result function return type is neither Result nor Term"))
}
}
ref output => return Err(Error::new(
output.span(),
"result functions must return either liblumen_alloc::erts::exception::Result or liblumen_alloc::erts::term::Term"
)),
};
Ok(Self {
result: Result {
process,
return_type,
},
native: Native {
fn_arg_vec: native_fn_arg_vec,
},
})
}
pub fn label(result_item_fn: &ItemFn) -> std::result::Result<Self, Error> {
if result_item_fn.sig.ident != "result" {
return Err(Error::new(
result_item_fn.sig.ident.span(),
format!(
"`{}` should be called `result` when using native_implemented_function macro",
result_item_fn.sig.ident
),
));
}
let result_fn_arg_vec: Vec<FnArg> = result_item_fn
.sig
.inputs
.iter()
.map(|input| match input {
FnArg::Typed(PatType {
pat: box Pat::Ident(PatIdent { .. }),
..
}) => input.clone(),
_ => unimplemented!(
"result function is not expected to have argument like {:?}",
input
),
})
.collect();
let (process, native_fn_arg_vec) = match result_item_fn.sig.inputs.first().unwrap() {
FnArg::Typed(PatType { ty, .. }) => match **ty {
Type::Reference(TypeReference {
elem:
box Type::Path(TypePath {
path: Path { ref segments, .. },
..
}),
..
}) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Process" => (Process::Ref, result_fn_arg_vec[1..].to_vec()),
s => unimplemented!(
"Extracting result function process from reference ident like {:?}",
s
),
}
}
Type::Path(TypePath {
path: Path { ref segments, .. },
..
}) => {
let PathSegment { ident, arguments } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Arc" => match arguments {
PathArguments::AngleBracketed(AngleBracketedGenericArguments { args: punctuated_generic_arguments, .. }) => {
match punctuated_generic_arguments.len() {
1 => {
match punctuated_generic_arguments.first().unwrap() {
GenericArgument::Type(Type::Path(TypePath { path: Path { segments, .. }, .. })) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Process" => (Process::Arc, result_fn_arg_vec[1..].to_vec()),
s => unimplemented!(
"Extracting result function process from reference ident like {:?}",
s
),
}
}
generic_argument => unimplemented!("Extracting result function process from argument to Arc like {:?}", generic_argument)
}
}
n => unimplemented!("Extracting result function process from {:?} arguments to Arc like {:?}", n, punctuated_generic_arguments)
}
}
_ => unimplemented!("Extracting result function process from arguments to Arc like {:?}", arguments),
}
"Term" => (Process::None, result_fn_arg_vec),
s => unimplemented!(
"Extracting result function process from path ident like {:?}",
s
),
}
}
_ => unimplemented!("Extracting result function process from type like {:?}", ty),
},
input => unimplemented!(
"Extracting result function process from argument like {:?}",
input
),
};
let return_type = match result_item_fn.sig.output {
syn::ReturnType::Type(
_,
box Type::Path(TypePath {
path: Path { ref segments, .. },
..
}),
) => {
let PathSegment { ident, .. } = segments.last().unwrap();
match ident.to_string().as_ref() {
"Result" => ReturnType::Result,
"Term" => ReturnType::Term,
_ => return Err(Error::new(ident.span(), "result function return type is neither Result nor Term"))
}
}
ref output => return Err(Error::new(
output.span(),
"result functions must return either liblumen_alloc::erts::exception::Result or liblumen_alloc::erts::term::Term"
)),
};
Ok(Self {
result: Result {
process,
return_type,
},
native: Native {
fn_arg_vec: native_fn_arg_vec,
},
})
}
pub fn arity(&self) -> u8 {
self.native.arity()
}
fn const_arity(&self) -> proc_macro2::TokenStream {
let arity = &self.arity();
quote! {
pub const ARITY: liblumen_alloc::Arity = #arity;
}
}
fn const_native(&self) -> proc_macro2::TokenStream {
let native_variant = self.native_variant();
quote! {
pub const NATIVE: liblumen_alloc::erts::process::Native = #native_variant;
}
}
fn const_closure_native(&self) -> proc_macro2::TokenStream {
quote! {
pub const CLOSURE_NATIVE: Option<std::ptr::NonNull<std::ffi::c_void>> = Some(unsafe { std::ptr::NonNull::new_unchecked(native as *mut std::ffi::c_void) });
}
}
pub fn native_fn(&self) -> proc_macro2::TokenStream {
let mut result_argument_ident: Vec<Box<dyn ToTokens>> = match self.result.process {
Process::Arc => vec![Box::new(quote! { arc_process.clone() })],
Process::Ref => vec![Box::new(quote! { &arc_process })],
Process::None => vec![],
};
result_argument_ident.extend(
self.native
.fn_arg_vec
.iter()
.map(fn_arg_to_ident)
.map(|ident| -> Box<dyn ToTokens> { Box::new(ident) }),
);
let native_fn_arg = &self.native.fn_arg_vec;
let result_call = match self.result.return_type {
ReturnType::Result => {
quote! {
arc_process.return_status(result(#(#result_argument_ident),*))
}
}
ReturnType::Term => {
quote! {
arc_process.term_to_return_status(result(#(#result_argument_ident),*))
}
}
};
quote! {
pub extern "C-unwind" fn native(#(#native_fn_arg),*) -> liblumen_alloc::erts::process::ffi::ErlangResult {
let arc_process = crate::runtime::process::current_process();
arc_process.reduce();
#result_call
}
}
}
fn native_variant(&self) -> proc_macro2::TokenStream {
match self.arity() {
0 => quote! {
liblumen_alloc::erts::process::Native::Zero(native)
},
1 => quote! {
liblumen_alloc::erts::process::Native::One(native)
},
2 => quote! {
liblumen_alloc::erts::process::Native::Two(native)
},
3 => quote! {
liblumen_alloc::erts::process::Native::Three(native)
},
4 => quote! {
liblumen_alloc::erts::process::Native::Four(native)
},
5 => quote! {
liblumen_alloc::erts::process::Native::Five(native)
},
arity => unimplemented!("Don't know how to convert arity ({}) to Native", arity),
}
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - FDCAN Core Release Register"]
pub fdcan_crel: FDCAN_CREL,
#[doc = "0x04 - FDCAN Core Release Register"]
pub fdcan_endn: FDCAN_ENDN,
_reserved2: [u8; 4usize],
#[doc = "0x0c - FDCAN Data Bit Timing and Prescaler Register"]
pub fdcan_dbtp: FDCAN_DBTP,
#[doc = "0x10 - FDCAN Test Register"]
pub fdcan_test: FDCAN_TEST,
#[doc = "0x14 - FDCAN RAM Watchdog Register"]
pub fdcan_rwd: FDCAN_RWD,
#[doc = "0x18 - FDCAN CC Control Register"]
pub fdcan_cccr: FDCAN_CCCR,
#[doc = "0x1c - FDCAN Nominal Bit Timing and Prescaler Register"]
pub fdcan_nbtp: FDCAN_NBTP,
#[doc = "0x20 - FDCAN Timestamp Counter Configuration Register"]
pub fdcan_tscc: FDCAN_TSCC,
#[doc = "0x24 - FDCAN Timestamp Counter Value Register"]
pub fdcan_tscv: FDCAN_TSCV,
#[doc = "0x28 - FDCAN Timeout Counter Configuration Register"]
pub fdcan_tocc: FDCAN_TOCC,
#[doc = "0x2c - FDCAN Timeout Counter Value Register"]
pub fdcan_tocv: FDCAN_TOCV,
_reserved11: [u8; 16usize],
#[doc = "0x40 - FDCAN Error Counter Register"]
pub fdcan_ecr: FDCAN_ECR,
#[doc = "0x44 - FDCAN Protocol Status Register"]
pub fdcan_psr: FDCAN_PSR,
#[doc = "0x48 - FDCAN Transmitter Delay Compensation Register"]
pub fdcan_tdcr: FDCAN_TDCR,
_reserved14: [u8; 4usize],
#[doc = "0x50 - FDCAN Interrupt Register"]
pub fdcan_ir: FDCAN_IR,
#[doc = "0x54 - FDCAN Interrupt Enable Register"]
pub fdcan_ie: FDCAN_IE,
#[doc = "0x58 - FDCAN Interrupt Line Select Register"]
pub fdcan_ils: FDCAN_ILS,
#[doc = "0x5c - FDCAN Interrupt Line Enable Register"]
pub fdcan_ile: FDCAN_ILE,
_reserved18: [u8; 32usize],
#[doc = "0x80 - FDCAN Global Filter Configuration Register"]
pub fdcan_rxgfc: FDCAN_RXGFC,
#[doc = "0x84 - FDCAN Extended ID and Mask Register"]
pub fdcan_xidam: FDCAN_XIDAM,
#[doc = "0x88 - FDCAN High Priority Message Status Register"]
pub fdcan_hpms: FDCAN_HPMS,
_reserved21: [u8; 4usize],
#[doc = "0x90 - FDCAN Rx FIFO 0 Status Register"]
pub fdcan_rxf0s: FDCAN_RXF0S,
#[doc = "0x94 - CAN Rx FIFO 0 Acknowledge Register"]
pub fdcan_rxf0a: FDCAN_RXF0A,
#[doc = "0x98 - FDCAN Rx FIFO 1 Status Register"]
pub fdcan_rxf1s: FDCAN_RXF1S,
#[doc = "0x9c - FDCAN Rx FIFO 1 Acknowledge Register"]
pub fdcan_rxf1a: FDCAN_RXF1A,
_reserved25: [u8; 32usize],
#[doc = "0xc0 - FDCAN Tx buffer configuration register"]
pub fdcan_txbc: FDCAN_TXBC,
#[doc = "0xc4 - FDCAN Tx FIFO/Queue Status Register"]
pub fdcan_txfqs: FDCAN_TXFQS,
#[doc = "0xc8 - FDCAN Tx Buffer Request Pending Register"]
pub fdcan_txbrp: FDCAN_TXBRP,
#[doc = "0xcc - FDCAN Tx Buffer Add Request Register"]
pub fdcan_txbar: FDCAN_TXBAR,
#[doc = "0xd0 - FDCAN Tx Buffer Cancellation Request Register"]
pub fdcan_txbcr: FDCAN_TXBCR,
#[doc = "0xd4 - FDCAN Tx Buffer Transmission Occurred Register"]
pub fdcan_txbto: FDCAN_TXBTO,
#[doc = "0xd8 - FDCAN Tx Buffer Cancellation Finished Register"]
pub fdcan_txbcf: FDCAN_TXBCF,
#[doc = "0xdc - FDCAN Tx Buffer Transmission Interrupt Enable Register"]
pub fdcan_txbtie: FDCAN_TXBTIE,
#[doc = "0xe0 - FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register"]
pub fdcan_txbcie: FDCAN_TXBCIE,
#[doc = "0xe4 - FDCAN Tx Event FIFO Status Register"]
pub fdcan_txefs: FDCAN_TXEFS,
#[doc = "0xe8 - FDCAN Tx Event FIFO Acknowledge Register"]
pub fdcan_txefa: FDCAN_TXEFA,
_reserved36: [u8; 20usize],
#[doc = "0x100 - FDCAN TT Trigger Memory Configuration Register"]
pub fdcan_ckdiv: FDCAN_CKDIV,
}
#[doc = "FDCAN Core Release Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_crel](fdcan_crel) module"]
pub type FDCAN_CREL = crate::Reg<u32, _FDCAN_CREL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_CREL;
#[doc = "`read()` method returns [fdcan_crel::R](fdcan_crel::R) reader structure"]
impl crate::Readable for FDCAN_CREL {}
#[doc = "FDCAN Core Release Register"]
pub mod fdcan_crel;
#[doc = "FDCAN Core Release Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_endn](fdcan_endn) module"]
pub type FDCAN_ENDN = crate::Reg<u32, _FDCAN_ENDN>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_ENDN;
#[doc = "`read()` method returns [fdcan_endn::R](fdcan_endn::R) reader structure"]
impl crate::Readable for FDCAN_ENDN {}
#[doc = "FDCAN Core Release Register"]
pub mod fdcan_endn;
#[doc = "FDCAN Data Bit Timing and Prescaler Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_dbtp](fdcan_dbtp) module"]
pub type FDCAN_DBTP = crate::Reg<u32, _FDCAN_DBTP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_DBTP;
#[doc = "`read()` method returns [fdcan_dbtp::R](fdcan_dbtp::R) reader structure"]
impl crate::Readable for FDCAN_DBTP {}
#[doc = "`write(|w| ..)` method takes [fdcan_dbtp::W](fdcan_dbtp::W) writer structure"]
impl crate::Writable for FDCAN_DBTP {}
#[doc = "FDCAN Data Bit Timing and Prescaler Register"]
pub mod fdcan_dbtp;
#[doc = "FDCAN Test Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_test](fdcan_test) module"]
pub type FDCAN_TEST = crate::Reg<u32, _FDCAN_TEST>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TEST;
#[doc = "`read()` method returns [fdcan_test::R](fdcan_test::R) reader structure"]
impl crate::Readable for FDCAN_TEST {}
#[doc = "`write(|w| ..)` method takes [fdcan_test::W](fdcan_test::W) writer structure"]
impl crate::Writable for FDCAN_TEST {}
#[doc = "FDCAN Test Register"]
pub mod fdcan_test;
#[doc = "FDCAN RAM Watchdog Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rwd](fdcan_rwd) module"]
pub type FDCAN_RWD = crate::Reg<u32, _FDCAN_RWD>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RWD;
#[doc = "`read()` method returns [fdcan_rwd::R](fdcan_rwd::R) reader structure"]
impl crate::Readable for FDCAN_RWD {}
#[doc = "`write(|w| ..)` method takes [fdcan_rwd::W](fdcan_rwd::W) writer structure"]
impl crate::Writable for FDCAN_RWD {}
#[doc = "FDCAN RAM Watchdog Register"]
pub mod fdcan_rwd;
#[doc = "FDCAN CC Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_cccr](fdcan_cccr) module"]
pub type FDCAN_CCCR = crate::Reg<u32, _FDCAN_CCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_CCCR;
#[doc = "`read()` method returns [fdcan_cccr::R](fdcan_cccr::R) reader structure"]
impl crate::Readable for FDCAN_CCCR {}
#[doc = "`write(|w| ..)` method takes [fdcan_cccr::W](fdcan_cccr::W) writer structure"]
impl crate::Writable for FDCAN_CCCR {}
#[doc = "FDCAN CC Control Register"]
pub mod fdcan_cccr;
#[doc = "FDCAN Nominal Bit Timing and Prescaler Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_nbtp](fdcan_nbtp) module"]
pub type FDCAN_NBTP = crate::Reg<u32, _FDCAN_NBTP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_NBTP;
#[doc = "`read()` method returns [fdcan_nbtp::R](fdcan_nbtp::R) reader structure"]
impl crate::Readable for FDCAN_NBTP {}
#[doc = "`write(|w| ..)` method takes [fdcan_nbtp::W](fdcan_nbtp::W) writer structure"]
impl crate::Writable for FDCAN_NBTP {}
#[doc = "FDCAN Nominal Bit Timing and Prescaler Register"]
pub mod fdcan_nbtp;
#[doc = "FDCAN Timestamp Counter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tscc](fdcan_tscc) module"]
pub type FDCAN_TSCC = crate::Reg<u32, _FDCAN_TSCC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TSCC;
#[doc = "`read()` method returns [fdcan_tscc::R](fdcan_tscc::R) reader structure"]
impl crate::Readable for FDCAN_TSCC {}
#[doc = "`write(|w| ..)` method takes [fdcan_tscc::W](fdcan_tscc::W) writer structure"]
impl crate::Writable for FDCAN_TSCC {}
#[doc = "FDCAN Timestamp Counter Configuration Register"]
pub mod fdcan_tscc;
#[doc = "FDCAN Timestamp Counter Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tscv](fdcan_tscv) module"]
pub type FDCAN_TSCV = crate::Reg<u32, _FDCAN_TSCV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TSCV;
#[doc = "`read()` method returns [fdcan_tscv::R](fdcan_tscv::R) reader structure"]
impl crate::Readable for FDCAN_TSCV {}
#[doc = "`write(|w| ..)` method takes [fdcan_tscv::W](fdcan_tscv::W) writer structure"]
impl crate::Writable for FDCAN_TSCV {}
#[doc = "FDCAN Timestamp Counter Value Register"]
pub mod fdcan_tscv;
#[doc = "FDCAN Timeout Counter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tocc](fdcan_tocc) module"]
pub type FDCAN_TOCC = crate::Reg<u32, _FDCAN_TOCC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TOCC;
#[doc = "`read()` method returns [fdcan_tocc::R](fdcan_tocc::R) reader structure"]
impl crate::Readable for FDCAN_TOCC {}
#[doc = "`write(|w| ..)` method takes [fdcan_tocc::W](fdcan_tocc::W) writer structure"]
impl crate::Writable for FDCAN_TOCC {}
#[doc = "FDCAN Timeout Counter Configuration Register"]
pub mod fdcan_tocc;
#[doc = "FDCAN Timeout Counter Value Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tocv](fdcan_tocv) module"]
pub type FDCAN_TOCV = crate::Reg<u32, _FDCAN_TOCV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TOCV;
#[doc = "`read()` method returns [fdcan_tocv::R](fdcan_tocv::R) reader structure"]
impl crate::Readable for FDCAN_TOCV {}
#[doc = "`write(|w| ..)` method takes [fdcan_tocv::W](fdcan_tocv::W) writer structure"]
impl crate::Writable for FDCAN_TOCV {}
#[doc = "FDCAN Timeout Counter Value Register"]
pub mod fdcan_tocv;
#[doc = "FDCAN Error Counter Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ecr](fdcan_ecr) module"]
pub type FDCAN_ECR = crate::Reg<u32, _FDCAN_ECR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_ECR;
#[doc = "`read()` method returns [fdcan_ecr::R](fdcan_ecr::R) reader structure"]
impl crate::Readable for FDCAN_ECR {}
#[doc = "`write(|w| ..)` method takes [fdcan_ecr::W](fdcan_ecr::W) writer structure"]
impl crate::Writable for FDCAN_ECR {}
#[doc = "FDCAN Error Counter Register"]
pub mod fdcan_ecr;
#[doc = "FDCAN Protocol Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_psr](fdcan_psr) module"]
pub type FDCAN_PSR = crate::Reg<u32, _FDCAN_PSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_PSR;
#[doc = "`read()` method returns [fdcan_psr::R](fdcan_psr::R) reader structure"]
impl crate::Readable for FDCAN_PSR {}
#[doc = "`write(|w| ..)` method takes [fdcan_psr::W](fdcan_psr::W) writer structure"]
impl crate::Writable for FDCAN_PSR {}
#[doc = "FDCAN Protocol Status Register"]
pub mod fdcan_psr;
#[doc = "FDCAN Transmitter Delay Compensation Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_tdcr](fdcan_tdcr) module"]
pub type FDCAN_TDCR = crate::Reg<u32, _FDCAN_TDCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TDCR;
#[doc = "`read()` method returns [fdcan_tdcr::R](fdcan_tdcr::R) reader structure"]
impl crate::Readable for FDCAN_TDCR {}
#[doc = "`write(|w| ..)` method takes [fdcan_tdcr::W](fdcan_tdcr::W) writer structure"]
impl crate::Writable for FDCAN_TDCR {}
#[doc = "FDCAN Transmitter Delay Compensation Register"]
pub mod fdcan_tdcr;
#[doc = "FDCAN Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ir](fdcan_ir) module"]
pub type FDCAN_IR = crate::Reg<u32, _FDCAN_IR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_IR;
#[doc = "`read()` method returns [fdcan_ir::R](fdcan_ir::R) reader structure"]
impl crate::Readable for FDCAN_IR {}
#[doc = "`write(|w| ..)` method takes [fdcan_ir::W](fdcan_ir::W) writer structure"]
impl crate::Writable for FDCAN_IR {}
#[doc = "FDCAN Interrupt Register"]
pub mod fdcan_ir;
#[doc = "FDCAN Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ie](fdcan_ie) module"]
pub type FDCAN_IE = crate::Reg<u32, _FDCAN_IE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_IE;
#[doc = "`read()` method returns [fdcan_ie::R](fdcan_ie::R) reader structure"]
impl crate::Readable for FDCAN_IE {}
#[doc = "`write(|w| ..)` method takes [fdcan_ie::W](fdcan_ie::W) writer structure"]
impl crate::Writable for FDCAN_IE {}
#[doc = "FDCAN Interrupt Enable Register"]
pub mod fdcan_ie;
#[doc = "FDCAN Interrupt Line Select Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ils](fdcan_ils) module"]
pub type FDCAN_ILS = crate::Reg<u32, _FDCAN_ILS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_ILS;
#[doc = "`read()` method returns [fdcan_ils::R](fdcan_ils::R) reader structure"]
impl crate::Readable for FDCAN_ILS {}
#[doc = "`write(|w| ..)` method takes [fdcan_ils::W](fdcan_ils::W) writer structure"]
impl crate::Writable for FDCAN_ILS {}
#[doc = "FDCAN Interrupt Line Select Register"]
pub mod fdcan_ils;
#[doc = "FDCAN Interrupt Line Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ile](fdcan_ile) module"]
pub type FDCAN_ILE = crate::Reg<u32, _FDCAN_ILE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_ILE;
#[doc = "`read()` method returns [fdcan_ile::R](fdcan_ile::R) reader structure"]
impl crate::Readable for FDCAN_ILE {}
#[doc = "`write(|w| ..)` method takes [fdcan_ile::W](fdcan_ile::W) writer structure"]
impl crate::Writable for FDCAN_ILE {}
#[doc = "FDCAN Interrupt Line Enable Register"]
pub mod fdcan_ile;
#[doc = "FDCAN Global Filter Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxgfc](fdcan_rxgfc) module"]
pub type FDCAN_RXGFC = crate::Reg<u32, _FDCAN_RXGFC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RXGFC;
#[doc = "`read()` method returns [fdcan_rxgfc::R](fdcan_rxgfc::R) reader structure"]
impl crate::Readable for FDCAN_RXGFC {}
#[doc = "`write(|w| ..)` method takes [fdcan_rxgfc::W](fdcan_rxgfc::W) writer structure"]
impl crate::Writable for FDCAN_RXGFC {}
#[doc = "FDCAN Global Filter Configuration Register"]
pub mod fdcan_rxgfc;
#[doc = "FDCAN Extended ID and Mask Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_xidam](fdcan_xidam) module"]
pub type FDCAN_XIDAM = crate::Reg<u32, _FDCAN_XIDAM>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_XIDAM;
#[doc = "`read()` method returns [fdcan_xidam::R](fdcan_xidam::R) reader structure"]
impl crate::Readable for FDCAN_XIDAM {}
#[doc = "`write(|w| ..)` method takes [fdcan_xidam::W](fdcan_xidam::W) writer structure"]
impl crate::Writable for FDCAN_XIDAM {}
#[doc = "FDCAN Extended ID and Mask Register"]
pub mod fdcan_xidam;
#[doc = "FDCAN High Priority Message Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_hpms](fdcan_hpms) module"]
pub type FDCAN_HPMS = crate::Reg<u32, _FDCAN_HPMS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_HPMS;
#[doc = "`read()` method returns [fdcan_hpms::R](fdcan_hpms::R) reader structure"]
impl crate::Readable for FDCAN_HPMS {}
#[doc = "FDCAN High Priority Message Status Register"]
pub mod fdcan_hpms;
#[doc = "FDCAN Rx FIFO 0 Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf0s](fdcan_rxf0s) module"]
pub type FDCAN_RXF0S = crate::Reg<u32, _FDCAN_RXF0S>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RXF0S;
#[doc = "`read()` method returns [fdcan_rxf0s::R](fdcan_rxf0s::R) reader structure"]
impl crate::Readable for FDCAN_RXF0S {}
#[doc = "`write(|w| ..)` method takes [fdcan_rxf0s::W](fdcan_rxf0s::W) writer structure"]
impl crate::Writable for FDCAN_RXF0S {}
#[doc = "FDCAN Rx FIFO 0 Status Register"]
pub mod fdcan_rxf0s;
#[doc = "CAN Rx FIFO 0 Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf0a](fdcan_rxf0a) module"]
pub type FDCAN_RXF0A = crate::Reg<u32, _FDCAN_RXF0A>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RXF0A;
#[doc = "`read()` method returns [fdcan_rxf0a::R](fdcan_rxf0a::R) reader structure"]
impl crate::Readable for FDCAN_RXF0A {}
#[doc = "`write(|w| ..)` method takes [fdcan_rxf0a::W](fdcan_rxf0a::W) writer structure"]
impl crate::Writable for FDCAN_RXF0A {}
#[doc = "CAN Rx FIFO 0 Acknowledge Register"]
pub mod fdcan_rxf0a;
#[doc = "FDCAN Rx FIFO 1 Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf1s](fdcan_rxf1s) module"]
pub type FDCAN_RXF1S = crate::Reg<u32, _FDCAN_RXF1S>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RXF1S;
#[doc = "`read()` method returns [fdcan_rxf1s::R](fdcan_rxf1s::R) reader structure"]
impl crate::Readable for FDCAN_RXF1S {}
#[doc = "`write(|w| ..)` method takes [fdcan_rxf1s::W](fdcan_rxf1s::W) writer structure"]
impl crate::Writable for FDCAN_RXF1S {}
#[doc = "FDCAN Rx FIFO 1 Status Register"]
pub mod fdcan_rxf1s;
#[doc = "FDCAN Rx FIFO 1 Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_rxf1a](fdcan_rxf1a) module"]
pub type FDCAN_RXF1A = crate::Reg<u32, _FDCAN_RXF1A>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_RXF1A;
#[doc = "`read()` method returns [fdcan_rxf1a::R](fdcan_rxf1a::R) reader structure"]
impl crate::Readable for FDCAN_RXF1A {}
#[doc = "`write(|w| ..)` method takes [fdcan_rxf1a::W](fdcan_rxf1a::W) writer structure"]
impl crate::Writable for FDCAN_RXF1A {}
#[doc = "FDCAN Rx FIFO 1 Acknowledge Register"]
pub mod fdcan_rxf1a;
#[doc = "FDCAN Tx FIFO/Queue Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txfqs](fdcan_txfqs) module"]
pub type FDCAN_TXFQS = crate::Reg<u32, _FDCAN_TXFQS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXFQS;
#[doc = "`read()` method returns [fdcan_txfqs::R](fdcan_txfqs::R) reader structure"]
impl crate::Readable for FDCAN_TXFQS {}
#[doc = "FDCAN Tx FIFO/Queue Status Register"]
pub mod fdcan_txfqs;
#[doc = "FDCAN Tx Buffer Request Pending Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbrp](fdcan_txbrp) module"]
pub type FDCAN_TXBRP = crate::Reg<u32, _FDCAN_TXBRP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBRP;
#[doc = "`read()` method returns [fdcan_txbrp::R](fdcan_txbrp::R) reader structure"]
impl crate::Readable for FDCAN_TXBRP {}
#[doc = "FDCAN Tx Buffer Request Pending Register"]
pub mod fdcan_txbrp;
#[doc = "FDCAN Tx Buffer Add Request Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbar](fdcan_txbar) module"]
pub type FDCAN_TXBAR = crate::Reg<u32, _FDCAN_TXBAR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBAR;
#[doc = "`read()` method returns [fdcan_txbar::R](fdcan_txbar::R) reader structure"]
impl crate::Readable for FDCAN_TXBAR {}
#[doc = "`write(|w| ..)` method takes [fdcan_txbar::W](fdcan_txbar::W) writer structure"]
impl crate::Writable for FDCAN_TXBAR {}
#[doc = "FDCAN Tx Buffer Add Request Register"]
pub mod fdcan_txbar;
#[doc = "FDCAN Tx Buffer Cancellation Request Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcr](fdcan_txbcr) module"]
pub type FDCAN_TXBCR = crate::Reg<u32, _FDCAN_TXBCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBCR;
#[doc = "`read()` method returns [fdcan_txbcr::R](fdcan_txbcr::R) reader structure"]
impl crate::Readable for FDCAN_TXBCR {}
#[doc = "`write(|w| ..)` method takes [fdcan_txbcr::W](fdcan_txbcr::W) writer structure"]
impl crate::Writable for FDCAN_TXBCR {}
#[doc = "FDCAN Tx Buffer Cancellation Request Register"]
pub mod fdcan_txbcr;
#[doc = "FDCAN Tx Buffer Transmission Occurred Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbto](fdcan_txbto) module"]
pub type FDCAN_TXBTO = crate::Reg<u32, _FDCAN_TXBTO>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBTO;
#[doc = "`read()` method returns [fdcan_txbto::R](fdcan_txbto::R) reader structure"]
impl crate::Readable for FDCAN_TXBTO {}
#[doc = "FDCAN Tx Buffer Transmission Occurred Register"]
pub mod fdcan_txbto;
#[doc = "FDCAN Tx Buffer Cancellation Finished Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcf](fdcan_txbcf) module"]
pub type FDCAN_TXBCF = crate::Reg<u32, _FDCAN_TXBCF>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBCF;
#[doc = "`read()` method returns [fdcan_txbcf::R](fdcan_txbcf::R) reader structure"]
impl crate::Readable for FDCAN_TXBCF {}
#[doc = "FDCAN Tx Buffer Cancellation Finished Register"]
pub mod fdcan_txbcf;
#[doc = "FDCAN Tx Buffer Transmission Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbtie](fdcan_txbtie) module"]
pub type FDCAN_TXBTIE = crate::Reg<u32, _FDCAN_TXBTIE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBTIE;
#[doc = "`read()` method returns [fdcan_txbtie::R](fdcan_txbtie::R) reader structure"]
impl crate::Readable for FDCAN_TXBTIE {}
#[doc = "`write(|w| ..)` method takes [fdcan_txbtie::W](fdcan_txbtie::W) writer structure"]
impl crate::Writable for FDCAN_TXBTIE {}
#[doc = "FDCAN Tx Buffer Transmission Interrupt Enable Register"]
pub mod fdcan_txbtie;
#[doc = "FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbcie](fdcan_txbcie) module"]
pub type FDCAN_TXBCIE = crate::Reg<u32, _FDCAN_TXBCIE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBCIE;
#[doc = "`read()` method returns [fdcan_txbcie::R](fdcan_txbcie::R) reader structure"]
impl crate::Readable for FDCAN_TXBCIE {}
#[doc = "`write(|w| ..)` method takes [fdcan_txbcie::W](fdcan_txbcie::W) writer structure"]
impl crate::Writable for FDCAN_TXBCIE {}
#[doc = "FDCAN Tx Buffer Cancellation Finished Interrupt Enable Register"]
pub mod fdcan_txbcie;
#[doc = "FDCAN Tx Event FIFO Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txefs](fdcan_txefs) module"]
pub type FDCAN_TXEFS = crate::Reg<u32, _FDCAN_TXEFS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXEFS;
#[doc = "`read()` method returns [fdcan_txefs::R](fdcan_txefs::R) reader structure"]
impl crate::Readable for FDCAN_TXEFS {}
#[doc = "FDCAN Tx Event FIFO Status Register"]
pub mod fdcan_txefs;
#[doc = "FDCAN Tx Event FIFO Acknowledge Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txefa](fdcan_txefa) module"]
pub type FDCAN_TXEFA = crate::Reg<u32, _FDCAN_TXEFA>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXEFA;
#[doc = "`read()` method returns [fdcan_txefa::R](fdcan_txefa::R) reader structure"]
impl crate::Readable for FDCAN_TXEFA {}
#[doc = "`write(|w| ..)` method takes [fdcan_txefa::W](fdcan_txefa::W) writer structure"]
impl crate::Writable for FDCAN_TXEFA {}
#[doc = "FDCAN Tx Event FIFO Acknowledge Register"]
pub mod fdcan_txefa;
#[doc = "FDCAN TT Trigger Memory Configuration Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_ckdiv](fdcan_ckdiv) module"]
pub type FDCAN_CKDIV = crate::Reg<u32, _FDCAN_CKDIV>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_CKDIV;
#[doc = "`read()` method returns [fdcan_ckdiv::R](fdcan_ckdiv::R) reader structure"]
impl crate::Readable for FDCAN_CKDIV {}
#[doc = "`write(|w| ..)` method takes [fdcan_ckdiv::W](fdcan_ckdiv::W) writer structure"]
impl crate::Writable for FDCAN_CKDIV {}
#[doc = "FDCAN TT Trigger Memory Configuration Register"]
pub mod fdcan_ckdiv;
#[doc = "FDCAN Tx buffer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fdcan_txbc](fdcan_txbc) module"]
pub type FDCAN_TXBC = crate::Reg<u32, _FDCAN_TXBC>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FDCAN_TXBC;
#[doc = "`read()` method returns [fdcan_txbc::R](fdcan_txbc::R) reader structure"]
impl crate::Readable for FDCAN_TXBC {}
#[doc = "`write(|w| ..)` method takes [fdcan_txbc::W](fdcan_txbc::W) writer structure"]
impl crate::Writable for FDCAN_TXBC {}
#[doc = "FDCAN Tx buffer configuration register"]
pub mod fdcan_txbc;
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
#[macro_use] extern crate likely;
extern crate linux_epoll;
extern crate treebitmap;
use self::access_control::*;
use ::linux_epoll::libc::gid_t;
use ::linux_epoll::libc::uid_t;
use ::linux_epoll::*;
use ::linux_epoll::arena::*;
use ::linux_epoll::cpu_affinity::LogicalCores;
use ::linux_epoll::file_descriptors::epoll::*;
use ::linux_epoll::file_descriptors::socket::*;
use ::linux_epoll::file_descriptors::socket::syscall::sockaddr_in;
use ::linux_epoll::file_descriptors::socket::syscall::sockaddr_in6;
use ::linux_epoll::file_descriptors::socket::syscall::sockaddr_un;
use ::linux_epoll::hashbrown::*;
use ::linux_epoll::message_dispatch::QueuePerThreadQueuesPublisher;
use ::linux_epoll::reactor::*;
use ::std::fmt;
use ::std::fmt::Debug;
use ::std::fmt::Formatter;
use ::std::mem::transmute;
use ::std::hash::Hash;
use ::std::net::Ipv4Addr;
use ::std::net::Ipv6Addr;
use ::std::net::SocketAddrV4;
use ::std::net::SocketAddrV6;
use ::std::ops::Deref;
use ::std::ops::DerefMut;
use ::std::path::PathBuf;
use ::std::ptr::NonNull;
use ::std::ptr::write;
use ::std::rc::Rc;
use ::std::sync::Arc;
use ::treebitmap::IpLookupTable;
/// Access control for streaming sockets.
pub mod access_control;
include!("AcceptedStreamingSocketMessage.rs");
include!("streaming_server_listener_reactor.rs");
include!("StreamingServerListenerSocketCommon.rs");
include!("StreamingServerListenerSocketInternetProtocolVersion4Reactor.rs");
include!("StreamingServerListenerSocketInternetProtocolVersion6Reactor.rs");
include!("StreamingServerListenerSocketReactor.rs");
include!("StreamingServerListenerSocketSettings.rs");
include!("StreamingServerListenerSocketUnixDomainReactor.rs");
include!("UnixDomainSocketAddress.rs");
|
// Advent of Code: Day 9
//
// We have an encrypted file that's a sequence of numbers. We're trying
// to break the encryption and in order to do so, we have to find the
// first number in the sequence (after the preamble) that is not the sum
// of two of the values in the previous preamble-length window. For the
// test input, the preamble length is 5, and we're trying to find the
// first number after the first 5 for which the number is not the sum
// of two of the numbers in the previous group of 5. For the test input
// the answer is 127.
//
// Part 2:
//
// We now want to find a group of consecutive number entries in the list
// which add up to our number that we found in part 1. Then we want to
// get the minimum and maximum numbers from that group and add them
// together for our answer. For the test input the answer is 62.
//
// Usage cargo run <input-file> <preamble-length>
use std::{env, fs::File, io::BufRead, io::BufReader};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
println!("Usage: cargo run <input-file> <preamble-length>");
return;
}
let input_file = &args[1];
let preamble_length: usize = args[2]
.parse()
.expect("preamble length must be a positive integer");
let file = File::open(input_file).expect("no such file");
let buf = BufReader::new(file);
let lines: Vec<usize> = buf
.lines()
.map(|l| l.expect("could not parse line"))
.map(|s| s.parse().expect("must be a positive integer"))
.collect();
let mut n: &usize = &0;
for i in preamble_length..lines.len() {
let window = &lines[(i - preamble_length)..i];
n = &lines[i];
if !sum_of_two_in_window(n, window) {
println!("The number that doesn't follow the pattern is {}", n);
break;
}
}
let mut start: usize = 0;
let mut end: usize = 0;
for i in 0..lines.len() {
let mut sum: usize = lines[i];
for j in (i + 1)..lines.len() {
sum += lines[j];
if sum >= *n {
start = i;
end = j;
break;
}
}
if sum == *n {
let range = &lines[start..=end];
let min = range.iter().min().unwrap();
let max = range.iter().max().unwrap();
println!("The answer for part 2 is {}", min + max);
break;
}
}
}
fn sum_of_two_in_window(n: &usize, window: &[usize]) -> bool {
for i in 0..window.len() {
let a = &window[i];
for j in 0..window.len() {
if j == i {
continue;
}
let b = &window[j];
if a + b == *n {
return true;
}
}
}
return false;
}
|
use arrow::datatypes::DataType;
use arrow_flight::{error::FlightError, Ticket};
use arrow_util::assert_batches_sorted_eq;
use data_types::{NamespaceId, TableId};
use datafusion::{
prelude::{col, lit},
scalar::ScalarValue,
};
use futures::FutureExt;
use http::StatusCode;
use influxdb_iox_client::table::generated_types::{Part, PartitionTemplate, TemplatePart};
use ingester_query_grpc::{influxdata::iox::ingester::v1 as proto, IngesterQueryRequest};
use prost::Message;
use test_helpers_end_to_end::{maybe_skip_integration, MiniCluster, Step, StepTest, StepTestState};
#[tokio::test]
async fn persist_on_demand() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
let table_name = "mytable";
let mut cluster = MiniCluster::create_shared_never_persist(database_url).await;
StepTest::new(
&mut cluster,
vec![
Step::RecordNumParquetFiles,
Step::WriteLineProtocol(format!("{table_name},tag1=A,tag2=B val=42i 123456")),
Step::Custom(Box::new(move |state: &mut StepTestState| {
async move {
// query the ingester
let query = IngesterQueryRequest::new(
state.cluster().namespace_id().await,
state.cluster().table_id(table_name).await,
vec![],
Some(::predicate::EMPTY_PREDICATE),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let ingester_response = state
.cluster()
.query_ingester(
query,
state.cluster().ingester().ingester_grpc_connection(),
)
.await
.unwrap();
assert_eq!(ingester_response.partitions.len(), 1);
let ingester_partition = ingester_response
.partitions
.into_iter()
.next()
.expect("just checked len");
let ingester_uuid = ingester_partition.app_metadata.ingester_uuid;
assert!(!ingester_uuid.is_empty());
let expected = [
"+------+------+--------------------------------+-----+",
"| tag1 | tag2 | time | val |",
"+------+------+--------------------------------+-----+",
"| A | B | 1970-01-01T00:00:00.000123456Z | 42 |",
"+------+------+--------------------------------+-----+",
];
assert_batches_sorted_eq!(&expected, &ingester_partition.record_batches);
}
.boxed()
})),
Step::Persist,
Step::WaitForPersisted {
expected_increase: 1,
},
// Ensure the ingester responds with the correct file count to tell the querier
// it needs to expire its catalog cache
Step::Custom(Box::new(move |state: &mut StepTestState| {
async move {
let query = IngesterQueryRequest::new(
state.cluster().namespace_id().await,
state.cluster().table_id(table_name).await,
vec![],
Some(::predicate::EMPTY_PREDICATE),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let ingester_response = state
.cluster()
.query_ingester(
query.clone(),
state.cluster().ingester().ingester_grpc_connection(),
)
.await
.unwrap();
assert_eq!(ingester_response.partitions.len(), 1);
let ingester_partition = ingester_response
.partitions
.into_iter()
.next()
.expect("just checked len");
let num_files_persisted =
ingester_partition.app_metadata.completed_persistence_count;
assert_eq!(num_files_persisted, 1);
}
.boxed()
})),
],
)
.run()
.await
}
#[tokio::test]
async fn ingester_flight_api() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
let table_name = "mytable";
// Set up cluster
// Don't use a shared cluster because the ingester is going to be restarted
let mut cluster = MiniCluster::create_non_shared(database_url).await;
// Write some data into the v2 HTTP API to set up the namespace and schema ==============
let lp = format!("{table_name},tag1=A,tag2=B val=42i 123456");
let response = cluster.write_to_router(lp, None).await;
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// Write some data directly into the ingester through its gRPC API
let lp = format!("{table_name},tag1=B,tag2=A val=84i 1234567");
cluster.write_to_ingester(lp, table_name).await;
// query the ingester
let query = IngesterQueryRequest::new(
cluster.namespace_id().await,
cluster.table_id(table_name).await,
vec![],
Some(::predicate::EMPTY_PREDICATE),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let ingester_response = cluster
.query_ingester(query.clone(), cluster.ingester().ingester_grpc_connection())
.await
.unwrap();
assert_eq!(ingester_response.partitions.len(), 1);
let ingester_partition = ingester_response
.partitions
.into_iter()
.next()
.expect("just checked len");
let ingester_uuid = ingester_partition.app_metadata.ingester_uuid.clone();
assert!(!ingester_uuid.is_empty());
let schema = ingester_partition.schema.unwrap();
let expected = [
"+------+------+--------------------------------+-----+",
"| tag1 | tag2 | time | val |",
"+------+------+--------------------------------+-----+",
"| A | B | 1970-01-01T00:00:00.000123456Z | 42 |",
"| B | A | 1970-01-01T00:00:00.001234567Z | 84 |",
"+------+------+--------------------------------+-----+",
];
assert_batches_sorted_eq!(&expected, &ingester_partition.record_batches);
// Also ensure that the schema of the batches matches what is
// reported by the performed_query.
ingester_partition
.record_batches
.iter()
.enumerate()
.for_each(|(i, b)| {
assert_eq!(schema, b.schema(), "Schema mismatch for returned batch {i}");
});
// Ensure the ingester UUID is the same in the next query
let ingester_response = cluster
.query_ingester(query.clone(), cluster.ingester().ingester_grpc_connection())
.await
.unwrap();
assert_eq!(ingester_response.partitions.len(), 1);
let ingester_partition = ingester_response
.partitions
.into_iter()
.next()
.expect("just checked len");
assert_eq!(ingester_partition.app_metadata.ingester_uuid, ingester_uuid);
// Restart the ingesters
cluster.restart_ingesters().await;
// Populate the ingester with some data so it returns a successful
// response containing the UUID.
let lp = format!("{table_name},tag1=A,tag2=B val=42i 123456");
cluster.write_to_ingester(lp, table_name).await;
// Query for the new UUID and assert it has changed.
let ingester_response = cluster
.query_ingester(query, cluster.ingester().ingester_grpc_connection())
.await
.unwrap();
assert_eq!(ingester_response.partitions.len(), 1);
let ingester_partition = ingester_response
.partitions
.into_iter()
.next()
.expect("just checked len");
assert_ne!(ingester_partition.app_metadata.ingester_uuid, ingester_uuid);
}
#[tokio::test]
async fn ingester_partition_pruning() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
// Set up cluster
let mut cluster = MiniCluster::create_shared_never_persist(database_url).await;
let mut steps: Vec<_> = vec![Step::Custom(Box::new(move |state: &mut StepTestState| {
async move {
let namespace_name = state.cluster().namespace();
let mut namespace_client = influxdb_iox_client::namespace::Client::new(
state.cluster().router().router_grpc_connection(),
);
namespace_client
.create_namespace(
namespace_name,
None,
None,
Some(PartitionTemplate {
parts: vec![
TemplatePart {
part: Some(Part::TagValue("tag1".into())),
},
TemplatePart {
part: Some(Part::TagValue("tag3".into())),
},
],
}),
)
.await
.unwrap();
let mut table_client = influxdb_iox_client::table::Client::new(
state.cluster().router().router_grpc_connection(),
);
// table1: create implicitly by writing to it
// table2: do not override partition template => use namespace template
table_client
.create_table(namespace_name, "table2", None)
.await
.unwrap();
// table3: overide namespace template
table_client
.create_table(
namespace_name,
"table3",
Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(Part::TagValue("tag2".into())),
}],
}),
)
.await
.unwrap();
}
.boxed()
}))]
.into_iter()
.chain((1..=3).flat_map(|tid| {
[Step::WriteLineProtocol(
[
format!("table{tid},tag1=v1a,tag2=v2a,tag3=v3a f=1 11"),
format!("table{tid},tag1=v1b,tag2=v2a,tag3=v3a f=1 11"),
format!("table{tid},tag1=v1a,tag2=v2b,tag3=v3a f=1 11"),
format!("table{tid},tag1=v1b,tag2=v2b,tag3=v3a f=1 11"),
format!("table{tid},tag1=v1a,tag2=v2a,tag3=v3b f=1 11"),
format!("table{tid},tag1=v1b,tag2=v2a,tag3=v3b f=1 11"),
format!("table{tid},tag1=v1a,tag2=v2b,tag3=v3b f=1 11"),
format!("table{tid},tag1=v1b,tag2=v2b,tag3=v3b f=1 11"),
]
.join("\n"),
)]
.into_iter()
}))
.collect();
steps.push(Step::Custom(Box::new(move |state: &mut StepTestState| {
async move {
// Note: The querier will perform correct type coercion. We must simulate this here, otherwise the ingester
// will NOT be able to prune the data because the predicate evaluation will fail with a type error
// and the predicate will be ignored.
let predicate = ::predicate::Predicate::new().with_expr(col("tag1").eq(lit(
ScalarValue::Dictionary(
Box::new(DataType::Int32),
Box::new(ScalarValue::from("v1a")),
),
)));
let query = IngesterQueryRequest::new(
state.cluster().namespace_id().await,
state.cluster().table_id("table1").await,
vec![],
Some(predicate),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let ingester_response = state
.cluster()
.query_ingester(
query.clone(),
state.cluster().ingester().ingester_grpc_connection(),
)
.await
.unwrap();
let expected = [
"+-----+------+------+------+--------------------------------+",
"| f | tag1 | tag2 | tag3 | time |",
"+-----+------+------+------+--------------------------------+",
"| 1.0 | v1a | v2a | v3a | 1970-01-01T00:00:00.000000011Z |",
"| 1.0 | v1a | v2a | v3b | 1970-01-01T00:00:00.000000011Z |",
"| 1.0 | v1a | v2b | v3a | 1970-01-01T00:00:00.000000011Z |",
"| 1.0 | v1a | v2b | v3b | 1970-01-01T00:00:00.000000011Z |",
"+-----+------+------+------+--------------------------------+",
];
let record_batches = ingester_response
.partitions
.into_iter()
.flat_map(|p| p.record_batches)
.collect::<Vec<_>>();
assert_batches_sorted_eq!(&expected, &record_batches);
}
.boxed()
})));
StepTest::new(&mut cluster, steps).run().await
}
#[tokio::test]
async fn ingester_flight_api_namespace_not_found() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
// Set up cluster
let cluster = MiniCluster::create_shared(database_url).await;
// query the ingester
let query = IngesterQueryRequest::new(
NamespaceId::new(i64::MAX),
TableId::new(42),
vec![],
Some(::predicate::EMPTY_PREDICATE),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let err = cluster
.query_ingester(query, cluster.ingester().ingester_grpc_connection())
.await
.unwrap_err();
if let FlightError::Tonic(status) = err {
assert_eq!(status.code(), tonic::Code::NotFound);
} else {
panic!("Wrong error variant: {err}")
}
}
#[tokio::test]
async fn ingester_flight_api_table_not_found() {
test_helpers::maybe_start_logging();
let database_url = maybe_skip_integration!();
// Set up cluster
let cluster = MiniCluster::create_shared(database_url).await;
// Write some data into the v2 HTTP API ==============
let lp = String::from("my_table,tag1=A,tag2=B val=42i 123456");
let response = cluster.write_to_router(lp, None).await;
assert_eq!(response.status(), StatusCode::NO_CONTENT);
let mut querier_flight =
influxdb_iox_client::flight::Client::new(cluster.ingester().ingester_grpc_connection())
.into_inner();
let query = IngesterQueryRequest::new(
cluster.namespace_id().await,
TableId::new(i64::MAX),
vec![],
Some(::predicate::EMPTY_PREDICATE),
);
let query: proto::IngesterQueryRequest = query.try_into().unwrap();
let ticket = Ticket {
ticket: query.encode_to_vec().into(),
};
let err = querier_flight.do_get(ticket).await.unwrap_err();
if let FlightError::Tonic(status) = err {
assert_eq!(status.code(), tonic::Code::NotFound);
} else {
panic!("Wrong error variant: {err}")
}
}
|
// Various tests related to testing how region inference works
// with respect to the object receivers.
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
trait Foo {
fn borrowed<'a>(&'a self) -> &'a ();
}
// Borrowed receiver but two distinct lifetimes, we get an error.
fn borrowed_receiver_different_lifetimes<'a,'b>(x: &'a dyn Foo) -> &'b () {
x.borrowed()
//[base]~^ ERROR cannot infer
//[nll]~^^ ERROR lifetime may not live long enough
}
fn main() {}
|
//! linux_raw syscalls for PIDs
//!
//! # Safety
//!
//! See the `rustix::backend` module documentation for details.
#![allow(unsafe_code)]
#![allow(clippy::undocumented_unsafe_blocks)]
use crate::backend::conv::ret_usize_infallible;
use crate::pid::{Pid, RawPid};
#[inline]
pub(crate) fn getpid() -> Pid {
unsafe {
let pid = ret_usize_infallible(syscall_readonly!(__NR_getpid)) as RawPid;
Pid::from_raw_unchecked(pid)
}
}
|
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use structopt::StructOpt;
use csv::{Reader, ReaderBuilder};
use serde_json::to_string;
pub type Value = serde_json::Value;
pub type Map = serde_json::Map<String, Value>;
#[async_std::main]
async fn main() -> Result<(), csv::Error> {
let opt = Opt::from_args();
let mut left = from_path(opt.left).await?;
let mut right = from_path(opt.right).await?;
let mut left_value = load(&mut left, 1).await?.pop().unwrap();
let mut right_value = load(&mut right, 1).await?.pop().unwrap();
loop {
if left_value.is_null() && right_value.is_null() {
return Ok(());
}
if left_value.is_null() {
println!("lmiss,{},{}", "", id(&right_value));
if let Some(v) = load(&mut right, 1).await?.pop() {
right_value = v;
} else {
right_value = Value::Null;
}
} else if right_value.is_null() {
println!("rmiss,{},{}", id(&left_value), "");
if let Some(v) = load(&mut left, 1).await?.pop() {
left_value = v;
} else {
left_value = Value::Null;
}
} else if id(&left_value) == id(&right_value) {
println!("eq,{},{}", id(&left_value), id(&right_value));
if let Some(v) = load(&mut left, 1).await?.pop() {
left_value = v;
} else {
left_value = Value::Null;
}
if let Some(v) = load(&mut right, 1).await?.pop() {
right_value = v;
} else {
right_value = Value::Null;
}
} else if id(&left_value) < id(&right_value) {
println!("rmiss,{},{}", id(&left_value), "");
if let Some(v) = load(&mut left, 1).await?.pop() {
left_value = v;
} else {
left_value = Value::Null;
}
} else if id(&left_value) > id(&right_value) {
println!("lmiss,{},{}", "", id(&right_value));
if let Some(v) = load(&mut right, 1).await?.pop() {
right_value = v;
} else {
right_value = Value::Null;
}
}
}
}
fn id(value: &Value) -> String {
value["id"].as_str().unwrap().to_string()
}
async fn load<R: std::io::Read>(
reader: &mut Reader<R>,
size: usize,
) -> Result<Vec<Value>, csv::Error> {
let mut hashmap_vec = Vec::new();
let mut curr_size = 0;
for result in reader.deserialize() {
let result: Map = result?;
let mut record: Map = Map::new();
//data fields must all be string
for (k, v) in result {
if v.is_string() {
record.insert(k, v);
} else {
record.insert(k, Value::String(to_string(&v).unwrap()));
}
}
hashmap_vec.push(Value::Object(record));
curr_size += 1;
if curr_size == size {
break;
}
}
Ok(hashmap_vec)
}
async fn from_path<P: AsRef<Path>>(path: P) -> Result<Reader<File>, csv::Error> {
ReaderBuilder::new().from_path(path)
}
#[derive(StructOpt, Debug)]
#[structopt(name = "diff")]
struct Opt {
/// left file
#[structopt(short, long, parse(from_os_str))]
left: PathBuf,
/// right file
#[structopt(short, long, parse(from_os_str))]
right: PathBuf,
}
|
/*
* MIT License
*
* Copyright (c) 2018 Clément SIBILLE
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::rc::Rc;
use std::cell::RefCell;
use sdl2::event::Event as SDLEvent;
use sdl2::video::GLContext;
use tuber::window::{Window, WindowEvent};
mod input;
use crate::input::keyboard::SDLKey;
pub struct SDLWindow {
sdl_window: sdl2::video::Window,
sdl_event_pump: Rc<RefCell<sdl2::EventPump>>,
_gl_context: GLContext,
}
impl SDLWindow {
pub fn new(sdl_video_subsystem: &sdl2::VideoSubsystem,
sdl_event_pump: Rc<RefCell<sdl2::EventPump>>) -> SDLWindow {
let sdl_window = sdl_video_subsystem.window("Untitled Window", 800, 600)
.position_centered()
.opengl()
.build()
.expect("Window creation failed");
let _gl_context = sdl_window.gl_create_context()
.expect("GL context creation failed");
SDLWindow {
sdl_window,
sdl_event_pump,
_gl_context
}
}
}
impl Window for SDLWindow {
fn display(&mut self) {
self.sdl_window.gl_swap_window();
}
fn poll_event(&mut self) -> Option<WindowEvent> {
if let Some(sdl_event) = self.sdl_event_pump.borrow_mut().poll_event() {
return Some(match sdl_event {
SDLEvent::Quit{..} =>
WindowEvent::Close,
SDLEvent::KeyDown{keycode: Some(k), ..} =>
WindowEvent::KeyDown(SDLKey(k).into()),
SDLEvent::KeyUp{keycode: Some(k), ..} =>
WindowEvent::KeyDown(SDLKey(k).into()),
_ =>
WindowEvent::Unknown
});
}
None
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 super::super::linux_def::*;
#[derive(Debug, Copy, Clone)]
#[repr(align(128))]
pub enum HostInputMsg {
FireTimer(FireTimer),
FdNotify(FdNotify),
IOBufWriteResp(IOBufWriteResp),
PrintStrResp(PrintStrResp),
WakeIOThreadResp(()),
}
//host call kernel
#[derive(Debug, Default, Copy, Clone)]
pub struct FireTimer {
pub TimerId: u64,
pub SeqNo: u64,
}
//host call kernel
#[derive(Debug, Default, Copy, Clone)]
pub struct FdNotify {
pub fd: i32,
pub mask: EventMask,
}
#[derive(Debug, Default, Copy, Clone)]
pub struct IOBufWriteResp {
pub fd: i32,
pub addr: u64,
pub len: usize,
pub ret: i64,
}
#[derive(Debug, Default, Copy, Clone)]
pub struct PrintStrResp {
pub addr: u64,
pub len: usize,
} |
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// 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 alloc::sync::Arc;
use spin::RwLock;
use lazy_static::lazy_static;
use core::ops::Deref;
use super::super::super::asm::muldiv64;
use super::super::super::qlib::linux::time::*;
use super::super::super::qlib::metric::*;
use super::super::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::super::super::Kernel::HostSpace;
use super::super::super::asm::*;
use super::sampler::*;
use super::parameters::*;
use super::*;
lazy_static! {
// fallbackMetric tracks failed updates. It is not sync, as it is not critical
// that all occurrences are captured and CalibratedClock may fallback many
// times.
pub static ref FALLBACK_METRIC : Arc<U64Metric> = NewU64Metric("/time/fallback", false,
"Incremented when a clock falls back to system calls due to a failed update");
}
// CalibratedClock implements a clock that tracks a reference clock.
//
// Users should call Update at regular intervals of around approxUpdateInterval
// to ensure that the clock does not drift significantly from the reference
// clock.
pub struct CalibratedClockInternal {
// ref sample the reference clock that this clock is calibrated
// against.
pub sampler: Sampler,
// ready indicates that the fields below are ready for use calculating
// time.
pub ready: bool,
// params are the current timekeeping parameters.
pub params: Parameters,
// errorNS is the estimated clock error in nanoseconds.
pub errorNS: ReferenceNS,
}
impl CalibratedClockInternal {
pub fn resetLocked(&mut self, str: &str) {
info!("{}", str);
self.ready = false;
self.sampler.Reset();
FALLBACK_METRIC.Incr();
}
pub fn updateParams(&mut self, actual: &Parameters) {
if !self.ready {
// At initial calibration there is nothing to correct.
self.params = *actual;
self.ready = true;
return;
}
let (newParams, errorNS) = match ErrorAdjust(&self.params, actual, actual.BaseCycles) {
Ok((n, e)) => (n, e),
Err(err) => {
// Something is very wrong. Reset and try again from the
// beginning.
self.resetLocked(format!("Unable to update params: {:?}.", err).as_str());
return;
}
};
let clockId = self.sampler.clockID;
logErrorAdjustement(clockId, errorNS, &self.params, &newParams);
if Magnitude(errorNS) > MAX_CLOCK_ERROR {
// We should never get such extreme error, something is very
// wrong. Reset everything and start again.
self.resetLocked("Extreme clock error.");
return;
}
self.params = newParams;
self.errorNS = errorNS;
}
}
#[derive(Clone)]
pub struct CalibratedClock(Arc<RwLock<CalibratedClockInternal>>);
impl Deref for CalibratedClock {
type Target = Arc<RwLock<CalibratedClockInternal>>;
fn deref(&self) -> &Arc<RwLock<CalibratedClockInternal>> {
&self.0
}
}
impl CalibratedClock {
pub fn New(c: ClockID) -> Self {
let internal = CalibratedClockInternal {
sampler: Sampler::New(c),
ready: false,
params: Parameters::default(),
errorNS: 0,
};
return Self(Arc::new(RwLock::new(internal)))
}
// reset forces the clock to restart the calibration process, logging the
// passed message.
fn reset(&self, str: &str) {
self.write().resetLocked(str);
}
// Update runs the update step of the clock, updating its synchronization with
// the reference clock.
//
// Update returns timekeeping and true with the new timekeeping parameters if
// the clock is calibrated. Update should be called regularly to prevent the
// clock from getting significantly out of sync from the reference clock.
//
// The returned timekeeping parameters are invalidated on the next call to
// Update.
pub fn Update(&self) -> (Parameters, bool) {
let mut c = self.write();
let sample = c.sampler.Sample();
match sample {
Err(err) => {
c.resetLocked(format!("Unable to update calibrated clock: {:?}.", err).as_str());
return (Parameters::default(), false)
}
Ok(()) => (),
}
let (oldest, newest) = match c.sampler.Range() {
None => return (Parameters::default(), false),
Some((o, n)) => (o, n),
};
let minCount = (newest.Before - oldest.After) as u64;
let maxCount = (newest.After - oldest.Before) as u64;
let refInterval = (newest.Ref - oldest.Ref) as u64;
// freq hz = count / (interval ns) * (nsPerS ns) / (1 s)
let nsPerS = SECOND as u64;
let (minHz, ok) = muldiv64(minCount, nsPerS, refInterval);
if !ok {
c.resetLocked(format!("Unable to update calibrated clock: ({} - {}) * {} / {} overflows.",
newest.Before, oldest.After, nsPerS, refInterval).as_str());
return (Parameters::default(), false)
}
let (maxHz, ok) = muldiv64(maxCount, nsPerS, refInterval);
if !ok {
c.resetLocked(format!("Unable to update calibrated clock: ({} - {}) * {} / {} overflows.",
newest.After, oldest.Before, nsPerS, refInterval).as_str());
return (Parameters::default(), false)
}
c.updateParams(&Parameters {
Frequency: (minHz + maxHz) / 2,
BaseRef: newest.Ref,
BaseCycles: newest.After,
});
return (c.params, true)
}
// GetTime returns the current time based on the clock calibration.
pub fn GetTime(&self) -> Result<i64> {
let now = {
let c = self.read();
if !c.ready {
let ret = c.sampler.Syscall();
return ret;
}
let now = c.sampler.Cycles();
let (v, ok) = c.params.ComputeTime(now);
if ok {
return Ok(v)
}
now
};
let mut c = self.write();
// Something is seriously wrong with the clock. Try
// again with syscalls.
let parameters = c.params;
c.resetLocked(format!("Time computation overflowed. params ={:?}, now = {}.",
¶meters, now).as_str());
return c.sampler.Syscall();
}
}
#[derive(Clone)]
pub struct CalibratedClocks {
pub monotonic: CalibratedClock,
pub realtime: CalibratedClock,
}
impl CalibratedClocks {
pub fn New() -> Self {
return Self {
monotonic: CalibratedClock::New(MONOTONIC),
realtime: CalibratedClock::New(REALTIME),
}
}
pub fn Update_withSample(&mut self) -> (Parameters, bool, Parameters, bool) {
let (monotonicParams, monotonicOk) = self.monotonic.Update();
let (realtimeParams, realtimeOk) = self.realtime.Update();
return (monotonicParams, monotonicOk, realtimeParams, realtimeOk)
}
pub fn Update(&mut self) -> (Parameters, bool, Parameters, bool) {
let freq = HostSpace::KernelVcpuFreq() as u64;
let tsc1 = Rdtsc();
let monotime = HostSpace::KernelGetTime(MONOTONIC).unwrap();
let tsc2 = Rdtsc();
let tsc = (tsc1 + tsc2) / 2;
let monotonicParams = Parameters {
Frequency: freq,
BaseRef: monotime,
BaseCycles: tsc,
};
let tsc1 = Rdtsc();
let realtime = HostSpace::KernelGetTime(REALTIME).unwrap();
let tsc2 = Rdtsc();
let tsc = (tsc1 + tsc2) / 2;
let realtimeParams = Parameters {
Frequency: freq,
BaseRef: realtime,
BaseCycles: tsc,
};
return (monotonicParams, true, realtimeParams, true)
}
pub fn GetTime(&self, id: ClockID) -> Result<i64> {
match id {
MONOTONIC => self.monotonic.GetTime(),
REALTIME => self.realtime.GetTime(),
_ => return Err(Error::SysError(SysErr::EINVAL))
}
}
}
|
/*
* Author: Dave Eddy <dave@daveeddy.com>
* Date: January 25, 2022
* License: MIT
*/
//! `vsv <anything>`.
use std::env;
use anyhow::{bail, ensure, Context, Result};
use clap::crate_name;
use yansi::Color;
use crate::utils;
use crate::{config, config::Config};
/// Handle `vsv <any-non-matching-command>`.
pub fn do_external(cfg: &Config) -> Result<()> {
assert!(!cfg.operands.is_empty());
let sv = cfg.sv_prog.to_owned();
ensure!(
cfg.operands.len() >= 2,
"argument expected for '{} {}'",
sv,
cfg.operands[0]
);
// format arguments
let args_s = cfg.operands.join(" ");
// set SVDIR env to match what user wanted
env::set_var(config::ENV_SVDIR, &cfg.svdir);
println!(
"[{}] {}",
crate_name!(),
Color::Cyan.paint(format!(
"Running {} command ({}={:?} {} {})",
sv,
config::ENV_SVDIR,
&cfg.svdir,
sv,
&args_s
))
);
// run the actual program
let status = utils::run_program_get_status(&sv, &cfg.operands)
.with_context(|| format!("failed to execute {}", sv))?;
// check the process status
let code = status.code().unwrap_or(-1);
let color = match code {
0 => Color::Green,
_ => Color::Red,
};
// print exit code
println!(
"[{}] {}",
crate_name!(),
color.paint(format!("[{} {}] exit code {}", sv, &args_s, code))
);
match code {
0 => Ok(()),
_ => bail!("call to {} failed", sv),
}
}
|
use fuzzcheck::DefaultMutator;
#[derive(Clone, DefaultMutator)]
pub enum X {
A(u8),
}
#[cfg(test)]
mod test {
use fuzzcheck::Mutator;
use super::*;
#[test]
#[no_coverage]
fn test_compile() {
let m = X::default_mutator();
let (_value, _): (X, _) = m.random_arbitrary(10.0);
}
}
|
use crate::types::*;
use neo4rs_macros::BoltStruct;
#[derive(Debug, PartialEq, Clone, BoltStruct)]
#[signature(0xB1, 0x01)]
pub struct Hello {
extra: BoltMap,
}
impl Hello {
pub fn new(extra: BoltMap) -> Hello {
Hello { extra }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::version::Version;
use bytes::*;
#[test]
fn should_serialize_hello() {
let hello = Hello::new(
vec![("scheme".into(), "basic".into())]
.into_iter()
.collect(),
);
let bytes: Bytes = hello.into_bytes(Version::V4_1).unwrap();
assert_eq!(
bytes,
Bytes::from_static(&[
0xB1,
0x01,
map::TINY | 1,
string::TINY | 6,
b's',
b'c',
b'h',
b'e',
b'm',
b'e',
string::TINY | 5,
b'b',
b'a',
b's',
b'i',
b'c',
])
);
}
}
|
fn sum_elements(a: *const f32, length: u32) -> f32 {
let mut result: f32 = 0.0;
let mut i = 0;
while i <= length - 1 {
result += unsafe { *a.offset(i as isize) };
i += 1;
}
result
}
|
#[doc = "Reader of register PP"]
pub type R = crate::R<u32, super::PP>;
#[doc = "Reader of field `SC`"]
pub type SC_R = crate::R<bool, bool>;
#[doc = "Reader of field `NB`"]
pub type NB_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Smart Card Support"]
#[inline(always)]
pub fn sc(&self) -> SC_R {
SC_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - 9-Bit Support"]
#[inline(always)]
pub fn nb(&self) -> NB_R {
NB_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
|
use crate::commands::{LllCommand, LllRunnable, ReloadDirList};
use crate::context::LllContext;
use crate::error::LllError;
use crate::history::DirectoryHistory;
use crate::window::LllView;
#[derive(Clone, Debug)]
pub struct ToggleHiddenFiles;
impl ToggleHiddenFiles {
pub fn new() -> Self {
ToggleHiddenFiles
}
pub const fn command() -> &'static str {
"toggle_hidden"
}
pub fn toggle_hidden(context: &mut LllContext) {
let opposite = !context.config_t.sort_option.show_hidden;
context.config_t.sort_option.show_hidden = opposite;
for tab in &mut context.tabs {
tab.history.depreciate_all_entries();
tab.curr_list.depreciate();
}
}
}
impl LllCommand for ToggleHiddenFiles {}
impl std::fmt::Display for ToggleHiddenFiles {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(Self::command())
}
}
impl LllRunnable for ToggleHiddenFiles {
fn execute(&self, context: &mut LllContext, view: &LllView) -> Result<(), LllError> {
Self::toggle_hidden(context);
ReloadDirList::new().execute(context, view)
}
}
|
use crate::object::Point;
use crate::global::*;
use rayon::prelude::*;
use super::common_step::*;
fn sor_method(grid: &Vec<Point>, even: bool) -> bool {
let index = init_index(even);
let update : Vec<(f64, bool, usize)> = index.par_iter().map( |i|
step(grid, grid[*i].index, true)).collect();
update.par_iter().for_each( |x| {
let mut _mut = grid[x.2].temperature.borrow_mut();
*_mut = x.0;
});
let flag = update.into_par_iter().reduce(|| (0.0, true, 0), |x, y| (0.0, x.1 & y.1, 0)).1;
if even {
sor_method(grid, false) & flag
} else {
flag
}
}
fn jacobi_method(grid: &Vec<Point>) -> bool {
let update : Vec<(f64, bool, usize)> = grid.par_iter().map(move |x|step(grid, x.index, false)).collect();
update.par_iter().for_each(|x| {
let mut t = grid[x.2].temperature.borrow_mut();
*t = x.0;
});
update.into_par_iter().reduce(|| (0.0, true, 0), |x, y| (0.0, x.1 & y.1, 0)).1
}
pub fn invoke(grid: &Vec<Point>) -> bool {
match &*MATH_METHOD {
MathMethod::Jacobi => jacobi_method(grid),
MathMethod::Sor => sor_method(grid, true)
}
} |
use crate::solver::*;
use crate::graph::Primal;
use itertools::Itertools;
impl Solve for Primal {
fn solve(self, td: Decomposition, k: usize, formula: Formula) -> Option<(Assignment, usize)> {
// for each variable list the clauses which contain that variable as a positive / negative literal
let occurences = formula.variable_occurences();
let nice_td = make_nice(&self, td, false);
let tree_index = tree_index(&nice_td, k, self.size());
let traversal = traverse_order(&nice_td);
let mut config_stack = Vec::<Vec<Configuration>>::new();
// keep track of clauses where not all variables are active
let mut forgotten = vec![false; formula.n_clauses];
for i in traversal.iter() {
let (_, node) = &nice_td[*i];
match node {
&Leaf => {
// push empty configuration
config_stack.push(vec![(0, 0, vec![])]);
}
&Introduce(var) => {
let mut configs = config_stack.pop()?;
// make duplicates of each config so we can try both values for var
duplicate_configs(&mut configs, var, &tree_index);
config_stack.push(configs);
}
&Forget(var) => {
let mut configs = config_stack.pop()?;
let forget_clauses = occurences[var].iter().filter(|&&c| !forgotten[c]).collect_vec();
// check all clauses that contain var if they are satisfied
configs = configs.into_iter().filter_map(|(mut a, mut s, v)| {
for clause in forget_clauses.iter() {
// check if any variable has the desired value
let satisfied = formula.clause(clause).iter().any(|&literal| {
let variable = literal.abs() as usize - 1;
if literal > 0 {
get_bit(&a, tree_index[variable])
} else {
!get_bit(&a, tree_index[variable])
}
});
if satisfied {
// clause satisfied: award points
s += formula.soft_weight(clause);
} else if formula.is_hard(clause) {
// hard clause not satisfied: reject config
return None;
}
}
// reset bit of variable
set_bit(&mut a, tree_index[var], false);
Some((a, s, v))
}).collect_vec();
// mark all clauses containing var as forgotten
forget_clauses.into_iter().for_each(|&c| forgotten[c] = true);
deduplicate(&mut configs);
config_stack.push(configs);
}
&Edge(_, _) => { /* nothing */ }
&Join => {
let left = config_stack.pop()?;
let right = config_stack.pop()?;
// keep only intersection of left and right
let intersection = config_intersection(left, right);
config_stack.push(intersection);
}
}
}
let last = config_stack.pop()?;
let (_, score, variables) = &last[0];
let mut assignment = vec![false; formula.n_vars];
for v in variables {
assignment[*v] = true;
}
Some((assignment, *score))
}
}
fn config_intersection(left: Vec<Configuration>, right: Vec<Configuration>) -> Vec<Configuration> {
let max_fingerprint = left.iter().map(|(a, _, _)| a).max().unwrap();
let mut indexes = vec![0; max_fingerprint+1];
for (i, (a, _, _)) in left.iter().enumerate() {
indexes[*a] = i + 1;
}
// since we must "guess" the same value for each variable from both sides, this is really just the intersection
right.into_iter().filter_map(|(a, s, v)| {
if indexes[a] > 0 {
let (_, other_s, other_v) = &left[indexes[a] - 1];
let combined_vars = v.iter().chain(other_v.iter()).unique().copied().collect();
Some((a, s + other_s, combined_vars))
} else {
None
}
}).collect_vec()
}
|
// Number of 1 Bits
// https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/
pub struct Solution;
// Cheating
#[cfg(disable)]
impl Solution {
#[allow(non_snake_case)]
pub fn hammingWeight(n: u32) -> i32 {
n.count_ones() as _
}
}
impl Solution {
#[allow(non_snake_case)]
pub fn hammingWeight(mut n: u32) -> i32 {
// Brian Kernighan’s Algorithm
let mut count = 0;
while n > 0 {
n &= n - 1;
count += 1;
}
count
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example1() {
assert_eq!(Solution::hammingWeight(0b1011), 3);
}
#[test]
fn example2() {
assert_eq!(Solution::hammingWeight(0b10000000), 1);
}
#[test]
fn example3() {
assert_eq!(
Solution::hammingWeight(0b11111111111111111111111111111101),
31,
);
}
#[test]
fn test_zero() {
assert_eq!(Solution::hammingWeight(0), 0);
}
}
|
pub mod apis;
pub mod applications;
pub mod sso; |
// Copyright 2019 Stichting Organism
//
// 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.
//! Schnorr Secret Key & Extended Secret Key generation
use crate::SchnorrError;
use mohan::{dalek::scalar::Scalar, ser};
use rand::{CryptoRng, RngCore};
use std::fmt::Debug;
use subtle::{Choice, ConstantTimeEq};
use zeroize::Zeroize;
/// The length of a curve25519 Schnorr `SecretKey`, in bytes.
pub const SECRET_KEY_LENGTH: usize = 32;
/// An Schnorr secret key.
#[derive(Default, Clone)]
pub struct SecretKey(pub(crate) Scalar);
impl Debug for SecretKey {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "SecretKey: {:?}", &self.0)
}
}
impl Eq for SecretKey {}
impl PartialEq for SecretKey {
fn eq(&self, other: &Self) -> bool {
self.ct_eq(other).unwrap_u8() == 1u8
}
}
impl ConstantTimeEq for SecretKey {
fn ct_eq(&self, other: &Self) -> Choice {
self.0.ct_eq(&other.0)
}
}
impl Zeroize for SecretKey {
fn zeroize(&mut self) {
mohan::zeroize_hack(&mut self.0);
}
}
/// Overwrite secret key material with null bytes when it goes out of scope.
impl Drop for SecretKey {
fn drop(&mut self) {
self.zeroize();
}
}
impl SecretKey {
/// Convert this secret key to a byte array.
#[inline]
pub fn to_bytes(&self) -> [u8; SECRET_KEY_LENGTH] {
self.0.to_bytes()
}
/// View this secret key as a byte array.
#[inline]
pub fn as_bytes<'a>(&'a self) -> &'a [u8; SECRET_KEY_LENGTH] {
&self.0.as_bytes()
}
/// Construct a `SecretKey` from a slice of bytes.
///
/// # Example
///
/// ```
/// # extern crate schnorr;
/// #
/// use schnorr::*;
///
/// # fn doctest() -> Result<SecretKey, SchnorrError> {
/// let secret_key_bytes: [u8; SECRET_KEY_LENGTH] = [
/// 157, 097, 177, 157, 239, 253, 090, 096,
/// 186, 132, 074, 244, 146, 236, 044, 196,
/// 068, 073, 197, 105, 123, 050, 105, 025,
/// 112, 059, 172, 003, 028, 174, 127, 096, ];
///
/// let secret_key: SecretKey = SecretKey::from_bytes(&secret_key_bytes)?;
/// #
/// # Ok(secret_key)
/// # }
/// #
/// # fn main() {
/// # let result = doctest();
/// # assert!(result.is_ok());
/// # }
/// ```
///
/// # Returns
///
/// A `Result` whose okay value is an Schnorr `SecretKey` or whose error value
/// is an `SchnorrError` wrapping the internal error that occurred.
#[inline]
pub fn from_bytes(bytes: &[u8]) -> Result<SecretKey, SchnorrError> {
if bytes.len() != SECRET_KEY_LENGTH {
return Err(SchnorrError::SerError);
}
let mut bits: [u8; 32] = [0u8; 32];
bits.copy_from_slice(&bytes[..32]);
Ok(SecretKey(Scalar::from_bits(bits)))
}
/// Generate a `SecretKey` from a `csprng`.
///
/// # Example
///
/// ```
/// extern crate rand;
/// extern crate schnorr;
///
/// # #[cfg(feature = "std")]
/// # fn main() {
/// #
/// use rand::Rng;
/// use rand::OsRng;
/// use schnorr::*;
///
/// let mut csprng: OsRng = OsRng::new().unwrap();
/// let secret_key: SecretKey = SecretKey::generate(&mut csprng);
/// # }
/// #
/// # #[cfg(not(feature = "std"))]
/// # fn main() { }
/// ```
///
/// Afterwards, you can generate the corresponding public—provided you also
/// supply a hash function which implements the `Digest` and `Default`
/// traits, and which returns 512 bits of output—via:
///
/// ```
/// # extern crate rand;
/// # extern crate schnorr;
/// #
/// # fn main() {
/// #
/// # use rand::Rng;
/// # use rand_chacha::ChaChaRng;
/// # use rand::SeedableRng;
/// # use schnorr::*;
/// #
/// # let mut csprng: ChaChaRng = ChaChaRng::from_seed([0u8; 32]);
/// # let secret_key: SecretKey = SecretKey::generate(&mut csprng);
///
/// let public_key: PublicKey = PublicKey::from_secret(&secret_key);
/// # }
/// ```
///
///
/// # Input
///
/// A CSPRNG with a `fill_bytes()` method, e.g. `rand::ChaChaRng`
pub fn generate<T>(csprng: &mut T) -> SecretKey
where
T: CryptoRng + RngCore,
{
SecretKey(Scalar::random(csprng))
}
///Helper Method to Convert key to scalar
pub fn to_scalar(&self) -> Scalar {
self.0
}
/// View this scalaras a byte array.
#[inline]
pub fn as_scalar<'a>(&'a self) -> &'a Scalar {
&self.0
}
///Helper Method to Convert Scalar to Key
pub fn from_scalar(s: Scalar) -> SecretKey {
SecretKey(s)
}
}
impl ser::Writeable for SecretKey {
fn write<W: ser::Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
self.0.write(writer)?;
Ok(())
}
}
impl ser::Readable for SecretKey {
fn read(reader: &mut dyn ser::Reader) -> Result<SecretKey, ser::Error> {
Ok(SecretKey(Scalar::read(reader)?))
}
}
impl std::borrow::Borrow<Scalar> for SecretKey {
#[inline]
fn borrow(&self) -> &Scalar {
self.as_scalar()
}
}
|
use game_lib::serde::{Deserialize, Serialize};
use semver::{Version, VersionReq};
use std::path::PathBuf;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(crate = "game_lib::serde")]
pub struct ModuleManifest {
pub id: String,
pub version: Version,
pub entry: PathBuf,
#[serde(default)]
pub dependencies: Vec<ModuleDependency>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(crate = "game_lib::serde")]
pub struct ModuleDependency {
pub id: String,
pub versions: VersionReq,
#[serde(default)]
pub optional: bool,
}
|
use euclid::*;
// use euclid::TypedPoint2D as Point;
use cgmath::Vector2;
type V2 = (f32, f32);
#[derive(Copy, Clone, Serialize)]
pub struct Point {
pos: V2,
vel: V2,
rad: f32,
mass: f32,
}
js_serializable!(Point);
pub type Objs = Vec<Point>;
const G: f32 = -9.8;
static mut P_COUNT: isize = 0;
use std::ops::DerefMut;
use std::{thread, time};
fn apply_force(mut p: Point) {}
impl Point {
pub fn new(pos: V2, vel: V2, rad: f32, mass: f32) -> Point {
Point {
pos: pos,
vel: vel,
rad: rad,
mass: mass,
}
}
pub fn speak(self) {
js!{console.log(@{self})}
}
pub fn apply_gravity(&mut self, dt: f32) {
self.vel = (self.vel.0, self.vel.1 + (G * dt));
}
pub fn update(&mut self, dt: f32) {
self.pos.0 += self.vel.0 * dt;
self.pos.1 += self.vel.1 * dt;
}
pub fn step(&mut self, dt: f32) {
self.apply_gravity(dt);
self.update(dt);
}
pub fn render(&self) -> String {
format!(
"<circle cy={y} cx={x} class=\"obj\" r={r}></circle>",
y = self.pos.1,
x = self.pos.0,
r = self.rad
)
}
}
#[derive(Serialize)]
pub struct Points {
ps: Vec<Point>,
}
js_serializable!(Points);
pub fn run(objs: &mut Objs) {
let p = Point::new((500.0, 500.0), (0.0, 0.0), 5.0, 1.0);
p.speak();
// let mut x: isize = 10;
// let ten_millis = time::Duration::from_millis(100);
// while x > 0 {
// updateObjs(objs, 1f32);
// draw(objs);
// x -= 1;
// thread::sleep(ten_millis);
// }
}
pub fn updateObjs(objs: &mut Objs, dt: f32) {
// for mut obj in objs {
// obj.step(dt);
// // js!{
// // console.log(@{obj})
// // };
// }
}
pub fn draw(objs: &mut Objs) {
// let mut html: String = "<svg width=1000 height=1000> <g transform=\"translate(0,1000) scale(1,-1)\">"
// .to_string();
// for obj in objs {
// html = [html, obj.render()].concat();
// }
// html = [html, "</g></svg>".to_string()].concat();
// println!("{}", html);
// js!{
// let divs = document.createRange().createContextualFragment(@{html});
// document.body.innerHTML = "";
// document.body.appendChild(divs);
// };
}
pub fn points() -> Points {
let data: Points = Points {
ps: vec![
Point::new((500.0, 500.0), (0.0, 0.0), 5.0, 1.0),
Point::new((80.0, 789.0), (3.0, 3.0), 5.0, 1.0),
Point::new((350.0, 900.0), (-5.0, 0.0), 5.0, 1.0),
],
};
data
} |
pub trait Draw {
fn draw(&self);
}
pub struct Button {
width: usize
}
impl Draw for Button {
fn draw(&self) {
println!("drawing button {}", self.width);
}
}
pub struct Screen<T: Draw> {
pub components: Vec<T>,
}
impl<T> Screen<T>
where T: Draw {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
pub fn new() -> Screen<T> {
Screen {
components: Vec::new()
}
}
pub fn push(&mut self, drawable: T) {
self.components.push(drawable);
}
}
fn main() {
let mut screen: Screen<Button> = Screen::new();
let b = Button { width: 455 };
screen.push(b);
screen.run();
println!("done");
} |
//! Defines usage types for memory bocks.
//! See `Usage` and implementations for details.
use memory::Properties;
/// Memory usage trait.
pub trait Usage {
/// Comparable fitness value.
type Fitness: Copy + Ord;
/// Get runtime usage value.
fn value(self) -> UsageValue;
/// Get comparable fitness value for memory properties.
/// Should return `None` if memory doesn't fit.
fn memory_fitness(&self, properties: Properties) -> Option<Self::Fitness>;
}
/// Full speed GPU access.
/// Optimal for render targets and persistent resources.
/// Avoid memory with host access.
#[derive(Clone, Copy, Debug)]
pub struct Data;
impl Usage for Data {
type Fitness = u8;
#[inline]
fn value(self) -> UsageValue {
UsageValue::Data
}
#[inline]
fn memory_fitness(&self, properties: Properties) -> Option<u8> {
if !properties.contains(Properties::DEVICE_LOCAL) {
None
} else {
Some(
((!properties.contains(Properties::HOST_VISIBLE)) as u8) << 3
| ((!properties.contains(Properties::LAZILY_ALLOCATED)) as u8) << 2
| ((!properties.contains(Properties::HOST_CACHED)) as u8) << 1
| ((!properties.contains(Properties::HOST_COHERENT)) as u8) << 0
| 0,
)
}
}
}
/// CPU to GPU data flow with update commands.
/// Used for dynamic buffer data, typically constant buffers.
/// Host access is guaranteed.
/// Prefers memory with fast GPU access.
#[derive(Clone, Copy, Debug)]
pub struct Dynamic;
impl Usage for Dynamic {
type Fitness = u8;
#[inline]
fn value(self) -> UsageValue {
UsageValue::Dynamic
}
#[inline]
fn memory_fitness(&self, properties: Properties) -> Option<u8> {
if !properties.contains(Properties::HOST_VISIBLE) {
None
} else {
assert!(!properties.contains(Properties::LAZILY_ALLOCATED));
Some(
(properties.contains(Properties::DEVICE_LOCAL) as u8) << 2
| (properties.contains(Properties::HOST_COHERENT) as u8) << 1
| ((!properties.contains(Properties::HOST_CACHED)) as u8) << 0
| 0,
)
}
}
}
/// CPU to GPU data flow with mapping.
/// Used for staging data before copying to the `Data` memory.
/// Host access is guaranteed.
#[derive(Clone, Copy, Debug)]
pub struct Upload;
impl Usage for Upload {
type Fitness = u8;
#[inline]
fn value(self) -> UsageValue {
UsageValue::Upload
}
#[inline]
fn memory_fitness(&self, properties: Properties) -> Option<u8> {
if !properties.contains(Properties::HOST_VISIBLE) {
None
} else {
assert!(!properties.contains(Properties::LAZILY_ALLOCATED));
Some(
((!properties.contains(Properties::DEVICE_LOCAL)) as u8) << 2
| ((!properties.contains(Properties::HOST_CACHED)) as u8) << 0
| (properties.contains(Properties::HOST_COHERENT) as u8) << 1
| 0,
)
}
}
}
/// GPU to CPU data flow with mapping.
/// Used for copying data from `Data` memory to be read by the host.
/// Host access is guaranteed.
#[derive(Clone, Copy, Debug)]
pub struct Download;
impl Usage for Download {
type Fitness = u8;
#[inline]
fn value(self) -> UsageValue {
UsageValue::Download
}
#[inline]
fn memory_fitness(&self, properties: Properties) -> Option<u8> {
if !properties.contains(Properties::HOST_VISIBLE) {
None
} else {
assert!(!properties.contains(Properties::LAZILY_ALLOCATED));
Some(
((!properties.contains(Properties::DEVICE_LOCAL)) as u8) << 2
| (properties.contains(Properties::HOST_CACHED) as u8) << 1
| (properties.contains(Properties::HOST_COHERENT) as u8) << 0
| 0,
)
}
}
}
/// Dynamic value that specify memory usage flags.
#[derive(Clone, Copy, Debug)]
pub enum UsageValue {
/// Runtime counterpart for `Data`.
Data,
/// Runtime counterpart for `Dynamic`.
Dynamic,
/// Runtime counterpart for `Upload`.
Upload,
/// Runtime counterpart for `Download`.
Download,
}
impl Usage for UsageValue {
type Fitness = u8;
#[inline]
fn value(self) -> UsageValue {
self
}
#[inline]
fn memory_fitness(&self, properties: Properties) -> Option<u8> {
match self {
UsageValue::Data => Data.memory_fitness(properties),
UsageValue::Dynamic => Dynamic.memory_fitness(properties),
UsageValue::Upload => Upload.memory_fitness(properties),
UsageValue::Download => Download.memory_fitness(properties),
}
}
}
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021-2022 brainpower <brainpower at mailbox dot org>
use std::fmt;
use std::process::ExitCode;
use std::process::Termination;
use crate::CheckArg;
use crate::RC;
impl Termination for RC {
fn report(self) -> ExitCode { ExitCode::from(self as u8) }
}
impl fmt::Display for RC {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RC::{:?}: {}", &self, CheckArg::strerr(&self))
}
}
|
pub mod configuration;
pub mod error;
pub mod handlers;
pub mod macros;
pub mod service;
use {
error::{Error, ErrorKind, Result},
hyper::{Body, Request},
lazy_static::lazy_static,
serde::{Deserialize, Serialize},
slog::Logger,
std::collections::HashMap,
};
pub mod log {
use {
lazy_static::lazy_static,
slog::{o, Drain, LevelFilter, Logger},
slog_async::Async,
slog_term::{CompactFormat, TermDecorator},
};
lazy_static! {
// The "base" logger that all crates should branch off of
pub static ref BASE_LOG: Logger = {
let decorator = TermDecorator::new().build();
let drain = CompactFormat::new(decorator).build().fuse();
let drain = Async::new(drain).build().fuse();
let drain = LevelFilter::new(drain, slog::Level::Debug).fuse();
let log = Logger::root(drain, o!());
log
};
}
}
lazy_static! {
pub static ref LOG: Logger = { log::BASE_LOG.new(slog::o!("mod" => "mpix")) };
}
pub struct Caps {
inner: Option<HashMap<String, String>>,
}
impl Caps {
pub fn empty() -> Self {
Self { inner: None }
}
pub fn with(capture_map: HashMap<String, String>) -> Self {
Self {
inner: Some(capture_map),
}
}
pub fn get<T: AsRef<str>>(&self, s: T) -> Result<String> {
let s = s.as_ref();
let val = self
.inner
.as_ref()
.and_then(|cap_map| cap_map.get(s).map(String::from))
.ok_or_else(|| {
ErrorKind::MissingUriParam(format!("missing expected uri parameter '{}'", s))
})?;
Ok(val)
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
name: String,
}
impl redis::FromRedisValue for User {
fn from_redis_value(v: &redis::Value) -> redis::RedisResult<User> {
match *v {
redis::Value::Data(ref bytes) => Ok(serde_json::from_slice(bytes)
.map_err(|_| (redis::ErrorKind::TypeError, "Invalid user json bytes"))?),
_ => Err((
redis::ErrorKind::TypeError,
"Response type not user compatible.",
))?,
}
}
}
pub struct Auth {
pub user_token: String,
}
pub struct Context {
request: Request<Body>,
captures: Caps,
auth: Option<Auth>,
redis: redis::Client,
}
impl Context {
fn redis() -> Result<redis::Client> {
Ok(redis::Client::open(
configuration::CONFIG.redis_url.as_ref(),
)?)
}
pub fn with_req(r: Request<Body>) -> Result<Self> {
Ok(Self {
request: r,
auth: None,
captures: Caps::empty(),
redis: Self::redis()?,
})
}
pub fn new(r: Request<Body>, auth: Option<Auth>, caps: Caps) -> Result<Self> {
Ok(Self {
request: r,
auth,
captures: caps,
redis: Self::redis()?,
})
}
}
#[derive(Debug, PartialEq)]
pub enum Environment {
Local,
Production,
}
impl std::str::FromStr for Environment {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s.trim().to_lowercase().as_ref() {
"local" => Environment::Local,
"production" => Environment::Production,
s => Err(format!("Invalid env: {}", s))?,
})
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::sync::Arc;
use failure::Error;
use fidl::endpoints::{create_proxy, ClientEnd};
use fidl_fuchsia_developer_tiles as tiles;
use fidl_fuchsia_ui_app::ViewProviderMarker;
use fidl_fuchsia_ui_scenic::{ScenicMarker, ScenicProxy};
use fidl_fuchsia_ui_viewsv1::{ViewManagerMarker, ViewManagerProxy};
use fuchsia_app::client::{connect_to_service, App, Launcher};
use fuchsia_async as fasync;
use fuchsia_scenic as scenic;
use futures::prelude::*;
/// A |ViewSink| is the component that the bridge can push new views into so
/// that they can be presented.
pub trait ViewSink: Send + Sync {
/// The bridge has generated a new "toplevel" view. We model these as
/// scenic ViewProvider instances that can be used to create a view
/// representing the surface.
///
/// Compositor objects that create top level surfaces should pass the
/// `ViewProvider` to the `ViewSink` so that they can be presented.
fn new_view_provider(&self, view_provider: ClientEnd<ViewProviderMarker>);
/// Gets a reference to the ViewManager service. This enables components
/// to easily create new views.
fn view_manager(&self) -> &ViewManagerProxy;
/// Gets a reference to the Scenic service.
fn scenic(&self) -> &ScenicProxy;
/// Gets a pointer to the scenic session. This enables components to create
/// scenic resources that can be consumed by views crated by the view
/// manager.
fn scenic_session(&self) -> scenic::SessionPtr;
}
pub type ViewSinkPtr = Arc<Box<dyn ViewSink>>;
/// A simple |ViewSink| that spawns a new 'tiles' process and pushes view
/// providers directly to the tiles instance.
///
/// Note that launching tiles will set a new root view and each bridge process
/// will create a new tiles instance. This component is intended for development
/// purposes.
pub struct TileViewSink {
/// We need to retain this to keep the tiles process alive.
_app: App,
/// The tiles controller interface.
tiles_controller: tiles::ControllerProxy,
/// A connection to the 'Scenic' service.
scenic: ScenicProxy,
/// A connection to the 'ViewManager' service.
view_manager: ViewManagerProxy,
/// A ref-counted pointer to a scenic 'session'.
scenic_session: scenic::SessionPtr,
}
impl TileViewSink {
/// Creates a new `TilesViewSink`.
///
/// As part of creating a `TilesViewSink`, a new `tiles` process will be
/// launched.
pub fn new() -> Result<ViewSinkPtr, Error> {
// Connect to Scenic
let scenic = connect_to_service::<ScenicMarker>()?;
let view_manager = connect_to_service::<ViewManagerMarker>()?;
let (session_proxy, session_request) = create_proxy()?;
scenic.create_session(session_request, None)?;
let scenic_session = scenic::Session::new(session_proxy);
// Spawn a tiles process. We'll forward our |ViewProvider|s here to be
// presented.
let launcher = Launcher::new()?;
let app =
launcher.launch("fuchsia-pkg://fuchsia.com/tiles#meta/tiles.cmx".to_string(), None)?;
let tiles_controller = app.connect_to_service(tiles::ControllerMarker)?;
Ok(Arc::new(Box::new(TileViewSink {
_app: app,
scenic,
scenic_session,
view_manager,
tiles_controller,
})))
}
}
impl ViewSink for TileViewSink {
fn new_view_provider(&self, view_provider: ClientEnd<ViewProviderMarker>) {
let fut = self.tiles_controller.add_tile_from_view_provider("tile", view_provider);
fasync::spawn_local(fut.map_ok(|_| ()).unwrap_or_else(|e| println!("Failed {:?}", e)));
}
fn view_manager(&self) -> &ViewManagerProxy {
&self.view_manager
}
fn scenic(&self) -> &ScenicProxy {
&self.scenic
}
fn scenic_session(&self) -> scenic::SessionPtr {
self.scenic_session.clone()
}
}
|
fn main() {
static COUNT: i32 = 100;
let x = 0;
let mut y = 0;
y += 1;
let z: i32 = 50;
println!("x={}, y={}, z={}", x, y, z);
println!("{}", COUNT * (y + 3));
}
|
fn main() {
let _s1 = String::new(); // unused, just for init method
let data = "This is some data we might store in a string; \
but it could be byte code.\nThis UTF-8 encoded string has the Display trait.";
println!("{}", &data); // ref to retain scope
// need mut here if we want to push_str later
// can bind the orig data obj because above was ref
let mut s1 = data.to_string(); // has the Display trait
s1.push_str(" More text!"); // needs to be mutable
println!("{}", s1); // consumed/moved; s1 goes out of scope
//alt
let s2 = String::from(data); // same as to_string
println!("{}", s2);
// anything UTF-8 encoded
let gretting1 = String::from("안녕하세요");
let gretting2 = String::from("السلام عليكم");
println!("{}.\n{}.", gretting1, gretting2);
let mut s3 = String::from("foo"); // mut
let s4 = "bar"; // not mut
s3.push_str(s4); // str is copy...
println!("s1 is {}. s2 is {}", s3, s4); // ... so we can still use it here
let mut s5 = String::from("lo");
s5.push('l'); // s5 must be mut; single quote
println!("{}", s5);
let hello = String::from("Hello, ");
let world = String::from("world!");
// the + operator uses the add method (sig: fn add(self, s: &str) -> String)
// so we need to use a &ref when + concatenating strings...
let hello_world = hello + &world; // ...hello is moved here, can non longer be used...
println!("{} Hello, {}", hello_world, world); // ...but world can.
let s6 = "tic";
let s7 = "tac";
let s8 = "toe";
// format doesn't take ownership of any of its params; println does
let s9 = format!("{}-{}-{}!", s6, s7, s8);
println!("{}", s9);
// English chars are 1B and therefore 1 length each
let s10 = "Hello";
let len1 = s10.len();
println!("{}", len1);
// but not all UTF-8 chars are 1B
let len2 = String::from("Здравствуйте").len(); // 12?...
println!("{}", len2); // ...24! 2 bytes per character!
// ...so you can't index into strings like most languages
// let h = s10[0]; // this will fail, try slices to be more specific:
let h = &s10[0..1];
println!("{}", h);
for c in "नमस्ते".chars() {
println!("{}", c); // missing 4th and 6th unicode scalar values (USV)
}
for b in "नमस्ते".bytes() {
println!("{}", b); // 18 bytes for 6 Hindu USVs!
}
} |
pub mod floor;
pub mod wall;
pub mod character;
pub mod player;
|
//! Utilities for manipulating audio buffers.
use audio_core::Translate;
use audio_core::{Channels, ChannelsMut};
/// Copy from the buffer specified by `from` into the buffer specified by `to`.
///
/// Only the common count of channels will be copied.
pub fn copy<I, O, T>(from: I, mut to: O)
where
I: Channels<T>,
O: ChannelsMut<T>,
T: Copy,
{
let end = usize::min(from.channels(), to.channels());
for chan in 0..end {
to.channel_mut(chan).copy_from(from.channel(chan));
}
}
/// Translate the content of one buffer `from` into the buffer specified by `to`.
///
/// Only the common count of channels will be copied.
pub fn translate<I, O, U, T>(from: I, mut to: O)
where
I: Channels<U>,
O: ChannelsMut<T>,
T: Translate<U>,
U: Copy,
{
let end = usize::min(from.channels(), to.channels());
for chan in 0..end {
to.channel_mut(chan).translate_from(from.channel(chan));
}
}
|
#[doc = "Reader of register APB_FZ1"]
pub type R = crate::R<u32, super::APB_FZ1>;
#[doc = "Writer for register APB_FZ1"]
pub type W = crate::W<u32, super::APB_FZ1>;
#[doc = "Register APB_FZ1 `reset()`'s with value 0"]
impl crate::ResetValue for super::APB_FZ1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DBG_TIM2_STOP`"]
pub type DBG_TIM2_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIM2_STOP`"]
pub struct DBG_TIM2_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIM2_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `DBG_TIM3_STOP`"]
pub type DBG_TIM3_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIM3_STOP`"]
pub struct DBG_TIM3_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIM3_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `DBG_RTC_STOP`"]
pub type DBG_RTC_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_RTC_STOP`"]
pub struct DBG_RTC_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_RTC_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `DBG_WWDG_STOP`"]
pub type DBG_WWDG_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_WWDG_STOP`"]
pub struct DBG_WWDG_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_WWDG_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `DBG_IWDG_STOP`"]
pub type DBG_IWDG_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_IWDG_STOP`"]
pub struct DBG_IWDG_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_IWDG_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `DBG_I2C1_STOP`"]
pub type DBG_I2C1_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_I2C1_STOP`"]
pub struct DBG_I2C1_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_I2C1_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `DBG_LPTIM2_STOP`"]
pub type DBG_LPTIM2_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_LPTIM2_STOP`"]
pub struct DBG_LPTIM2_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_LPTIM2_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `DBG_LPTIM1_STOP`"]
pub type DBG_LPTIM1_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_LPTIM1_STOP`"]
pub struct DBG_LPTIM1_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_LPTIM1_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM2 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim2_stop(&self) -> DBG_TIM2_STOP_R {
DBG_TIM2_STOP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TIM3 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim3_stop(&self) -> DBG_TIM3_STOP_R {
DBG_TIM3_STOP_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 10 - RTC counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_rtc_stop(&self) -> DBG_RTC_STOP_R {
DBG_RTC_STOP_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - Window watchdog counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_wwdg_stop(&self) -> DBG_WWDG_STOP_R {
DBG_WWDG_STOP_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Independent watchdog counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_iwdg_stop(&self) -> DBG_IWDG_STOP_R {
DBG_IWDG_STOP_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 21 - I2C1 SMBUS timeout counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_i2c1_stop(&self) -> DBG_I2C1_STOP_R {
DBG_I2C1_STOP_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 30 - LPTIM2 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_lptim2_stop(&self) -> DBG_LPTIM2_STOP_R {
DBG_LPTIM2_STOP_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_lptim1_stop(&self) -> DBG_LPTIM1_STOP_R {
DBG_LPTIM1_STOP_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM2 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim2_stop(&mut self) -> DBG_TIM2_STOP_W {
DBG_TIM2_STOP_W { w: self }
}
#[doc = "Bit 1 - TIM3 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim3_stop(&mut self) -> DBG_TIM3_STOP_W {
DBG_TIM3_STOP_W { w: self }
}
#[doc = "Bit 10 - RTC counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_rtc_stop(&mut self) -> DBG_RTC_STOP_W {
DBG_RTC_STOP_W { w: self }
}
#[doc = "Bit 11 - Window watchdog counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_wwdg_stop(&mut self) -> DBG_WWDG_STOP_W {
DBG_WWDG_STOP_W { w: self }
}
#[doc = "Bit 12 - Independent watchdog counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_iwdg_stop(&mut self) -> DBG_IWDG_STOP_W {
DBG_IWDG_STOP_W { w: self }
}
#[doc = "Bit 21 - I2C1 SMBUS timeout counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_i2c1_stop(&mut self) -> DBG_I2C1_STOP_W {
DBG_I2C1_STOP_W { w: self }
}
#[doc = "Bit 30 - LPTIM2 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_lptim2_stop(&mut self) -> DBG_LPTIM2_STOP_W {
DBG_LPTIM2_STOP_W { w: self }
}
#[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_lptim1_stop(&mut self) -> DBG_LPTIM1_STOP_W {
DBG_LPTIM1_STOP_W { w: self }
}
}
|
use std::io::Write;
#[macro_use]
extern crate serde_derive;
use serde::{Serialize, Serializer};
use std::sync::atomic::{AtomicUsize, Ordering};
pub trait Metric {
/// Adds `value` to the current counter.
fn add(&self, value: usize);
/// Increments by 1 unit the current counter.
fn inc(&self) {
self.add(1);
}
/// Returns current value of the counter.
fn count(&self) -> usize;
fn reset(&self) {}
}
pub trait MetricWriter {
fn write(&self, buffer: &mut (dyn Write + Send));
}
impl MetricWriter for () {
fn write(&self, _: &mut (dyn Write + Send)) {}
}
impl Metric for () {
fn add(&self, _: usize) { }
fn count(&self) -> usize {
0
}
}
#[derive(Default)]
pub struct DiffMetric {
current_value: AtomicUsize,
previous_value: AtomicUsize,
}
impl Serialize for DiffMetric {
/// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the
/// flushing of metrics.
/// !!! Any print of the metrics will also reset them. Use with caution !!!
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// There's no serializer.serialize_usize() for some reason :(
let snapshot = self.current_value.load(Ordering::Relaxed);
let res = serializer.serialize_u64(snapshot as u64 - self.previous_value.load(Ordering::Relaxed) as u64);
if res.is_ok() {
self.previous_value.store(snapshot, Ordering::Relaxed);
}
res
}
}
impl Metric for DiffMetric {
fn add(&self, value: usize) {
self.current_value.fetch_add(value, Ordering::Relaxed);
}
fn count(&self) -> usize {
self.current_value.load(Ordering::Relaxed)
}
}
impl Metric for AtomicUsize {
/// Adds `value` to the current counter.
fn add(&self, value: usize) {
self.fetch_add(value, Ordering::Relaxed);
}
/// Returns current value of the counter.
fn count(&self) -> usize {
self.load(Ordering::Relaxed)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_works() {
println!("blah");
}
} |
extern crate aoc;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
fn main() -> Result<(), io::Error> {
let arg = aoc::get_cmdline_arg()?;
let reader = BufReader::new(File::open(arg)?);
let mut twos = 0;
let mut threes = 0;
let lines = reader.lines().map(|line| line.unwrap()).collect::<Vec<_>>();
let mut map = HashMap::new();
for line in &lines {
for c in line.chars() {
*map.entry(c).or_insert(0) += 1;
}
if let Some(_) = map.iter().find(|(_, v)| **v == 2) {
twos += 1;
}
if let Some(_) = map.iter().find(|(_, v)| **v == 3) {
threes += 1;
}
map.clear();
}
println!("part 1: {}", twos * threes);
'outer: for line1 in &lines {
for line2 in &lines {
if line1 == line2 || line1.len() != line2.len() {
continue;
}
let chars1 = line1.chars().collect::<Vec<_>>();
let chars2 = line2.chars().collect::<Vec<_>>();
let mut count = 0;
let mut not_common = None;
for i in 0..line1.len() {
if chars1[i] != chars2[i] {
count += 1;
not_common = Some(chars1[i]);
if count > 1 {
break;
}
}
}
if count == 1 {
println!("{}", line1.replace(not_common.unwrap(), ""));
break 'outer;
}
}
}
Ok(())
}
|
pub(crate) mod de;
pub(crate) mod ser;
pub mod time;
mod to_hana;
pub use to_hana::ToHana;
|
use super::*;
#[derive(Clone)]
pub struct Variable {
pub name: String
}
impl Variable {
pub fn as_expression(&self) -> Expression {
Expression::Variable(self.clone())
}
pub fn to_expression(self) -> Expression {
Expression::Variable(self)
}
}
impl Evaluate for Variable {
fn evaluate_f64(&self, assignments: &Vec<Assignment>) -> Result<f64,String> {
println!("Evaluating variable {}", self);
for assignment in assignments.iter() {
if self.name == assignment.var.name {
return assignment.constant.evaluate_f64(assignments);
}
}
// TODO provide more info
Err ("Incorrect variable supplied".to_string())
}
}
impl fmt::Display for Variable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
|
use types::{int_t, size_t, char_t};
use consts::fcntl::{O_RDONLY};
use core::raw::Repr;
use core::intrinsics::size_of;
use core::ops::Drop;
use posix::unistd::{close, read};
use posix::fcntl::{open};
pub struct FD {
fd: int_t,
}
impl FD {
pub fn raw(&self) -> int_t {
self.fd
}
}
impl Drop for FD {
fn drop(&mut self) {
unsafe {
close(self.fd);
}
}
}
pub trait Rand {
fn fill<T>(&self, &mut [T]);
}
pub struct OSRand {
fd: FD,
}
impl Rand for OSRand {
fn fill<T>(&self, dst: &mut [T]) {
let raw = dst.repr();
unsafe {
read(self.fd.raw(), raw.data as *mut _, (raw.len * size_of::<T>()) as size_t);
}
}
}
pub fn os_rand() -> OSRand {
let fd = unsafe { open(cs!("/dev/urandom"), O_RDONLY, 0) };
OSRand { fd: FD { fd: fd } }
}
|
#[macro_use]
extern crate criterion;
extern crate geo;
use criterion::Criterion;
use geo::prelude::*;
use geo::LineString;
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("convex hull f32", |bencher| {
let points = include!("../src/algorithm/test_fixtures/norway_main.rs");
let line_string = LineString::<f32>::from(points);
bencher.iter(|| {
line_string.convex_hull();
});
});
c.bench_function("convex hull f64", |bencher| {
let points = include!("../src/algorithm/test_fixtures/norway_main.rs");
let line_string = LineString::<f64>::from(points);
bencher.iter(|| {
line_string.convex_hull();
});
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
pub struct Model {
}
impl Model {
fn new(path: &str) -> Model {
}
}
|
use super::*;
use rustls::Session;
use std::io::Write;
/// A wrapper around an underlying raw stream which implements the TLS or SSL
/// protocol.
#[derive(Debug)]
pub struct TlsStream<IO> {
pub(crate) io: IO,
pub(crate) session: ClientSession,
pub(crate) state: TlsState,
#[cfg(feature = "early-data")]
pub(crate) early_data: (usize, Vec<u8>),
}
pub(crate) enum MidHandshake<IO> {
Handshaking(TlsStream<IO>),
#[cfg(feature = "early-data")]
EarlyData(TlsStream<IO>),
End,
}
impl<IO> TlsStream<IO> {
#[inline]
pub fn get_ref(&self) -> (&IO, &ClientSession) {
(&self.io, &self.session)
}
#[inline]
pub fn get_mut(&mut self) -> (&mut IO, &mut ClientSession) {
(&mut self.io, &mut self.session)
}
#[inline]
pub fn into_inner(self) -> (IO, ClientSession) {
(self.io, self.session)
}
}
impl<IO> Future for MidHandshake<IO>
where
IO: AsyncRead + AsyncWrite,
{
type Item = TlsStream<IO>;
type Error = io::Error;
#[inline]
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let MidHandshake::Handshaking(stream) = self {
let state = stream.state;
let (io, session) = stream.get_mut();
let mut stream = Stream::new(io, session).set_eof(!state.readable());
if stream.session.is_handshaking() {
try_nb!(stream.complete_io());
}
if stream.session.wants_write() {
try_nb!(stream.complete_io());
}
}
match mem::replace(self, MidHandshake::End) {
MidHandshake::Handshaking(stream) => Ok(Async::Ready(stream)),
#[cfg(feature = "early-data")]
MidHandshake::EarlyData(stream) => Ok(Async::Ready(stream)),
MidHandshake::End => panic!(),
}
}
}
impl<IO> io::Read for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self.state {
#[cfg(feature = "early-data")]
TlsState::EarlyData => {
{
let mut stream = Stream::new(&mut self.io, &mut self.session);
let (pos, data) = &mut self.early_data;
// complete handshake
if stream.session.is_handshaking() {
stream.complete_io()?;
}
// write early data (fallback)
if !stream.session.is_early_data_accepted() {
while *pos < data.len() {
let len = stream.write(&data[*pos..])?;
*pos += len;
}
}
// end
self.state = TlsState::Stream;
data.clear();
}
self.read(buf)
}
TlsState::Stream | TlsState::WriteShutdown => {
let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());
match stream.read(buf) {
Ok(0) => {
self.state.shutdown_read();
Ok(0)
}
Ok(n) => Ok(n),
Err(ref e) if e.kind() == io::ErrorKind::ConnectionAborted => {
self.state.shutdown_read();
if self.state.writeable() {
stream.session.send_close_notify();
self.state.shutdown_write();
}
Ok(0)
}
Err(e) => Err(e),
}
}
TlsState::ReadShutdown | TlsState::FullyShutdown => Ok(0),
}
}
}
impl<IO> io::Write for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());
match self.state {
#[cfg(feature = "early-data")]
TlsState::EarlyData => {
let (pos, data) = &mut self.early_data;
// write early data
if let Some(mut early_data) = stream.session.early_data() {
let len = early_data.write(buf)?;
data.extend_from_slice(&buf[..len]);
return Ok(len);
}
// complete handshake
if stream.session.is_handshaking() {
stream.complete_io()?;
}
// write early data (fallback)
if !stream.session.is_early_data_accepted() {
while *pos < data.len() {
let len = stream.write(&data[*pos..])?;
*pos += len;
}
}
// end
self.state = TlsState::Stream;
data.clear();
stream.write(buf)
}
_ => stream.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
Stream::new(&mut self.io, &mut self.session)
.set_eof(!self.state.readable())
.flush()?;
self.io.flush()
}
}
impl<IO> AsyncRead for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite,
{
unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool {
false
}
}
impl<IO> AsyncWrite for TlsStream<IO>
where
IO: AsyncRead + AsyncWrite,
{
fn shutdown(&mut self) -> Poll<(), io::Error> {
if self.state.writeable() {
self.session.send_close_notify();
self.state.shutdown_write();
}
let mut stream = Stream::new(&mut self.io, &mut self.session).set_eof(!self.state.readable());
try_nb!(stream.flush());
stream.io.shutdown()
}
}
|
use rocket_contrib::json::{Json, JsonValue};
use merkletree_rs::{db, MerkleTree, TestValue, Value};
use crate::client_call::{SplitSet, MessageBlock};
use reqwest;
use reqwest::Response;
use std::io::{Read};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AdContent {
pub mode : String,
pub category : String,
pub time : String,
pub day : String,
}
#[post("/rtm/send_ads/<user_id>", format = "application/json", data = "<ad_target>")]
pub fn trigger_ad_service( ad_target : Json<AdContent>, user_id : String) -> String {
let ad_target : AdContent = ad_target.into_inner();
println!("{:?}", ad_target);
//call filtering service to get the validated list
let uri = "http://localhost:8000/ir/filter_users/".to_string() + &user_id;
let client = reqwest::Client::new();
let mut response = client.post(&uri)
.json(&ad_target)
.send()
.expect("Failed to send request");
assert_eq!(response.status(), 200);
// if let Ok(split_set) = response.json::<SplitSet>() {
// if split_set.share_rtm == "null" {
// println!("Stopped ");
// }
// }
// let mut buf = String::new();
// println!("Eligible numbers shamir-share received: {}", buf);
println!("Transfer the ads and splits to OAP....");
if let Ok(split_set) = response.json::<SplitSet>() {
println!("Forwarding the keys to OAP..");
crate::client_call::post_request(&split_set, "OAP".to_string(), "What are you doing Ananya?".to_string());
}
"------------------------- Transmission done succesfully!-------------------------".to_string()
}
|
use std::path::{Path, PathBuf};
use serde::Deserialize;
use toml;
use crate::error::{Detail, Result};
use crate::security;
use crate::security::ed25519;
pub const DIR_SECURITY: &str = "security";
pub const DEFAULT_IDENTITY_METHOD: &str = "private_key";
pub struct Context<'ctx> {
dir: Box<&'ctx Path>,
settings: Box<Settings>,
}
impl<'ctx> Context<'ctx> {
/// 指定されたローカルディレクトリにコンテキストをマップする。
pub fn new(dir: &Path) -> Result<Box<Context>> {
if !dir.exists() || !dir.is_dir() {
return Err(Detail::FileOrDirectoryNotExist { location: dir.to_string_lossy().to_string() });
}
log::debug!("Loading the configuration: {}", dir.to_string_lossy());
let conf_file = dir.join("carillon.toml");
let conf = std::fs::read_to_string(conf_file.as_path())?;
let conf: Settings = toml::from_str(conf.as_str()).map_err(|err| {
let position = err.line_col();
Detail::InvalidConfig {
message: err.to_string(),
location: conf_file.to_string_lossy().to_string(),
line: position.map(|x| x.0 as u64 + 1).unwrap_or(0u64),
column: position.map(|x| x.1 as u64 + 1).unwrap_or(0u64),
}
})?;
Ok(Box::new(Context { dir: Box::new(dir.clone()), settings: Box::new(conf) }))
}
/// このコンテキストの鍵ペアをロードします。
pub fn key_pair(&self) -> Result<Box<dyn security::KeyPair>> {
match &self.settings.node.identity {
Identity::PrivateKey { algorithm, location } => {
let algorithm = match algorithm.as_str() {
"ed25519" => ed25519::algorithm(),
unsupported => {
return Err(Detail::UnsupportedSetting {
location: self.dir.to_string_lossy().to_string(),
item: "public-key algorithm",
value: unsupported.to_string(),
});
}
};
let path = self.resolve(location.as_str());
if !path.is_file() {
Err(Detail::FileOrDirectoryNotExist { location: path.to_string_lossy().to_string() })
} else {
let bytes = std::fs::read(path)?;
let key_pair = algorithm.restore_key_pair(&bytes)?;
Ok(key_pair)
}
}
}
}
/// このコンテキストのディレクトリを基準に指定されたパスを参照します。指定されたパスが絶対パスの場合は
fn resolve(&self, path: &str) -> PathBuf {
if Path::new(path).is_absolute() {
PathBuf::from(path)
} else {
self.dir.join(path)
}
}
}
pub fn localnode_key_pair_file(key_algorithm: &str) -> String {
format!("localnode_{}", key_algorithm)
}
#[derive(Debug, Deserialize)]
struct Settings {
node: Node,
}
#[derive(Debug, Deserialize)]
struct Node {
identity: Identity,
}
#[derive(Debug, Deserialize)]
enum Identity {
#[serde(rename = "private_key")]
PrivateKey { algorithm: String, location: String },
}
|
mod material;
pub use material::*;
mod colored;
pub use colored::*;
mod select;
mod combine;
#[cfg(test)]
pub mod test;
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Error type for wrapping errors known to an `ffx` command and whose occurrence should
// not a priori be considered a bug in ffx.
// TODO(57592): consider extending this to allow custom types from plugins.
#[derive(thiserror::Error, Debug)]
pub enum FfxError {
#[error(transparent)]
Error(#[from] anyhow::Error),
}
// Utility macro for constructing a FfxError::Error with a simple error string.
#[macro_export]
macro_rules! printable_error {
($error_message: expr) => {{
use ::ffx_error::FfxError;
FfxError::Error(anyhow::anyhow!($error_message))
}};
}
|
use {
super::Collider,
crate::terrain::{ChunkMap, Vox, WorldVec},
vek::{Aabb, Vec3},
};
pub struct TerrainDetector<'a> {
collider: Collider,
chunk_map: &'a ChunkMap,
near_offsets: Vec<[i32; 3]>,
}
impl<'a> TerrainDetector<'a> {
pub fn try_new(collider: Collider, chunk_map: &'a ChunkMap) -> Option<Self> {
let aabb = collider.aabb(&Vec3::zero())?;
let mut near_offsets = vec![];
for y in aabb.min.y.floor() as i32..aabb.max.y.ceil() as i32 + 1 {
for z in aabb.min.z.floor() as i32..aabb.max.z.ceil() as i32 + 1 {
for x in aabb.min.x.floor() as i32..aabb.max.x.ceil() as i32 + 1 {
near_offsets.push([x, y, z])
}
}
}
Some(Self {
collider,
chunk_map,
near_offsets,
})
}
pub fn try_nearest_collision<F>(
&self,
entity_position: Vec3<f32>,
hit: F,
) -> Option<TerrainCollision>
where
F: FnOnce(&Vox) -> bool + Copy,
{
let entity_aabb = self.collider.aabb(&entity_position)?;
self.near_offsets
.iter()
.filter_map(|offset| self.try_collision_at(entity_position, entity_aabb, hit, *offset))
.min_by_key(|terrain_collision| terrain_collision.distance_key())
}
pub fn has_collision_at<F>(&self, entity_position: Vec3<f32>, hit: F) -> bool
where
F: FnOnce(&Vox) -> bool + Copy,
{
let maybe_aabb = self.collider.aabb(&entity_position);
if maybe_aabb.is_none() {
return false;
}
let entity_aabb = maybe_aabb.unwrap();
self.near_offsets.iter().any(|offset| {
self.try_collision_at(entity_position, entity_aabb, hit, *offset)
.is_some()
})
}
pub fn any_collision_at<F>(
&self,
entity_position: Vec3<f32>,
hit: F,
) -> Option<TerrainCollision>
where
F: FnOnce(&Vox) -> bool + Copy,
{
let entity_aabb = self.collider.aabb(&entity_position)?;
self.near_offsets
.iter()
.find_map(|offset| self.try_collision_at(entity_position, entity_aabb, hit, *offset))
}
pub fn all_collisions_at<F>(&self, entity_position: Vec3<f32>, hit: F) -> Vec<TerrainCollision>
where
F: FnOnce(&Vox) -> bool + Copy,
{
let maybe_entity_aabb = self.collider.aabb(&entity_position);
if maybe_entity_aabb.is_none() {
return vec![];
}
let entity_aabb = maybe_entity_aabb.unwrap();
self.near_offsets
.iter()
.cloned()
.filter_map(|offset| self.try_collision_at(entity_position, entity_aabb, hit, offset))
.collect()
}
fn try_collision_at<F>(
&self,
entity_position: Vec3<f32>,
entity_aabb: Aabb<f32>,
hit: F,
offset: [i32; 3],
) -> Option<TerrainCollision>
where
F: FnOnce(&Vox) -> bool,
{
let world_vec = WorldVec::from(entity_position) + offset;
let maybe_vox = self.chunk_map.get_vox(world_vec).filter(|x| hit(x));
if maybe_vox.is_none() {
return None;
}
let vox = maybe_vox.unwrap();
let vox_aabb = vox.aabb(world_vec);
if !entity_aabb.collides_with_aabb(vox_aabb) {
return None;
}
Some(TerrainCollision {
world_vec,
vox,
entity_position,
entity_aabb,
vox_position: vox_aabb.center(),
vox_aabb,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TerrainCollision {
pub world_vec: WorldVec,
pub vox: Vox,
pub entity_position: Vec3<f32>,
pub entity_aabb: Aabb<f32>,
pub vox_position: Vec3<f32>,
pub vox_aabb: Aabb<f32>,
}
impl TerrainCollision {
pub fn distance_key(&self) -> u32 {
(self.entity_position - self.vox_position)
.magnitude_squared()
.to_bits()
}
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtQuick/qquickimageprovider.h
// dst-file: /src/quick/qquickimageprovider.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::qml::qqmlengine::QQmlImageProviderBase; // 771
use std::ops::Deref;
use super::super::core::qstring::QString; // 771
use super::super::core::qsize::QSize; // 771
use super::super::gui::qimage::QImage; // 771
// use super::qquickimageprovider::QQuickTextureFactory; // 773
use super::super::gui::qpixmap::QPixmap; // 771
use super::super::core::qobject::QObject; // 771
use super::qquickwindow::QQuickWindow; // 773
use super::qsgtexture::QSGTexture; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QQuickImageProvider_Class_Size() -> c_int;
// proto: QImage QQuickImageProvider::requestImage(const QString & id, QSize * size, const QSize & requestedSize);
fn _ZN19QQuickImageProvider12requestImageERK7QStringP5QSizeRKS3_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: QQuickTextureFactory * QQuickImageProvider::requestTexture(const QString & id, QSize * size, const QSize & requestedSize);
fn _ZN19QQuickImageProvider14requestTextureERK7QStringP5QSizeRKS3_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: void QQuickImageProvider::~QQuickImageProvider();
fn _ZN19QQuickImageProviderD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QPixmap QQuickImageProvider::requestPixmap(const QString & id, QSize * size, const QSize & requestedSize);
fn _ZN19QQuickImageProvider13requestPixmapERK7QStringP5QSizeRKS3_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
fn QQuickTextureFactory_Class_Size() -> c_int;
// proto: void QQuickTextureFactory::~QQuickTextureFactory();
fn _ZN20QQuickTextureFactoryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QImage QQuickTextureFactory::image();
fn _ZNK20QQuickTextureFactory5imageEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QSGTexture * QQuickTextureFactory::createTexture(QQuickWindow * window);
fn _ZNK20QQuickTextureFactory13createTextureEP12QQuickWindow(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: int QQuickTextureFactory::textureByteCount();
fn _ZNK20QQuickTextureFactory16textureByteCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QSize QQuickTextureFactory::textureSize();
fn _ZNK20QQuickTextureFactory11textureSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QQuickTextureFactory::QQuickTextureFactory();
fn _ZN20QQuickTextureFactoryC2Ev(qthis: u64 /* *mut c_void*/);
} // <= ext block end
// body block begin =>
// class sizeof(QQuickImageProvider)=16
#[derive(Default)]
pub struct QQuickImageProvider {
qbase: QQmlImageProviderBase,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QQuickTextureFactory)=1
#[derive(Default)]
pub struct QQuickTextureFactory {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QQuickImageProvider {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuickImageProvider {
return QQuickImageProvider{qbase: QQmlImageProviderBase::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QQuickImageProvider {
type Target = QQmlImageProviderBase;
fn deref(&self) -> &QQmlImageProviderBase {
return & self.qbase;
}
}
impl AsRef<QQmlImageProviderBase> for QQuickImageProvider {
fn as_ref(& self) -> & QQmlImageProviderBase {
return & self.qbase;
}
}
// proto: QImage QQuickImageProvider::requestImage(const QString & id, QSize * size, const QSize & requestedSize);
impl /*struct*/ QQuickImageProvider {
pub fn requestImage<RetType, T: QQuickImageProvider_requestImage<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.requestImage(self);
// return 1;
}
}
pub trait QQuickImageProvider_requestImage<RetType> {
fn requestImage(self , rsthis: & QQuickImageProvider) -> RetType;
}
// proto: QImage QQuickImageProvider::requestImage(const QString & id, QSize * size, const QSize & requestedSize);
impl<'a> /*trait*/ QQuickImageProvider_requestImage<QImage> for (&'a QString, &'a QSize, &'a QSize) {
fn requestImage(self , rsthis: & QQuickImageProvider) -> QImage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN19QQuickImageProvider12requestImageERK7QStringP5QSizeRKS3_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN19QQuickImageProvider12requestImageERK7QStringP5QSizeRKS3_(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QImage::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QQuickTextureFactory * QQuickImageProvider::requestTexture(const QString & id, QSize * size, const QSize & requestedSize);
impl /*struct*/ QQuickImageProvider {
pub fn requestTexture<RetType, T: QQuickImageProvider_requestTexture<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.requestTexture(self);
// return 1;
}
}
pub trait QQuickImageProvider_requestTexture<RetType> {
fn requestTexture(self , rsthis: & QQuickImageProvider) -> RetType;
}
// proto: QQuickTextureFactory * QQuickImageProvider::requestTexture(const QString & id, QSize * size, const QSize & requestedSize);
impl<'a> /*trait*/ QQuickImageProvider_requestTexture<QQuickTextureFactory> for (&'a QString, &'a QSize, &'a QSize) {
fn requestTexture(self , rsthis: & QQuickImageProvider) -> QQuickTextureFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN19QQuickImageProvider14requestTextureERK7QStringP5QSizeRKS3_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN19QQuickImageProvider14requestTextureERK7QStringP5QSizeRKS3_(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QQuickTextureFactory::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickImageProvider::~QQuickImageProvider();
impl /*struct*/ QQuickImageProvider {
pub fn free<RetType, T: QQuickImageProvider_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QQuickImageProvider_free<RetType> {
fn free(self , rsthis: & QQuickImageProvider) -> RetType;
}
// proto: void QQuickImageProvider::~QQuickImageProvider();
impl<'a> /*trait*/ QQuickImageProvider_free<()> for () {
fn free(self , rsthis: & QQuickImageProvider) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN19QQuickImageProviderD2Ev()};
unsafe {_ZN19QQuickImageProviderD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QPixmap QQuickImageProvider::requestPixmap(const QString & id, QSize * size, const QSize & requestedSize);
impl /*struct*/ QQuickImageProvider {
pub fn requestPixmap<RetType, T: QQuickImageProvider_requestPixmap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.requestPixmap(self);
// return 1;
}
}
pub trait QQuickImageProvider_requestPixmap<RetType> {
fn requestPixmap(self , rsthis: & QQuickImageProvider) -> RetType;
}
// proto: QPixmap QQuickImageProvider::requestPixmap(const QString & id, QSize * size, const QSize & requestedSize);
impl<'a> /*trait*/ QQuickImageProvider_requestPixmap<QPixmap> for (&'a QString, &'a QSize, &'a QSize) {
fn requestPixmap(self , rsthis: & QQuickImageProvider) -> QPixmap {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN19QQuickImageProvider13requestPixmapERK7QStringP5QSizeRKS3_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN19QQuickImageProvider13requestPixmapERK7QStringP5QSizeRKS3_(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QPixmap::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
impl /*struct*/ QQuickTextureFactory {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQuickTextureFactory {
return QQuickTextureFactory{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QQuickTextureFactory {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QQuickTextureFactory {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QQuickTextureFactory::~QQuickTextureFactory();
impl /*struct*/ QQuickTextureFactory {
pub fn free<RetType, T: QQuickTextureFactory_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QQuickTextureFactory_free<RetType> {
fn free(self , rsthis: & QQuickTextureFactory) -> RetType;
}
// proto: void QQuickTextureFactory::~QQuickTextureFactory();
impl<'a> /*trait*/ QQuickTextureFactory_free<()> for () {
fn free(self , rsthis: & QQuickTextureFactory) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QQuickTextureFactoryD2Ev()};
unsafe {_ZN20QQuickTextureFactoryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QImage QQuickTextureFactory::image();
impl /*struct*/ QQuickTextureFactory {
pub fn image<RetType, T: QQuickTextureFactory_image<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.image(self);
// return 1;
}
}
pub trait QQuickTextureFactory_image<RetType> {
fn image(self , rsthis: & QQuickTextureFactory) -> RetType;
}
// proto: QImage QQuickTextureFactory::image();
impl<'a> /*trait*/ QQuickTextureFactory_image<QImage> for () {
fn image(self , rsthis: & QQuickTextureFactory) -> QImage {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QQuickTextureFactory5imageEv()};
let mut ret = unsafe {_ZNK20QQuickTextureFactory5imageEv(rsthis.qclsinst)};
let mut ret1 = QImage::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSGTexture * QQuickTextureFactory::createTexture(QQuickWindow * window);
impl /*struct*/ QQuickTextureFactory {
pub fn createTexture<RetType, T: QQuickTextureFactory_createTexture<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.createTexture(self);
// return 1;
}
}
pub trait QQuickTextureFactory_createTexture<RetType> {
fn createTexture(self , rsthis: & QQuickTextureFactory) -> RetType;
}
// proto: QSGTexture * QQuickTextureFactory::createTexture(QQuickWindow * window);
impl<'a> /*trait*/ QQuickTextureFactory_createTexture<QSGTexture> for (&'a QQuickWindow) {
fn createTexture(self , rsthis: & QQuickTextureFactory) -> QSGTexture {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QQuickTextureFactory13createTextureEP12QQuickWindow()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZNK20QQuickTextureFactory13createTextureEP12QQuickWindow(rsthis.qclsinst, arg0)};
let mut ret1 = QSGTexture::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QQuickTextureFactory::textureByteCount();
impl /*struct*/ QQuickTextureFactory {
pub fn textureByteCount<RetType, T: QQuickTextureFactory_textureByteCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.textureByteCount(self);
// return 1;
}
}
pub trait QQuickTextureFactory_textureByteCount<RetType> {
fn textureByteCount(self , rsthis: & QQuickTextureFactory) -> RetType;
}
// proto: int QQuickTextureFactory::textureByteCount();
impl<'a> /*trait*/ QQuickTextureFactory_textureByteCount<i32> for () {
fn textureByteCount(self , rsthis: & QQuickTextureFactory) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QQuickTextureFactory16textureByteCountEv()};
let mut ret = unsafe {_ZNK20QQuickTextureFactory16textureByteCountEv(rsthis.qclsinst)};
return ret as i32;
// return 1;
}
}
// proto: QSize QQuickTextureFactory::textureSize();
impl /*struct*/ QQuickTextureFactory {
pub fn textureSize<RetType, T: QQuickTextureFactory_textureSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.textureSize(self);
// return 1;
}
}
pub trait QQuickTextureFactory_textureSize<RetType> {
fn textureSize(self , rsthis: & QQuickTextureFactory) -> RetType;
}
// proto: QSize QQuickTextureFactory::textureSize();
impl<'a> /*trait*/ QQuickTextureFactory_textureSize<QSize> for () {
fn textureSize(self , rsthis: & QQuickTextureFactory) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QQuickTextureFactory11textureSizeEv()};
let mut ret = unsafe {_ZNK20QQuickTextureFactory11textureSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QQuickTextureFactory::QQuickTextureFactory();
impl /*struct*/ QQuickTextureFactory {
pub fn new<T: QQuickTextureFactory_new>(value: T) -> QQuickTextureFactory {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QQuickTextureFactory_new {
fn new(self) -> QQuickTextureFactory;
}
// proto: void QQuickTextureFactory::QQuickTextureFactory();
impl<'a> /*trait*/ QQuickTextureFactory_new for () {
fn new(self) -> QQuickTextureFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QQuickTextureFactoryC2Ev()};
let ctysz: c_int = unsafe{QQuickTextureFactory_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN20QQuickTextureFactoryC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QQuickTextureFactory{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
use crate::utils;
use macro_utils::*;
use std::io::{Read, Write};
use std::str::FromStr;
use yaserde::{YaDeserialize, YaSerialize};
#[derive(Default, PartialEq, Debug, UtilsTupleSerDe)]
pub struct ContentType(pub String);
//generated file
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "xmime",
namespace = "xmime: http://www.w3.org/2005/05/xmlmime"
)]
pub struct Base64Binary {
#[yaserde(attribute, prefix = "xmime" rename = "contentType")]
pub xmime_content_type: Option<ContentType>,
}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "xmime",
namespace = "xmime: http://www.w3.org/2005/05/xmlmime"
)]
pub struct HexBinary {
#[yaserde(attribute, prefix = "xmime" rename = "contentType")]
pub xmime_content_type: Option<ContentType>,
}
|
use std::error::Error;
use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
use super::command::GuanCommand;
use crate::pipeline::Pipeline;
pub struct LsStagesArgs {
pub pipeline_file_path: String,
}
pub struct LsStagesCommand {
args: LsStagesArgs,
}
impl LsStagesCommand {
pub fn new(args: LsStagesArgs) -> LsStagesCommand {
LsStagesCommand { args }
}
}
impl GuanCommand for LsStagesCommand {
fn execute(&self) -> Result<(), Box<dyn Error>> {
let pipeline = Pipeline::load_from_file(&self.args.pipeline_file_path)
.expect("Can't open pipeline definition file");
let mut stdout = StandardStream::stdout(ColorChoice::Auto);
for stage in pipeline.stages.iter() {
stdout.set_color(ColorSpec::new().set_fg(Some(Color::Cyan)))?;
write!(&mut stdout, "{}", stage.id)?;
stdout.reset()?;
println!(" {}", stage.name);
}
Ok(())
}
}
|
use actix_web::{get, HttpRequest, HttpResponse, Responder};
#[get("/health")]
pub async fn get_health(_req: HttpRequest) -> impl Responder {
HttpResponse::NoContent()
}
#[cfg(test)]
mod tests {
use super::get_health;
use actix_web::{http::StatusCode, test, App};
#[actix_rt::test]
async fn test_get_health_get() {
let app = App::new().service(get_health);
let mut test_app = test::init_service(app).await;
let req = test::TestRequest::with_header("content-type", "text/plain")
.uri("/health")
.to_request();
let resp = test::call_service(&mut test_app, req).await;
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
}
#[actix_rt::test]
async fn test_get_health_post() {
let app = App::new().service(get_health);
let mut test_app = test::init_service(app).await;
let req = test::TestRequest::post().uri("/health").to_request();
let resp = test::call_service(&mut test_app, req).await;
assert!(resp.status().is_client_error());
}
}
|
pub struct Solution;
impl Solution {
pub fn my_atoi(str: String) -> i32 {
let chars = str.chars().skip_while(|&c| c == ' ');
let (chars, sign) = {
let mut chars = chars.peekable();
if chars.peek() == Some(&'+') {
chars.next();
(chars, 1)
} else if chars.peek() == Some(&'-') {
chars.next();
(chars, -1)
} else {
(chars, 1)
}
};
chars
.take_while(|&c| c.is_digit(10))
.map(|c| c.to_digit(10).unwrap() as i32)
.fold(Some(0_i32), |x, d| {
x.and_then(|y| y.checked_mul(10_i32))
.and_then(|z| z.checked_add(sign * d))
})
.unwrap_or({
if sign > 0 {
std::i32::MAX
} else {
std::i32::MIN
}
})
}
}
#[test]
fn test0008() {
assert_eq!(Solution::my_atoi("42".to_string()), 42);
assert_eq!(Solution::my_atoi(" -42".to_string()), -42);
assert_eq!(Solution::my_atoi("4193 with words".to_string()), 4193);
assert_eq!(Solution::my_atoi("words and 987".to_string()), 0);
assert_eq!(Solution::my_atoi("-91283472332".to_string()), -2147483648);
}
|
use signal::Signal;
use order::{OrderBuilder, OrderKind};
use order::policy::{OrderPolicy, OrderPolicyError};
pub struct MarketOrderPolicy {}
impl MarketOrderPolicy {
pub fn new() -> MarketOrderPolicy {
MarketOrderPolicy {}
}
}
impl OrderPolicy for MarketOrderPolicy {
fn create_order(&self, signal: &Signal) -> Result<OrderBuilder, OrderPolicyError> {
Ok(
OrderBuilder::unallocated(
OrderKind::MarketOrder,
signal.symbol_id().clone(),
signal.direction().clone()
)
)
}
}
|
#![recursion_limit = "256"]
use log::info;
use std::sync::Arc;
use structopt::StructOpt;
use tower_lsp::{LspService, Server};
mod completion;
mod definition;
mod diagnostics;
mod format;
mod server;
mod sources;
#[cfg(test)]
mod support;
use server::Backend;
#[derive(StructOpt, Debug)]
#[structopt(name = "veridian", about = "A SystemVerilog/Verilog Language Server")]
struct Opt {}
#[tokio::main]
async fn main() {
let _ = Opt::from_args();
let log_handle = flexi_logger::Logger::with_str("info").start().unwrap();
info!("starting veridian...");
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
let (service, messages) = LspService::new(|client| Arc::new(Backend::new(client, log_handle)));
Server::new(stdin, stdout)
.interleave(messages)
.serve(service)
.await;
}
|
mod physics;
pub use physics::*;
use specs::prelude::*;
use specs::{System, WriteStorage, ReadStorage};
use crate::ecs::components::*;
use crate::ecs::resources::*;
use nalgebra_glm::{vec2, Mat4, vec3};
use nalgebra::{Vector3, Matrix4};
use glfw::{Key, WindowEvent};
use ncollide3d::shape::{ShapeHandle, Cuboid};
use nphysics3d::object::ColliderDesc;
use nphysics3d::material::MaterialHandle;
use glfw::ffi::glfwGetTime;
use crate::shaders::outline::OutlineData;
use crate::shaders::ShaderData;
use crate::gl_wrapper::fbo::FBO;
use crate::containers::CONTAINER;
use crate::shapes::PredefinedShapes;
use crate::shaders::cube_map::CubeMapShader;
use crate::gl_wrapper::texture_cube_map::TextureCubeMap;
use crate::gl_wrapper::ubo::{Std140, GlslTypes, UBO, ComputeStd140LayoutSize};
use std::os::raw::c_void;
use crate::gl_wrapper::BufferUpdateFrequency;
struct CameraUBO<'a> {
pub view: &'a Mat4,
pub projection: &'a Mat4,
}
impl<'a> Std140 for CameraUBO<'a> {
fn get_std140_layout(&self) -> &'static [GlslTypes] {
&[
GlslTypes::Mat4,
GlslTypes::Mat4
]
}
fn write_to_ubo(&self, ubo: &UBO) {
unsafe {
// gl_call!(gl::NamedBufferSubData(ubo.id, 0, 4 * 16, self.view.as_ptr() as *mut c_void));
// gl_call!(gl::NamedBufferSubData(ubo.id, 4 * 16, 4 * 16, self.projection.as_ptr() as *mut c_void));
let buf: *mut c_void = gl_call!(gl::MapNamedBufferRange(ubo.id, 0, ubo.layout.compute_std140_layout_size() as isize, gl::MAP_WRITE_BIT | gl::MAP_UNSYNCHRONIZED_BIT));
let buf = buf.cast::<f32>();
self.view.as_ptr().copy_to_nonoverlapping(buf, 16);
self.projection.as_ptr().copy_to_nonoverlapping(buf.offset(16), 16);
gl_call!(gl::UnmapNamedBuffer(ubo.id));
}
}
}
pub struct TransformSystem {
pub reader_id: ReaderId<ComponentEvent>,
pub dirty: BitSet,
}
impl<'a> System<'a> for TransformSystem {
type SystemData = (Entities<'a>, WriteStorage<'a, Transform>);
fn run(&mut self, (_entities, mut transforms): Self::SystemData) {
self.dirty.clear();
let events = transforms.channel().read(&mut self.reader_id);
for event in events {
match event {
ComponentEvent::Modified(id) | ComponentEvent::Inserted(id) => {
self.dirty.add(*id);
}
ComponentEvent::Removed(_) => (),
}
}
for (mut transforms, _entity) in (&mut transforms.restrict_mut(), &self.dirty).join() {
let mut transform = transforms.get_mut_unchecked();
transform.model_matrix = {
let translate_matrix = Matrix4::new_translation(&transform.position);
let rotate_matrix = Matrix4::from_euler_angles(
transform.rotation.x,
transform.rotation.y,
transform.rotation.z,
);
let scale_matrix: Mat4 = Matrix4::new_nonuniform_scaling(&transform.scale);
translate_matrix * rotate_matrix * scale_matrix
};
}
// Workaround for unflagging the components
transforms.channel().read(&mut self.reader_id);
}
}
pub struct InputSystem;
impl<'a> System<'a> for InputSystem {
type SystemData = (Write<'a, InputEventQueue>,
ReadStorage<'a, Input>,
WriteStorage<'a, Transform>,
ReadStorage<'a, Camera>,
Read<'a, ActiveCamera>,
Write<'a, InputCache>);
fn run(&mut self, (mut input_event_queue, _inputs, mut transforms, cameras, active_camera, mut input_cache): Self::SystemData) {
let active_camera = active_camera.entity.unwrap();
let _camera = cameras.get(active_camera).unwrap();
while let Some(ref event) = input_event_queue.queue.pop_front() {
let transform = transforms.get_mut(active_camera).unwrap();
match event {
WindowEvent::CursorPos(x, y) => {
let x = *x as f32;
let y = *y as f32;
let current_pos = vec2(x, y);
input_cache.cursor_rel_pos = current_pos - input_cache.last_cursor_pos;
input_cache.last_cursor_pos = vec2(x, y);
let (x, y) = (input_cache.cursor_rel_pos.x, input_cache.cursor_rel_pos.y);
// println!("x: {} y: {}", x, y);
// transform.rotation.y += x * 0.001;
// transform.rotation.x -= y * 0.001;
}
WindowEvent::Key(key, _, action, _) => {
input_cache.key_states.insert(*key, *action);
}
_ => {}
}
}
if input_cache.is_key_pressed(Key::W) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position += transform.forward().scale(0.03f32);
}
if input_cache.is_key_pressed(Key::S) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position -= transform.forward().scale(0.03f32);
}
if input_cache.is_key_pressed(Key::A) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position -= transform.forward().cross(&Vector3::y()).scale(0.03f32);
}
if input_cache.is_key_pressed(Key::D) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position += transform.forward().cross(&Vector3::y()).scale(0.03f32);
}
if input_cache.is_key_pressed(Key::Q) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position.y += 0.03;
}
if input_cache.is_key_pressed(Key::Z) {
let transform = transforms.get_mut(active_camera).unwrap();
transform.position.y -= 0.03;
}
}
}
pub struct MeshRendererSystem {
camera_matrices_ubo: UBO
}
impl Default for MeshRendererSystem {
fn default() -> Self {
let camera_matrices_ubo = UBO::new(&[
GlslTypes::Mat4,
GlslTypes::Mat4,
], BufferUpdateFrequency::Often);
camera_matrices_ubo.bind(0);
MeshRendererSystem { camera_matrices_ubo }
}
}
impl<'a> System<'a> for MeshRendererSystem {
type SystemData = (Entities<'a>,
ReadStorage<'a, Transform>,
ReadStorage<'a, MeshRenderer>,
ReadStorage<'a, Camera>,
Read<'a, ActiveCamera>,
ReadStorage<'a, PointLight>,
ReadStorage<'a, Outliner>);
fn run(&mut self, (entities, transforms, mesh_renderer, camera, active_camera, point_lights, outliners): Self::SystemData) {
let (camera, cam_tr) = match active_camera.entity {
Some(e) => (
camera.get(e).expect("Active camera must have a Camera component"),
transforms.get(e).expect("Active camera must have a Transform component")
),
None => return
};
let direction = vec3(
cam_tr.rotation.x.cos() * cam_tr.rotation.y.cos(),
cam_tr.rotation.x.sin(),
cam_tr.rotation.x.cos() * cam_tr.rotation.y.sin(),
);
let view_matrix = nalgebra_glm::look_at(&cam_tr.position, &(cam_tr.position + direction), &Vector3::y());
let projection_matrix = match camera.projection {
Projection::Orthographic(size) => {
nalgebra_glm::ortho(-camera.aspect_ratio * size, camera.aspect_ratio * size, -size, size, camera.near_plane, camera.far_plane)
}
Projection::Perspective(fov) => {
nalgebra_glm::perspective(camera.aspect_ratio, fov, camera.near_plane, camera.far_plane)
}
};
{
let camera_ubo_struct = CameraUBO { view: &view_matrix, projection: &projection_matrix };
self.camera_matrices_ubo.update(&camera_ubo_struct);
}
// Post processing
if camera.post_processing_effects.is_empty() {
FBO::bind_default();
} else {
camera.fb.bind();
}
gl_call!(gl::Viewport(0, 0, 1920, 1080));
gl_call!(gl::Enable(gl::DEPTH_TEST));
gl_call!(gl::DepthFunc(gl::LESS));
gl_call!(gl::Enable(gl::STENCIL_TEST));
gl_call!(gl::StencilMask(0xFF));
if let Background::Color(r, g, b) = camera.background {
gl_call!(gl::ClearColor(r, g, b, 1.0));
}
gl_call!(gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT));
gl_call!(gl::StencilFunc(gl::ALWAYS, 1, 0xFF));
for (entity, transform, mesh_renderer) in (&entities, &transforms, &mesh_renderer).join() {
let model_matrix = transform.model_matrix;
let mesh_renderer = mesh_renderer as &MeshRenderer;
mesh_renderer.mesh.vao.bind();
let shader_data = &mesh_renderer.material.shader_data;
shader_data.bind_model(&model_matrix);
shader_data.bind_lights(&transforms, &point_lights);
// Outline stencil test
if outliners.get(entity).is_some() {
gl_call!(gl::StencilMask(0xFF));
gl_call!(gl::StencilOp(gl::REPLACE, gl::REPLACE, gl::REPLACE));
} else {
// Disable stencil write
gl_call!(gl::StencilMask(0x00));
gl_call!(gl::StencilOp(gl::KEEP, gl::KEEP, gl::KEEP));
}
gl_call!(gl::DrawElements(gl::TRIANGLES,
mesh_renderer.mesh.indices.len() as i32,
gl::UNSIGNED_INT, std::ptr::null()));
}
// Draw skybox
if let Background::Skybox(texture) = &camera.background {
// Disable stencil write
gl_call!(gl::StencilMask(0x00));
gl_call!(gl::StencilOp(gl::KEEP, gl::KEEP, gl::KEEP));
gl_call!(gl::DepthFunc(gl::LEQUAL));
let cubemap_shader = CONTAINER.get_local::<CubeMapShader>();
cubemap_shader.bind();
let cube_vao = CONTAINER.get_local::<PredefinedShapes>().shapes.get("unit_cube").unwrap();
cube_vao.bind();
TextureCubeMap::activate(0);
texture.bind();
gl_call!(gl::DrawArrays(gl::TRIANGLES, 0, 36));
}
// Draw outlined objects
gl_call!(gl::StencilFunc(gl::NOTEQUAL, 1, 0xFF));
gl_call!(gl::StencilMask(0x00));
gl_call!(gl::Disable(gl::DEPTH_TEST));
for (transform, mesh_renderer, outliner) in (&transforms, &mesh_renderer, &outliners).join() {
// Calculate scaled model matrix
let scaled_model_matrix = {
let translate_matrix = Matrix4::new_translation(&transform.position);
let rotate_matrix = Matrix4::from_euler_angles(
transform.rotation.x,
transform.rotation.y,
transform.rotation.z,
);
let scale_vec = transform.scale * outliner.scale;
let scale_matrix: Mat4 = Matrix4::new_nonuniform_scaling(&scale_vec);
translate_matrix * rotate_matrix * scale_matrix
};
let mesh_renderer = mesh_renderer as &MeshRenderer;
mesh_renderer.mesh.vao.bind();
let shader_data = OutlineData {
color: outliner.color
};
shader_data.bind_model(&scaled_model_matrix);
gl_call!(gl::DrawElements(gl::TRIANGLES,
mesh_renderer.mesh.indices.len() as i32,
gl::UNSIGNED_INT, std::ptr::null()));
}
if !camera.post_processing_effects.is_empty() {
let mut last_fb = &camera.fb;
for i in 0..camera.post_processing_effects.len() - 1 {
last_fb = camera.post_processing_effects[i].apply(last_fb);
}
camera.post_processing_effects.last().unwrap().apply_to_screen(last_fb);
}
}
}
//////////////////
// Physics systems
//////////////////
pub struct BoxColliderSystem {
pub reader_id: ReaderId<ComponentEvent>,
pub dirty: BitSet,
}
impl<'a> System<'a> for BoxColliderSystem {
type SystemData = (ReadStorage<'a, Transform>,
Write<'a, PhysicsWorld>,
ReadStorage<'a, BoxCollider>);
fn run(&mut self, (transforms, mut physics_world, box_colliders): Self::SystemData) {
let mut inserted = BitSet::new();
let events = box_colliders.channel().read(&mut self.reader_id);
for event in events {
match event {
ComponentEvent::Inserted(id) => {
inserted.add(*id);
}
ComponentEvent::Modified(id) => {
self.dirty.add(*id);
}
ComponentEvent::Removed(_) => (),
}
}
for (transform, box_collider, _entity) in (&transforms, &box_colliders, &inserted).join() {
let transform = transform as &Transform;
let box_collider = box_collider as &BoxCollider;
let half_size = box_collider.box_size.scale(0.5);
let shape = ShapeHandle::<f32>::new(Cuboid::new(half_size));
let _collider = ColliderDesc::new(shape)
.translation(transform.position)
.rotation(transform.rotation)
.material(MaterialHandle::new(box_collider.material))
.build(&mut physics_world.world);
}
}
}
#[derive(Default)]
pub struct PrintFramerate {
prev: f64,
frames: u32,
}
impl<'a> System<'a> for PrintFramerate {
type SystemData = Read<'a, Time>;
fn run(&mut self, _time: Self::SystemData) {
self.frames += 1;
let now = unsafe { glfwGetTime() };
let delta = now - self.prev;
if delta >= 1.0 {
self.prev = now;
println!("Framerate: {}", f64::from(self.frames) / delta);
self.frames = 0;
}
}
} |
use super::{Channel, Colorspace};
#[derive(Debug, Copy)]
pub struct ColorL<T> {
pub l: T,
}
impl<T: Clone> Clone for ColorL<T> {
fn clone(&self) -> ColorL<T> {
ColorL { l: self.l.clone() }
}
}
impl<T: Channel> ColorL<T> {
pub fn new_l(l: T) -> ColorL<T> {
ColorL { l: l }
}
}
impl<T> Colorspace for ColorL<T> where T: Channel+Copy {
fn white() -> Self {
ColorL { l: Channel::max_value() }
}
fn black() -> Self {
ColorL { l: Channel::min_value() }
}
} |
pub use article::Article;
pub use language_site::LanguageSite;
pub use section::Section;
pub use site::{Site, SiteConfig};
pub use site_index::{ArticleSearchIndex, DisambiguationSearchIndex, SearchIndex};
mod article;
mod language_site;
mod section;
mod site;
mod site_index;
|
use opcode::*;
use std::trie::*;
use std::ptr::*;
use libjit::*;
use std::to_bytes::*;
use std::hash::*;
/**
* Represents a basic block.
* http://en.wikipedia.org/wiki/Basic_block
*/
#[Deriving(Hash)]
struct BasicBlock {
/// Basic blocks that control can flow to this one from.
prev_blocks: ~[@mut BasicBlock],
/// The next basic block in the control flow. This is either
/// because it starts with the next instruction, is the target
/// or an unconditional branch, or is the fall-through for
/// a conditional branch.
next_block: Option<@mut BasicBlock>,
/// The target basic block for a condiditional (Iftrue) branch.
conditional_block: Option<@mut BasicBlock>,
/// The instructions within the basic block.
opcodes: ~[Opcode],
/// The JIT Label that marks the start of this basic block.
label: ~Label
}
impl IterBytes for BasicBlock {
pub fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool {
(to_unsafe_ptr(self) as u64).iter_bytes(lsb0, f)
}
}
impl Eq for BasicBlock {
pub fn eq(&self, other: &BasicBlock) -> bool {
return self.hash() == other.hash();
}
}
impl BasicBlock {
/**
* Creates a new BasicBlock.
*/
pub fn new() -> @mut BasicBlock {
@mut BasicBlock {
prev_blocks: ~[],
conditional_block: None,
next_block: None,
opcodes: ~[],
label: Label::new()
}
}
/**
* Pushes an Opcode to the end of the basic block.
*/
pub fn push_opcode(&mut self, opcode: Opcode) {
self.opcodes.push(opcode);
}
/**
* Prints a basic block for diagnostic purposes.
*/
pub fn print(&self) {
println(fmt!("BasicBlock: 0x%X", to_unsafe_ptr(self) as uint));
println("prev_blocks:");
for block in self.prev_blocks.iter() {
println(fmt!(" 0x%X", to_unsafe_ptr(*block) as uint));
}
print("next_block: ");
match self.next_block {
None => { println("none"); }
Some(b) => { println(fmt!("0x%X", to_unsafe_ptr(b) as uint)); }
}
print("conditional_block: ");
match self.conditional_block {
None => { println("none"); }
Some(b) => { println(fmt!("0x%X", to_unsafe_ptr(b) as uint)); }
}
println("opcodes");
for opcode in self.opcodes.iter() {
println(fmt!(" %?", opcode));
}
println("");
}
}
/**
* Computes the basic blocks for a stream of Opcodes.
*
* # Arguments
*
* * function - The function to compute a basic block representation of.
*
* Returns a list of basic blocks.
*/
pub fn get_basic_blocks(function: &[Opcode]) -> ~[@mut BasicBlock] {
let mut basic_blocks_map = TrieMap::new();
basic_blocks_map.insert(0u, BasicBlock::new());
for (index, opcode) in range(0, function.len()).zip(function.iter()) {
match *opcode {
Jmp(n) | Iftrue(n) => {
match basic_blocks_map.find(&(n as uint)) {
None => {
basic_blocks_map.insert(n as uint, BasicBlock::new());
}
_ => { }
}
basic_blocks_map.insert(index + 1, BasicBlock::new());
}
_ => { }
}
}
// r-values lifetime bug again.
let temp = basic_blocks_map.find(&0);
let mut current_block: @mut BasicBlock = **temp.get_ref();
// TODO: the types here are an absolute mess
for (index, opcode) in range(0, function.len()).zip(function.iter()) {
match *opcode {
Jmp(n) => {
let next_block = basic_blocks_map.find(&(n as uint));
next_block.get_ref().prev_blocks.push(current_block);
current_block.next_block = Some(**next_block.get_ref());
current_block = **next_block.get_ref();
}
Iftrue(n) => {
let conditional_block = basic_blocks_map.find(&(n as uint));
conditional_block.get_ref().prev_blocks.push(current_block);
current_block.conditional_block = Some(**conditional_block.get_ref());
let next_block = basic_blocks_map.find(&(index + 1));
current_block.next_block = Some(**next_block.get_ref());
current_block = **next_block.get_ref();
}
_ => {
if (index != 0) {
let temp = basic_blocks_map.find(&index);
match temp {
Some(b) => {
match current_block.next_block {
None => {
current_block.next_block = Some(*b);
b.prev_blocks.push(current_block);
}
_ => { }
}
current_block = *b;
}
_ => { }
}
}
current_block.push_opcode(*opcode);
}
}
}
let mut basic_blocks: ~[@mut BasicBlock] = ~[];
basic_blocks_map.each_value(|v| {
basic_blocks.push(*v);
true
});
return basic_blocks;
}
/**
* Prints a list of basic blocks for diagnostic purposes.
* @type {[type]}
*/
pub fn print_basic_blocks(basic_blocks: &[@mut BasicBlock]) {
for basic_block in basic_blocks.iter() {
basic_block.print();
}
}
|
extern crate hack;
use std::io::Read;
use std::path::{Path};
use std::collections::{HashMap};
use hack::instruction::*;
use hack::Word;
fn main() {
let file = std::env::args().nth(1).unwrap();
let lines = read_all_lines(&file);
// let lines: Vec<String> = lines.into_iter().filter(|l| !l.starts_with("//") && !l.trim().is_empty()).collect();
let parsed = sanitize(&lines);
symbol_table(&parsed);
for (i, l) in parsed.iter().enumerate() {
println!("{}: {:?}", i, l);
}
// tokenizer(&lines);
// lex(&lines);
return;
println!("START:");
for line in &lines {
println!("{}", line);
}
for (i, line) in lines.iter().enumerate() {
let instruction = line.trim_matches(char::is_whitespace).parse::<Instruction>().unwrap();
println!("{:>3} | {:0>16b}: {}", i, hack::Word::from(instruction), instruction);
}
// if let Some(file) = file {
// // std::fs::metadata(
// }
// else {
// println!("No file given");
// }
}
enum Token {
Label(String),
AddressInstruction(String),
ComputeInstruction(String),
Empty,
}
impl FromStr for Token {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
for c in s.char_indices().skip_while((
}
}
fn label() {
}
fn tokenizer(lines: &[String]) {
for line in lines {
let mut chars = line.char_indices().peekable();
while let Some((index, character)) = chars.next() {
if character == '(' {
}
}
while let Some((index, character)) = chars.next() {
if character == '(' {
if let Some(end_index) = chars.find(')') {
if end_index !=
}
while let Some((index, character)) = chars.next() {
if character == ')' {
break;
}
}
}
}
}
}
fn sanitize(raw_lines: &[String]) -> Vec<Option<String>> {
raw_lines.iter().map(|line| {
line.chars()
.filter(|&c| !c.is_whitespace())
.take_while(|&c| c != '/')
.collect::<String>()
})
.map(|sanitized| if sanitized.is_empty() {None} else {Some(sanitized)}).collect()
}
fn symbol_table(lines: &[Option<String>]) -> HashMap<String, Word> {
let mut symbol_table = HashMap::with_capacity(128);
symbol_table.insert("R0".into(), 0);
symbol_table.insert("R1".into(), 1);
symbol_table.insert("R2".into(), 2);
symbol_table.insert("R3".into(), 3);
symbol_table.insert("R4".into(), 4);
symbol_table.insert("R5".into(), 5);
symbol_table.insert("R6".into(), 6);
symbol_table.insert("R7".into(), 7);
symbol_table.insert("R8".into(), 8);
symbol_table.insert("R9".into(), 9);
symbol_table.insert("R10".into(), 10);
symbol_table.insert("R11".into(), 11);
symbol_table.insert("R12".into(), 12);
symbol_table.insert("R13".into(), 13);
symbol_table.insert("R14".into(), 14);
symbol_table.insert("R15".into(), 15);
symbol_table.insert("SCREEN".into(), 16384);
symbol_table.insert("KBD".into(), 24576);
symbol_table.insert("SP".into(), 0);
symbol_table.insert("LCL".into(), 1);
symbol_table.insert("ARG".into(), 2);
symbol_table.insert("THIS".into(), 3);
symbol_table.insert("THAT".into(), 4);
let mut next_variable_address = 1024;
// for (line_number, line) in lines.iter().enumerate().filter(|&(_, ref i)| i.is_some()) {
// if let Some(ref line) = line {
// for c
// }
// println!("{}", line_number);
// }
symbol_table
}
fn second_pass(instructions: &[String]) -> Vec<Instruction> {
instructions.iter().map(|s| s.parse().unwrap()).collect()
// instructions.iter().map(|s| parse(&s)).collect()
}
fn read_all_lines<P: AsRef<Path>>(file_path: P) -> Vec<String> {
let mut file = std::fs::File::open(file_path).expect("File not found");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Couldn't read lines from file");
contents.split_terminator('\n').map(String::from).collect()
}
|
//! Defines data structures which represent an InfluxQL
//! statement after it has been processed
use crate::error;
use crate::plan::rewriter::ProjectionType;
use datafusion::common::Result;
use influxdb_influxql_parser::common::{
LimitClause, MeasurementName, OffsetClause, OrderByClause, QualifiedMeasurementName,
WhereClause,
};
use influxdb_influxql_parser::expression::{ConditionalExpression, Expr};
use influxdb_influxql_parser::select::{
FieldList, FillClause, FromMeasurementClause, GroupByClause, MeasurementSelection,
SelectStatement, TimeZoneClause,
};
use influxdb_influxql_parser::time_range::TimeRange;
use schema::{InfluxColumnType, Schema};
use std::collections::HashSet;
use std::fmt::{Display, Formatter};
use super::SchemaProvider;
/// A set of tag keys.
pub(super) type TagSet = HashSet<String>;
/// Represents a validated and normalized top-level [`SelectStatement`].
#[derive(Debug, Default, Clone)]
pub(super) struct SelectQuery {
pub(super) select: Select,
}
#[derive(Debug, Default, Clone)]
pub(super) struct Select {
/// The projection type of the selection.
pub(super) projection_type: ProjectionType,
/// The interval derived from the arguments to the `TIME` function
/// when a `GROUP BY` clause is declared with `TIME`.
pub(super) interval: Option<Interval>,
/// The number of additional intervals that must be read
/// for queries that group by time and use window functions such as
/// `DIFFERENCE` or `DERIVATIVE`. This ensures data for the first
/// window is available.
///
/// See: <https://github.com/influxdata/influxdb/blob/f365bb7e3a9c5e227dbf66d84adf674d3d127176/query/compile.go#L50>
pub(super) extra_intervals: usize,
/// Projection clause of the selection.
pub(super) fields: Vec<Field>,
/// A list of data sources for the selection.
pub(super) from: Vec<DataSource>,
/// A conditional expression to filter the selection, excluding any predicates for the `time`
/// column.
pub(super) condition: Option<ConditionalExpression>,
/// The time range derived from the `WHERE` clause of the `SELECT` statement.
pub(super) time_range: TimeRange,
/// The GROUP BY clause of the selection.
pub(super) group_by: Option<GroupByClause>,
/// The set of possible tags for the selection, by combining
/// the tag sets of all inputs via the `FROM` clause.
pub(super) tag_set: TagSet,
/// The [fill] clause specifies the fill behaviour for the selection. If the value is [`None`],
/// it is the same behavior as `fill(null)`.
///
/// [fill]: https://docs.influxdata.com/influxdb/v1.8/query_language/explore-data/#group-by-time-intervals-and-fill
pub(super) fill: Option<FillClause>,
/// Configures the ordering of the selection by time.
pub(super) order_by: Option<OrderByClause>,
/// A value to restrict the number of rows returned.
pub(super) limit: Option<LimitClause>,
/// A value to specify an offset to start retrieving rows.
pub(super) offset: Option<OffsetClause>,
/// The timezone for the query, specified as [`tz('<time zone>')`][time_zone_clause].
///
/// [time_zone_clause]: https://docs.influxdata.com/influxdb/v1.8/query_language/explore-data/#the-time-zone-clause
pub(super) timezone: Option<chrono_tz::Tz>,
}
impl From<Select> for SelectStatement {
fn from(value: Select) -> Self {
Self {
fields: FieldList::new(
value
.fields
.into_iter()
.map(|c| influxdb_influxql_parser::select::Field {
expr: c.expr,
alias: Some(c.name.into()),
})
.collect(),
),
from: FromMeasurementClause::new(
value
.from
.into_iter()
.map(|tr| match tr {
DataSource::Table(name) => {
MeasurementSelection::Name(QualifiedMeasurementName {
database: None,
retention_policy: None,
name: MeasurementName::Name(name.as_str().into()),
})
}
DataSource::Subquery(q) => {
MeasurementSelection::Subquery(Box::new((*q).into()))
}
})
.collect(),
),
condition: where_clause(value.condition, value.time_range),
group_by: value.group_by,
fill: value.fill,
order_by: value.order_by,
limit: value.limit,
offset: value.offset,
series_limit: None,
series_offset: None,
timezone: value.timezone.map(TimeZoneClause::new),
}
}
}
/// Combine the `condition` and `time_range` into a single `WHERE` predicate.
fn where_clause(
condition: Option<ConditionalExpression>,
time_range: TimeRange,
) -> Option<WhereClause> {
let time_expr: Option<ConditionalExpression> = match (time_range.lower, time_range.upper) {
(Some(lower), Some(upper)) if lower == upper => {
Some(format!("time = {lower}").parse().unwrap())
}
(Some(lower), Some(upper)) => Some(
format!("time >= {lower} AND time <= {upper}")
.parse()
.unwrap(),
),
(Some(lower), None) => Some(format!("time >= {lower}").parse().unwrap()),
(None, Some(upper)) => Some(format!("time <= {upper}").parse().unwrap()),
(None, None) => None,
};
match (time_expr, condition) {
(Some(lhs), Some(rhs)) => Some(WhereClause::new(lhs.and(rhs))),
(Some(expr), None) | (None, Some(expr)) => Some(WhereClause::new(expr)),
(None, None) => None,
}
}
/// Represents a data source that is either a table or a subquery in a [`Select`] from clause.
#[derive(Debug, Clone)]
pub(super) enum DataSource {
Table(String),
Subquery(Box<Select>),
}
impl DataSource {
pub(super) fn schema(&self, s: &dyn SchemaProvider) -> Result<DataSourceSchema<'_>> {
match self {
Self::Table(table_name) => s
.table_schema(table_name)
.map(DataSourceSchema::Table)
.ok_or_else(|| error::map::internal("expected table")),
Self::Subquery(q) => Ok(DataSourceSchema::Subquery(q)),
}
}
}
pub(super) enum DataSourceSchema<'a> {
Table(Schema),
Subquery(&'a Select),
}
impl<'a> DataSourceSchema<'a> {
/// Returns `true` if the specified name is a tag field or a projection of a tag field if
/// the `DataSource` is a subquery.
pub(super) fn is_tag_field(&self, name: &str) -> bool {
match self {
DataSourceSchema::Table(s) => {
matches!(s.field_type_by_name(name), Some(InfluxColumnType::Tag))
}
DataSourceSchema::Subquery(q) => q.tag_set.contains(name),
}
}
/// Returns `true` if the specified name is a tag from the perspective of an outer
/// query consuming the results of this subquery or table. If a subquery has aliases
/// on its SELECT list, then those aliases are considered to be the names of the
/// columns in the outer query.
pub(super) fn is_projected_tag_field(&self, name: &str) -> bool {
match self {
DataSourceSchema::Table(_) => self.is_tag_field(name),
DataSourceSchema::Subquery(q) => q
.fields
.iter()
.any(|f| f.name == name && f.data_type == Some(InfluxColumnType::Tag)),
}
}
}
#[derive(Debug, Clone)]
pub(super) struct Field {
pub(super) expr: Expr,
pub(super) name: String,
pub(super) data_type: Option<InfluxColumnType>,
}
impl Display for Field {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.expr, f)?;
write!(f, " AS {}", self.name)
}
}
/// Represents the interval duration and offset
/// derived from the `TIME` function when specified
/// in a `GROUP BY` clause.
#[derive(Debug, Clone, Copy)]
pub(super) struct Interval {
/// The nanosecond duration of the interval
pub duration: i64,
/// The nanosecond offset of the interval.
pub offset: Option<i64>,
}
|
use std::{borrow::Cow, fmt};
#[derive(Debug)]
pub struct KafkaMessage<'a> {
pub topic: Cow<'a, str>,
pub partition: i32,
pub offset: i64,
pub key: Option<Cow<'a, [u8]>>,
pub value: Option<Cow<'a, [u8]>>,
}
impl<'a> KafkaMessage<'a> {
pub fn into_offset(self) -> KafkaOffset<'a> {
KafkaOffset {
topic: self.topic,
partition: self.partition,
offset: self.offset,
}
}
pub fn detached(&self) -> KafkaMessage<'static> {
KafkaMessage {
topic: self.topic.as_ref().to_owned().into(),
partition: self.partition,
offset: self.offset,
key: self.key.as_ref().map(|k| Cow::Owned(k.as_ref().to_owned())),
value: self
.value
.as_ref()
.map(|k| Cow::Owned(k.as_ref().to_owned())),
}
}
}
pub struct KafkaOffset<'a> {
pub topic: Cow<'a, str>,
pub partition: i32,
pub offset: i64,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KafkaPartition {
pub topic_name: String,
pub partition_index: i32,
}
impl fmt::Display for KafkaPartition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}[{}]", self.topic_name, self.partition_index)
}
}
|
#![cfg_attr(feature = "unstable", feature(test))]
pub mod sort;
|
#![feature(associated_consts)]
pub mod store;
|
use serde_json::{json, Value};
use morgan::verifier::new_validator_for_tests;
use morgan_client::rpc_client::RpcClient;
use morgan_client::rpc_request::RpcRequest;
use morgan_tokenbot::drone::run_local_drone;
use morgan_interface::bpf_loader;
use morgan_wallet::wallet::{process_command, WalletCommand, WalletConfig};
use std::fs::{remove_dir_all, File};
use std::io::Read;
use std::path::PathBuf;
use std::sync::mpsc::channel;
#[test]
fn test_wallet_deploy_program() {
morgan_logger::setup();
let mut pathbuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
pathbuf.push("tests");
pathbuf.push("fixtures");
pathbuf.push("noop");
pathbuf.set_extension("so");
let (server, leader_data, alice, ledger_path) = new_validator_for_tests();
let (sender, receiver) = channel();
run_local_drone(alice, sender, None);
let drone_addr = receiver.recv().unwrap();
let rpc_client = RpcClient::new_socket(leader_data.rpc);
let mut config = WalletConfig::default();
config.drone_port = drone_addr.port();
config.json_rpc_url = format!("http://{}:{}", leader_data.rpc.ip(), leader_data.rpc.port());
config.command = WalletCommand::Airdrop(50);
process_command(&config).unwrap();
config.command = WalletCommand::Deploy(pathbuf.to_str().unwrap().to_string());
let response = process_command(&config);
let json: Value = serde_json::from_str(&response.unwrap()).unwrap();
let program_id_str = json
.as_object()
.unwrap()
.get("programId")
.unwrap()
.as_str()
.unwrap();
let params = json!([program_id_str]);
let account_info = rpc_client
.retry_make_rpc_request(&RpcRequest::GetAccountInfo, Some(params), 0)
.unwrap();
let account_info_obj = account_info.as_object().unwrap();
assert_eq!(
account_info_obj.get("difs").unwrap().as_u64().unwrap(),
1
);
let owner_array = account_info.get("owner").unwrap();
assert_eq!(owner_array, &json!(bpf_loader::id()));
assert_eq!(
account_info_obj
.get("executable")
.unwrap()
.as_bool()
.unwrap(),
true
);
let mut file = File::open(pathbuf.to_str().unwrap().to_string()).unwrap();
let mut elf = Vec::new();
file.read_to_end(&mut elf).unwrap();
assert_eq!(
account_info_obj.get("data").unwrap().as_array().unwrap(),
&elf
);
server.close().unwrap();
remove_dir_all(ledger_path).unwrap();
}
|
//! Future-aware synchronization
//!
//! This module, which is modeled after `std::sync`, contains user-space
//! synchronization tools that work with futures, streams and sinks. In
//! particular, these synchronizers do *not* block physical OS threads, but
//! instead work at the task level.
//!
//! More information and examples of how to use these synchronization primitives
//! can be found [online at tokio.rs].
//!
//! [online at tokio.rs]: https://tokio.rs/docs/going-deeper-futures/synchronization/
pub mod oneshot;
pub mod mpsc;
mod bilock;
pub use self::bilock::{BiLock, BiLockGuard, BiLockAcquire, BiLockAcquired};
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qaccessibleplugin.h
// dst-file: /src/gui/qaccessibleplugin.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qstring::*; // 771
use super::qaccessible::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QAccessiblePlugin_Class_Size() -> c_int;
// proto: void QAccessiblePlugin::QAccessiblePlugin(QObject * parent);
fn C_ZN17QAccessiblePluginC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: const QMetaObject * QAccessiblePlugin::metaObject();
fn C_ZNK17QAccessiblePlugin10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QAccessiblePlugin::~QAccessiblePlugin();
fn C_ZN17QAccessiblePluginD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QAccessibleInterface * QAccessiblePlugin::create(const QString & key, QObject * object);
fn C_ZN17QAccessiblePlugin6createERK7QStringP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QAccessiblePlugin)=1
#[derive(Default)]
pub struct QAccessiblePlugin {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QAccessiblePlugin {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QAccessiblePlugin {
return QAccessiblePlugin{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QAccessiblePlugin {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QAccessiblePlugin {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QAccessiblePlugin::QAccessiblePlugin(QObject * parent);
impl /*struct*/ QAccessiblePlugin {
pub fn new<T: QAccessiblePlugin_new>(value: T) -> QAccessiblePlugin {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QAccessiblePlugin_new {
fn new(self) -> QAccessiblePlugin;
}
// proto: void QAccessiblePlugin::QAccessiblePlugin(QObject * parent);
impl<'a> /*trait*/ QAccessiblePlugin_new for (Option<&'a QObject>) {
fn new(self) -> QAccessiblePlugin {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QAccessiblePluginC2EP7QObject()};
let ctysz: c_int = unsafe{QAccessiblePlugin_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN17QAccessiblePluginC2EP7QObject(arg0)};
let rsthis = QAccessiblePlugin{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QAccessiblePlugin::metaObject();
impl /*struct*/ QAccessiblePlugin {
pub fn metaObject<RetType, T: QAccessiblePlugin_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QAccessiblePlugin_metaObject<RetType> {
fn metaObject(self , rsthis: & QAccessiblePlugin) -> RetType;
}
// proto: const QMetaObject * QAccessiblePlugin::metaObject();
impl<'a> /*trait*/ QAccessiblePlugin_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QAccessiblePlugin) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QAccessiblePlugin10metaObjectEv()};
let mut ret = unsafe {C_ZNK17QAccessiblePlugin10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QAccessiblePlugin::~QAccessiblePlugin();
impl /*struct*/ QAccessiblePlugin {
pub fn free<RetType, T: QAccessiblePlugin_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QAccessiblePlugin_free<RetType> {
fn free(self , rsthis: & QAccessiblePlugin) -> RetType;
}
// proto: void QAccessiblePlugin::~QAccessiblePlugin();
impl<'a> /*trait*/ QAccessiblePlugin_free<()> for () {
fn free(self , rsthis: & QAccessiblePlugin) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QAccessiblePluginD2Ev()};
unsafe {C_ZN17QAccessiblePluginD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QAccessibleInterface * QAccessiblePlugin::create(const QString & key, QObject * object);
impl /*struct*/ QAccessiblePlugin {
pub fn create<RetType, T: QAccessiblePlugin_create<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.create(self);
// return 1;
}
}
pub trait QAccessiblePlugin_create<RetType> {
fn create(self , rsthis: & QAccessiblePlugin) -> RetType;
}
// proto: QAccessibleInterface * QAccessiblePlugin::create(const QString & key, QObject * object);
impl<'a> /*trait*/ QAccessiblePlugin_create<QAccessibleInterface> for (&'a QString, &'a QObject) {
fn create(self , rsthis: & QAccessiblePlugin) -> QAccessibleInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QAccessiblePlugin6createERK7QStringP7QObject()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN17QAccessiblePlugin6createERK7QStringP7QObject(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QAccessibleInterface::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
pub mod issue22;
pub mod issue37;
pub mod issue39;
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qline.h
// dst-file: /src/core/qline.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qpoint::*; // 773
// use super::qline::QLine; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QLine_Class_Size() -> c_int;
// proto: bool QLine::isNull();
fn C_ZNK5QLine6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QLine QLine::translated(const QPoint & p);
fn C_ZNK5QLine10translatedERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QLine::setP2(const QPoint & p2);
fn C_ZN5QLine5setP2ERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QLine::x2();
fn C_ZNK5QLine2x2Ev(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QLine::QLine(const QPoint & pt1, const QPoint & pt2);
fn C_ZN5QLineC2ERK6QPointS2_(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: void QLine::setP1(const QPoint & p1);
fn C_ZN5QLine5setP1ERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QLine::translate(const QPoint & p);
fn C_ZN5QLine9translateERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: int QLine::dx();
fn C_ZNK5QLine2dxEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QLine::y2();
fn C_ZNK5QLine2y2Ev(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QLine::dy();
fn C_ZNK5QLine2dyEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QLine::y1();
fn C_ZNK5QLine2y1Ev(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QPoint QLine::p1();
fn C_ZNK5QLine2p1Ev(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QPoint QLine::p2();
fn C_ZNK5QLine2p2Ev(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QLine::QLine(int x1, int y1, int x2, int y2);
fn C_ZN5QLineC2Eiiii(arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int) -> u64;
// proto: void QLine::translate(int dx, int dy);
fn C_ZN5QLine9translateEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: QLine QLine::translated(int dx, int dy);
fn C_ZNK5QLine10translatedEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void;
// proto: void QLine::setPoints(const QPoint & p1, const QPoint & p2);
fn C_ZN5QLine9setPointsERK6QPointS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QLine::setLine(int x1, int y1, int x2, int y2);
fn C_ZN5QLine7setLineEiiii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int);
// proto: int QLine::x1();
fn C_ZNK5QLine2x1Ev(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QLine::QLine();
fn C_ZN5QLineC2Ev() -> u64;
fn QLineF_Class_Size() -> c_int;
// proto: void QLineF::translate(qreal dx, qreal dy);
fn C_ZN6QLineF9translateEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double);
// proto: void QLineF::setPoints(const QPointF & p1, const QPointF & p2);
fn C_ZN6QLineF9setPointsERK7QPointFS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: void QLineF::setP2(const QPointF & p2);
fn C_ZN6QLineF5setP2ERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QLineF QLineF::translated(qreal dx, qreal dy);
fn C_ZNK6QLineF10translatedEdd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double) -> *mut c_void;
// proto: void QLineF::setLength(qreal len);
fn C_ZN6QLineF9setLengthEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: qreal QLineF::x1();
fn C_ZNK6QLineF2x1Ev(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QLineF::angle();
fn C_ZNK6QLineF5angleEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QLineF::QLineF(const QPointF & pt1, const QPointF & pt2);
fn C_ZN6QLineFC2ERK7QPointFS2_(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: qreal QLineF::length();
fn C_ZNK6QLineF6lengthEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QLineF::QLineF(const QLine & line);
fn C_ZN6QLineFC2ERK5QLine(arg0: *mut c_void) -> u64;
// proto: void QLineF::setAngle(qreal angle);
fn C_ZN6QLineF8setAngleEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: qreal QLineF::x2();
fn C_ZNK6QLineF2x2Ev(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QLineF::translate(const QPointF & p);
fn C_ZN6QLineF9translateERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QLineF::dx();
fn C_ZNK6QLineF2dxEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QLineF::QLineF();
fn C_ZN6QLineFC2Ev() -> u64;
// proto: QPointF QLineF::p1();
fn C_ZNK6QLineF2p1Ev(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QLineF QLineF::normalVector();
fn C_ZNK6QLineF12normalVectorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QLine QLineF::toLine();
fn C_ZNK6QLineF6toLineEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QPointF QLineF::pointAt(qreal t);
fn C_ZNK6QLineF7pointAtEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> *mut c_void;
// proto: QPointF QLineF::p2();
fn C_ZNK6QLineF2p2Ev(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: qreal QLineF::y2();
fn C_ZNK6QLineF2y2Ev(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QLineF::QLineF(qreal x1, qreal y1, qreal x2, qreal y2);
fn C_ZN6QLineFC2Edddd(arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double) -> u64;
// proto: qreal QLineF::dy();
fn C_ZNK6QLineF2dyEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: QLineF QLineF::unitVector();
fn C_ZNK6QLineF10unitVectorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QLineF::isNull();
fn C_ZNK6QLineF6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: qreal QLineF::y1();
fn C_ZNK6QLineF2y1Ev(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: qreal QLineF::angleTo(const QLineF & l);
fn C_ZNK6QLineF7angleToERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_double;
// proto: QLineF QLineF::translated(const QPointF & p);
fn C_ZNK6QLineF10translatedERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QLineF::setLine(qreal x1, qreal y1, qreal x2, qreal y2);
fn C_ZN6QLineF7setLineEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double);
// proto: static QLineF QLineF::fromPolar(qreal length, qreal angle);
fn C_ZN6QLineF9fromPolarEdd(arg0: c_double, arg1: c_double) -> *mut c_void;
// proto: void QLineF::setP1(const QPointF & p1);
fn C_ZN6QLineF5setP1ERK7QPointF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QLineF::angle(const QLineF & l);
fn C_ZNK6QLineF5angleERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_double;
} // <= ext block end
// body block begin =>
// class sizeof(QLine)=16
#[derive(Default)]
pub struct QLine {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QLineF)=32
#[derive(Default)]
pub struct QLineF {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QLine {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QLine {
return QLine{qclsinst: qthis, ..Default::default()};
}
}
// proto: bool QLine::isNull();
impl /*struct*/ QLine {
pub fn isNull<RetType, T: QLine_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QLine_isNull<RetType> {
fn isNull(self , rsthis: & QLine) -> RetType;
}
// proto: bool QLine::isNull();
impl<'a> /*trait*/ QLine_isNull<i8> for () {
fn isNull(self , rsthis: & QLine) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine6isNullEv()};
let mut ret = unsafe {C_ZNK5QLine6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QLine QLine::translated(const QPoint & p);
impl /*struct*/ QLine {
pub fn translated<RetType, T: QLine_translated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.translated(self);
// return 1;
}
}
pub trait QLine_translated<RetType> {
fn translated(self , rsthis: & QLine) -> RetType;
}
// proto: QLine QLine::translated(const QPoint & p);
impl<'a> /*trait*/ QLine_translated<QLine> for (&'a QPoint) {
fn translated(self , rsthis: & QLine) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine10translatedERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK5QLine10translatedERK6QPoint(rsthis.qclsinst, arg0)};
let mut ret1 = QLine::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLine::setP2(const QPoint & p2);
impl /*struct*/ QLine {
pub fn setP2<RetType, T: QLine_setP2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setP2(self);
// return 1;
}
}
pub trait QLine_setP2<RetType> {
fn setP2(self , rsthis: & QLine) -> RetType;
}
// proto: void QLine::setP2(const QPoint & p2);
impl<'a> /*trait*/ QLine_setP2<()> for (&'a QPoint) {
fn setP2(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine5setP2ERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN5QLine5setP2ERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QLine::x2();
impl /*struct*/ QLine {
pub fn x2<RetType, T: QLine_x2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x2(self);
// return 1;
}
}
pub trait QLine_x2<RetType> {
fn x2(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::x2();
impl<'a> /*trait*/ QLine_x2<i32> for () {
fn x2(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2x2Ev()};
let mut ret = unsafe {C_ZNK5QLine2x2Ev(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLine::QLine(const QPoint & pt1, const QPoint & pt2);
impl /*struct*/ QLine {
pub fn new<T: QLine_new>(value: T) -> QLine {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QLine_new {
fn new(self) -> QLine;
}
// proto: void QLine::QLine(const QPoint & pt1, const QPoint & pt2);
impl<'a> /*trait*/ QLine_new for (&'a QPoint, &'a QPoint) {
fn new(self) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLineC2ERK6QPointS2_()};
let ctysz: c_int = unsafe{QLine_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN5QLineC2ERK6QPointS2_(arg0, arg1)};
let rsthis = QLine{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QLine::setP1(const QPoint & p1);
impl /*struct*/ QLine {
pub fn setP1<RetType, T: QLine_setP1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setP1(self);
// return 1;
}
}
pub trait QLine_setP1<RetType> {
fn setP1(self , rsthis: & QLine) -> RetType;
}
// proto: void QLine::setP1(const QPoint & p1);
impl<'a> /*trait*/ QLine_setP1<()> for (&'a QPoint) {
fn setP1(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine5setP1ERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN5QLine5setP1ERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QLine::translate(const QPoint & p);
impl /*struct*/ QLine {
pub fn translate<RetType, T: QLine_translate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.translate(self);
// return 1;
}
}
pub trait QLine_translate<RetType> {
fn translate(self , rsthis: & QLine) -> RetType;
}
// proto: void QLine::translate(const QPoint & p);
impl<'a> /*trait*/ QLine_translate<()> for (&'a QPoint) {
fn translate(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine9translateERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN5QLine9translateERK6QPoint(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QLine::dx();
impl /*struct*/ QLine {
pub fn dx<RetType, T: QLine_dx<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dx(self);
// return 1;
}
}
pub trait QLine_dx<RetType> {
fn dx(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::dx();
impl<'a> /*trait*/ QLine_dx<i32> for () {
fn dx(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2dxEv()};
let mut ret = unsafe {C_ZNK5QLine2dxEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QLine::y2();
impl /*struct*/ QLine {
pub fn y2<RetType, T: QLine_y2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y2(self);
// return 1;
}
}
pub trait QLine_y2<RetType> {
fn y2(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::y2();
impl<'a> /*trait*/ QLine_y2<i32> for () {
fn y2(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2y2Ev()};
let mut ret = unsafe {C_ZNK5QLine2y2Ev(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QLine::dy();
impl /*struct*/ QLine {
pub fn dy<RetType, T: QLine_dy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dy(self);
// return 1;
}
}
pub trait QLine_dy<RetType> {
fn dy(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::dy();
impl<'a> /*trait*/ QLine_dy<i32> for () {
fn dy(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2dyEv()};
let mut ret = unsafe {C_ZNK5QLine2dyEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QLine::y1();
impl /*struct*/ QLine {
pub fn y1<RetType, T: QLine_y1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y1(self);
// return 1;
}
}
pub trait QLine_y1<RetType> {
fn y1(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::y1();
impl<'a> /*trait*/ QLine_y1<i32> for () {
fn y1(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2y1Ev()};
let mut ret = unsafe {C_ZNK5QLine2y1Ev(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QPoint QLine::p1();
impl /*struct*/ QLine {
pub fn p1<RetType, T: QLine_p1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.p1(self);
// return 1;
}
}
pub trait QLine_p1<RetType> {
fn p1(self , rsthis: & QLine) -> RetType;
}
// proto: QPoint QLine::p1();
impl<'a> /*trait*/ QLine_p1<QPoint> for () {
fn p1(self , rsthis: & QLine) -> QPoint {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2p1Ev()};
let mut ret = unsafe {C_ZNK5QLine2p1Ev(rsthis.qclsinst)};
let mut ret1 = QPoint::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPoint QLine::p2();
impl /*struct*/ QLine {
pub fn p2<RetType, T: QLine_p2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.p2(self);
// return 1;
}
}
pub trait QLine_p2<RetType> {
fn p2(self , rsthis: & QLine) -> RetType;
}
// proto: QPoint QLine::p2();
impl<'a> /*trait*/ QLine_p2<QPoint> for () {
fn p2(self , rsthis: & QLine) -> QPoint {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2p2Ev()};
let mut ret = unsafe {C_ZNK5QLine2p2Ev(rsthis.qclsinst)};
let mut ret1 = QPoint::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLine::QLine(int x1, int y1, int x2, int y2);
impl<'a> /*trait*/ QLine_new for (i32, i32, i32, i32) {
fn new(self) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLineC2Eiiii()};
let ctysz: c_int = unsafe{QLine_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let qthis: u64 = unsafe {C_ZN5QLineC2Eiiii(arg0, arg1, arg2, arg3)};
let rsthis = QLine{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QLine::translate(int dx, int dy);
impl<'a> /*trait*/ QLine_translate<()> for (i32, i32) {
fn translate(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine9translateEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN5QLine9translateEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QLine QLine::translated(int dx, int dy);
impl<'a> /*trait*/ QLine_translated<QLine> for (i32, i32) {
fn translated(self , rsthis: & QLine) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine10translatedEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let mut ret = unsafe {C_ZNK5QLine10translatedEii(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QLine::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLine::setPoints(const QPoint & p1, const QPoint & p2);
impl /*struct*/ QLine {
pub fn setPoints<RetType, T: QLine_setPoints<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPoints(self);
// return 1;
}
}
pub trait QLine_setPoints<RetType> {
fn setPoints(self , rsthis: & QLine) -> RetType;
}
// proto: void QLine::setPoints(const QPoint & p1, const QPoint & p2);
impl<'a> /*trait*/ QLine_setPoints<()> for (&'a QPoint, &'a QPoint) {
fn setPoints(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine9setPointsERK6QPointS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN5QLine9setPointsERK6QPointS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QLine::setLine(int x1, int y1, int x2, int y2);
impl /*struct*/ QLine {
pub fn setLine<RetType, T: QLine_setLine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLine(self);
// return 1;
}
}
pub trait QLine_setLine<RetType> {
fn setLine(self , rsthis: & QLine) -> RetType;
}
// proto: void QLine::setLine(int x1, int y1, int x2, int y2);
impl<'a> /*trait*/ QLine_setLine<()> for (i32, i32, i32, i32) {
fn setLine(self , rsthis: & QLine) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLine7setLineEiiii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
unsafe {C_ZN5QLine7setLineEiiii(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: int QLine::x1();
impl /*struct*/ QLine {
pub fn x1<RetType, T: QLine_x1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x1(self);
// return 1;
}
}
pub trait QLine_x1<RetType> {
fn x1(self , rsthis: & QLine) -> RetType;
}
// proto: int QLine::x1();
impl<'a> /*trait*/ QLine_x1<i32> for () {
fn x1(self , rsthis: & QLine) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK5QLine2x1Ev()};
let mut ret = unsafe {C_ZNK5QLine2x1Ev(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QLine::QLine();
impl<'a> /*trait*/ QLine_new for () {
fn new(self) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN5QLineC2Ev()};
let ctysz: c_int = unsafe{QLine_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN5QLineC2Ev()};
let rsthis = QLine{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
impl /*struct*/ QLineF {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QLineF {
return QLineF{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QLineF::translate(qreal dx, qreal dy);
impl /*struct*/ QLineF {
pub fn translate<RetType, T: QLineF_translate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.translate(self);
// return 1;
}
}
pub trait QLineF_translate<RetType> {
fn translate(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::translate(qreal dx, qreal dy);
impl<'a> /*trait*/ QLineF_translate<()> for (f64, f64) {
fn translate(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF9translateEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
unsafe {C_ZN6QLineF9translateEdd(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QLineF::setPoints(const QPointF & p1, const QPointF & p2);
impl /*struct*/ QLineF {
pub fn setPoints<RetType, T: QLineF_setPoints<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPoints(self);
// return 1;
}
}
pub trait QLineF_setPoints<RetType> {
fn setPoints(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setPoints(const QPointF & p1, const QPointF & p2);
impl<'a> /*trait*/ QLineF_setPoints<()> for (&'a QPointF, &'a QPointF) {
fn setPoints(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF9setPointsERK7QPointFS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN6QLineF9setPointsERK7QPointFS2_(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QLineF::setP2(const QPointF & p2);
impl /*struct*/ QLineF {
pub fn setP2<RetType, T: QLineF_setP2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setP2(self);
// return 1;
}
}
pub trait QLineF_setP2<RetType> {
fn setP2(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setP2(const QPointF & p2);
impl<'a> /*trait*/ QLineF_setP2<()> for (&'a QPointF) {
fn setP2(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF5setP2ERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QLineF5setP2ERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QLineF QLineF::translated(qreal dx, qreal dy);
impl /*struct*/ QLineF {
pub fn translated<RetType, T: QLineF_translated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.translated(self);
// return 1;
}
}
pub trait QLineF_translated<RetType> {
fn translated(self , rsthis: & QLineF) -> RetType;
}
// proto: QLineF QLineF::translated(qreal dx, qreal dy);
impl<'a> /*trait*/ QLineF_translated<QLineF> for (f64, f64) {
fn translated(self , rsthis: & QLineF) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF10translatedEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let mut ret = unsafe {C_ZNK6QLineF10translatedEdd(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QLineF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLineF::setLength(qreal len);
impl /*struct*/ QLineF {
pub fn setLength<RetType, T: QLineF_setLength<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLength(self);
// return 1;
}
}
pub trait QLineF_setLength<RetType> {
fn setLength(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setLength(qreal len);
impl<'a> /*trait*/ QLineF_setLength<()> for (f64) {
fn setLength(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF9setLengthEd()};
let arg0 = self as c_double;
unsafe {C_ZN6QLineF9setLengthEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QLineF::x1();
impl /*struct*/ QLineF {
pub fn x1<RetType, T: QLineF_x1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x1(self);
// return 1;
}
}
pub trait QLineF_x1<RetType> {
fn x1(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::x1();
impl<'a> /*trait*/ QLineF_x1<f64> for () {
fn x1(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2x1Ev()};
let mut ret = unsafe {C_ZNK6QLineF2x1Ev(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: qreal QLineF::angle();
impl /*struct*/ QLineF {
pub fn angle<RetType, T: QLineF_angle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.angle(self);
// return 1;
}
}
pub trait QLineF_angle<RetType> {
fn angle(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::angle();
impl<'a> /*trait*/ QLineF_angle<f64> for () {
fn angle(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF5angleEv()};
let mut ret = unsafe {C_ZNK6QLineF5angleEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QLineF::QLineF(const QPointF & pt1, const QPointF & pt2);
impl /*struct*/ QLineF {
pub fn new<T: QLineF_new>(value: T) -> QLineF {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QLineF_new {
fn new(self) -> QLineF;
}
// proto: void QLineF::QLineF(const QPointF & pt1, const QPointF & pt2);
impl<'a> /*trait*/ QLineF_new for (&'a QPointF, &'a QPointF) {
fn new(self) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineFC2ERK7QPointFS2_()};
let ctysz: c_int = unsafe{QLineF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN6QLineFC2ERK7QPointFS2_(arg0, arg1)};
let rsthis = QLineF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: qreal QLineF::length();
impl /*struct*/ QLineF {
pub fn length<RetType, T: QLineF_length<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.length(self);
// return 1;
}
}
pub trait QLineF_length<RetType> {
fn length(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::length();
impl<'a> /*trait*/ QLineF_length<f64> for () {
fn length(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF6lengthEv()};
let mut ret = unsafe {C_ZNK6QLineF6lengthEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QLineF::QLineF(const QLine & line);
impl<'a> /*trait*/ QLineF_new for (&'a QLine) {
fn new(self) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineFC2ERK5QLine()};
let ctysz: c_int = unsafe{QLineF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN6QLineFC2ERK5QLine(arg0)};
let rsthis = QLineF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QLineF::setAngle(qreal angle);
impl /*struct*/ QLineF {
pub fn setAngle<RetType, T: QLineF_setAngle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAngle(self);
// return 1;
}
}
pub trait QLineF_setAngle<RetType> {
fn setAngle(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setAngle(qreal angle);
impl<'a> /*trait*/ QLineF_setAngle<()> for (f64) {
fn setAngle(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF8setAngleEd()};
let arg0 = self as c_double;
unsafe {C_ZN6QLineF8setAngleEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QLineF::x2();
impl /*struct*/ QLineF {
pub fn x2<RetType, T: QLineF_x2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.x2(self);
// return 1;
}
}
pub trait QLineF_x2<RetType> {
fn x2(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::x2();
impl<'a> /*trait*/ QLineF_x2<f64> for () {
fn x2(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2x2Ev()};
let mut ret = unsafe {C_ZNK6QLineF2x2Ev(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QLineF::translate(const QPointF & p);
impl<'a> /*trait*/ QLineF_translate<()> for (&'a QPointF) {
fn translate(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF9translateERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QLineF9translateERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QLineF::dx();
impl /*struct*/ QLineF {
pub fn dx<RetType, T: QLineF_dx<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dx(self);
// return 1;
}
}
pub trait QLineF_dx<RetType> {
fn dx(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::dx();
impl<'a> /*trait*/ QLineF_dx<f64> for () {
fn dx(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2dxEv()};
let mut ret = unsafe {C_ZNK6QLineF2dxEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QLineF::QLineF();
impl<'a> /*trait*/ QLineF_new for () {
fn new(self) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineFC2Ev()};
let ctysz: c_int = unsafe{QLineF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN6QLineFC2Ev()};
let rsthis = QLineF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QPointF QLineF::p1();
impl /*struct*/ QLineF {
pub fn p1<RetType, T: QLineF_p1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.p1(self);
// return 1;
}
}
pub trait QLineF_p1<RetType> {
fn p1(self , rsthis: & QLineF) -> RetType;
}
// proto: QPointF QLineF::p1();
impl<'a> /*trait*/ QLineF_p1<QPointF> for () {
fn p1(self , rsthis: & QLineF) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2p1Ev()};
let mut ret = unsafe {C_ZNK6QLineF2p1Ev(rsthis.qclsinst)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QLineF QLineF::normalVector();
impl /*struct*/ QLineF {
pub fn normalVector<RetType, T: QLineF_normalVector<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.normalVector(self);
// return 1;
}
}
pub trait QLineF_normalVector<RetType> {
fn normalVector(self , rsthis: & QLineF) -> RetType;
}
// proto: QLineF QLineF::normalVector();
impl<'a> /*trait*/ QLineF_normalVector<QLineF> for () {
fn normalVector(self , rsthis: & QLineF) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF12normalVectorEv()};
let mut ret = unsafe {C_ZNK6QLineF12normalVectorEv(rsthis.qclsinst)};
let mut ret1 = QLineF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QLine QLineF::toLine();
impl /*struct*/ QLineF {
pub fn toLine<RetType, T: QLineF_toLine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toLine(self);
// return 1;
}
}
pub trait QLineF_toLine<RetType> {
fn toLine(self , rsthis: & QLineF) -> RetType;
}
// proto: QLine QLineF::toLine();
impl<'a> /*trait*/ QLineF_toLine<QLine> for () {
fn toLine(self , rsthis: & QLineF) -> QLine {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF6toLineEv()};
let mut ret = unsafe {C_ZNK6QLineF6toLineEv(rsthis.qclsinst)};
let mut ret1 = QLine::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPointF QLineF::pointAt(qreal t);
impl /*struct*/ QLineF {
pub fn pointAt<RetType, T: QLineF_pointAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.pointAt(self);
// return 1;
}
}
pub trait QLineF_pointAt<RetType> {
fn pointAt(self , rsthis: & QLineF) -> RetType;
}
// proto: QPointF QLineF::pointAt(qreal t);
impl<'a> /*trait*/ QLineF_pointAt<QPointF> for (f64) {
fn pointAt(self , rsthis: & QLineF) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF7pointAtEd()};
let arg0 = self as c_double;
let mut ret = unsafe {C_ZNK6QLineF7pointAtEd(rsthis.qclsinst, arg0)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPointF QLineF::p2();
impl /*struct*/ QLineF {
pub fn p2<RetType, T: QLineF_p2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.p2(self);
// return 1;
}
}
pub trait QLineF_p2<RetType> {
fn p2(self , rsthis: & QLineF) -> RetType;
}
// proto: QPointF QLineF::p2();
impl<'a> /*trait*/ QLineF_p2<QPointF> for () {
fn p2(self , rsthis: & QLineF) -> QPointF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2p2Ev()};
let mut ret = unsafe {C_ZNK6QLineF2p2Ev(rsthis.qclsinst)};
let mut ret1 = QPointF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QLineF::y2();
impl /*struct*/ QLineF {
pub fn y2<RetType, T: QLineF_y2<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y2(self);
// return 1;
}
}
pub trait QLineF_y2<RetType> {
fn y2(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::y2();
impl<'a> /*trait*/ QLineF_y2<f64> for () {
fn y2(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2y2Ev()};
let mut ret = unsafe {C_ZNK6QLineF2y2Ev(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QLineF::QLineF(qreal x1, qreal y1, qreal x2, qreal y2);
impl<'a> /*trait*/ QLineF_new for (f64, f64, f64, f64) {
fn new(self) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineFC2Edddd()};
let ctysz: c_int = unsafe{QLineF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let qthis: u64 = unsafe {C_ZN6QLineFC2Edddd(arg0, arg1, arg2, arg3)};
let rsthis = QLineF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: qreal QLineF::dy();
impl /*struct*/ QLineF {
pub fn dy<RetType, T: QLineF_dy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dy(self);
// return 1;
}
}
pub trait QLineF_dy<RetType> {
fn dy(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::dy();
impl<'a> /*trait*/ QLineF_dy<f64> for () {
fn dy(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2dyEv()};
let mut ret = unsafe {C_ZNK6QLineF2dyEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: QLineF QLineF::unitVector();
impl /*struct*/ QLineF {
pub fn unitVector<RetType, T: QLineF_unitVector<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.unitVector(self);
// return 1;
}
}
pub trait QLineF_unitVector<RetType> {
fn unitVector(self , rsthis: & QLineF) -> RetType;
}
// proto: QLineF QLineF::unitVector();
impl<'a> /*trait*/ QLineF_unitVector<QLineF> for () {
fn unitVector(self , rsthis: & QLineF) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF10unitVectorEv()};
let mut ret = unsafe {C_ZNK6QLineF10unitVectorEv(rsthis.qclsinst)};
let mut ret1 = QLineF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QLineF::isNull();
impl /*struct*/ QLineF {
pub fn isNull<RetType, T: QLineF_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QLineF_isNull<RetType> {
fn isNull(self , rsthis: & QLineF) -> RetType;
}
// proto: bool QLineF::isNull();
impl<'a> /*trait*/ QLineF_isNull<i8> for () {
fn isNull(self , rsthis: & QLineF) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF6isNullEv()};
let mut ret = unsafe {C_ZNK6QLineF6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: qreal QLineF::y1();
impl /*struct*/ QLineF {
pub fn y1<RetType, T: QLineF_y1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.y1(self);
// return 1;
}
}
pub trait QLineF_y1<RetType> {
fn y1(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::y1();
impl<'a> /*trait*/ QLineF_y1<f64> for () {
fn y1(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF2y1Ev()};
let mut ret = unsafe {C_ZNK6QLineF2y1Ev(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: qreal QLineF::angleTo(const QLineF & l);
impl /*struct*/ QLineF {
pub fn angleTo<RetType, T: QLineF_angleTo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.angleTo(self);
// return 1;
}
}
pub trait QLineF_angleTo<RetType> {
fn angleTo(self , rsthis: & QLineF) -> RetType;
}
// proto: qreal QLineF::angleTo(const QLineF & l);
impl<'a> /*trait*/ QLineF_angleTo<f64> for (&'a QLineF) {
fn angleTo(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF7angleToERKS_()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK6QLineF7angleToERKS_(rsthis.qclsinst, arg0)};
return ret as f64; // 1
// return 1;
}
}
// proto: QLineF QLineF::translated(const QPointF & p);
impl<'a> /*trait*/ QLineF_translated<QLineF> for (&'a QPointF) {
fn translated(self , rsthis: & QLineF) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF10translatedERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK6QLineF10translatedERK7QPointF(rsthis.qclsinst, arg0)};
let mut ret1 = QLineF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLineF::setLine(qreal x1, qreal y1, qreal x2, qreal y2);
impl /*struct*/ QLineF {
pub fn setLine<RetType, T: QLineF_setLine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLine(self);
// return 1;
}
}
pub trait QLineF_setLine<RetType> {
fn setLine(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setLine(qreal x1, qreal y1, qreal x2, qreal y2);
impl<'a> /*trait*/ QLineF_setLine<()> for (f64, f64, f64, f64) {
fn setLine(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF7setLineEdddd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
unsafe {C_ZN6QLineF7setLineEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: static QLineF QLineF::fromPolar(qreal length, qreal angle);
impl /*struct*/ QLineF {
pub fn fromPolar_s<RetType, T: QLineF_fromPolar_s<RetType>>( overload_args: T) -> RetType {
return overload_args.fromPolar_s();
// return 1;
}
}
pub trait QLineF_fromPolar_s<RetType> {
fn fromPolar_s(self ) -> RetType;
}
// proto: static QLineF QLineF::fromPolar(qreal length, qreal angle);
impl<'a> /*trait*/ QLineF_fromPolar_s<QLineF> for (f64, f64) {
fn fromPolar_s(self ) -> QLineF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF9fromPolarEdd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let mut ret = unsafe {C_ZN6QLineF9fromPolarEdd(arg0, arg1)};
let mut ret1 = QLineF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QLineF::setP1(const QPointF & p1);
impl /*struct*/ QLineF {
pub fn setP1<RetType, T: QLineF_setP1<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setP1(self);
// return 1;
}
}
pub trait QLineF_setP1<RetType> {
fn setP1(self , rsthis: & QLineF) -> RetType;
}
// proto: void QLineF::setP1(const QPointF & p1);
impl<'a> /*trait*/ QLineF_setP1<()> for (&'a QPointF) {
fn setP1(self , rsthis: & QLineF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN6QLineF5setP1ERK7QPointF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN6QLineF5setP1ERK7QPointF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QLineF::angle(const QLineF & l);
impl<'a> /*trait*/ QLineF_angle<f64> for (&'a QLineF) {
fn angle(self , rsthis: & QLineF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK6QLineF5angleERKS_()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK6QLineF5angleERKS_(rsthis.qclsinst, arg0)};
return ret as f64; // 1
// return 1;
}
}
// <= body block end
|
pub mod a2s;
pub mod q3m;
pub mod q3s;
use crate::models::TProtocol;
use std::collections::HashMap;
pub fn make_default_protocols() -> HashMap<String, TProtocol> {
let mut out = HashMap::new();
let q3s_proto = TProtocol::from(q3s::ProtocolImpl::default());
let q3m_proto = TProtocol::from(q3m::ProtocolImpl {
q3s_protocol: Some(q3s_proto.clone()),
..Default::default()
});
out.insert("q3s".into(), q3s_proto);
out.insert("q3m".into(), q3m_proto);
out
}
|
// Copyright 2018 Kyle Mayes
//
// 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.
extern crate glob;
use std::env;
use std::path::{Path, PathBuf};
use std::process::{Command};
use glob::{MatchOptions};
/// `libclang` directory patterns for FreeBSD and Linux.
const DIRECTORIES_LINUX: &[&str] = &[
"/usr/lib*",
"/usr/lib*/*",
"/usr/lib*/*/*",
"/usr/local/lib*",
"/usr/local/lib*/*",
"/usr/local/lib*/*/*",
"/usr/local/llvm*/lib",
];
/// `libclang` directory patterns for OS X.
const DIRECTORIES_OSX: &[&str] = &[
"/usr/local/opt/llvm*/lib",
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
"/Library/Developer/CommandLineTools/usr/lib",
"/usr/local/opt/llvm*/lib/llvm*/lib",
];
/// `libclang` directory patterns for Windows.
const DIRECTORIES_WINDOWS: &[&str] = &[
"C:\\LLVM\\lib",
"C:\\Program Files*\\LLVM\\lib",
"C:\\MSYS*\\MinGW*\\lib",
];
/// Executes the supplied console command, returning the `stdout` output if the command was
/// successfully executed.
fn run_command(command: &str, arguments: &[&str]) -> Option<String> {
let output = Command::new(command).args(arguments).output().ok()?;
Some(String::from_utf8_lossy(&output.stdout).into_owned())
}
/// Executes `llvm-config`, returning the `stdout` output if the command was successfully executed.
pub fn run_llvm_config(arguments: &[&str]) -> Result<String, String> {
let command = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".into());
match run_command(&command, arguments) {
Some(output) => Ok(output),
None => Err(format!(
"couldn't execute `llvm-config {}`, set the LLVM_CONFIG_PATH environment variable to a \
path to a valid `llvm-config` executable",
arguments.join(" "),
)),
}
}
/// Returns the paths to and the filenames of the files matching the supplied filename patterns in
/// the supplied directory.
fn search_directory(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
// Join the directory to the filename patterns to obtain the path patterns.
let paths = filenames.iter().filter_map(|f| directory.join(f).to_str().map(ToOwned::to_owned));
// Prevent wildcards from matching path separators.
let mut options = MatchOptions::new();
options.require_literal_separator = true;
paths.flat_map(|p| {
if let Ok(paths) = glob::glob_with(&p, &options) {
paths.filter_map(Result::ok).collect()
} else {
vec![]
}
}).filter_map(|p| {
let filename = p.file_name().and_then(|f| f.to_str())?;
Some((directory.to_owned(), filename.into()))
}).collect::<Vec<_>>()
}
/// Returns the paths to and the filenames of the files matching the supplied filename patterns in
/// the supplied directory, checking any relevant sibling directories.
fn search_directories(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
let mut results = search_directory(directory, filenames);
// On Windows, `libclang.dll` is usually found in the LLVM `bin` directory while
// `libclang.lib` is usually found in the LLVM `lib` directory. To keep things
// consistent with other platforms, only LLVM `lib` directories are included in the
// backup search directory globs so we need to search the LLVM `bin` directory here.
if cfg!(target_os="windows") && directory.ends_with("lib") {
let sibling = directory.parent().unwrap().join("bin");
results.extend(search_directory(&sibling, filenames).into_iter());
}
results
}
/// Returns the paths to and the filenames of the `libclang` static or dynamic libraries matching
/// the supplied filename patterns.
pub fn search_libclang_directories(files: &[String], variable: &str) -> Vec<(PathBuf, String)> {
// Search the directory provided by the relevant environment variable.
if let Ok(directory) = env::var(variable).map(|d| Path::new(&d).to_path_buf()) {
return search_directories(&directory, files);
}
let mut found = vec![];
// Search the toolchain directory in the directory provided by `xcode-select --print-path`.
if cfg!(target_os="macos") {
if let Some(output) = run_command("xcode-select", &["--print-path"]) {
let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
let directory = directory.join("Toolchains/XcodeDefault.xctoolchain/usr/lib");
found.extend(search_directories(&directory, files));
}
}
// Search the `bin` and `lib` directories in directory provided by `llvm-config --prefix`.
if let Ok(output) = run_llvm_config(&["--prefix"]) {
let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
found.extend(search_directories(&directory.join("bin"), files));
found.extend(search_directories(&directory.join("lib"), files));
}
// Search the directories provided by the `LD_LIBRARY_PATH` environment variable.
if let Ok(path) = env::var("LD_LIBRARY_PATH") {
for directory in path.split(':').map(Path::new) {
found.extend(search_directories(&directory, files));
}
}
// Determine the `libclang` directory patterns.
let directories = if cfg!(any(target_os="freebsd", target_os="linux")) {
DIRECTORIES_LINUX
} else if cfg!(target_os="macos") {
DIRECTORIES_OSX
} else if cfg!(target_os="windows") {
DIRECTORIES_WINDOWS
} else {
&[]
};
// Search the directories provided by the `libclang` directory patterns.
let mut options = MatchOptions::new();
options.case_sensitive = false;
options.require_literal_separator = true;
for directory in directories.iter().rev() {
if let Ok(directories) = glob::glob_with(directory, &options) {
for directory in directories.filter_map(Result::ok).filter(|p| p.is_dir()) {
found.extend(search_directories(&directory, files));
}
}
}
found
}
|
use egraph_dataset::dataset_1138_bus;
use ndarray::prelude::*;
use petgraph::{graph::node_index, prelude::*};
use petgraph_algorithm_shortest_path::*;
fn run<F>(f: F)
where
F: Fn(&UnGraph<(), ()>) -> Array2<f32>,
{
let graph: UnGraph<(), ()> = dataset_1138_bus();
let actual = f(&graph);
let expected = petgraph::algo::floyd_warshall(&graph, |_| 1.).unwrap();
let n = graph.node_count();
for u in 0..n {
for v in 0..n {
assert_eq!(
actual[[u, v]],
expected[&(node_index(u), node_index(v))],
"d[{}, {}]",
u,
v
);
}
}
}
#[test]
fn test_all_sources_bfs() {
run(|graph| all_sources_bfs(graph, 1.));
}
#[test]
fn test_all_sources_dijkstra() {
run(|graph| all_sources_dijkstra(graph, &mut |_| 1.));
}
#[test]
fn test_warshall_floyd() {
run(|graph| warshall_floyd(graph, &mut |_| 1.));
}
|
/* History
Holds the memory of each set of rounds - a double list of choices.
makes it easy to get the last set of results and add a new result.
we separate the history data from the strategy implementation in order to allow strategies
to play against themselves without colliding data.
*/
use choice::*;
pub struct History {
pub left: Vec<Choice>,
pub right: Vec<Choice>
}
impl History {
pub fn new(rounds: usize) -> History {
History {
left: Vec::with_capacity(rounds),
right: Vec::with_capacity(rounds)
}
}
pub fn last(&self) -> Option<ChoicePair> {
let pa = self.left.last();
let pb = self.right.last();
match (pa, pb) {
(Some(a), Some(b)) => {
Some( ChoicePair::new(*a,*b) )
},
_ => None
}
}
// add a new set of results to the history
// ownership passes to the list
pub fn push(&mut self, cp: ChoicePair) {
let ChoicePair(a, b) = cp;
self.left.push(a);
self.right.push(b);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_history() {
let mut history = History::new(2);
match history.last() {
Some(_) => assert!(false),
None => assert!(true)
}
let cp = ChoicePair(true, true);
history.push(cp);
match history.last() {
Some(_cp) => assert!(true),
None => assert!(false)
}
let cp = ChoicePair(true, false);
history.push(cp);
match history.last() {
Some(cp) => {
assert_eq!(cp.0, true);
assert_eq!(cp.1, false);
}
None => assert!(false)
}
}
}
|
use super::*;
use as_derive_utils::spanned_err;
use quote::ToTokens;
use syn::{WhereClause, WherePredicate};
use crate::utils::{LinearResult, SynResultExt};
/// Parses and prints the syntactically valid where clauses in object safe traits.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct MethodWhereClause<'a> {
pub requires_self_sized: bool,
_marker: PhantomData<&'a ()>,
}
impl<'a> MethodWhereClause<'a> {
pub fn new(where_: &'a WhereClause, ctokens: &'a CommonTokens) -> Result<Self, syn::Error> {
let mut this = MethodWhereClause::default();
let mut error = LinearResult::ok(());
for predicate in &where_.predicates {
match predicate {
WherePredicate::Type(ty_pred) => {
if ty_pred.bounds.is_empty() {
error.push_err(spanned_err!(predicate, "The bounds are empty"));
}
if ty_pred.bounded_ty == ctokens.self_ty
&& ty_pred.bounds[0] == ctokens.sized_bound
{
this.requires_self_sized = true;
} else {
error.push_err(spanned_err!(predicate, "This bound is not supported"));
}
}
WherePredicate::Lifetime { .. } => {
error.push_err(spanned_err!(
predicate,
"Lifetime constraints are not currently supported"
));
}
WherePredicate::Eq { .. } => {
error.push_err(spanned_err!(
predicate,
"Type equality constraints are not currently supported",
));
}
}
}
error.into_result().map(|_| this)
}
pub fn get_tokenizer(&self, ctokens: &'a CommonTokens) -> MethodWhereClauseTokenizer<'_> {
MethodWhereClauseTokenizer {
where_clause: self,
ctokens,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MethodWhereClauseTokenizer<'a> {
where_clause: &'a MethodWhereClause<'a>,
ctokens: &'a CommonTokens,
}
impl<'a> ToTokens for MethodWhereClauseTokenizer<'a> {
fn to_tokens(&self, ts: &mut TokenStream2) {
let where_clause = self.where_clause;
let ctokens = self.ctokens;
if where_clause.requires_self_sized {
ctokens.self_sized.to_tokens(ts);
}
}
}
|
//! Tests the latency model.
use crate::PerfModelTest;
use telamon::device::{ArgMap, Context};
use telamon::helper::{Builder, Reduce, SignatureBuilder};
use telamon::ir;
use telamon::search_space::{Action, DimKind, InstFlag, Order};
/// Tests the latency of an empty loop.
pub struct EmptyLoop;
impl EmptyLoop {
const N: u32 = 1_000_000;
}
impl PerfModelTest for EmptyLoop {
fn name() -> &'static str {
"latency_empty_loop"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
}
fn gen_function(builder: &mut Builder) -> Self {
let size = builder.param_size("n", Self::N);
builder.open_dim_ex(size, DimKind::LOOP);
builder.mov(&0i32);
EmptyLoop
}
}
/// Tests the latency of two nested empty loops.
pub struct TwoEmptyLoop {
d0: ir::DimId,
d1: ir::DimId,
}
impl TwoEmptyLoop {
const N: u32 = 1000;
}
impl PerfModelTest for TwoEmptyLoop {
fn name() -> &'static str {
"latency_two_empty_loop"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
}
fn gen_function(builder: &mut Builder) -> Self {
let size = builder.param_size("n", Self::N);
let d0 = builder.open_dim_ex(size.clone(), DimKind::LOOP);
let d1 = builder.open_dim_ex(size, DimKind::LOOP);
builder.mov(&0i32);
TwoEmptyLoop {
d0: d0[0],
d1: d1[0],
}
}
fn get_actions(&self) -> Vec<Action> {
let d0 = self.d0.into();
let d1 = self.d1.into();
vec![Action::Order(d0, d1, Order::OUTER)]
}
}
/// Tests the latency of a small chain of instruction in a loop iteration.
pub struct InstChain;
impl InstChain {
const N: u32 = 1_000_000;
}
impl PerfModelTest for InstChain {
fn name() -> &'static str {
"inst_chain"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i32);
builder.array::<i64>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let size = builder.param_size("n", Self::N);
let d0 = builder.open_dim_ex(size, DimKind::LOOP);
let i0 = builder.mul(&"x", &"x");
let i1 = builder.mul(&"x", &i0);
let i2 = builder.mul(&"x", &i1);
builder.close_dim(&d0);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &i2, true, pattern, InstFlag::NO_CACHE);
InstChain
}
}
/// Tests the latency of a long chain of instruction in a loop iteration.
pub struct LongInstChain;
impl LongInstChain {
const N: u32 = 10_000;
}
impl PerfModelTest for LongInstChain {
fn name() -> &'static str {
"long_inst_chain"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i64);
builder.array::<i64>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let size = builder.param_size("n", Self::N);
let d0 = builder.open_dim_ex(size, DimKind::LOOP);
let mut inst = builder.mul(&"x", &"x");
for _ in 1..100 {
inst = builder.mul(&"x", &inst);
}
builder.close_dim(&d0);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &inst, true, pattern, InstFlag::NO_CACHE);
LongInstChain
}
}
/// Tests the latency on an unrolled reduction loop.
pub struct UnrollReduction {
d0: ir::DimId,
d1: ir::DimId,
}
impl UnrollReduction {
const N: u32 = 10_000;
}
impl PerfModelTest for UnrollReduction {
fn name() -> &'static str {
"unroll_reduction"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i32);
builder.array::<i32>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let init = builder.mov(&"x");
let d0_size = builder.param_size("n", Self::N);
let d1_size = builder.cst_size(100);
let d0 = builder.open_dim_ex(d0_size, DimKind::LOOP);
let d1 = builder.open_dim_ex(d1_size, DimKind::UNROLL);
let inst = builder.add(&"x", &Reduce(init));
builder.close_dim(&d0);
builder.close_dim(&d1);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &inst, true, pattern, InstFlag::NO_CACHE);
UnrollReduction {
d0: d0[0],
d1: d1[0],
}
}
fn get_actions(&self) -> Vec<Action> {
let d0 = self.d0.into();
let d1 = self.d1.into();
vec![Action::Order(d0, d1, Order::OUTER)]
}
}
/// Tests the latency when two loops are ordered sequentially.
pub struct OrderedLoops;
impl OrderedLoops {
const SIZE: u32 = 1000;
}
impl PerfModelTest for OrderedLoops {
fn name() -> &'static str {
"ordered_loops"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::SIZE as i32);
builder.scalar("k", Self::SIZE as i32);
builder.scalar("m", Self::SIZE as i32);
}
fn gen_function(builder: &mut Builder) -> Self {
let size_n = builder.param_size("n", Self::SIZE);
let size_k = builder.param_size("k", Self::SIZE);
let size_m = builder.param_size("m", Self::SIZE);
builder.open_dim_ex(size_n, DimKind::LOOP);
let d1 = builder.open_dim_ex(size_k, DimKind::LOOP);
builder.mov(&"n");
builder.close_dim(&d1);
let d2 = builder.open_dim_ex(size_m, DimKind::LOOP);
builder.mov(&"n");
builder.order(&d1, &d2, Order::BEFORE);
OrderedLoops
}
}
/// Tests the latency when two thread loops are ordered sequentially.
pub struct OrderedThreadDims;
impl OrderedThreadDims {
const N: u32 = 1_000;
const K: u32 = 100;
}
impl PerfModelTest for OrderedThreadDims {
fn name() -> &'static str {
"ordered_thread_dims"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("k", Self::K as i32);
builder.scalar("x", 1i32);
builder.array::<i32>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let size_n = builder.param_size("n", Self::N);
let size_0 = builder.cst_size(1024);
let size_1 = builder.param_size("k", Self::K);
let size_2 = builder.cst_size(64);
builder.open_dim_ex(size_n, DimKind::LOOP);
let d1 = builder.open_dim_ex(size_0.clone(), DimKind::THREAD);
let pattern = ir::AccessPattern::Unknown(None);
let init =
builder.ld_ex(ir::Type::I(32), &"out", pattern, InstFlag::CACHE_GLOBAL);
let d1_1 = builder.open_dim_ex(size_1.clone(), DimKind::LOOP);
let d1_2 = builder.open_dim_ex(size_2.clone(), DimKind::UNROLL);
let inst = builder.mul(&"x", &Reduce(init));
builder.close_dim(&d1);
builder.close_dim(&d1_1);
builder.close_dim(&d1_2);
let d2 = builder.open_dim_ex(size_0.clone(), DimKind::THREAD);
let d2_1 = builder.open_dim_ex(size_1.clone(), DimKind::LOOP);
let d2_2 = builder.open_dim_ex(size_2.clone(), DimKind::UNROLL);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &inst, true, pattern, InstFlag::CACHE_GLOBAL);
builder.order(&d1, &d1_1, Order::OUTER);
builder.order(&d1_1, &d1_2, Order::OUTER);
builder.order(&d2, &d2_1, Order::OUTER);
builder.order(&d2_1, &d2_2, Order::OUTER);
builder.order(&d1, &d2, Order::BEFORE);
OrderedThreadDims
}
}
/// Test the latency in presence of point to point communication between loops.
pub struct DimMap;
impl DimMap {
const N: u32 = 10_000;
}
impl PerfModelTest for DimMap {
fn name() -> &'static str {
"dim_map"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i64);
builder.array::<i64>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let size_0 = builder.param_size("n", Self::N);
let size_1 = builder.cst_size(4);
let init = builder.mov(&"x");
let init2 = builder.mov(&"x");
let d0 = builder.open_dim_ex(size_0, DimKind::LOOP);
let d1 = builder.open_dim_ex(size_1.clone(), DimKind::UNROLL);
let i0 = builder.mul(&Reduce(init), &"x");
let i1 = builder.mov(&i0);
builder.close_dim(&d1);
let d2 = builder.open_dim_ex(size_1, DimKind::UNROLL);
let op = builder.dim_map(i1, &[(&d1, &d2)], ir::DimMapScope::Thread);
let i2 = builder.mad(&op, &op, &Reduce(init2));
builder.close_dim(&d2);
builder.close_dim(&d0);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &i2, true, pattern, InstFlag::NO_CACHE);
builder.order(&d1, &d2, Order::BEFORE);
DimMap
}
}
/// Test a latency that depends on the operand position, in the slow position.
pub struct OperandPositionSlow;
impl OperandPositionSlow {
const N: u32 = 10_000;
}
impl PerfModelTest for OperandPositionSlow {
fn name() -> &'static str {
"operand_position_slow"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i64);
builder.array::<i64>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let init = builder.mov(&"x");
let d0_size = builder.param_size("n", Self::N);
let d1_size = builder.cst_size(100);
let d0 = builder.open_dim_ex(d0_size, DimKind::LOOP);
let d1 = builder.open_dim_ex(d1_size, DimKind::UNROLL);
let inst = builder.mad(&Reduce(init), &"x", &"x");
builder.close_dim(&d0);
builder.close_dim(&d1);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &inst, true, pattern, InstFlag::NO_CACHE);
builder.order(&d0, &d1, Order::OUTER);
OperandPositionSlow
}
}
/// Test a latency that depends on the operand position, in the fast position.
pub struct OperandPositionFast;
impl OperandPositionFast {
const N: u32 = 10_000;
}
impl PerfModelTest for OperandPositionFast {
fn name() -> &'static str {
"operand_position_fast"
}
fn gen_signature<'a, AM: ArgMap<'a> + Context>(builder: &mut SignatureBuilder<AM>) {
builder.scalar("n", Self::N as i32);
builder.scalar("x", 1i64);
builder.array::<i64>("out", 1);
}
fn gen_function(builder: &mut Builder) -> Self {
let init = builder.mov(&"x");
let d0_size = builder.param_size("n", Self::N);
let d1_size = builder.cst_size(100);
let d0 = builder.open_dim_ex(d0_size, DimKind::LOOP);
let d1 = builder.open_dim_ex(d1_size, DimKind::UNROLL);
let inst = builder.mad(&"x", &"x", &Reduce(init));
builder.close_dim(&d0);
builder.close_dim(&d1);
let pattern = ir::AccessPattern::Unknown(None);
builder.st_ex(&"out", &inst, true, pattern, InstFlag::NO_CACHE);
builder.order(&d0, &d1, Order::OUTER);
OperandPositionFast
}
}
// TODO(test): syncthread.
// TODO(test): mixed inst chain. (mixing add/mul/..)
// TODO(test): loads and stores
// TODO(test): temporary loads and stores.
|
use std::io::Read;
use iron::prelude::*;
use iron::request::Body;
use iron::{status, Handler};
use serde_json;
use api::MatrixApi;
use config::Config;
use errors::*;
use handlers::matrix::Dispatcher;
use log::{self, IronLogger};
use middleware::AccessToken;
use models::{ConnectionPool, Events};
/// Transactions is an endpoint of the application service API which is called by the homeserver
/// to push new events.
pub struct Transactions {
config: Config,
matrix_api: Box<MatrixApi>,
}
impl Transactions {
/// Transactions endpoint with middleware
pub fn chain(config: Config, matrix_api: Box<MatrixApi>) -> Chain {
let transactions = Transactions { config: config.clone(), matrix_api };
let mut chain = Chain::new(transactions);
chain.link_before(AccessToken { config });
chain
}
}
impl Handler for Transactions {
fn handle(&self, request: &mut Request) -> IronResult<Response> {
let logger = IronLogger::from_request(request)?;
let events_batch = match deserialize_events(&mut request.body) {
Ok(events_batch) => events_batch,
Err(err) => {
log::log_error(&logger, &err);
return Ok(Response::with((status::Ok, "{}".to_string())));
}
};
let connection = ConnectionPool::from_request(request)?;
if let Err(err) =
Dispatcher::new(&self.config, &connection, &logger, self.matrix_api.clone()).process(events_batch.events)
{
log::log_error(&logger, &err);
}
Ok(Response::with((status::Ok, "{}".to_string())))
}
}
fn deserialize_events(body: &mut Body) -> Result<Events> {
let mut payload = String::new();
body.read_to_string(&mut payload).chain_err(|| ErrorKind::InternalServerError)?;
serde_json::from_str(&payload)
.chain_err(|| {
ErrorKind::InvalidJSON(format!(
"Could not deserialize events that were sent to the transactions endpoint: \
`{}`",
payload
))
})
.map_err(Error::from)
}
|
//! Tests auto-converted from "sass-spec/spec/values/identifiers/escape"
#[allow(unused)]
use super::rsass;
#[allow(unused)]
use rsass::precision;
// Ignoring "normalize", start_version is 3.7.
// Ignoring "script", start_version is 3.7.
|
extern crate rand;
extern crate portaudio;
extern crate hound;
pub mod clock;
pub mod consts;
pub mod synth;
pub mod events;
pub mod device;
pub mod effects;
pub mod conversions;
pub mod sampler;
pub mod files;
use clock::*;
use device::*;
use std::rc::Rc;
pub fn render_audio(clock: Rc<Clock>, master: Rc<StereoEmitter>, length: usize) -> (Vec<f32>, Vec<f32>) {
let mut left = Vec::<f32>::new();
let mut right = Vec::<f32>::new();
while left.len() < length {
assert!(master.output().0.len() == master.output().1.len());
for i in 0..master.output().0.len() {
left.push(master.output().0[i]);
right.push(master.output().1[i]);
}
clock.increment();
}
assert!(left.len() == right.len());
left.truncate(length);
right.truncate(length);
(left, right)
}
|
use std::{fs, thread, time};
use regex::Regex;
fn read_file(filename: &str) -> Vec<(String, String)> {
let mut file_string = fs::read_to_string(filename).expect("Couldn't read file...");
let mut packets: Vec<(String, String)> = Vec::new();
let mut line_cache: Vec<&str> = Vec::new();
for line in file_string.lines() {
if line.is_empty() {
packets.push((line_cache[0].to_string(), line_cache[1].to_string()));
line_cache = Vec::new();
} else {
line_cache.push(line);
}
}
packets.push((line_cache[0].to_string(), line_cache[1].to_string()));
packets
}
fn insert_list(mut string: String, index: usize) -> String {
let mut list_end = string.len();
for (i, ch) in string.chars().skip(index).enumerate() {
if !ch.is_digit(10) && ch != ',' {
list_end = i + index + 1;
}
}
string.insert(index, '[');
string.insert(list_end, ']');
return (string);
}
fn solve_mixed_types(packet: & (String, String)) -> (String, String) {
let mut ended = false;
let mut string1 = packet.0.clone();
let mut string2 = packet.1.clone();
let mut s1_ind = 0;
let mut s2_ind = 0;
while (ended == false) {
let mut broke = "";
let mut index = 0;
while (s1_ind != string1.len() && s2_ind != string2.len()) {
let s1_ch = string1.chars().nth(s1_ind).unwrap();
let s2_ch = string2.chars().nth(s2_ind).unwrap();
if (s1_ch == s2_ch)
|| (s1_ch.is_digit(10) && s2_ch.is_digit(10))
{
s1_ind += 1;
s2_ind += 1;
continue;
} else if (s1_ch.is_digit(10) || s1_ch == ']' ) && s2_ch == '[' {
index = s1_ind;
broke = "string1";
break;
} else if s1_ch == '[' && (s2_ch.is_digit(10) || s2_ch == ']') {
index = s1_ind;
broke = "string2";
break;
} else if s1_ch == ']' && (s2_ch.is_digit(10) || s2_ch == ',') {
s2_ind += 1;
} else if (s1_ch.is_digit(10) || s1_ch == ',') && s2_ch == ']' {
s1_ind += 1;
}
}
if !broke.is_empty() {
match broke {
"string1" => string1 = insert_list(string1, index),
"string2" => string2 = insert_list(string2, index),
_ => unreachable!(),
}
broke = "";
} else if broke.is_empty() {
ended = true;
}
}
return ((string1, string2));
}
fn get_next_list(string: &str, index: usize) -> (usize, Vec<u8>) {
let mut index_copy = index;
while index_copy != string.len() {
let s_ch = string.chars().nth(index_copy).unwrap();
if s_ch == ']' {
// stop
break;
}
index_copy += 1;
}
let regex = Regex::new(r"\d+").unwrap();
let new_string = string[index..index_copy].to_string();
let numbers: Vec<u8> = regex.find_iter(&new_string).filter_map(|digits| digits.as_str().parse().ok()).collect();
println!("{:?}", string[index..index_copy].to_string());
return (index_copy, numbers);
}
fn is_list_winner(string1: &str, s1_ind: usize, string2: &str, s2_ind: usize) -> (bool, usize, usize) {
let (new_s1_ind, s1_numbers) = get_next_list(string1, s1_ind);
let (new_s2_ind, s2_numbers) = get_next_list(string2, s2_ind);
println!("{:?}, {:?}", s1_numbers, s2_numbers);
for (num1, num2) in s1_numbers.iter().zip(s2_numbers.iter()) {
if num1 == num2 {
continue;
} else if num1 > num2 {
println!("Integers were not in the correct orders");
return(true, 0, 0);
} else {
println!("Integers were in the correct order");
return(true, 0, 0);
}
}
if s1_numbers.len() < s2_numbers.len() {
println!("Integers were in the correct order");
return(true, 0, 0);
} else if s1_numbers.len() > s2_numbers.len() {
println!("Integers were not in the correct order");
return(true, 0, 0);
} else {
return(false, new_s1_ind, new_s2_ind);
}
}
fn check_ordering(string1: String, string2: String, index: usize) {
let mut s1_ind = 0;
let mut s2_ind = 0;
while(s1_ind != string1.len() && s2_ind != string2.len()) {
let s1_ch = string1.chars().nth(s1_ind).unwrap();
let s2_ch = string2.chars().nth(s2_ind).unwrap();
println!("s1_ind: {}, s1_ch: {}, s2_ind: {}, s2_ch: {}", s1_ind, s1_ch, s2_ind, s2_ch);
if (s1_ch == '[' && s2_ch == '[') {
s1_ind +=1;
s2_ind +=1;
} else if (s1_ch == ',' && s2_ch == ',') {
s1_ind +=1;
s2_ind +=1;
} else if (s1_ch.is_digit(10) && s2_ch.is_digit(10)) {
// Get next list
let ( win, mut new_s1_ind, mut new_s2_ind) = is_list_winner(&string1, s1_ind, &string2, s2_ind);
if !win {
s1_ind = new_s1_ind;
s2_ind = new_s2_ind;
} else {
break;
}
s1_ind +=1;
s2_ind +=1;
} else if (s1_ch == ']' && s2_ch == ']') {
s1_ind +=1;
s2_ind +=1;
} else if (s1_ch == ']' && s2_ch.is_digit(10)) {
// s1 probably was an empty list
println!("Integers were in the correct orders");
break;
} else if (s2_ch == ']' && s1_ch.is_digit(10)) {
// s2 probably was an empty list
println!("Integers were in the incorrect order");
break;
}
//println!("cond 1:{} cond2:{}", s1_ch != ']', s2_ch == ']');
thread::sleep(time::Duration::from_secs(2));
}
}
fn solve(packets: Vec<(String, String)>) {
for (pack_index, packet) in packets.iter().enumerate() {
println!("{:?}", packet);
let mut new_packet = solve_mixed_types(packet);
println!("{:?}", new_packet);
check_ordering(new_packet.0, new_packet.1, pack_index);
}
}
fn main() {
let mut packets = read_file("input-test.txt");
//let mut packet = ("[[9,6], 1]".to_string(), "[[8,7,6], [1]]".to_string());
//let mut packets = Vec::new();
//packets.push(packet);
solve(packets);
}
|
use crate::buf::{Buf, Channel, ChannelMut, Channels, ChannelsMut, ExactSizeBuf};
/// A chunk of another buffer.
///
/// See [Buf::chunk].
pub struct Chunk<B> {
buf: B,
n: usize,
len: usize,
}
impl<B> Chunk<B> {
/// Construct a new limited buffer.
pub(crate) fn new(buf: B, n: usize, len: usize) -> Self {
Self { buf, n, len }
}
}
/// ```rust
/// use audio::Buf;
///
/// let buf = audio::interleaved![[0; 4]; 2];
///
/// assert_eq!((&buf).chunk(0, 3).channels(), 2);
/// assert_eq!((&buf).chunk(0, 3).frames_hint(), Some(3));
///
/// assert_eq!((&buf).chunk(1, 3).channels(), 2);
/// assert_eq!((&buf).chunk(1, 3).frames_hint(), Some(1));
///
/// assert_eq!((&buf).chunk(2, 3).channels(), 2);
/// assert_eq!((&buf).chunk(2, 3).frames_hint(), Some(0));
/// ```
impl<B> Buf for Chunk<B>
where
B: Buf,
{
fn frames_hint(&self) -> Option<usize> {
let frames = self.buf.frames_hint()?;
let len = frames.saturating_sub(self.n.saturating_mul(self.len));
Some(usize::min(len, self.len))
}
fn channels(&self) -> usize {
self.buf.channels()
}
}
/// ```rust
/// use audio::{Buf, ExactSizeBuf};
///
/// let buf = audio::interleaved![[0; 4]; 2];
///
/// assert_eq!((&buf).chunk(0, 3).frames(), 3);
/// assert_eq!((&buf).chunk(1, 3).frames(), 1);
/// assert_eq!((&buf).chunk(2, 3).frames(), 0);
/// ```
impl<B> ExactSizeBuf for Chunk<B>
where
B: ExactSizeBuf,
{
fn frames(&self) -> usize {
let len = self
.buf
.frames()
.saturating_sub(self.n.saturating_mul(self.len));
usize::min(len, self.len)
}
}
impl<B, T> Channels<T> for Chunk<B>
where
B: Channels<T>,
{
fn channel(&self, channel: usize) -> Channel<'_, T> {
self.buf.channel(channel).chunk(self.n, self.len)
}
}
impl<B, T> ChannelsMut<T> for Chunk<B>
where
B: ChannelsMut<T>,
{
fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
self.buf.channel_mut(channel).chunk(self.n, self.len)
}
fn copy_channels(&mut self, from: usize, to: usize)
where
T: Copy,
{
self.buf.copy_channels(from, to);
}
}
|
//!
//! Types a functionality for handling Canvas and Widget theming.
//!
use canvas;
use color::{Color, black, white};
use position::{Margin, Padding, Position, HorizontalAlign, VerticalAlign};
use rustc_serialize::{json, Encodable, Decodable};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::str;
use widget;
/// A serializable collection of canvas and widget styling defaults.
#[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
pub struct Theme {
/// A name for the theme used for identification.
pub name: String,
/// Padding for Canvas layout and positioning.
pub padding: Padding,
/// Margin for Canvas layout and positioning.
pub margin: Margin,
/// A default widget position.
pub position: Position,
/// A default alignment for widgets.
pub align: Align,
/// A default background for the theme.
pub background_color: Color,
/// A default color for widget shapes.
pub shape_color: Color,
/// A default color for widget frames.
pub frame_color: Color,
/// A default width for widget frames.
pub frame_width: f64,
/// A default color for widget labels.
pub label_color: Color,
/// A default "large" font size.
pub font_size_large: u32,
/// A default "medium" font size.
pub font_size_medium: u32,
/// A default "small" font size.
pub font_size_small: u32,
/// Optional style defaults for a Canvas split.
pub maybe_canvas_split: Option<canvas::split::Style>,
/// Optional style defaults for a Floating Canvas.
pub maybe_canvas_floating: Option<canvas::floating::Style>,
/// Optional style defaults for a Button widget.
pub maybe_button: Option<widget::button::Style>,
/// Optional style defaults for a DropDownList.
pub maybe_drop_down_list: Option<widget::drop_down_list::Style>,
/// Optional style defaults for an EnvelopeEditor.
pub maybe_envelope_editor: Option<widget::envelope_editor::Style>,
/// Optional style defaults for a NumberDialer.
pub maybe_number_dialer: Option<widget::number_dialer::Style>,
/// Optional style defaults for a Slider.
pub maybe_slider: Option<widget::slider::Style>,
/// Optional style defaults for a TextBox.
pub maybe_text_box: Option<widget::text_box::Style>,
/// Optional style defaults for a Toggle.
pub maybe_toggle: Option<widget::toggle::Style>,
/// Optional style defaults for an XYPad.
pub maybe_xy_pad: Option<widget::xy_pad::Style>,
}
/// The alignment of an element's dimensions with another's.
#[derive(Copy, Debug, Clone, RustcEncodable, RustcDecodable)]
pub struct Align {
/// Positioning relative to an elements width and position on the x axis.
pub horizontal: HorizontalAlign,
/// Positioning relative to an elements height and position on the y axis.
pub vertical: VerticalAlign,
}
impl Theme {
/// The default theme if not loading from file.
pub fn default() -> Theme {
Theme {
name: "Demo Theme".to_string(),
padding: Padding {
top: 0.0,
bottom: 0.0,
left: 0.0,
right: 0.0,
},
margin: Margin {
top: 0.0,
bottom: 0.0,
left: 0.0,
right: 0.0,
},
position: Position::default(),
align: Align {
horizontal: HorizontalAlign::Left,
vertical: VerticalAlign::Top,
},
background_color: black(),
shape_color: white(),
frame_color: black(),
frame_width: 1.0,
label_color: black(),
font_size_large: 26,
font_size_medium: 18,
font_size_small: 12,
maybe_canvas_split: None,
maybe_canvas_floating: None,
maybe_button: None,
maybe_drop_down_list: None,
maybe_envelope_editor: None,
maybe_number_dialer: None,
maybe_slider: None,
maybe_text_box: None,
maybe_toggle: None,
maybe_xy_pad: None,
}
}
/// Load a theme from file.
pub fn load(path: &str) -> Result<Theme, String> {
let mut file = match File::open(&Path::new(path)) {
Ok(file) => file,
Err(e) => return Err(format!("Failed to open file for Theme: {}",
Error::description(&e))),
};
let mut contents = Vec::new();
if let Err(e) = ::std::io::Read::read_to_end(&mut file, &mut contents) {
return Err(format!("Failed to load Theme correctly: {}",
Error::description(&e)));
}
let json_object = match json::Json::from_str(str::from_utf8(&contents[..]).unwrap()) {
Ok(json_object) => json_object,
Err(e) => return Err(format!("Failed to construct json_object from str: {}",
Error::description(&e))),
};
let mut decoder = json::Decoder::new(json_object);
let theme = match Decodable::decode(&mut decoder) {
Ok(theme) => Ok(theme),
Err(e) => Err(format!("Failed to construct Theme from json decoder: {}",
Error::description(&e))),
};
theme
}
/// Save a theme to file.
pub fn save(&self, path: &str) -> Result<(), String> {
let json_string = match json::encode(self) {
Ok(x) => x,
Err(e) => return Err(e.description().to_owned())
};
let mut file = match File::create(&Path::new(path)) {
Ok(file) => file,
Err(e) => return Err(format!("Failed to create a File at the given path: {}",
Error::description(&e)))
};
match ::std::io::Write::write_all(&mut file, json_string.as_bytes()) {
Ok(()) => Ok(()),
Err(e) => Err(format!("Theme failed to save correctly: {}", Error::description(&e))),
}
}
}
|
#[cfg(test)]
mod test_block_chain;
|
use std::fs::read_to_string;
fn main() {
for noun in 0..100 {
for verb in 0..100 {
let (mut prog, mut pos) = (read_to_string("in2.txt").unwrap().trim_end().split(',').map(|int| int.parse::<i32>().unwrap()).collect::<Vec<_>>(), 0);
prog[1] = noun;
prog[2] = verb;
loop {
match prog[pos] {
1 => {
let store = prog[pos + 3] as usize;
prog[store] = prog[prog[pos + 1] as usize] + prog[prog[pos + 2] as usize];
},
2 => {
let store = prog[pos + 3] as usize;
prog[store] = prog[prog[pos + 1] as usize] * prog[prog[pos + 2] as usize];
},
99 => break,
_ => panic!("unknown opcode"),
};
pos += 4;
}
if noun == 12 && verb == 2 { println!("Part A: {}", prog[0]); } // 3895705
if prog[0] == 19690720 { println!("Part B: {}", 100 * noun + verb); } // 6417
}
}
}
|
use super::components::*;
use commons::math::*;
use ggez::graphics::Color;
use ggez::{GameError, GameResult};
use myelin_geometry::Polygon;
use nalgebra::{Point2, Vector2};
use rand::prelude::StdRng;
use rand::{thread_rng, Rng, SeedableRng};
use serde::{Deserialize, Serialize};
use specs::prelude::*;
use specs::{World, WorldExt};
use specs_derive::Component;
pub struct BordersTeleportSystem;
impl<'a> System<'a> for BordersTeleportSystem {
type SystemData = (ReadExpect<'a, Cfg>, WriteStorage<'a, Vehicle>);
fn run(&mut self, (cfg, mut mobs): Self::SystemData) {
use specs::Join;
let (width, height) = (cfg.screen_width, cfg.screen_height);
for (vehicle) in (&mut mobs).join() {
if vehicle.pos.x > width as f32 {
vehicle.pos.x -= width as f32;
}
if vehicle.pos.x < 0.0 {
vehicle.pos.x += width as f32;
}
if vehicle.pos.y > height as f32 {
vehicle.pos.y -= height as f32;
}
if vehicle.pos.y < 0.0 {
vehicle.pos.y += height as f32;
}
}
}
}
pub struct SteeringSeparationSystem;
impl<'a> System<'a> for SteeringSeparationSystem {
type SystemData = (
Entities<'a>,
WriteStorage<'a, Vehicle>,
ReadStorage<'a, SteeringSeparation>,
);
fn run(&mut self, (entities, mut vehicles, separations): Self::SystemData) {
use specs::Join;
let mut changes = vec![];
for (entity_a, vehicle_a, separation_a) in (&*entities, &vehicles, &separations).join() {
for (entity_b, vehicle_b, separation_b) in (&*entities, &vehicles, &separations).join()
{
if entity_a == entity_b {
continue;
}
if !separation_a.enabled || !separation_b.enabled {
continue;
}
let min_distance = separation_a.distance + separation_b.distance;
let vector = (vehicle_b.pos - vehicle_a.pos);
let distance = vector.magnitude();
if distance < min_distance {
let vel = lerp_2(
vehicle_a.max_speed * separation_a.weight,
0.0,
0.0,
min_distance,
distance,
);
let vector = vector.normalize() * -1.0;
changes.push((entity_a, vector * vel));
}
}
}
let vehicles = &mut vehicles;
for (entity, desired_vel) in changes {
let vehicle = vehicles.get_mut(entity).unwrap();
vehicle.desired_vel += desired_vel;
}
}
}
pub struct SteeringVelocitySystem;
impl<'a> System<'a> for SteeringVelocitySystem {
type SystemData = (ReadStorage<'a, SteeringVelocity>, WriteStorage<'a, Vehicle>);
fn run(&mut self, (velocity, mut vehicles): Self::SystemData) {
use specs::Join;
for (velocity, vehicle) in (&velocity, &mut vehicles).join() {
if !velocity.enabled {
continue;
}
let vehicle: &mut Vehicle = vehicle;
// TODO: change vel?
vehicle.desired_vel += velocity.vel * velocity.weight;
vehicle.desired_dir = velocity.vel.normalize();
}
}
}
pub struct SteeringWallsSystem;
impl<'a> System<'a> for SteeringWallsSystem {
type SystemData = (WriteStorage<'a, Vehicle>, ReadStorage<'a, Wall>);
fn run(&mut self, (mut vehicles, walls): Self::SystemData) {
use specs::Join;
for (vehicle) in (&mut vehicles).join() {
for (wall) in (&walls).join() {
if let Some(vector) =
compute_vector_from_point_to_segment(wall.pos, wall.vec, vehicle.pos)
{
let distance = vector.magnitude();
if distance < wall.min_distance {
// let dir = vector.normalize() * -1.0;
let force_intensity = lerp_2(0.0, 1.0, wall.min_distance, 0.0, distance);
let desired_vel = wall.force * force_intensity;
// println!(
// "wall collision pos {:?} vec {:?} dir {:?} distance {:?}",
// vehicle.pos, vector, dir, distance
// );
// TODO: change vel?
vehicle.desired_vel += desired_vel;
}
}
}
}
}
}
pub struct MoveSystem;
impl<'a> System<'a> for MoveSystem {
type SystemData = (ReadExpect<'a, GameTime>, WriteStorage<'a, Vehicle>);
fn run(&mut self, (game_time, mut vehicles): Self::SystemData) {
use specs::Join;
let delta_time = game_time.delta_time;
for (vehicle) in (&mut vehicles).join() {
let vehicle: &mut Vehicle = vehicle;
// apply steerning
{
// compute new velocity
let desired_velocity = vehicle.desired_vel;
vehicle.desired_vel = Vector2::zeros();
let current_vel = vehicle.vel_dir * vehicle.speed;
let mut delta_velocity = desired_velocity - current_vel;
if delta_velocity.magnitude() > vehicle.max_acc {
delta_velocity = delta_velocity.normalize() * vehicle.max_acc;
}
let new_vel = current_vel + delta_velocity * delta_time;
// normalize velocity
let mut new_speed = new_vel.magnitude();
vehicle.vel_dir = new_vel / new_speed;
if new_speed > vehicle.max_speed {
new_speed = vehicle.max_speed;
}
vehicle.speed = new_speed;
}
// move
{
vehicle.pos += vehicle.vel_dir * vehicle.speed * delta_time;
}
// update direction
{
vehicle.dir = rotate_towards(
vehicle.dir,
vehicle.desired_dir,
vehicle.rotation_speed * delta_time,
);
}
}
}
}
pub struct SteerArrivalSystem;
impl<'a> System<'a> for SteerArrivalSystem {
type SystemData = (
WriteStorage<'a, Vehicle>,
WriteStorage<'a, SteeringArrival>,
WriteExpect<'a, DebugStuff>,
);
fn run(&mut self, (mut mobs, mut steering_arrival, mut debug_stuff): Self::SystemData) {
use specs::Join;
let min_distance = 0.1;
for (vehicle, arrival) in (&mut mobs, &mut steering_arrival).join() {
let arrival: &mut SteeringArrival = arrival;
if !arrival.enabled {
continue;
}
let vehicle: &mut Vehicle = vehicle;
let delta = arrival.target_pos - vehicle.pos;
let distance: f32 = delta.magnitude();
if !distance.is_normal() || distance < min_distance {
// arrival
arrival.arrived = true;
continue;
}
arrival.arrived = false;
let dir = delta / distance;
let slowdown_distance = vehicle.max_speed * arrival.distance;
let speed = if distance > slowdown_distance {
vehicle.desired_dir = dir;
vehicle.max_speed
} else {
lerp_2(0.0, vehicle.max_speed, 0.0, slowdown_distance, distance)
};
let desired_vel = dir * speed * arrival.weight;
debug_stuff.push_line(
vehicle.pos,
vehicle.pos + desired_vel,
Color::new(1.0, 1.0, 0.0, 1.0),
);
vehicle.desired_vel += desired_vel - vehicle.get_velocity();
}
}
}
pub struct SteeringFormationSystem;
impl<'a> System<'a> for SteeringFormationSystem {
type SystemData = (
Entities<'a>,
ReadStorage<'a, Vehicle>,
WriteStorage<'a, SteeringArrival>,
ReadStorage<'a, SteeringFormationMember>,
);
fn run(&mut self, (entities, vehicles, mut arrivals, formations): Self::SystemData) {
use specs::Join;
let mut leader: Option<(P2, V2, P2)> = None;
let mut followers = BitSet::new();
let mut total_followers = 0;
// for (e, v, f, a) in (&entities, &vehicles, &formations, &arrivals).join() {
// if f.index == 0 {
// leader = Some((v.pos, v.get_velocity(), a.target_pos));
// } else {
// followers.add(e.id());
// total_followers += 1;
// }
// }
//
// let (leader_pos) = leader.unwrap();
// let formation =
// for (_e, a, f) in (followers, &mut arrivals, &formations).join() {
// a.target_pos = formation.get_pos(f.index);
// }
}
}
pub struct UpdateModelPosSystem;
impl<'a> System<'a> for UpdateModelPosSystem {
type SystemData = (ReadStorage<'a, Vehicle>, WriteStorage<'a, Model>);
fn run(&mut self, (vehicles, mut models): Self::SystemData) {
use specs::Join;
for (vehicle, model) in (&vehicles, &mut models).join() {
model.pos = vehicle.pos;
model.dir = vehicle.dir;
}
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SCGCTIMER {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S0R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S0W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S1R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S1W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S2R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S2W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S3R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S3W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S4R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S4W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S4W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S5R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S5W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S5W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S6R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S6W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S6W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct SYSCTL_SCGCTIMER_S7R {
bits: bool,
}
impl SYSCTL_SCGCTIMER_S7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _SYSCTL_SCGCTIMER_S7W<'a> {
w: &'a mut W,
}
impl<'a> _SYSCTL_SCGCTIMER_S7W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - 16/32-Bit General-Purpose Timer 0 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s0(&self) -> SYSCTL_SCGCTIMER_S0R {
let bits = ((self.bits >> 0) & 1) != 0;
SYSCTL_SCGCTIMER_S0R { bits }
}
#[doc = "Bit 1 - 16/32-Bit General-Purpose Timer 1 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s1(&self) -> SYSCTL_SCGCTIMER_S1R {
let bits = ((self.bits >> 1) & 1) != 0;
SYSCTL_SCGCTIMER_S1R { bits }
}
#[doc = "Bit 2 - 16/32-Bit General-Purpose Timer 2 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s2(&self) -> SYSCTL_SCGCTIMER_S2R {
let bits = ((self.bits >> 2) & 1) != 0;
SYSCTL_SCGCTIMER_S2R { bits }
}
#[doc = "Bit 3 - 16/32-Bit General-Purpose Timer 3 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s3(&self) -> SYSCTL_SCGCTIMER_S3R {
let bits = ((self.bits >> 3) & 1) != 0;
SYSCTL_SCGCTIMER_S3R { bits }
}
#[doc = "Bit 4 - 16/32-Bit General-Purpose Timer 4 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s4(&self) -> SYSCTL_SCGCTIMER_S4R {
let bits = ((self.bits >> 4) & 1) != 0;
SYSCTL_SCGCTIMER_S4R { bits }
}
#[doc = "Bit 5 - 16/32-Bit General-Purpose Timer 5 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s5(&self) -> SYSCTL_SCGCTIMER_S5R {
let bits = ((self.bits >> 5) & 1) != 0;
SYSCTL_SCGCTIMER_S5R { bits }
}
#[doc = "Bit 6 - 16/32-Bit General-Purpose Timer 6 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s6(&self) -> SYSCTL_SCGCTIMER_S6R {
let bits = ((self.bits >> 6) & 1) != 0;
SYSCTL_SCGCTIMER_S6R { bits }
}
#[doc = "Bit 7 - 16/32-Bit General-Purpose Timer 7 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s7(&self) -> SYSCTL_SCGCTIMER_S7R {
let bits = ((self.bits >> 7) & 1) != 0;
SYSCTL_SCGCTIMER_S7R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - 16/32-Bit General-Purpose Timer 0 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s0(&mut self) -> _SYSCTL_SCGCTIMER_S0W {
_SYSCTL_SCGCTIMER_S0W { w: self }
}
#[doc = "Bit 1 - 16/32-Bit General-Purpose Timer 1 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s1(&mut self) -> _SYSCTL_SCGCTIMER_S1W {
_SYSCTL_SCGCTIMER_S1W { w: self }
}
#[doc = "Bit 2 - 16/32-Bit General-Purpose Timer 2 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s2(&mut self) -> _SYSCTL_SCGCTIMER_S2W {
_SYSCTL_SCGCTIMER_S2W { w: self }
}
#[doc = "Bit 3 - 16/32-Bit General-Purpose Timer 3 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s3(&mut self) -> _SYSCTL_SCGCTIMER_S3W {
_SYSCTL_SCGCTIMER_S3W { w: self }
}
#[doc = "Bit 4 - 16/32-Bit General-Purpose Timer 4 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s4(&mut self) -> _SYSCTL_SCGCTIMER_S4W {
_SYSCTL_SCGCTIMER_S4W { w: self }
}
#[doc = "Bit 5 - 16/32-Bit General-Purpose Timer 5 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s5(&mut self) -> _SYSCTL_SCGCTIMER_S5W {
_SYSCTL_SCGCTIMER_S5W { w: self }
}
#[doc = "Bit 6 - 16/32-Bit General-Purpose Timer 6 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s6(&mut self) -> _SYSCTL_SCGCTIMER_S6W {
_SYSCTL_SCGCTIMER_S6W { w: self }
}
#[doc = "Bit 7 - 16/32-Bit General-Purpose Timer 7 Sleep Mode Clock Gating Control"]
#[inline(always)]
pub fn sysctl_scgctimer_s7(&mut self) -> _SYSCTL_SCGCTIMER_S7W {
_SYSCTL_SCGCTIMER_S7W { w: self }
}
}
|
use super::{sort_by_cost_weight_ratio, Item, Problem, Solution, SolverTrait, ratio};
use arrayvec::ArrayVec;
use itertools::izip;
#[derive(Debug, Clone)]
pub struct TabuSearchSolver {
pub memory_size: usize,
pub iterations: usize,
}
fn cost_weight(state: &[bool], items: &[Item]) -> (u32, u32) {
state
.iter()
.zip(items.iter())
.filter(|(&in_pack, _)| in_pack)
.fold((0, 0), |(cost, weight), (_, item)| {
(cost + item.cost, weight + item.weight)
})
}
struct TabuMemory {
tabu_raw: Vec<bool>,
capacity: usize,
size: usize,
target: usize,
problem_size: usize,
}
impl<'a> TabuMemory {
fn new(problem_size: usize, memory_size: usize) -> TabuMemory {
let tabu_raw = vec![false; problem_size * memory_size];
TabuMemory {
capacity: memory_size,
tabu_raw,
size: 0,
problem_size,
target: 0,
}
}
fn blacklist<'b>(&self, state: &[bool], pass_memory: &'b mut [bool]) -> &'b [bool] {
pass_memory
.iter_mut()
.for_each(|x| *x = false);
self
.tabu_raw
.chunks(self.problem_size)
.take(self.size)
.fold(pass_memory, |blacklist, memory_state| {
// finds at most 2 different bools beetwen state and items in memory
// on 1 sets blacklist on 2 nothing
match memory_state
.iter()
.zip(state.iter())
.enumerate()
.filter(|(_, (m, s))| m != s)
.collect::<ArrayVec<[_; 2]>>()
.as_slice()
{
&[(i, _)] => blacklist[i] = true,
_ => (),
};
blacklist
}) as &[bool]
}
fn insert(&mut self, state: &[bool]) {
self.tabu_raw
.chunks_mut(self.problem_size)
.skip(self.target)
.take(1)
.for_each(|x| {
x.iter_mut()
.zip(state.iter())
.for_each(|(mem, &state)| *mem = state)
});
self.size = (self.size + 1).min(self.capacity);
self.target = (self.target + 1) % self.capacity;
}
}
impl SolverTrait for TabuSearchSolver {
fn construction(&self, problem: &Problem) -> Solution {
// Maybe this mappings helps little? not sure
let (items, mapping) = sort_by_cost_weight_ratio(&problem.items, problem.max_weight);
if items.len() == 0 {
return Solution::empty(problem.id, problem.size);
}
let mut state = vec![true; items.len()];
let mut best_solution = vec![false; items.len()];
let mut best_cost = 0;
let mut tabu = TabuMemory::new(items.len(), self.memory_size);
let mut blacklist_for_less_allocations = vec![false; items.len()];
const RANDOM_CONST: u8 = 5;
//state.iter_mut().for_each(|s| *s = rand::random::<u8>() > RANDOM_CONST);
for _ in 0..self.iterations {
let (cost, weight) = cost_weight(&state, &items);
let blacklist = tabu.blacklist(&state, &mut blacklist_for_less_allocations);
// maximize function (- over_capacity, cost, _)
let max_cost_fn = izip!((0..), state.iter(), items.iter(), blacklist.iter())
.filter(|(_, _, _, &blacklist)| !blacklist)
.map(|(i, ¤t_state, item, _)| {
let (new_weight, new_cost) = if current_state {
(weight - item.weight, cost - item.cost)
} else {
(weight + item.weight, cost + item.cost)
};
if new_weight > problem.max_weight {
(ratio::new(new_cost, new_weight), new_cost, new_weight, i)
} else {
(ratio::new(3*new_cost, 2*new_weight.max(1)), new_cost, new_weight, i)
}
})
.max().unwrap_or_else(||{
// reset
let random = rand::random::<usize>() % items.len();
state.iter_mut().for_each(|s| *s = rand::random::<u8>() > RANDOM_CONST);
state[random] = true;
let (cost, weight) = cost_weight(&state, &items);
state[random] = false;
(ratio::new(0,1), cost, weight, random)
});
tabu.insert(&state);
let index_to_switch = max_cost_fn.3;
state[index_to_switch] = !state[index_to_switch];
if max_cost_fn.2 <= problem.max_weight && best_cost < max_cost_fn.1 {
best_solution.iter_mut().zip(state.iter()).for_each(|(b, &s)| *b = s);
best_cost = max_cost_fn.1;
}
//switch state
}
if problem.max_weight < items.iter().zip(best_solution.iter()).map(|(item, &included)| if included {item.weight} else {0}).sum(){
Solution::none(problem.id, problem.size)
} else {
Solution {
id: problem.id,
cost: best_cost,
items: Some(best_solution.into_iter().enumerate().fold(
vec![false; problem.size],
|mut acc, (i, x)| {
if let Some(&mapping) = mapping.get(i) {
acc[mapping] = x;
}
acc
},
)),
size: problem.size,
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.