text stringlengths 8 4.13M |
|---|
//! exploration of the search space.
mod candidate;
mod logger;
mod monitor;
mod parallel_list;
mod store;
pub mod choice;
pub mod config;
pub mod eventlog;
pub mod local_selection;
pub mod mcts;
pub use self::candidate::Candidate;
pub use self::config::{BanditConfig, Config, SearchAlgorithm};
pub use self::logger::LogMessage;
use self::choice::fix_order;
use self::monitor::{monitor, MonitorMessage};
use self::parallel_list::ParallelCandidateList;
use self::store::Store;
use crate::device::{Context, EvalMode};
use crate::model::bound;
use crate::search_space::SearchSpace;
use crossbeam;
use futures::executor;
use futures::prelude::*;
use log::{error, info, warn};
use std::sync::{
self,
atomic::{AtomicUsize, Ordering},
mpsc, Mutex,
};
use utils::unwrap;
pub type CheckResultFn<'a> =
dyn Fn(&Candidate, &dyn Context) -> Result<(), String> + Sync + 'a;
// TODO(cc_perf): To improve performances, the following should be considered:
// * choices should be ranked once and then reused for multiple steps.
// * empty and unitary choices should be applied a soon as they are detected.
// * illegal actions should be forbidden by applying their inverse as soon as possible.
// * avoid one copy of the candidate by reusing previous one when applying a choice might
// be beneficial.
/// Entry point of the exploration. This function returns the best candidate that it has found in
/// the given time (or at whatever point we decided to stop the search - potentially after an
/// exhaustive search)
pub fn find_best(
config: &Config,
context: &dyn Context,
search_space: Vec<SearchSpace>,
check_result_fn: Option<&CheckResultFn<'_>>,
) -> Option<SearchSpace> {
find_best_ex(
config,
context,
search_space
.into_iter()
.map(|s| {
let bound = bound(&s, context);
Candidate::new(s, bound)
})
.collect(),
check_result_fn,
)
.map(|c| c.space)
}
struct MctsBuilder<'a> {
space: SearchSpace,
config: &'a Config,
bandit_config: &'a BanditConfig,
context: &'a dyn Context,
check_result_fn: Option<&'a CheckResultFn<'a>>,
}
impl<'a> MctsBuilder<'a> {
fn search<N, E>(
self,
tree_policy: Box<dyn mcts::TreePolicy<N, E>>,
default_policy: Box<dyn mcts::TreePolicy<N, E>>,
) -> Option<Candidate>
where
N: Sync + Send + std::fmt::Debug + Default + mcts::Reset,
E: Sync + Send + std::fmt::Debug + Default + mcts::Reset,
{
let MctsBuilder {
space,
config,
bandit_config,
context,
check_result_fn,
} = self;
crossbeam::scope(|scope| {
let (log_sender, log_receiver) = mpsc::sync_channel(100);
unwrap!(scope
.builder()
.name("Telamon - Logger".to_string())
.spawn(|_| unwrap!(logger::log(config, log_receiver))));
let store = mcts::MctsStore::new(
space,
context,
bandit_config,
tree_policy,
default_policy,
log_sender.clone(),
);
unwrap!(scope
.builder()
.name("Telamon - Search".to_string())
.spawn(move |_| launch_search(
config,
store,
context,
log_sender,
check_result_fn
))
.unwrap()
.join())
})
.unwrap()
}
}
/// Same as `find_best`, but allows to specify pre-existing actions and also returns the
/// actions for the best candidate.
pub fn find_best_ex(
config: &Config,
context: &dyn Context,
candidates: Vec<Candidate>,
check_result_fn: Option<&CheckResultFn<'_>>,
) -> Option<Candidate> {
match config.algorithm {
config::SearchAlgorithm::Mcts(ref bandit_config) => {
assert!(candidates.len() == 1);
let builder = MctsBuilder {
space: candidates.into_iter().next().unwrap().space,
config,
bandit_config,
context,
check_result_fn,
};
let default_policy = Box::new(bandit_config.new_nodes_order);
match &bandit_config.tree_policy {
config::TreePolicy::UCT(uct_config) => builder
.search::<(), mcts::UCTStats>(
Box::new(mcts::UCTPolicy::from(uct_config.clone())),
default_policy,
),
config::TreePolicy::TAG(tag_config) => builder
.search::<(), mcts::TAGStats>(
Box::new(mcts::TAGPolicy::from(tag_config.clone())),
default_policy,
),
config::TreePolicy::Bound => builder.search::<(), ()>(
Box::new(config::NewNodeOrder::Bound),
default_policy,
),
config::TreePolicy::WeightedRandom => builder.search::<(), ()>(
Box::new(config::NewNodeOrder::WeightedRandom),
default_policy,
),
config::TreePolicy::RoundRobin => builder
.search::<(), mcts::CommonStats>(
Box::new(mcts::RoundRobinPolicy),
default_policy,
),
}
}
config::SearchAlgorithm::BoundOrder => crossbeam::scope(|scope| {
let (log_sender, log_receiver) = sync::mpsc::sync_channel(100);
unwrap!(scope
.builder()
.name("Telamon - Logger".to_string())
.spawn(|_| (unwrap!(logger::log(config, log_receiver)))));
let candidate_list = ParallelCandidateList::new(config.num_workers);
candidate_list.insert_many(candidates);
unwrap!(scope
.builder()
.name("Telamon - Search".to_string())
.spawn(move |_| launch_search(
config,
candidate_list,
context,
log_sender,
check_result_fn
))
.unwrap()
.join())
})
.unwrap(),
}
}
/// Launch all threads needed for the search. wait for each one of them to finish. Monitor is
/// supposed to return the best candidate found
fn launch_search<T: Store>(
config: &Config,
candidate_store: T,
context: &dyn Context,
log_sender: sync::mpsc::SyncSender<LogMessage<T::Event>>,
check_result_fn: Option<&CheckResultFn<'_>>,
) -> Option<Candidate> {
let (monitor_sender, monitor_receiver) = futures::sync::mpsc::channel(100);
let maybe_candidate = crossbeam::scope(|scope| {
let best_cand_opt = scope
.builder()
.name("Telamon - Monitor".to_string())
.spawn(|_| {
monitor(
config,
context,
&candidate_store,
monitor_receiver,
log_sender,
)
})
.unwrap();
explore_space(
config,
&candidate_store,
monitor_sender,
context,
check_result_fn,
);
unwrap!(best_cand_opt.join())
})
.unwrap();
// At this point all threads have ended and nobody is going to be
// exploring the candidate store anymore, so the stats printer
// should have a consistent view on the tree.
candidate_store.print_stats();
maybe_candidate
}
/// Defines the work that explorer threads will do in a closure that will be passed to
/// context.async_eval. Also defines a callback that will be executed by the evaluator
fn explore_space<T>(
config: &Config,
candidate_store: &T,
eval_sender: futures::sync::mpsc::Sender<MonitorMessage<T>>,
context: &dyn Context,
check_result_fn: Option<&CheckResultFn<'_>>,
) where
T: Store,
{
let best_mutex = &Mutex::new(None);
let n_evals = &AtomicUsize::new(0);
let n_restarts = AtomicUsize::new(0);
let is_leader = AtomicUsize::new(0);
let stabilizer = &context.stabilizer().skip_bad_candidates(true);
let barrier = std::sync::Barrier::new(config.num_workers);
context.async_eval(config.num_workers, EvalMode::FindBest, &|evaluator| {
while let Some((cand, payload)) = candidate_store.explore(context) {
let space = fix_order(cand.space);
let eval_sender = eval_sender.clone();
evaluator.add_kernel(Candidate { space, ..cand }, move |leaf, compiled| {
let mut best = best_mutex.lock().unwrap();
let n_evals = n_evals.fetch_add(1, Ordering::SeqCst);
let mut eval = match stabilizer
.wrap(compiled)
.bound(Some(leaf.bound.value()))
.best(*best)
.evaluate()
{
Some(eval) => eval,
None => {
error!(
"evaluation failed for actions {:?}, with kernel {}",
leaf.actions, compiled
);
std::f64::INFINITY
}
};
if let Some(check_result_fn) = check_result_fn {
if eval.is_finite()
&& (config.check_all || best.is_none() || Some(eval) < *best)
{
// The values computed by the kernel are kept in the context, so we
// need to do this *now* before the evaluator runs any other version of
// the kernel.
if let Err(err) = check_result_fn(&leaf, context) {
error!(
"Invalid results (score {:.4e}ns) at #{} for {}: {}",
eval, n_evals, leaf, err
);
config
.output_path(format!("error_{}", n_evals))
.and_then(|path| leaf.dump_to(path, context, eval, &err))
.unwrap_or_else(|err| {
error!("Error while dumping candidate: {}", err)
});
eval = std::f64::INFINITY;
}
}
}
// Only update best if the check passed!
if eval.is_finite() && (best.is_none() || Some(eval) < *best) {
*best = Some(eval);
}
if let Err(err) =
executor::spawn(eval_sender.send((leaf, eval, payload)).map(|_| ()))
.wait_future()
{
warn!("Got disconnected , {:?}", err);
}
});
if config
.restart_every_n_evals
.map(|restart_every| {
n_evals.load(Ordering::SeqCst)
> restart_every * n_restarts.load(Ordering::SeqCst)
})
.unwrap_or(false)
{
is_leader.fetch_add(1, Ordering::SeqCst);
barrier.wait();
if is_leader.fetch_sub(1, Ordering::SeqCst) == config.num_workers {
info!("Performing restart");
candidate_store.restart();
n_restarts.fetch_add(1, Ordering::SeqCst);
}
barrier.wait();
}
}
});
}
/// Explores the full search space.
pub fn gen_space<F, G>(
context: &dyn Context,
space: SearchSpace,
mut on_node: F,
mut on_leaf: G,
) where
F: FnMut(&Candidate),
G: FnMut(&Candidate),
{
let perf_bound = bound(&space, context);
let mut stack = vec![Candidate::new(space, perf_bound)];
let mut total = 0;
info!("Beginning exploration");
while let Some(candidate) = stack.pop() {
total += 1;
if total % 10 == 0 {
warn!("{} candidates", total);
}
let choice_opt = choice::default_list(&candidate.space).next();
if let Some(choice) = choice_opt {
on_node(&candidate);
stack.extend(candidate.apply_choice(context, choice));
} else {
let space = fix_order(candidate.space);
on_leaf(&Candidate { space, ..candidate });
}
}
info!("{} candidates explored", total);
}
|
pub mod stack;
pub mod store;
pub mod abstract_machine;
|
use crate::{MessageType, MatchScaleFn};
fn match_scale_accelerometer_data(_: usize) -> Option<f32> {
None
}
fn match_scale_activity(k: usize) -> Option<f32> {
match k {
0 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_ant_channel_id(_: usize) -> Option<f32> {
None
}
fn match_scale_ant_rx(k: usize) -> Option<f32> {
match k {
0 => Some(32768.0f32),
_ => None,
}
}
fn match_scale_ant_tx(k: usize) -> Option<f32> {
match k {
0 => Some(32768.0f32),
_ => None,
}
}
fn match_scale_aviation_attitude(k: usize) -> Option<f32> {
match k {
2 => Some(10430.38f32),
3 => Some(10430.38f32),
4 => Some(100.0f32),
5 => Some(100.0f32),
6 => Some(1024.0f32),
9 => Some(10430.38f32),
_ => None,
}
}
fn match_scale_barometer_data(_: usize) -> Option<f32> {
None
}
fn match_scale_bike_profile(k: usize) -> Option<f32> {
match k {
3 => Some(100.0f32),
8 => Some(1000.0f32),
9 => Some(1000.0f32),
10 => Some(10.0f32),
11 => Some(10.0f32),
19 => Some(2.0f32),
_ => None,
}
}
fn match_scale_blood_pressure(_: usize) -> Option<f32> {
None
}
fn match_scale_cadence_zone(_: usize) -> Option<f32> {
None
}
fn match_scale_camera_event(_: usize) -> Option<f32> {
None
}
fn match_scale_capabilities(_: usize) -> Option<f32> {
None
}
fn match_scale_climb_pro(_: usize) -> Option<f32> {
None
}
fn match_scale_connectivity(_: usize) -> Option<f32> {
None
}
fn match_scale_course(_: usize) -> Option<f32> {
None
}
fn match_scale_course_point(k: usize) -> Option<f32> {
match k {
4 => Some(100.0f32),
_ => None,
}
}
fn match_scale_developer_data_id(_: usize) -> Option<f32> {
None
}
fn match_scale_device_aux_battery_info(k: usize) -> Option<f32> {
match k {
1 => Some(256.0f32),
_ => None,
}
}
fn match_scale_device_info(k: usize) -> Option<f32> {
match k {
5 => Some(100.0f32),
10 => Some(256.0f32),
_ => None,
}
}
fn match_scale_device_settings(k: usize) -> Option<f32> {
match k {
5 => Some(4.0f32),
_ => None,
}
}
fn match_scale_dive_alarm(k: usize) -> Option<f32> {
match k {
0 => Some(1000.0f32),
1 => Some(1.0f32),
_ => None,
}
}
fn match_scale_dive_gas(_: usize) -> Option<f32> {
None
}
fn match_scale_dive_settings(k: usize) -> Option<f32> {
match k {
6 => Some(100.0f32),
7 => Some(100.0f32),
8 => Some(100.0f32),
17 => Some(1.0f32),
18 => Some(1.0f32),
_ => None,
}
}
fn match_scale_dive_summary(k: usize) -> Option<f32> {
match k {
2 => Some(1000.0f32),
3 => Some(1000.0f32),
4 => Some(1.0f32),
5 => Some(1.0f32),
6 => Some(1.0f32),
7 => Some(1.0f32),
8 => Some(1.0f32),
11 => Some(1000.0f32),
17 => Some(1000.0f32),
22 => Some(1000.0f32),
23 => Some(1000.0f32),
24 => Some(1000.0f32),
25 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_event(k: usize) -> Option<f32> {
match k {
23 => Some(10.0f32),
24 => Some(10.0f32),
_ => None,
}
}
fn match_scale_exd_data_concept_configuration(_: usize) -> Option<f32> {
None
}
fn match_scale_exd_data_field_configuration(_: usize) -> Option<f32> {
None
}
fn match_scale_exd_screen_configuration(_: usize) -> Option<f32> {
None
}
fn match_scale_exercise_title(_: usize) -> Option<f32> {
None
}
fn match_scale_field_capabilities(_: usize) -> Option<f32> {
None
}
fn match_scale_field_description(_: usize) -> Option<f32> {
None
}
fn match_scale_file_capabilities(_: usize) -> Option<f32> {
None
}
fn match_scale_file_creator(_: usize) -> Option<f32> {
None
}
fn match_scale_file_id(_: usize) -> Option<f32> {
None
}
fn match_scale_goal(_: usize) -> Option<f32> {
None
}
fn match_scale_gps_metadata(k: usize) -> Option<f32> {
match k {
3 => Some(5.0f32),
4 => Some(1000.0f32),
5 => Some(100.0f32),
7 => Some(100.0f32),
_ => None,
}
}
fn match_scale_gyroscope_data(_: usize) -> Option<f32> {
None
}
fn match_scale_hr(k: usize) -> Option<f32> {
match k {
0 => Some(32768.0f32),
1 => Some(256.0f32),
9 => Some(1024.0f32),
10 => Some(1024.0f32),
_ => None,
}
}
fn match_scale_hr_zone(_: usize) -> Option<f32> {
None
}
fn match_scale_hrm_profile(_: usize) -> Option<f32> {
None
}
fn match_scale_hrv(k: usize) -> Option<f32> {
match k {
0 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_jump(k: usize) -> Option<f32> {
match k {
7 => Some(1000.0f32),
8 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_lap(k: usize) -> Option<f32> {
match k {
7 => Some(1000.0f32),
8 => Some(1000.0f32),
9 => Some(100.0f32),
13 => Some(1000.0f32),
14 => Some(1000.0f32),
37 => Some(100.0f32),
42 => Some(5.0f32),
43 => Some(5.0f32),
45 => Some(100.0f32),
46 => Some(100.0f32),
47 => Some(100.0f32),
48 => Some(100.0f32),
49 => Some(100.0f32),
52 => Some(1000.0f32),
53 => Some(1000.0f32),
54 => Some(1000.0f32),
55 => Some(1000.0f32),
56 => Some(1000.0f32),
57 => Some(1000.0f32),
58 => Some(1000.0f32),
59 => Some(1000.0f32),
60 => Some(1000.0f32),
62 => Some(5.0f32),
77 => Some(10.0f32),
78 => Some(100.0f32),
79 => Some(10.0f32),
80 => Some(128.0f32),
81 => Some(128.0f32),
82 => Some(128.0f32),
84 => Some(100.0f32),
85 => Some(100.0f32),
86 => Some(100.0f32),
87 => Some(10.0f32),
88 => Some(10.0f32),
89 => Some(10.0f32),
91 => Some(2.0f32),
92 => Some(2.0f32),
93 => Some(2.0f32),
94 => Some(2.0f32),
95 => Some(2.0f32),
98 => Some(1000.0f32),
102 => Some(0.7111111f32),
103 => Some(0.7111111f32),
104 => Some(0.7111111f32),
105 => Some(0.7111111f32),
110 => Some(1000.0f32),
111 => Some(1000.0f32),
112 => Some(5.0f32),
113 => Some(5.0f32),
114 => Some(5.0f32),
117 => Some(2.0f32),
118 => Some(100.0f32),
119 => Some(100.0f32),
120 => Some(10.0f32),
121 => Some(1000.0f32),
156 => Some(100.0f32),
157 => Some(100.0f32),
158 => Some(100.0f32),
159 => Some(100.0f32),
160 => Some(100.0f32),
_ => None,
}
}
fn match_scale_length(k: usize) -> Option<f32> {
match k {
3 => Some(1000.0f32),
4 => Some(1000.0f32),
6 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_magnetometer_data(_: usize) -> Option<f32> {
None
}
fn match_scale_memo_glob(_: usize) -> Option<f32> {
None
}
fn match_scale_mesg_capabilities(_: usize) -> Option<f32> {
None
}
fn match_scale_met_zone(k: usize) -> Option<f32> {
match k {
2 => Some(10.0f32),
3 => Some(10.0f32),
_ => None,
}
}
fn match_scale_monitoring(k: usize) -> Option<f32> {
match k {
2 => Some(100.0f32),
3 => Some(2.0f32),
4 => Some(1000.0f32),
12 => Some(100.0f32),
14 => Some(100.0f32),
15 => Some(100.0f32),
28 => Some(10.0f32),
31 => Some(1000.0f32),
32 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_monitoring_info(k: usize) -> Option<f32> {
match k {
3 => Some(5000.0f32),
4 => Some(5000.0f32),
_ => None,
}
}
fn match_scale_nmea_sentence(_: usize) -> Option<f32> {
None
}
fn match_scale_obdii_data(_: usize) -> Option<f32> {
None
}
fn match_scale_ohr_settings(_: usize) -> Option<f32> {
None
}
fn match_scale_one_d_sensor_calibration(_: usize) -> Option<f32> {
None
}
fn match_scale_power_zone(_: usize) -> Option<f32> {
None
}
fn match_scale_record(k: usize) -> Option<f32> {
match k {
2 => Some(5.0f32),
5 => Some(100.0f32),
6 => Some(1000.0f32),
8 => Some(100.0f32),
9 => Some(100.0f32),
11 => Some(1000.0f32),
12 => Some(100.0f32),
17 => Some(16.0f32),
32 => Some(1000.0f32),
39 => Some(10.0f32),
40 => Some(100.0f32),
41 => Some(10.0f32),
43 => Some(2.0f32),
44 => Some(2.0f32),
45 => Some(2.0f32),
46 => Some(2.0f32),
47 => Some(2.0f32),
48 => Some(128.0f32),
51 => Some(100.0f32),
52 => Some(256.0f32),
53 => Some(128.0f32),
54 => Some(100.0f32),
55 => Some(100.0f32),
56 => Some(100.0f32),
57 => Some(10.0f32),
58 => Some(10.0f32),
59 => Some(10.0f32),
69 => Some(0.7111111f32),
70 => Some(0.7111111f32),
71 => Some(0.7111111f32),
72 => Some(0.7111111f32),
73 => Some(1000.0f32),
78 => Some(5.0f32),
81 => Some(2.0f32),
83 => Some(100.0f32),
84 => Some(100.0f32),
85 => Some(10.0f32),
92 => Some(1000.0f32),
93 => Some(1000.0f32),
94 => Some(1.0f32),
95 => Some(1.0f32),
96 => Some(1.0f32),
98 => Some(1.0f32),
139 => Some(100.0f32),
_ => None,
}
}
fn match_scale_schedule(_: usize) -> Option<f32> {
None
}
fn match_scale_sdm_profile(k: usize) -> Option<f32> {
match k {
2 => Some(10.0f32),
3 => Some(100.0f32),
_ => None,
}
}
fn match_scale_segment_file(_: usize) -> Option<f32> {
None
}
fn match_scale_segment_id(_: usize) -> Option<f32> {
None
}
fn match_scale_segment_lap(k: usize) -> Option<f32> {
match k {
7 => Some(1000.0f32),
8 => Some(1000.0f32),
9 => Some(100.0f32),
13 => Some(1000.0f32),
14 => Some(1000.0f32),
34 => Some(5.0f32),
35 => Some(5.0f32),
37 => Some(100.0f32),
38 => Some(100.0f32),
39 => Some(100.0f32),
40 => Some(100.0f32),
41 => Some(100.0f32),
44 => Some(1000.0f32),
45 => Some(1000.0f32),
46 => Some(1000.0f32),
47 => Some(1000.0f32),
48 => Some(1000.0f32),
49 => Some(1000.0f32),
50 => Some(1000.0f32),
51 => Some(1000.0f32),
52 => Some(1000.0f32),
54 => Some(5.0f32),
56 => Some(1000.0f32),
59 => Some(2.0f32),
60 => Some(2.0f32),
61 => Some(2.0f32),
62 => Some(2.0f32),
63 => Some(2.0f32),
66 => Some(128.0f32),
67 => Some(128.0f32),
68 => Some(128.0f32),
71 => Some(1000.0f32),
75 => Some(0.7111111f32),
76 => Some(0.7111111f32),
77 => Some(0.7111111f32),
78 => Some(0.7111111f32),
89 => Some(100.0f32),
90 => Some(100.0f32),
_ => None,
}
}
fn match_scale_segment_leaderboard_entry(k: usize) -> Option<f32> {
match k {
4 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_segment_point(k: usize) -> Option<f32> {
match k {
3 => Some(100.0f32),
4 => Some(5.0f32),
5 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_session(k: usize) -> Option<f32> {
match k {
7 => Some(1000.0f32),
8 => Some(1000.0f32),
9 => Some(100.0f32),
14 => Some(1000.0f32),
15 => Some(1000.0f32),
24 => Some(10.0f32),
35 => Some(10.0f32),
36 => Some(1000.0f32),
41 => Some(10.0f32),
42 => Some(100.0f32),
44 => Some(100.0f32),
49 => Some(5.0f32),
50 => Some(5.0f32),
52 => Some(100.0f32),
53 => Some(100.0f32),
54 => Some(100.0f32),
55 => Some(100.0f32),
56 => Some(100.0f32),
59 => Some(1000.0f32),
60 => Some(1000.0f32),
61 => Some(1000.0f32),
62 => Some(1000.0f32),
63 => Some(1000.0f32),
65 => Some(1000.0f32),
66 => Some(1000.0f32),
67 => Some(1000.0f32),
68 => Some(1000.0f32),
69 => Some(1000.0f32),
71 => Some(5.0f32),
87 => Some(100.0f32),
88 => Some(100.0f32),
89 => Some(10.0f32),
90 => Some(100.0f32),
91 => Some(10.0f32),
92 => Some(128.0f32),
93 => Some(128.0f32),
94 => Some(128.0f32),
95 => Some(100.0f32),
96 => Some(100.0f32),
97 => Some(100.0f32),
98 => Some(10.0f32),
99 => Some(10.0f32),
100 => Some(10.0f32),
101 => Some(2.0f32),
102 => Some(2.0f32),
103 => Some(2.0f32),
104 => Some(2.0f32),
105 => Some(2.0f32),
112 => Some(1000.0f32),
116 => Some(0.7111111f32),
117 => Some(0.7111111f32),
118 => Some(0.7111111f32),
119 => Some(0.7111111f32),
124 => Some(1000.0f32),
125 => Some(1000.0f32),
126 => Some(5.0f32),
127 => Some(5.0f32),
128 => Some(5.0f32),
131 => Some(2.0f32),
132 => Some(100.0f32),
133 => Some(100.0f32),
134 => Some(10.0f32),
137 => Some(10.0f32),
139 => Some(1000.0f32),
168 => Some(65536.0f32),
199 => Some(100.0f32),
200 => Some(100.0f32),
208 => Some(100.0f32),
209 => Some(100.0f32),
210 => Some(100.0f32),
_ => None,
}
}
fn match_scale_set(k: usize) -> Option<f32> {
match k {
0 => Some(1000.0f32),
4 => Some(16.0f32),
_ => None,
}
}
fn match_scale_slave_device(_: usize) -> Option<f32> {
None
}
fn match_scale_software(k: usize) -> Option<f32> {
match k {
3 => Some(100.0f32),
_ => None,
}
}
fn match_scale_speed_zone(k: usize) -> Option<f32> {
match k {
0 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_sport(_: usize) -> Option<f32> {
None
}
fn match_scale_stress_level(_: usize) -> Option<f32> {
None
}
fn match_scale_three_d_sensor_calibration(k: usize) -> Option<f32> {
match k {
5 => Some(65535.0f32),
_ => None,
}
}
fn match_scale_timestamp_correlation(k: usize) -> Option<f32> {
match k {
0 => Some(32768.0f32),
2 => Some(32768.0f32),
_ => None,
}
}
fn match_scale_totals(_: usize) -> Option<f32> {
None
}
fn match_scale_training_file(_: usize) -> Option<f32> {
None
}
fn match_scale_user_profile(k: usize) -> Option<f32> {
match k {
3 => Some(100.0f32),
4 => Some(10.0f32),
31 => Some(1000.0f32),
32 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_video(_: usize) -> Option<f32> {
None
}
fn match_scale_video_clip(_: usize) -> Option<f32> {
None
}
fn match_scale_video_description(_: usize) -> Option<f32> {
None
}
fn match_scale_video_frame(_: usize) -> Option<f32> {
None
}
fn match_scale_video_title(_: usize) -> Option<f32> {
None
}
fn match_scale_watchface_settings(_: usize) -> Option<f32> {
None
}
fn match_scale_weather_alert(_: usize) -> Option<f32> {
None
}
fn match_scale_weather_conditions(k: usize) -> Option<f32> {
match k {
4 => Some(1000.0f32),
_ => None,
}
}
fn match_scale_weight_scale(k: usize) -> Option<f32> {
match k {
0 => Some(100.0f32),
1 => Some(100.0f32),
2 => Some(100.0f32),
3 => Some(100.0f32),
4 => Some(100.0f32),
5 => Some(100.0f32),
7 => Some(4.0f32),
9 => Some(4.0f32),
_ => None,
}
}
fn match_scale_workout(k: usize) -> Option<f32> {
match k {
14 => Some(100.0f32),
_ => None,
}
}
fn match_scale_workout_session(k: usize) -> Option<f32> {
match k {
4 => Some(100.0f32),
_ => None,
}
}
fn match_scale_workout_step(k: usize) -> Option<f32> {
match k {
12 => Some(100.0f32),
_ => None,
}
}
fn match_scale_zones_target(_: usize) -> Option<f32> {
None
}
fn match_scale_none(_: usize) -> Option<f32> {
return None;
}
/// Determines whether any SDK-defined `Message` defines a scale for any of its fields.
///
/// The method is called with a `MessageType` argument and returns a static closure which is called with a field_id `usize`
/// and yields an `Option<f32>`.
///
/// # Example
///
/// ```
/// let message_type = MessageType::Workout;
/// let parsed_value = 14;
/// let scale_fn = match_message_scale(message_type);
/// let scale = scale_fn(parsed_value);
/// assert_eq!(scale, Some(100.0));
/// ```
pub fn get_field_scale_fn(m: MessageType) -> MatchScaleFn {
match m {
MessageType::FileId => match_scale_file_id,
MessageType::FileCreator => match_scale_file_creator,
MessageType::TimestampCorrelation => match_scale_timestamp_correlation,
MessageType::Software => match_scale_software,
MessageType::SlaveDevice => match_scale_slave_device,
MessageType::Capabilities => match_scale_capabilities,
MessageType::FileCapabilities => match_scale_file_capabilities,
MessageType::MesgCapabilities => match_scale_mesg_capabilities,
MessageType::FieldCapabilities => match_scale_field_capabilities,
MessageType::DeviceSettings => match_scale_device_settings,
MessageType::UserProfile => match_scale_user_profile,
MessageType::HrmProfile => match_scale_hrm_profile,
MessageType::SdmProfile => match_scale_sdm_profile,
MessageType::BikeProfile => match_scale_bike_profile,
MessageType::Connectivity => match_scale_connectivity,
MessageType::WatchfaceSettings => match_scale_watchface_settings,
MessageType::OhrSettings => match_scale_ohr_settings,
MessageType::ZonesTarget => match_scale_zones_target,
MessageType::Sport => match_scale_sport,
MessageType::HrZone => match_scale_hr_zone,
MessageType::SpeedZone => match_scale_speed_zone,
MessageType::CadenceZone => match_scale_cadence_zone,
MessageType::PowerZone => match_scale_power_zone,
MessageType::MetZone => match_scale_met_zone,
MessageType::DiveSettings => match_scale_dive_settings,
MessageType::DiveAlarm => match_scale_dive_alarm,
MessageType::DiveGas => match_scale_dive_gas,
MessageType::Goal => match_scale_goal,
MessageType::Activity => match_scale_activity,
MessageType::Session => match_scale_session,
MessageType::Lap => match_scale_lap,
MessageType::Length => match_scale_length,
MessageType::Record => match_scale_record,
MessageType::Event => match_scale_event,
MessageType::DeviceInfo => match_scale_device_info,
MessageType::DeviceAuxBatteryInfo => match_scale_device_aux_battery_info,
MessageType::TrainingFile => match_scale_training_file,
MessageType::WeatherConditions => match_scale_weather_conditions,
MessageType::WeatherAlert => match_scale_weather_alert,
MessageType::GpsMetadata => match_scale_gps_metadata,
MessageType::CameraEvent => match_scale_camera_event,
MessageType::GyroscopeData => match_scale_gyroscope_data,
MessageType::AccelerometerData => match_scale_accelerometer_data,
MessageType::MagnetometerData => match_scale_magnetometer_data,
MessageType::BarometerData => match_scale_barometer_data,
MessageType::ThreeDSensorCalibration => match_scale_three_d_sensor_calibration,
MessageType::OneDSensorCalibration => match_scale_one_d_sensor_calibration,
MessageType::VideoFrame => match_scale_video_frame,
MessageType::ObdiiData => match_scale_obdii_data,
MessageType::NmeaSentence => match_scale_nmea_sentence,
MessageType::AviationAttitude => match_scale_aviation_attitude,
MessageType::Video => match_scale_video,
MessageType::VideoTitle => match_scale_video_title,
MessageType::VideoDescription => match_scale_video_description,
MessageType::VideoClip => match_scale_video_clip,
MessageType::Set => match_scale_set,
MessageType::Jump => match_scale_jump,
MessageType::ClimbPro => match_scale_climb_pro,
MessageType::FieldDescription => match_scale_field_description,
MessageType::DeveloperDataId => match_scale_developer_data_id,
MessageType::Course => match_scale_course,
MessageType::CoursePoint => match_scale_course_point,
MessageType::SegmentId => match_scale_segment_id,
MessageType::SegmentLeaderboardEntry => match_scale_segment_leaderboard_entry,
MessageType::SegmentPoint => match_scale_segment_point,
MessageType::SegmentLap => match_scale_segment_lap,
MessageType::SegmentFile => match_scale_segment_file,
MessageType::Workout => match_scale_workout,
MessageType::WorkoutSession => match_scale_workout_session,
MessageType::WorkoutStep => match_scale_workout_step,
MessageType::ExerciseTitle => match_scale_exercise_title,
MessageType::Schedule => match_scale_schedule,
MessageType::Totals => match_scale_totals,
MessageType::WeightScale => match_scale_weight_scale,
MessageType::BloodPressure => match_scale_blood_pressure,
MessageType::MonitoringInfo => match_scale_monitoring_info,
MessageType::Monitoring => match_scale_monitoring,
MessageType::Hr => match_scale_hr,
MessageType::StressLevel => match_scale_stress_level,
MessageType::MemoGlob => match_scale_memo_glob,
MessageType::AntChannelId => match_scale_ant_channel_id,
MessageType::AntRx => match_scale_ant_rx,
MessageType::AntTx => match_scale_ant_tx,
MessageType::ExdScreenConfiguration => match_scale_exd_screen_configuration,
MessageType::ExdDataFieldConfiguration => match_scale_exd_data_field_configuration,
MessageType::ExdDataConceptConfiguration => match_scale_exd_data_concept_configuration,
MessageType::DiveSummary => match_scale_dive_summary,
MessageType::Hrv => match_scale_hrv,
_ => match_scale_none
}
}
|
use board::grid::GoCell;
use board::stones::grouprc::GoGroupRc;
use board::stones::stone::Stone;
pub trait GroupManipulation {
fn place_stone(&mut self, cell: GoCell, stone: Stone) -> GoGroupRc;
fn fusion_with(&mut self, cell: GoCell) -> (GoGroupRc, usize);
fn split_with(&mut self, cell: GoCell) -> (GoGroupRc, Vec<GoGroupRc>);
fn capture(&mut self, group: &GoGroupRc);
}
|
/// In-memory [`RawStream`][crate::RawStream]
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct Buffer(Vec<u8>);
impl Buffer {
#[inline]
pub fn new() -> Self {
Default::default()
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for Buffer {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[cfg(feature = "auto")]
impl is_terminal::IsTerminal for Buffer {
#[inline]
fn is_terminal(&self) -> bool {
false
}
}
impl std::io::Write for Buffer {
#[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.extend(buf);
Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(all(windows, feature = "wincon"))]
impl anstyle_wincon::WinconStream for Buffer {
fn set_colors(
&mut self,
fg: Option<anstyle::AnsiColor>,
bg: Option<anstyle::AnsiColor>,
) -> std::io::Result<()> {
use std::io::Write as _;
if let Some(fg) = fg {
write!(self, "{}", fg.render_fg())?;
}
if let Some(bg) = bg {
write!(self, "{}", bg.render_bg())?;
}
if fg.is_none() && bg.is_none() {
write!(self, "{}", anstyle::Reset.render())?;
}
Ok(())
}
fn get_colors(
&self,
) -> std::io::Result<(Option<anstyle::AnsiColor>, Option<anstyle::AnsiColor>)> {
Ok((None, None))
}
}
|
#[doc = "Reader of register WAITSTAT"]
pub type R = crate::R<u32, super::WAITSTAT>;
#[doc = "Reader of field `WAITREQ`"]
pub type WAITREQ_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - Channel \\[n\\]
Wait Status"]
#[inline(always)]
pub fn waitreq(&self) -> WAITREQ_R {
WAITREQ_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
use crate::*;
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct Songs {
pub songs: HashMap<HashSha256, Song>,
pub converter: Converter,
}
impl Songs {
pub fn song(&self, chart: &Chart) -> Song {
let sha256 = self.get_sha256(chart.md5());
match sha256 {
Some(sha256) => self.songs.get(&sha256).cloned().unwrap(),
None => Song::make_from_chart(chart),
}
}
pub fn song_by_sha256(&self, sha256: &HashSha256) -> Option<&Song> {
self.songs.get(sha256)
}
fn song_a(&self, chart: &Chart) -> Option<&Song> {
match self.get_sha256(chart.md5()) {
Some(sha256) => self.songs.get(&sha256),
None => None,
}
}
pub fn get_md5(&self, sha256: &HashSha256) -> Option<HashMd5> {
self.converter.get_md5(sha256)
}
pub fn get_sha256(&self, md5: &HashMd5) -> Option<HashSha256> {
self.converter.get_sha256(md5)
}
pub fn get_list(&self, chart: &[&Chart]) -> Vec<SongFormat> {
chart
.iter()
.filter_map(|c| self.song_a(c))
.map(SongFormat::from)
.collect()
}
}
#[derive(Clone, Debug, Serialize)]
pub struct SongFormat {
title: String,
notes: i32,
sha256: HashSha256,
md5: HashMd5,
}
impl Default for SongFormat {
fn default() -> Self {
Self {
title: "曲データなし".to_string(),
notes: 0,
sha256: Default::default(),
md5: Default::default(),
}
}
}
impl From<&Song> for SongFormat {
fn from(s: &Song) -> Self {
Self {
title: s.title(),
notes: s.notes(),
sha256: s.get_sha256().clone(),
md5: s.get_md5().clone(),
}
}
}
#[derive(Default)]
pub struct SongsBuilder {
songs: HashMap<HashSha256, Song>,
md5_to_sha256: HashMap<HashMd5, HashSha256>,
sha256_to_md5: HashMap<HashSha256, HashMd5>,
}
impl SongsBuilder {
pub fn push(
&mut self,
md5: HashMd5,
sha256: HashSha256,
title: Title,
artist: Artist,
notes: i32,
include_features: IncludeFeatures,
) {
let song = Song::new(
md5.clone(),
sha256.clone(),
title,
artist,
notes,
include_features,
);
self.songs.insert(sha256.clone(), song);
self.sha256_to_md5.insert(sha256.clone(), md5.clone());
self.md5_to_sha256.insert(md5, sha256);
}
pub fn build(self) -> Songs {
Songs {
songs: self.songs,
converter: Converter::new(self.md5_to_sha256, self.sha256_to_md5),
}
}
}
|
#![allow(deprecated)]
extern crate libc;
extern crate futex;
use futex::raw::RwLock;
use std::thread;
use std::sync::Arc;
fn main() {
println!("lul");
let futex = Arc::new(RwLock::new());
let futex2 = futex.clone();
futex.acquire_read();
futex.acquire_read();
futex.acquire_read();
let thread = thread::spawn(move || {
futex2.acquire_read();
println!("thread reader");
thread::sleep_ms(100);
futex2.release_read();
futex2.acquire_write();
println!("thread writer");
thread::sleep_ms(100);
futex2.release_write();
thread::sleep_ms(100);
futex2.acquire_read();
println!("thread reader 2");
thread::sleep_ms(100);
futex2.release_read();
});
thread::sleep_ms(100);
futex.release_read();
futex.release_read();
println!("last reader going down");
thread::sleep_ms(100);
futex.release_read();
thread::sleep_ms(100);
futex.acquire_write();
println!("main writer");
thread::sleep_ms(100);
futex.release_write();
thread.join().unwrap();
println!("done");
}
|
// 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::ie::SupportedRate,
failure::{format_err, Error},
std::collections::HashSet,
};
pub struct ApRates(pub Vec<SupportedRate>);
pub struct ClientRates(pub Vec<SupportedRate>);
/// Returns the rates specified by the AP that are also supported by the client, with basic bits
/// following their values in the AP.
/// Returns Error if intersection fails.
/// Note: The client MUST support ALL the basic rates specified by the AP or the intersection fails.
pub fn intersect_rates(ap: ApRates, client: ClientRates) -> Result<Vec<SupportedRate>, Error> {
let mut ap = ap.0;
let client = client.0.into_iter().map(|r| r.rate()).collect::<HashSet<_>>();
// The client MUST support ALL basic rates specified by the AP.
if ap.iter().any(|ra| ra.basic() && !client.contains(&ra.rate())) {
return Err(format_err!("At least one basic rate not supported."));
}
// Remove rates that are not supported by the client.
ap.retain(|ra| client.contains(&ra.rate()));
if ap.is_empty() {
Err(format_err!("Client does not support any AP rates."))
} else {
Ok(ap)
}
}
#[cfg(test)]
mod tests {
use super::*;
impl SupportedRate {
fn new_basic(rate: u8) -> Self {
Self(rate).with_basic(true)
}
}
#[test]
fn some_basic_rate_missing() {
let ap = vec![SupportedRate::new_basic(120), SupportedRate::new_basic(111)];
let client = vec![SupportedRate(111)];
// AP basic rate 120 is not supported, resulting in an Error
let error = intersect_rates(ApRates(ap), ClientRates(client)).unwrap_err();
assert!(format!("{}", error).contains("At least one basic rate not supported."));
}
#[test]
fn all_basic_rates_supported() {
let ap = vec![SupportedRate::new_basic(120), SupportedRate(111)];
let client = vec![SupportedRate(120)];
assert_eq!(
vec![SupportedRate::new_basic(120)],
intersect_rates(ApRates(ap), ClientRates(client)).unwrap()
);
}
#[test]
fn all_basic_and_non_basic_rates_supported() {
let ap = vec![SupportedRate::new_basic(120), SupportedRate(111)];
let client = vec![SupportedRate(120)];
assert_eq!(
vec![SupportedRate::new_basic(120)],
intersect_rates(ApRates(ap), ClientRates(client)).unwrap()
);
}
#[test]
fn no_rates_are_supported() {
let ap = vec![SupportedRate(120)];
let client = vec![];
let error = intersect_rates(ApRates(ap), ClientRates(client)).unwrap_err();
assert!(format!("{}", error).contains("Client does not support any AP rates."));
}
#[test]
fn preserve_ap_rates_basicness() {
let ap = vec![SupportedRate(120), SupportedRate(111)];
let client = vec![SupportedRate::new_basic(120)];
// AP side 120 is not basic so the result should be non-basic.
assert_eq!(
vec![SupportedRate(120)],
intersect_rates(ApRates(ap), ClientRates(client)).unwrap()
);
}
}
|
mod event_handler;
mod event_handlers;
mod raw_event_handler;
mod raw_event_handlers;
pub use event_handler::BotEventHandler;
pub use raw_event_handler::BotRawEventHandler;
|
extern crate sigar_rs;
use sigar_rs::net;
fn main() {
let conns = net::connection_list(net::FLAG_NETCONN_CLIENT | net::FLAG_NETCONN_TCP).unwrap();
let size = if conns.len() > 10 { 10 } else { conns.len() };
let mut i = 0usize;
while i < size {
println!("#{:?} {:?}", i + 1, conns[i]);
i += 1;
}
}
|
// 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 {failure::Error, fidl_fuchsia_settings::*};
pub async fn command(
proxy: DoNotDisturbProxy,
user_dnd: Option<bool>,
night_mode_dnd: Option<bool>,
) -> Result<String, Error> {
let mut output = String::new();
if let Some(user_dnd_value) = user_dnd {
let mut settings = DoNotDisturbSettings::empty();
settings.user_initiated_do_not_disturb = Some(user_dnd_value);
let mutate_result = proxy.set(settings).await?;
match mutate_result {
Ok(_) =>
output.push_str(&format!(
"Successfully set user_initiated_do_not_disturb to {}", user_dnd_value)),
Err(err) => output.push_str(&format!("{:?}", err)),
}
} else if let Some(night_mode_dnd_value) = night_mode_dnd {
let mut settings = DoNotDisturbSettings::empty();
settings.night_mode_initiated_do_not_disturb = Some(night_mode_dnd_value);
let mutate_result = proxy.set(settings).await?;
match mutate_result {
Ok(_) => output.push_str(&format!(
"Successfully set night_mode_initiated_do_not_disturb to {}",
night_mode_dnd_value
)),
Err(err) => output.push_str(&format!("{:?}", err)),
}
} else {
let setting = proxy.watch().await?;
let setting_string =
describe_do_not_disturb_setting(&setting);
output.push_str(&setting_string);
}
Ok(output)
}
fn describe_do_not_disturb_setting(do_not_disturb_setting: &DoNotDisturbSettings) -> String {
let mut output = String::new();
output.push_str("DoNotDisturb { ");
if let Some(user_dnd) = do_not_disturb_setting.user_initiated_do_not_disturb {
output.push_str(&format!("user_initiated_do_not_disturb: {} ", user_dnd))
}
if let Some(night_mode_dnd) = do_not_disturb_setting.night_mode_initiated_do_not_disturb {
output.push_str(&format!("night_mode_initiated_do_not_disturb: {} ", night_mode_dnd))
}
output.push_str("}");
output
}
|
use super::{
channel::{Capacity, Packet},
execution_controller::ExecutionController,
heap::{Data, Function, Heap, Text},
lir::Instruction,
};
use crate::{
channel::ChannelId,
heap::{
DisplayWithSymbolTable, HirId, InlineObject, List, Pointer, ReceivePort, SendPort, Struct,
SymbolId, SymbolTable, Tag,
},
tracer::{FiberTracer, TracedFiberEnded, TracedFiberEndedReason},
Lir,
};
use candy_frontend::{
hir::{self, Id},
impl_countable_id,
module::Module,
};
use derive_more::{Deref, From};
use itertools::Itertools;
use std::{
fmt::{self, Debug},
iter::Step,
};
use strum::EnumIs;
use tracing::trace;
const TRACE: bool = false;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FiberId(usize);
impl_countable_id!(FiberId);
impl Debug for FiberId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "fiber_{:x}", self.0)
}
}
/// A fiber represents an execution thread of a program. It's a stack-based
/// machine that runs instructions from a LIR. Fibers are owned by a `Vm`.
pub struct Fiber<T: FiberTracer> {
pub status: Status,
next_instruction: Option<InstructionPointer>,
pub data_stack: Vec<InlineObject>,
pub call_stack: Vec<InstructionPointer>,
pub heap: Heap,
pub tracer: T,
}
#[derive(Clone, Debug, EnumIs)]
pub enum Status {
Running,
CreatingChannel { capacity: Capacity },
Sending { channel: ChannelId, packet: Packet },
Receiving { channel: ChannelId },
InParallelScope { body: Function },
InTry { body: Function },
Done,
Panicked(Panic),
}
#[derive(Clone, Copy, Deref, Eq, From, Hash, Ord, PartialEq, PartialOrd)]
pub struct InstructionPointer(usize);
impl InstructionPointer {
pub fn null_pointer() -> Self {
Self(0)
}
fn next(&self) -> Self {
Self(self.0 + 1)
}
}
impl Step for InstructionPointer {
fn steps_between(start: &Self, end: &Self) -> Option<usize> {
Some(**end - **start)
}
fn forward_checked(start: Self, count: usize) -> Option<Self> {
(*start).checked_add(count).map(Self)
}
fn backward_checked(start: Self, count: usize) -> Option<Self> {
(*start).checked_sub(count).map(Self)
}
}
impl Debug for InstructionPointer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ip-{}", self.0)
}
}
pub struct VmEnded {
pub heap: Heap,
pub reason: EndedReason,
}
pub struct FiberEnded<T: FiberTracer> {
pub heap: Heap,
pub tracer: T,
pub reason: EndedReason,
}
#[derive(Clone, Debug)]
pub enum EndedReason {
Finished(InlineObject),
Panicked(Panic),
}
#[derive(Clone, Debug)]
pub struct Panic {
pub reason: String,
pub responsible: Id,
pub panicked_child: Option<FiberId>,
}
impl Panic {
pub fn new(reason: String, responsible: Id) -> Self {
Self {
reason,
responsible,
panicked_child: None,
}
}
pub fn new_without_responsible(reason: String) -> Self {
Self::new(reason, Id::complicated_responsibility())
}
}
impl<T: FiberTracer> Fiber<T> {
fn new_with_heap(heap: Heap, tracer: T) -> Self {
Self {
status: Status::Done,
next_instruction: None,
data_stack: vec![],
call_stack: vec![],
heap,
tracer,
}
}
pub fn for_function(
heap: Heap,
function: Function,
arguments: &[InlineObject],
responsible: HirId,
tracer: T,
) -> Self {
let mut fiber = Self::new_with_heap(heap, tracer);
let platform_id = HirId::create(&mut fiber.heap, true, hir::Id::platform());
fiber.tracer.call_started(
&mut fiber.heap,
platform_id,
function.into(),
arguments.to_vec(),
platform_id,
);
platform_id.drop(&mut fiber.heap);
fiber.status = Status::Running;
fiber.call_function(function, arguments, responsible);
fiber
}
pub fn for_module_function(
mut heap: Heap,
module: Module,
function: Function,
tracer: T,
) -> Self {
assert_eq!(
function.captured_len(),
0,
"Function is not a module function (it captures stuff).",
);
assert_eq!(
function.argument_count(),
0,
"Function is not a module function (it has arguments).",
);
let responsible = HirId::create(&mut heap, true, Id::new(module, vec![]));
Self::for_function(heap, function, &[], responsible, tracer)
}
pub fn tear_down(mut self) -> FiberEnded<T> {
let reason = match self.status {
Status::Done => EndedReason::Finished(self.pop_from_data_stack()),
Status::Panicked(panic) => EndedReason::Panicked(panic),
_ => panic!("Called `tear_down` on a fiber that's still running."),
};
FiberEnded {
heap: self.heap,
tracer: self.tracer,
reason,
}
}
pub fn adopt_finished_child(&mut self, child_id: FiberId, ended: FiberEnded<T>) {
self.heap.adopt(ended.heap);
let reason = match ended.reason {
EndedReason::Finished(return_value) => TracedFiberEndedReason::Finished(return_value),
EndedReason::Panicked(panic) => TracedFiberEndedReason::Panicked(panic),
};
self.tracer.child_fiber_ended(TracedFiberEnded {
id: child_id,
heap: &mut self.heap,
tracer: ended.tracer,
reason,
});
}
pub fn status(&self) -> Status {
self.status.clone()
}
pub fn call_stack(&self) -> &[InstructionPointer] {
&self.call_stack
}
// If the status of this fiber is something else than `Status::Running`
// after running, then the VM that manages this fiber is expected to perform
// some action and to then call the corresponding `complete_*` method before
// calling `run` again.
pub fn complete_channel_create(&mut self, channel: ChannelId) {
assert!(self.status.is_creating_channel());
let fields = [
(
SymbolId::SEND_PORT,
SendPort::create(&mut self.heap, channel),
),
(
SymbolId::RECEIVE_PORT,
ReceivePort::create(&mut self.heap, channel),
),
];
let struct_ = Struct::create_with_symbol_keys(&mut self.heap, true, fields);
self.push_to_data_stack(struct_);
self.status = Status::Running;
}
pub fn complete_send(&mut self) {
assert!(self.status.is_sending());
self.push_to_data_stack(Tag::create_nothing());
self.status = Status::Running;
}
pub fn complete_receive(&mut self, packet: Packet) {
assert!(self.status.is_receiving());
let object = packet.object.clone_to_heap(&mut self.heap);
self.push_to_data_stack(object);
self.status = Status::Running;
}
pub fn complete_parallel_scope(&mut self, result: Result<InlineObject, Panic>) {
assert!(self.status.is_in_parallel_scope());
match result {
Ok(object) => {
self.push_to_data_stack(object);
self.status = Status::Running;
}
Err(panic) => self.panic(panic),
}
}
pub fn complete_try(&mut self, ended_reason: &EndedReason) {
assert!(self.status.is_in_try());
let result = match ended_reason {
EndedReason::Finished(return_value) => Ok(*return_value),
EndedReason::Panicked(panic) => {
Err(Text::create(&mut self.heap, true, &panic.reason).into())
}
};
let result = Tag::create_result(&mut self.heap, true, result);
self.push_to_data_stack(result);
self.status = Status::Running;
}
fn get_from_data_stack(&self, offset: usize) -> InlineObject {
self.data_stack[self.data_stack.len() - 1 - offset]
}
#[allow(unused_parens)]
pub fn panic(&mut self, panic: Panic) {
assert!(!matches!(
self.status,
(Status::Done | Status::Panicked { .. }),
));
self.heap.reset_reference_counts();
self.tracer.dup_all_stored_objects(&mut self.heap);
self.heap.drop_all_unreferenced();
self.status = Status::Panicked(panic);
}
pub fn run(
&mut self,
lir: &Lir,
execution_controller: &mut dyn ExecutionController<T>,
id: FiberId,
) {
assert!(
self.status.is_running(),
"Called Fiber::run on a fiber that is not ready to run.",
);
while self.status.is_running() && execution_controller.should_continue_running() {
let Some(current_instruction) = self.next_instruction else {
self.status = Status::Done;
self.tracer
.call_ended(&mut self.heap, *self.data_stack.last().unwrap());
break;
};
let instruction = lir
.instructions
.get(*current_instruction)
.expect("invalid instruction pointer");
self.next_instruction = Some(current_instruction.next());
self.run_instruction(&lir.symbol_table, instruction);
execution_controller.instruction_executed(id, self, current_instruction);
}
}
pub fn run_instruction(&mut self, symbol_table: &SymbolTable, instruction: &Instruction) {
if TRACE {
trace!("Running instruction: {instruction:?}");
let current_instruction = self.next_instruction.unwrap();
trace!("Instruction pointer: {:?}", current_instruction);
trace!(
"Data stack: {}",
if self.data_stack.is_empty() {
"<empty>".to_string()
} else {
self.data_stack
.iter()
.map(|it| format!("{it:?}"))
.join(", ")
},
);
trace!(
"Call stack: {}",
if self.call_stack.is_empty() {
"<empty>".to_string()
} else {
self.call_stack
.iter()
.map(|ip| format!("{ip:?}"))
.join(", ")
},
);
trace!("Heap: {:?}", self.heap);
}
match instruction {
Instruction::CreateTag { symbol_id } => {
let value = self.pop_from_data_stack();
let tag = Tag::create_with_value(&mut self.heap, true, *symbol_id, value);
self.push_to_data_stack(tag);
}
Instruction::CreateList { num_items } => {
let mut item_addresses = vec![];
for _ in 0..*num_items {
item_addresses.push(self.pop_from_data_stack());
}
let items = item_addresses.into_iter().rev().collect_vec();
let list = List::create(&mut self.heap, true, &items);
self.push_to_data_stack(list);
}
Instruction::CreateStruct { num_fields } => {
// PERF: Avoid collecting keys and values into a `Vec` before creating the `HashMap`
let mut key_value_addresses = vec![];
for _ in 0..(2 * num_fields) {
key_value_addresses.push(self.pop_from_data_stack());
}
let entries = key_value_addresses.into_iter().rev().tuples().collect();
let struct_ = Struct::create(&mut self.heap, true, &entries);
self.push_to_data_stack(struct_);
}
Instruction::CreateFunction {
captured,
num_args,
body,
} => {
let captured = captured
.iter()
.map(|offset| {
let object = self.get_from_data_stack(*offset);
object.dup(&mut self.heap);
object
})
.collect_vec();
let function = Function::create(&mut self.heap, true, &captured, *num_args, *body);
self.push_to_data_stack(function);
}
Instruction::PushConstant(constant) => {
self.push_to_data_stack(*constant);
}
Instruction::PushFromStack(offset) => {
let address = self.get_from_data_stack(*offset);
address.dup(&mut self.heap);
self.push_to_data_stack(address);
}
Instruction::PopMultipleBelowTop(n) => {
let top = self.pop_from_data_stack();
for _ in 0..*n {
self.pop_from_data_stack().drop(&mut self.heap);
}
self.push_to_data_stack(top);
}
Instruction::Call { num_args } => {
let responsible = self.pop_from_data_stack().try_into().unwrap();
let mut arguments = (0..*num_args)
.map(|_| self.pop_from_data_stack())
.collect_vec();
// PERF: Build the reverse list in place.
arguments.reverse();
let callee = self.pop_from_data_stack();
self.call(symbol_table, callee, &arguments, responsible);
}
Instruction::TailCall {
num_locals_to_pop,
num_args,
} => {
let responsible = self.pop_from_data_stack().try_into().unwrap();
let mut arguments = (0..*num_args)
.map(|_| self.pop_from_data_stack())
.collect_vec();
// PERF: Built the reverse list in place
arguments.reverse();
let callee = self.pop_from_data_stack();
for _ in 0..*num_locals_to_pop {
self.pop_from_data_stack().drop(&mut self.heap);
}
// Tail calling a function is basically just a normal call, but
// pretending we are our caller.
self.next_instruction = self.call_stack.pop();
self.call(symbol_table, callee, &arguments, responsible);
}
Instruction::Return => {
self.next_instruction = self.call_stack.pop();
}
Instruction::Panic => {
let responsible_for_panic = self.pop_from_data_stack();
let reason = self.pop_from_data_stack();
let Ok(reason) = Text::try_from(reason) else {
// Panic expressions only occur inside the needs function
// where we have validated the inputs before calling the
// instructions, or when lowering compiler errors from the
// HIR to the MIR.
panic!("We should never generate a LIR where the reason is not a text.");
};
let responsible: HirId = responsible_for_panic.try_into().unwrap();
self.panic(Panic::new(
reason.get().to_owned(),
responsible.get().to_owned(),
));
}
Instruction::TraceCallStarts { num_args } => {
let responsible = self.pop_from_data_stack().try_into().unwrap();
let mut args = vec![];
for _ in 0..*num_args {
args.push(self.pop_from_data_stack());
}
let callee = self.pop_from_data_stack();
let call_site = self.pop_from_data_stack().try_into().unwrap();
args.reverse();
self.tracer
.call_started(&mut self.heap, call_site, callee, args, responsible);
}
Instruction::TraceCallEnds => {
let return_value = self.pop_from_data_stack();
self.tracer.call_ended(&mut self.heap, return_value);
}
Instruction::TraceExpressionEvaluated => {
let value = self.pop_from_data_stack();
let expression = self.pop_from_data_stack().try_into().unwrap();
self.tracer
.value_evaluated(&mut self.heap, expression, value);
}
Instruction::TraceFoundFuzzableFunction => {
let function = self.pop_from_data_stack().try_into().expect("Instruction TraceFoundFuzzableFunction executed, but stack top is not a function.");
let definition = self.pop_from_data_stack().try_into().unwrap();
self.tracer
.found_fuzzable_function(&mut self.heap, definition, function);
}
}
}
pub fn call(
&mut self,
symbol_table: &SymbolTable,
callee: InlineObject,
arguments: &[InlineObject],
responsible: HirId,
) {
match callee.into() {
Data::Function(function) => self.call_function(function, arguments, responsible),
Data::Builtin(builtin) => {
callee.drop(&mut self.heap);
self.run_builtin_function(symbol_table, builtin.get(), arguments, responsible);
}
Data::Tag(tag) => {
if tag.has_value() {
self.panic(Panic::new(
"A tag's value cannot be overwritten by calling it. Use `tag.withValue` instead.".to_string(),
responsible.get().to_owned(),
));
return;
}
if let [value] = arguments {
let tag = Tag::create_with_value(&mut self.heap, true, tag.symbol_id(), *value);
self.push_to_data_stack(tag);
value.dup(&mut self.heap);
} else {
self.panic(Panic::new(
format!(
"A tag can only hold exactly one value, but you called it with {} arguments.",
arguments.len(),
),
responsible.get().to_owned(),
));
}
}
_ => {
self.panic(Panic::new(
format!(
"You can only call functions, builtins and tags, but you tried to call {}.",
DisplayWithSymbolTable::to_string(&callee, symbol_table),
),
responsible.get().to_owned(),
));
}
};
}
pub fn call_function(
&mut self,
function: Function,
arguments: &[InlineObject],
responsible: HirId,
) {
let expected_num_args = function.argument_count();
if arguments.len() != expected_num_args {
self.panic(Panic::new(
format!(
"A function expected {expected_num_args} parameters, but you called it with {} arguments.",
arguments.len(),
),
responsible.get().to_owned(),)
);
return;
}
if let Some(next_instruction) = self.next_instruction {
self.call_stack.push(next_instruction);
}
let captured = function.captured();
for captured in captured {
captured.dup(&mut self.heap);
}
self.data_stack.extend_from_slice(captured);
self.data_stack.extend_from_slice(arguments);
self.push_to_data_stack(responsible);
self.next_instruction = Some(function.body());
}
fn push_to_data_stack(&mut self, value: impl Into<InlineObject>) {
self.data_stack.push(value.into());
}
fn pop_from_data_stack(&mut self) -> InlineObject {
self.data_stack.pop().expect("Data stack is empty.")
}
}
trait NthLast {
fn nth_last(&mut self, index: usize) -> Pointer;
}
impl NthLast for Vec<Pointer> {
fn nth_last(&mut self, index: usize) -> Pointer {
self[self.len() - 1 - index]
}
}
|
#[derive(Debug, Fail)]
pub enum TrieBuildFailure {
#[fail(display = "TrieBuildFailure::Unimplemented: {}", _0)]
Unimplemented(&'static str),
#[fail(display = "TrieBuildFailure::UnreachableRule")]
UnreachableRule,
}
|
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 moved into s2
println!("s1: {}", s1) // compile error because s1 is invalid
}
|
pub mod subprocess;
pub mod tokio;
use crate::cache::{push_cache_digest, Digest};
use crate::datastore::{generate_cache_file_path, CACHE_INFO_IN_MEMORY};
use icon::Icon;
use printer::println_json;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
use utils::{count_lines, read_first_lines};
// TODO: make it configurable so that it can support powershell easier?
// https://github.com/liuchengxu/vim-clap/issues/640
/// Builds [`std::process::Command`] from a cmd string which can use pipe.
///
/// This can work with the piped command, e.g., `git ls-files | uniq`.
pub fn shell_command(shell_cmd: &str) -> Command {
if cfg!(target_os = "windows") {
let mut cmd = Command::new("cmd");
cmd.args(["/C", shell_cmd]);
cmd
} else {
let mut cmd = Command::new("bash");
cmd.arg("-c").arg(shell_cmd);
cmd
}
}
/// Executes the command and redirects the output to a file.
pub fn write_stdout_to_file<P: AsRef<Path>>(
cmd: &mut Command,
output_file: P,
) -> std::io::Result<()> {
let file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(output_file)?;
let exit_status = cmd.stdout(file).spawn()?.wait()?;
if exit_status.success() {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"Failed to execute the command: {cmd:?}, exit code: {:?}",
exit_status.code()
),
))
}
}
/// Converts [`std::process::Output`] to a Vec of String.
///
/// Remove the last line if it's empty.
pub fn process_output(output: std::process::Output) -> std::io::Result<Vec<String>> {
if !output.status.success() && !output.stderr.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
String::from_utf8_lossy(&output.stderr),
));
}
let mut lines = output
.stdout
.par_split(|x| x == &b'\n')
.map(|s| String::from_utf8_lossy(s).to_string())
.collect::<Vec<_>>();
// Remove the last empty line.
if lines.last().map(|s| s.is_empty()).unwrap_or(false) {
lines.pop();
}
Ok(lines)
}
/// This type represents an identifier of an unique user-invoked shell command.
///
/// It's only used to determine the cache location for this command and should
/// never be used to be executed directly, in which case it's encouraged to use
/// `std::process::Command` or `subprocess::Exec:shell` instead.
/// Furthermore, it's recommended to execute the command directly instead of using
/// running in a shell like ['cmd', '/C'] due to some issue on Windows like [1].
///
/// [1] https://stackoverflow.com/questions/44757893/cmd-c-doesnt-work-in-rust-when-command-includes-spaces
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct ShellCommand {
/// Raw shell command string.
pub command: String,
/// Working directory of command.
///
/// The same command with different cwd normally has
/// different results, thus we need to record the cwd too.
pub dir: PathBuf,
}
impl ShellCommand {
/// Creates a new instance of [`ShellCommand`].
pub fn new(command: String, dir: PathBuf) -> Self {
Self { command, dir }
}
/// Returns the cache digest if the cache exists.
pub fn cache_digest(&self) -> Option<Digest> {
let mut info = CACHE_INFO_IN_MEMORY.lock();
let maybe_usable_digest = info.lookup_usable_digest(self);
if maybe_usable_digest.is_some() {
info.store_cache_info_if_idle();
}
maybe_usable_digest
}
pub fn cache_file_path(&self) -> std::io::Result<PathBuf> {
let cached_filename = utils::calculate_hash(self);
generate_cache_file_path(cached_filename.to_string())
}
// TODO: remove this.
/// Caches the output into a tempfile and also writes the cache digest to the disk.
pub fn write_cache(self, total: usize, cmd_stdout: &[u8]) -> std::io::Result<PathBuf> {
use std::io::Write;
let cache_filename = utils::calculate_hash(&self);
let cache_file = generate_cache_file_path(cache_filename.to_string())?;
std::fs::File::create(&cache_file)?.write_all(cmd_stdout)?;
let digest = Digest::new(self, total, cache_file.clone());
push_cache_digest(digest);
Ok(cache_file)
}
}
/// Threshold for making a cache for the results.
const OUTPUT_THRESHOLD: usize = 200_000;
/// This struct represents all the info about the processed result of executed command.
#[derive(Debug, Clone, Serialize)]
pub struct ExecInfo {
/// The number of total output lines.
pub total: usize,
/// The lines that will be printed.
pub lines: Vec<String>,
/// If these info are from the cache.
pub using_cache: bool,
/// Optional temp cache file for the whole output.
pub tempfile: Option<PathBuf>,
pub icon_added: bool,
}
impl ExecInfo {
/// Print the fields that are not empty to the terminal in json format.
pub fn print(&self) {
let Self {
using_cache,
tempfile,
total,
lines,
icon_added,
} = self;
if self.using_cache {
if self.tempfile.is_some() {
if self.lines.is_empty() {
println_json!(using_cache, tempfile, total, icon_added);
} else {
println_json!(using_cache, tempfile, total, lines, icon_added);
}
} else {
println_json!(total, lines);
}
} else if self.tempfile.is_some() {
println_json!(tempfile, total, lines, icon_added);
} else {
println_json!(total, lines, icon_added);
}
}
}
/// A wrapper of `std::process::Command` that can reuse the cache if possible.
///
/// When no cache is usable, the command will be executed and the output will be redirected to a
/// cache file if there are too many items in the output.
#[derive(Debug)]
pub struct CacheableCommand<'a> {
/// Ready to be executed and get the output.
std_cmd: &'a mut Command,
/// Used to find and reuse the cache if any.
shell_cmd: ShellCommand,
number: usize,
icon: Icon,
output_threshold: usize,
}
impl<'a> CacheableCommand<'a> {
/// Contructs CacheableCommand from various common opts.
pub fn new(
std_cmd: &'a mut Command,
shell_cmd: ShellCommand,
number: Option<usize>,
icon: Icon,
output_threshold: Option<usize>,
) -> Self {
Self {
std_cmd,
shell_cmd,
number: number.unwrap_or(100),
icon,
output_threshold: output_threshold.unwrap_or(OUTPUT_THRESHOLD),
}
}
/// Checks if the cache exists given `shell_cmd` and `no_cache` flag.
/// If the cache exists, return the cached info, otherwise execute
/// the command.
pub fn try_cache_or_execute(&mut self, no_cache: bool) -> std::io::Result<ExecInfo> {
if no_cache {
self.execute()
} else {
self.shell_cmd
.cache_digest()
.map(|digest| self.exec_info_from_cache_digest(&digest))
.unwrap_or_else(|| self.execute())
}
}
fn exec_info_from_cache_digest(&self, digest: &Digest) -> std::io::Result<ExecInfo> {
let Digest {
total, cached_path, ..
} = digest;
let lines_iter = read_first_lines(&cached_path, self.number)?;
let lines = if let Some(icon_kind) = self.icon.icon_kind() {
lines_iter.map(|x| icon_kind.add_icon_to_text(x)).collect()
} else {
lines_iter.collect()
};
Ok(ExecInfo {
using_cache: true,
total: *total,
tempfile: Some(cached_path.clone()),
lines,
icon_added: self.icon.enabled(),
})
}
/// Execute the command and redirect the stdout to a file.
pub fn execute(&mut self) -> std::io::Result<ExecInfo> {
let cache_file_path = self.shell_cmd.cache_file_path()?;
write_stdout_to_file(self.std_cmd, &cache_file_path)?;
let lines_iter = read_first_lines(&cache_file_path, 100)?;
let lines = if let Some(icon_kind) = self.icon.icon_kind() {
lines_iter.map(|x| icon_kind.add_icon_to_text(x)).collect()
} else {
lines_iter.collect()
};
let total = count_lines(std::fs::File::open(&cache_file_path)?)?;
// Store the cache file if the total number of items exceeds the threshold, so that the
// cache can be reused if the identical command is executed again.
if total > self.output_threshold {
let digest = Digest::new(self.shell_cmd.clone(), total, cache_file_path.clone());
{
let cache_info = crate::datastore::CACHE_INFO_IN_MEMORY.clone();
let mut cache_info = cache_info.lock();
cache_info.limited_push(digest)?;
}
}
Ok(ExecInfo {
using_cache: false,
total,
tempfile: Some(cache_file_path),
lines,
icon_added: self.icon.enabled(),
})
}
}
|
use ckb_testtool::context::Context;
use ckb_tool::ckb_types::{bytes::Bytes, core::TransactionBuilder, packed::*, prelude::*};
use std::fs::File;
use std::io::Read;
const MAX_CYCLES: u64 = 1000_0000;
#[test]
fn it_works() {
// deploy contract
let mut context = Context::default();
let contract_bin = {
let mut buf = Vec::new();
File::open("contract/target/riscv64imac-unknown-none-elf/debug/contract")
.unwrap()
.read_to_end(&mut buf)
.expect("read code");
Bytes::from(buf)
};
let contract_out_point = context.deploy_cell(contract_bin);
// deploy shared library
let shared_lib_bin = {
let mut buf = Vec::new();
File::open("shared-lib/shared-lib.so")
.unwrap()
.read_to_end(&mut buf)
.expect("read code");
Bytes::from(buf)
};
let shared_lib_out_point = context.deploy_cell(shared_lib_bin);
let shared_lib_dep = CellDep::new_builder().out_point(shared_lib_out_point).build();
// prepare scripts
let lock_script = context
.build_script(&contract_out_point, Default::default())
.expect("script");
let lock_script_dep = CellDep::new_builder().out_point(contract_out_point).build();
// prepare cells
let input_out_point = context.create_cell(
CellOutput::new_builder()
.capacity(1000u64.pack())
.lock(lock_script.clone())
.build(),
Bytes::new(),
);
let input = CellInput::new_builder()
.previous_output(input_out_point)
.build();
let outputs = vec![
CellOutput::new_builder()
.capacity(500u64.pack())
.lock(lock_script.clone())
.build(),
CellOutput::new_builder()
.capacity(500u64.pack())
.lock(lock_script)
.build(),
];
let mut outputs_data : Vec<Bytes> = Vec::new();
outputs_data.push(vec![42u8; 1000].into());
outputs_data.push(Bytes::new());
// build transaction
let tx = TransactionBuilder::default()
.input(input)
.outputs(outputs)
.outputs_data(outputs_data.pack())
.cell_dep(lock_script_dep)
.cell_dep(shared_lib_dep)
.build();
let tx = context.complete_tx(tx);
// run
let cycles = context
.verify_tx(&tx, MAX_CYCLES)
.expect("pass verification");
println!("consumed cycles {}", cycles);
}
|
#[macro_use]
extern crate slog;
pub mod get_command;
pub mod config; |
use super::*;
pub use self::traits::*;
mod traits;
/// Like a [`Vec`], but inlined / "stored in the stack"
///
/// It is backed by a partially uninitialised [`array`], that keeps track of
/// its initialised / uninitialised slots by using a `len: usize` field.
///
/// **Its capacity is the length of the backing [`array`]**, and is thus
/// (statically) fixed within its type: see [the `Array` trait].
/// Only an [`array`] that implements [the `Array` trait] can be used as a
/// backing array.
///
/// It can be constructed:
///
/// - either by hand with [its constructor][`StackVec::new`]:
/// ```rust
/// # use ::stackvec::prelude::*;
/// let empty_vec: StackVec<[i32; 16]>
/// = Default::default();
/// assert_eq!(
/// empty_vec.as_slice(),
/// &[],
/// );
/// ```
///
/// - or by [collecting][`Iterator::collect`]
/// an [iterable][`iter::IntoIterator`]:
/// ```rust
/// # use ::stackvec::prelude::*;
/// let vec: StackVec<[i32; 16]>
/// = (0 .. 5)
/// .filter(|&x| x % 2 == 0)
/// .map(|x| x * x)
/// .collect();
/// assert_eq!(
/// vec.as_slice(),
/// &[0, 4, 16],
/// );
/// ```
///
/// [`array`]: https://doc.rust-lang.org/std/primitive.array.html
/// [the `Array` trait]: `stackvec::Array`
pub struct StackVec<A: Array> {
array: mem::ManuallyDrop<A>,
len: usize,
}
impl<A: Array> Default for StackVec<A> {
/// Default constructor: new empty [`StackVec`]
#[inline(always)]
fn default () -> Self
{
debug_assert!(Self::CAPACITY <= isize::MAX as usize);
StackVec {
len: 0,
array: mem::ManuallyDrop::new(unsafe { mem::uninitialized() }),
}
}
}
impl<A: Array> StackVec<A> {
/// The (statically) fixed capacity of the [`StackVec`]
pub const CAPACITY: usize = A::LEN;
/// The (statically) fixed capacity of the [`StackVec`]
#[inline]
pub fn capacity (&self) -> usize { Self::CAPACITY }
/// Constructor: alias for [`Stackvec::default`](
/// struct.StackVec.html#impl-Default)
#[inline(always)]
pub fn new () -> Self
{
Self::default()
}
/// Attempts to push a `value` into the [`StackVec`].
///
/// If it is full, it fails returning the given `value` wrapped in
/// a `Err(OutOfCapacityError(value))`
#[inline]
pub fn try_push (
self: &mut Self,
value: A::Item,
) -> Result<(), OutOfCapacityError<A::Item>>
{
debug_assert!(self.len <= Self::CAPACITY);
if self.len == Self::CAPACITY {
Err(OutOfCapacityError(value))
} else {
unsafe {
self.push_unchecked(value)
};
Ok(())
}
}
/// Pushes the given `value` into the [`StackVec`] if there is room for it,
/// else it does nothing.
///
/// This has the same semantics as
/// `let _ = stackvec.try_push(value);`
/// but may be more efficient.
#[inline]
pub fn push_or_ignore (
self: &mut Self,
value: A::Item,
)
{
debug_assert!(self.len <= Self::CAPACITY);
if self.len < Self::CAPACITY {
unsafe { self.push_unchecked(value) }
};
}
/// Pushes the given `value`
/// into the [`StackVec`], without any kind of bound-checking whatsoever.
///
/// This is generally not recommended, use with caution!
///
/// For a safe alternative use
/// [`self.try_push().expect("stackvec cannot be full")`]
/// [`StackVec::try_push`]
///
/// # Safety
///
/// The assertion that `stackvec.len() < stackvec.capacity()` must hold
/// for the operation to be safe.
#[inline]
pub unsafe fn push_unchecked (
self: &mut Self,
value: A::Item,
)
{
debug_assert!(self.len < Self::CAPACITY); // implicit assertion
ptr::write(
self.array.as_mut_ptr()
.offset(self.len as isize),
value,
);
self.len += 1;
}
/// Removes `value` and returns `Some(value)`, where `value` is the last
/// element of the non-empty [`StackVec`], else it just returns `None`.
#[inline]
pub fn pop (
self: &mut Self,
) -> Option<A::Item>
{
debug_assert!(self.len <= Self::CAPACITY);
if self.len > 0 {
self.len -= 1;
Some(
unsafe {
ptr::read(
self.array.as_ptr()
.offset(self.len as isize),
)
}
)
} else {
None
}
}
/// Shortens the [`StackVec`], keeping the first `new_len` elements and
/// dropping the rest.
///
/// If `new_len` is greater than the current length, this has no effect.
///
/// This has the same semantics as
/// `(new_len .. stackvec.len()).for_each(|_| { stackvec.pop(); })`
/// but may be more efficient.
#[inline]
pub fn truncate (
self: &mut Self,
new_len: usize,
)
{
for new_len in Iterator::rev(new_len .. self.len) {
self.len = new_len;
unsafe {
ptr::drop_in_place(
self.array.as_mut_ptr()
.offset(new_len as isize)
);
};
};
}
/// Clears the [`StackVec`], removing all the values.
///
/// This is exactly the same as `stackvec.truncate(0)`.
#[inline]
pub fn clear (
self: &mut Self,
)
{
self.truncate(0)
}
/// Extracts a slice containing the entire [`StackVec`].
///
/// Equivalent to `&stackvec[..]`.
#[inline]
pub fn as_slice (
self: &Self,
) -> &[A::Item]
{
&* self
}
/// Extracts a mutable slice of the entire [`StackVec`].
///
/// Equivalent to `&mut stackvec[..]`.
#[inline]
pub fn as_mut_slice (
self: &mut Self,
) -> &mut [A::Item]
{
&mut* self
}
/// Returns `true` iff the [`StackVec`] is empty
/// (`self.len() == 0`)
#[inline]
pub fn is_empty (
self: &Self,
) -> bool
{
self.len() == 0
}
/// Returns `true` iff the [`StackVec`] is full
/// (`self.len() == self.capacity()`)
#[inline]
pub fn is_full (
self: &Self,
) -> bool
{
debug_assert!(self.len <= Self::CAPACITY);
self.len() == Self::CAPACITY
}
/// Fills the [`StackVec`] with the different values created by the
/// given `factory`.
///
/// # Examples
///
/// ```rust
/// # use ::stackvec::prelude::*;
/// let vec = StackVec::<[Option<String>; 64]>::
/// default()
/// .fill_using(|| None);
/// ```
///
/// ```rust
/// # use ::stackvec::prelude::*;
/// let vec = StackVec::<[String; 64]>::
/// default()
/// .fill_using(Default::default);
/// ```
///
/// ```rust
/// # use ::stackvec::prelude::*;
/// let s = String::from("!");
/// let vec = StackVec::<[String; 64]>::
/// from_iter(
/// ["Hello", "world"]
/// .into_iter()
/// .map(String::from)
/// ).fill_using(|| s.clone());
/// ```
///
/// See [`StackVec<Array>::try_into::<Array>`][`stackvec::traits::TryInto`]
/// for more detailed examples.
#[inline]
pub fn fill_using (
self: &mut Self,
factory: impl FnMut() -> A::Item,
)
{
self.extend(
iter::repeat_with(factory)
)
}
}
impl<A: Array> StackVec<A>
where
A::Item: Copy,
{
/// Fills the [`StackVec`] with [copies][`Copy`] of the given `value`.
///
/// # Example
/// ```rust
/// # use ::stackvec::prelude::*;
/// let vec = StackVec::<[&'static str; 64]>::
/// from_iter(
/// ["Hello", "world"]
/// .into_iter()
/// ).fill_with("!");
/// ```
#[inline]
pub fn fill_with (
self: &mut Self,
value: A::Item,
)
{
self.extend(
iter::repeat(value)
)
}
}
impl<A: Array> Drop for StackVec<A> {
#[inline]
fn drop (
self: &mut Self,
)
{
self.clear()
}
}
impl<A: Array> ops::Deref for StackVec<A> {
type Target = [A::Item];
#[inline]
fn deref (
self: &Self,
) -> &Self::Target
{
unsafe {
slice::from_raw_parts(
self.array.as_ptr(),
self.len,
)
}
}
}
impl<A: Array> ops::DerefMut for StackVec<A> {
#[inline]
fn deref_mut (
self: &mut Self,
) -> &mut Self::Target
{
unsafe {
slice::from_raw_parts_mut(
self.array.as_mut_ptr(),
self.len,
)
}
}
}
impl<A: Array> fmt::Debug for StackVec<A>
where
A::Item: fmt::Debug,
{
fn fmt (
self: &Self,
stream: &mut fmt::Formatter,
) -> fmt::Result
{
try!(fmt::Display::fmt("[", stream));
let mut iterator = self.iter();
if let Some(first) = iterator.next() {
try!(fmt::Debug::fmt(first, stream));
for x in iterator {
try!(write!(stream, ", {:?}", x));
};
};
fmt::Display::fmt("]", stream)
}
}
|
use crate::{Coordinate, CoordinateType, Point};
/// A line segment made up of exactly two [`Point`s](struct.Point.html).
#[derive(Eq, PartialEq, Clone, Copy, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Line<T>
where
T: CoordinateType,
{
pub start: Coordinate<T>,
pub end: Coordinate<T>,
}
impl<T> Line<T>
where
T: CoordinateType,
{
/// Creates a new line segment.
///
/// # Examples
///
/// ```
/// use geo_types::{Coordinate, Line};
///
/// let line = Line::new(Coordinate { x: 0., y: 0. }, Coordinate { x: 1., y: 2. });
///
/// assert_eq!(line.start, Coordinate { x: 0., y: 0. });
/// assert_eq!(line.end, Coordinate { x: 1., y: 2. });
/// ```
pub fn new<C>(start: C, end: C) -> Line<T>
where
C: Into<Coordinate<T>>,
{
Line {
start: start.into(),
end: end.into(),
}
}
/// Calculate the difference in ‘x’ components (Δx).
///
/// Equivalent to:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let line = Line::new(
/// # Point(Coordinate { x: 4., y: -12. }),
/// # Point(Coordinate { x: 0., y: 9. }),
/// # );
/// # assert_eq!(
/// # line.dx(),
/// line.end.x - line.start.x
/// # );
/// ```
pub fn dx(&self) -> T {
self.end.x - self.start.x
}
/// Calculate the difference in ‘y’ components (Δy).
///
/// Equivalent to:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let line = Line::new(
/// # Point(Coordinate { x: 4., y: -12. }),
/// # Point(Coordinate { x: 0., y: 9. }),
/// # );
/// # assert_eq!(
/// # line.dy(),
/// line.end.y - line.start.y
/// # );
/// ```
pub fn dy(&self) -> T {
self.end.y - self.start.y
}
/// Calculate the slope (Δy/Δx).
///
/// Equivalent to:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let line = Line::new(
/// # Point(Coordinate { x: 4., y: -12. }),
/// # Point(Coordinate { x: 0., y: 9. }),
/// # );
/// # assert_eq!(
/// # line.slope(),
/// line.dy() / line.dx()
/// # );
/// ```
///
/// Note that:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let a = Point(Coordinate { x: 4., y: -12. });
/// # let b = Point(Coordinate { x: 0., y: 9. });
/// # assert!(
/// Line::new(a, b).slope() == Line::new(b, a).slope()
/// # );
/// ```
pub fn slope(&self) -> T {
self.dy() / self.dx()
}
/// Calculate the [determinant](https://en.wikipedia.org/wiki/Determinant) of the line.
///
/// Equivalent to:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let line = Line::new(
/// # Point(Coordinate { x: 4., y: -12. }),
/// # Point(Coordinate { x: 0., y: 9. }),
/// # );
/// # assert_eq!(
/// # line.determinant(),
/// line.start.x * line.end.y - line.start.y * line.end.x
/// # );
/// ```
///
/// Note that:
///
/// ```rust
/// # use geo_types::{Line, Coordinate, Point};
/// # let a = Point(Coordinate { x: 4., y: -12. });
/// # let b = Point(Coordinate { x: 0., y: 9. });
/// # assert!(
/// Line::new(a, b).determinant() == -Line::new(b, a).determinant()
/// # );
/// ```
pub fn determinant(&self) -> T {
self.start.x * self.end.y - self.start.y * self.end.x
}
pub fn start_point(&self) -> Point<T> {
Point(self.start)
}
pub fn end_point(&self) -> Point<T> {
Point(self.end)
}
pub fn points(&self) -> (Point<T>, Point<T>) {
(self.start_point(), self.end_point())
}
}
impl<T: CoordinateType> From<[(T, T); 2]> for Line<T> {
fn from(coord: [(T, T); 2]) -> Line<T> {
Line::new(coord[0], coord[1])
}
}
#[cfg(feature = "rstar")]
impl<T> ::rstar::RTreeObject for Line<T>
where
T: ::num_traits::Float + ::rstar::RTreeNum,
{
type Envelope = ::rstar::AABB<Point<T>>;
fn envelope(&self) -> Self::Envelope {
let bounding_rect = crate::private_utils::line_bounding_rect(*self);
::rstar::AABB::from_corners(bounding_rect.min().into(), bounding_rect.max().into())
}
}
#[cfg(feature = "rstar")]
impl<T> ::rstar::PointDistance for Line<T>
where
T: ::num_traits::Float + ::rstar::RTreeNum,
{
fn distance_2(&self, point: &Point<T>) -> T {
let d = crate::private_utils::point_line_euclidean_distance(*point, *self);
d.powi(2)
}
}
|
// Copyright 2017 rust-ipfs-api Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
use crate::serde::Deserialize;
use std::fmt::{self, Display, Formatter};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ApiError {
pub message: String,
pub code: u8,
}
impl Display for ApiError {
fn fmt(&self, mut formatter: &mut Formatter<'_>) -> Result<(), fmt::Error> {
write!(&mut formatter, "[{}] {}", self.code, self.message)
}
}
|
use actix::{Actor, StreamHandler};
use actix_web::dev::Payload;
use actix_web::error::Error;
use actix_web::ws::{handshake, Message, ProtocolError, WebsocketContext, WsStream};
use actix_web::{HttpMessage, HttpRequest, HttpResponse};
pub fn start<F, A, S>(req: &HttpRequest<S>, actor: A, map: F) -> Result<HttpResponse, Error>
where
A: Actor<Context = WebsocketContext<A, S>> + StreamHandler<Message, ProtocolError>,
S: 'static,
F: FnOnce(WsStream<Payload>) -> WsStream<Payload>,
{
let mut resp = handshake(req)?;
let stream = map(WsStream::new(req.payload()));
let body = WebsocketContext::create(req.clone(), actor, stream);
Ok(resp.body(body))
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
contacts_service::{handle::ContactsServiceHandle, storage::database::ContactsBackend, ContactsServiceInitializer},
error::WalletError,
output_manager_service::{
config::OutputManagerServiceConfig,
handle::OutputManagerHandle,
storage::database::OutputManagerBackend,
OutputManagerServiceInitializer,
TxId,
},
storage::database::{WalletBackend, WalletDatabase},
transaction_service::{
config::TransactionServiceConfig,
handle::TransactionServiceHandle,
storage::database::TransactionBackend,
TransactionServiceInitializer,
},
};
use blake2::Digest;
use log::*;
use std::{marker::PhantomData, sync::Arc, time::Duration};
use tari_comms::{
multiaddr::Multiaddr,
peer_manager::{NodeId, Peer, PeerFeatures, PeerFlags},
types::CommsPublicKey,
CommsNode,
};
use tari_comms_dht::{store_forward::StoreAndForwardRequester, Dht};
use tari_core::transactions::{
tari_amount::MicroTari,
transaction::{OutputFeatures, UnblindedOutput},
types::{CryptoFactories, PrivateKey},
};
use tari_crypto::{
common::Blake256,
ristretto::{RistrettoPublicKey, RistrettoSchnorr, RistrettoSecretKey},
signatures::{SchnorrSignature, SchnorrSignatureError},
tari_utilities::hex::Hex,
};
use tari_p2p::{
comms_connector::pubsub_connector,
initialization::{initialize_comms, CommsConfig},
services::{
comms_outbound::CommsOutboundServiceInitializer,
liveness::{LivenessConfig, LivenessHandle, LivenessInitializer},
},
};
use tari_service_framework::StackBuilder;
use tokio::runtime::Runtime;
const LOG_TARGET: &str = "wallet";
#[derive(Clone)]
pub struct WalletConfig {
pub comms_config: CommsConfig,
pub factories: CryptoFactories,
pub transaction_service_config: Option<TransactionServiceConfig>,
}
/// A structure containing the config and services that a Wallet application will require. This struct will start up all
/// the services and provide the APIs that applications will use to interact with the services
pub struct Wallet<T, U, V, W>
where
T: WalletBackend + 'static,
U: TransactionBackend + Clone + 'static,
V: OutputManagerBackend + 'static,
W: ContactsBackend + 'static,
{
pub comms: CommsNode,
pub dht_service: Dht,
pub store_and_forward_requester: StoreAndForwardRequester,
pub liveness_service: LivenessHandle,
pub output_manager_service: OutputManagerHandle,
pub transaction_service: TransactionServiceHandle,
pub contacts_service: ContactsServiceHandle,
pub db: WalletDatabase<T>,
pub runtime: Runtime,
pub factories: CryptoFactories,
#[cfg(feature = "test_harness")]
pub transaction_backend: U,
_u: PhantomData<U>,
_v: PhantomData<V>,
_w: PhantomData<W>,
}
impl<T, U, V, W> Wallet<T, U, V, W>
where
T: WalletBackend + 'static,
U: TransactionBackend + Clone + 'static,
V: OutputManagerBackend + 'static,
W: ContactsBackend + 'static,
{
pub fn new(
config: WalletConfig,
mut runtime: Runtime,
wallet_backend: T,
transaction_backend: U,
output_manager_backend: V,
contacts_backend: W,
) -> Result<Wallet<T, U, V, W>, WalletError>
{
let db = WalletDatabase::new(wallet_backend);
let base_node_peers = runtime.block_on(db.get_peers())?;
#[cfg(feature = "test_harness")]
let transaction_backend_handle = transaction_backend.clone();
let factories = config.factories;
let (publisher, subscription_factory) = pubsub_connector(
runtime.handle().clone(),
config.comms_config.max_concurrent_inbound_tasks,
);
let subscription_factory = Arc::new(subscription_factory);
let (comms, dht) = runtime.block_on(initialize_comms(config.comms_config.clone(), publisher))?;
let fut = StackBuilder::new(runtime.handle().clone(), comms.shutdown_signal())
.add_initializer(CommsOutboundServiceInitializer::new(dht.outbound_requester()))
.add_initializer(LivenessInitializer::new(
LivenessConfig {
auto_ping_interval: Some(Duration::from_secs(30)),
enable_auto_join: true,
..Default::default()
},
Arc::clone(&subscription_factory),
dht.dht_requester(),
comms.connection_manager(),
))
.add_initializer(OutputManagerServiceInitializer::new(
OutputManagerServiceConfig::default(),
subscription_factory.clone(),
output_manager_backend,
factories.clone(),
))
.add_initializer(TransactionServiceInitializer::new(
config.transaction_service_config.unwrap_or_default(),
subscription_factory.clone(),
transaction_backend,
comms.node_identity(),
factories.clone(),
))
.add_initializer(ContactsServiceInitializer::new(contacts_backend))
.finish();
let handles = runtime.block_on(fut).expect("Service initialization failed");
let mut output_manager_handle = handles
.get_handle::<OutputManagerHandle>()
.expect("Could not get Output Manager Service Handle");
let mut transaction_service_handle = handles
.get_handle::<TransactionServiceHandle>()
.expect("Could not get Transaction Service Handle");
let liveness_handle = handles
.get_handle::<LivenessHandle>()
.expect("Could not get Liveness Service Handle");
let contacts_handle = handles
.get_handle::<ContactsServiceHandle>()
.expect("Could not get Contacts Service Handle");
for p in base_node_peers {
runtime.block_on(transaction_service_handle.set_base_node_public_key(p.public_key.clone()))?;
runtime.block_on(output_manager_handle.set_base_node_public_key(p.public_key.clone()))?;
}
let store_and_forward_requester = dht.store_and_forward_requester();
Ok(Wallet {
comms,
dht_service: dht,
store_and_forward_requester,
liveness_service: liveness_handle,
output_manager_service: output_manager_handle,
transaction_service: transaction_service_handle,
contacts_service: contacts_handle,
db,
runtime,
factories,
#[cfg(feature = "test_harness")]
transaction_backend: transaction_backend_handle,
_u: PhantomData,
_v: PhantomData,
_w: PhantomData,
})
}
/// This method consumes the wallet so that the handles are dropped which will result in the services async loops
/// exiting.
pub fn shutdown(mut self) {
self.runtime.block_on(self.comms.shutdown());
}
/// This function will set the base_node that the wallet uses to broadcast transactions and monitor the blockchain
/// state
pub fn set_base_node_peer(&mut self, public_key: CommsPublicKey, net_address: String) -> Result<(), WalletError> {
let address = net_address.parse::<Multiaddr>()?;
let peer = Peer::new(
public_key.clone(),
NodeId::from_key(&public_key).unwrap(),
vec![address].into(),
PeerFlags::empty(),
PeerFeatures::COMMUNICATION_NODE,
&[],
);
let existing_peers = self.runtime.block_on(self.db.get_peers())?;
// Remove any peers in db to only persist a single peer at a time.
for p in existing_peers {
let _ = self.runtime.block_on(self.db.remove_peer(p.public_key.clone()))?;
}
self.runtime.block_on(self.db.save_peer(peer.clone()))?;
self.runtime
.block_on(self.comms.peer_manager().add_peer(peer.clone()))?;
self.runtime.block_on(
self.transaction_service
.set_base_node_public_key(peer.public_key.clone()),
)?;
self.runtime
.block_on(self.output_manager_service.set_base_node_public_key(peer.public_key))?;
Ok(())
}
/// Import an external spendable UTXO into the wallet. The output will be added to the Output Manager and made
/// spendable. A faux incoming transaction will be created to provide a record of the event. The TxId of the
/// generated transaction is returned.
pub fn import_utxo(
&mut self,
amount: MicroTari,
spending_key: &PrivateKey,
source_public_key: &CommsPublicKey,
message: String,
) -> Result<TxId, WalletError>
{
let unblinded_output = UnblindedOutput::new(amount, spending_key.clone(), None);
self.runtime
.block_on(self.output_manager_service.add_output(unblinded_output.clone()))?;
let tx_id = self.runtime.block_on(self.transaction_service.import_utxo(
amount.clone(),
source_public_key.clone(),
message,
))?;
info!(
target: LOG_TARGET,
"UTXO (Commitment: {}) imported into wallet",
unblinded_output
.as_transaction_input(&self.factories.commitment, OutputFeatures::default())
.commitment
.to_hex()
);
Ok(tx_id)
}
pub fn sign_message(
&mut self,
secret: RistrettoSecretKey,
nonce: RistrettoSecretKey,
message: &str,
) -> Result<SchnorrSignature<RistrettoPublicKey, RistrettoSecretKey>, SchnorrSignatureError>
{
let challenge = Blake256::digest(message.as_bytes());
RistrettoSchnorr::sign(secret, nonce, challenge.clone().as_slice())
}
pub fn verify_message_signature(
&mut self,
public_key: RistrettoPublicKey,
public_nonce: RistrettoPublicKey,
signature: RistrettoSecretKey,
message: String,
) -> bool
{
let signature = RistrettoSchnorr::new(public_nonce, signature);
let challenge = Blake256::digest(message.as_bytes());
signature.verify_challenge(&public_key, challenge.clone().as_slice())
}
/// Have all the wallet components that need to start a sync process with the set base node to confirm the wallets
/// state is accurately reflected on the blockchain
pub fn sync_with_base_node(&mut self) -> Result<u64, WalletError> {
self.runtime
.block_on(self.store_and_forward_requester.request_saf_messages_from_neighbours())?;
let request_key = self
.runtime
.block_on(self.output_manager_service.sync_with_base_node())?;
Ok(request_key)
}
}
|
//! Actix Connector - tcp connector service
//!
//! ## Package feature
//!
//! * `tls` - enables ssl support via `native-tls` crate
//! * `ssl` - enables ssl support via `openssl` crate
//! * `rust-tls` - enables ssl support via `rustls` crate
mod connector;
mod resolver;
pub mod ssl;
pub use self::connector::{
Connect, Connector, ConnectorError, DefaultConnector, RequestPort, TcpConnector,
};
pub use self::resolver::{RequestHost, Resolver};
|
#[macro_use]
extern crate serde_derive;
extern crate rmp_serde as rmps;
use std::io::Cursor;
use serde::Deserialize;
use crate::rmps::decode::Error;
use crate::rmps::Deserializer;
#[test]
fn pass_newtype() {
let buf = [0x2a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Struct(u32);
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Struct(42), actual);
}
#[test]
fn pass_tuple_struct() {
let buf = [0x92, 0x2a, 0xce, 0x0, 0x1, 0x88, 0x94];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Decoded(u32, u32);
let mut de = Deserializer::new(cur);
let actual: Decoded = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Decoded(42, 100500), actual);
}
#[test]
fn pass_single_field_struct() {
let buf = [0x91, 0x2a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Struct {
inner: u32,
};
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Struct { inner: 42 }, actual);
}
#[test]
fn pass_struct() {
let buf = [0x92, 0x2a, 0xce, 0x0, 0x1, 0x88, 0x94];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Decoded {
id: u32,
value: u32,
};
let mut de = Deserializer::new(cur);
let actual: Decoded = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(
Decoded {
id: 42,
value: 100500
},
actual
);
}
#[test]
fn pass_struct_from_map() {
#[derive(Debug, PartialEq, Deserialize)]
struct Struct {
et: String,
le: u8,
shit: u8,
}
let buf = [
0x83, // 3 (size)
0xa2, 0x65, 0x74, // "et"
0xa5, 0x76, 0x6f, 0x69, 0x6c, 0x61, // "voila"
0xa2, 0x6c, 0x65, // "le"
0x00, // 0
0xa4, 0x73, 0x68, 0x69, 0x74, // "shit"
0x01, // 1
];
let cur = Cursor::new(&buf[..]);
// It appears no special behavior is needed for deserializing structs encoded as maps.
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
let expected = Struct {
et: "voila".into(),
le: 0,
shit: 1,
};
assert_eq!(expected, actual);
}
#[test]
fn pass_unit_variant() {
let buf = [0x00, 0x01];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq)]
enum Enum {
A,
B,
}
const _: () = {
#[allow(unused_extern_crates, clippy::useless_attribute)]
extern crate serde as _serde;
#[automatically_derived]
impl<'de> _serde::Deserialize<'de> for Enum {
fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, __D::Error>
where
__D: _serde::Deserializer<'de>,
{
#[allow(non_camel_case_types)]
enum __Field {
__field0,
__field1,
}
struct __FieldVisitor;
impl<'de> _serde::de::Visitor<'de> for __FieldVisitor {
type Value = __Field;
fn expecting(
&self,
__formatter: &mut _serde::__private::Formatter,
) -> _serde::__private::fmt::Result {
_serde::__private::Formatter::write_str(__formatter, "variant identifier")
}
fn visit_u64<__E>(
self,
__value: u64,
) -> _serde::__private::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
0u64 => _serde::__private::Ok(__Field::__field0),
1u64 => _serde::__private::Ok(__Field::__field1),
_ => _serde::__private::Err(_serde::de::Error::invalid_value(
_serde::de::Unexpected::Unsigned(__value),
&"variant index 0 <= i < 2",
)),
}
}
fn visit_str<__E>(
self,
__value: &str,
) -> _serde::__private::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
"A" => _serde::__private::Ok(__Field::__field0),
"B" => _serde::__private::Ok(__Field::__field1),
_ => _serde::__private::Err(_serde::de::Error::unknown_variant(
__value, VARIANTS,
)),
}
}
fn visit_bytes<__E>(
self,
__value: &[u8],
) -> _serde::__private::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
b"A" => _serde::__private::Ok(__Field::__field0),
b"B" => _serde::__private::Ok(__Field::__field1),
_ => {
let __value = &_serde::__private::from_utf8_lossy(__value);
_serde::__private::Err(_serde::de::Error::unknown_variant(
__value, VARIANTS,
))
}
}
}
}
impl<'de> _serde::Deserialize<'de> for __Field {
#[inline]
fn deserialize<__D>(
__deserializer: __D,
) -> _serde::__private::Result<Self, __D::Error>
where
__D: _serde::Deserializer<'de>,
{
_serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor)
}
}
struct __Visitor<'de> {
marker: _serde::__private::PhantomData<Enum>,
lifetime: _serde::__private::PhantomData<&'de ()>,
}
impl<'de> _serde::de::Visitor<'de> for __Visitor<'de> {
type Value = Enum;
fn expecting(
&self,
__formatter: &mut _serde::__private::Formatter,
) -> _serde::__private::fmt::Result {
_serde::__private::Formatter::write_str(__formatter, "enum Enum")
}
fn visit_enum<__A>(
self,
__data: __A,
) -> _serde::__private::Result<Self::Value, __A::Error>
where
__A: _serde::de::EnumAccess<'de>,
{
match match _serde::de::EnumAccess::variant(__data) {
_serde::__private::Ok(__val) => __val,
_serde::__private::Err(__err) => {
return _serde::__private::Err(__err);
}
} {
(__Field::__field0, __variant) => {
match _serde::de::VariantAccess::unit_variant(__variant) {
_serde::__private::Ok(__val) => __val,
_serde::__private::Err(__err) => {
return _serde::__private::Err(__err);
}
};
_serde::__private::Ok(Enum::A)
}
(__Field::__field1, __variant) => {
match _serde::de::VariantAccess::unit_variant(__variant) {
_serde::__private::Ok(__val) => __val,
_serde::__private::Err(__err) => {
return _serde::__private::Err(__err);
}
};
_serde::__private::Ok(Enum::B)
}
}
}
}
const VARIANTS: &'static [&'static str] = &["A", "B"];
_serde::Deserializer::deserialize_enum(
__deserializer,
"Enum",
VARIANTS,
__Visitor {
marker: _serde::__private::PhantomData::<Enum>,
lifetime: _serde::__private::PhantomData,
},
)
}
}
};
let mut de = Deserializer::new(cur);
let enum_a = Enum::deserialize(&mut de).unwrap();
assert_eq!(enum_a, Enum::A);
assert_eq!(1, de.get_ref().position());
let enum_b = Enum::deserialize(&mut de).unwrap();
assert_eq!(enum_a, Enum::A);
assert_eq!(enum_b, Enum::B);
assert_eq!(2, de.get_ref().position());
}
#[test]
fn pass_tuple_enum_with_arg() {
// The encoded byte-array is: {1 => 42}.
let buf = [0x81, 0x01, 0x2a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
A,
B(u32),
}
let mut de = Deserializer::new(cur);
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::B(42), actual);
assert_eq!(3, de.get_ref().position())
}
#[test]
fn pass_tuple_enum_with_args() {
// The encoded bytearray is: {1 => [42, 58]}.
let buf = [0x81, 0x01, 0x92, 0x2a, 0x3a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
A,
B(u32, u32),
}
let mut de = Deserializer::new(cur);
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::B(42, 58), actual);
assert_eq!(5, de.get_ref().position())
}
#[test]
fn fail_enum_overflow() {
// The encoded bytearray is: {1 => [42]}.
let buf = [0x81, 0x01, 0x2a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
// TODO: Rename to Enum: A, B, C, ...
enum Enum {
A,
}
let mut de = Deserializer::new(cur);
let actual: Result<Enum, Error> = Deserialize::deserialize(&mut de);
match actual.err().unwrap() {
Error::Syntax(..) => (),
other => panic!("unexpected result: {:?}", other),
}
}
#[test]
fn pass_struct_enum_with_arg() {
// The encoded bytearray is: {1 => [42]}.
let buf = [0x81, 0x01, 0x91, 0x2a];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
A,
B { id: u32 },
}
let mut de = Deserializer::new(cur);
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::B { id: 42 }, actual);
assert_eq!(4, de.get_ref().position())
}
#[test]
fn pass_newtype_variant() {
// The encoded bytearray is: {0 => 'le message'}.
let buf = [
0x81, 0x0, 0xaa, 0x6c, 0x65, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Newtype(String);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
A(Newtype),
}
let mut de = Deserializer::new(cur);
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::A(Newtype("le message".into())), actual);
assert_eq!(buf.len() as u64, de.get_ref().position())
}
#[cfg(disabled)] // This test doesn't actually compile anymore
#[test]
fn pass_enum_custom_policy() {
use rmp_serde::decode::VariantVisitor;
use std::io::Read;
// We expect enums to be endoded as id, [...] (without wrapping tuple).
let buf = [0x01, 0x90];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
A,
B,
}
struct CustomDeserializer<R: Read> {
inner: Deserializer<R>,
}
impl<R: Read> serde::Deserializer for CustomDeserializer<R> {
type Error = Error;
fn deserialize<V>(&mut self, visitor: V) -> Result<V::Value, Error>
where
V: serde::de::Visitor,
{
self.inner.deserialize(visitor)
}
fn deserialize_enum<V>(
&mut self,
_enum: &str,
_variants: &'static [&'static str],
mut visitor: V,
) -> Result<V::Value, Error>
where
V: serde::de::EnumVisitor,
{
visitor.visit(VariantVisitor::new(&mut self.inner))
}
forward_to_deserialize! {
bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string unit seq
seq_fixed_size bytes map tuple_struct unit_struct struct struct_field
tuple option newtype_struct ignored_any
}
}
let mut de = CustomDeserializer {
inner: Deserializer::new(cur),
};
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::B, actual);
assert_eq!(2, de.inner.get_ref().position());
}
#[test]
fn pass_struct_variant() {
#[derive(Debug, PartialEq, Deserialize)]
enum Custom {
First { data: u32 },
Second { data: u32 },
}
let out_first = vec![0x81, 0x00, 0x91, 0x2a];
let out_second = vec![0x81, 0x01, 0x91, 0x2a];
for (expected, out) in vec![
(Custom::First { data: 42 }, out_first),
(Custom::Second { data: 42 }, out_second),
] {
let mut de = Deserializer::new(Cursor::new(&out[..]));
let val: Custom = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(expected, val);
}
}
#[test]
fn pass_adjacently_tagged_enum() {
// ["Foo", 123]
let buf = [146, 163, 70, 111, 111, 123];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
#[serde(tag = "t", content = "c")]
enum Enum {
Foo(i32),
Bar(u32),
}
let mut de = Deserializer::new(cur);
let actual = Deserialize::deserialize(&mut de);
assert!(actual.is_ok());
assert_eq!(Enum::Foo(123), actual.unwrap());
}
#[test]
#[should_panic(expected = "assertion failed")]
fn fail_internally_tagged_enum_tuple() {
// ["Foo", 123]
let buf = [146, 163, 70, 111, 111, 123];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
#[serde(tag = "t")]
enum Enum {
Foo(i32),
Bar(u32),
}
let mut de = Deserializer::new(cur);
let actual: Result<Enum, Error> = Deserialize::deserialize(&mut de);
assert!(actual.is_ok())
}
#[test]
fn pass_internally_tagged_enum_struct() {
let buf = [
130, 161, 116, 163, 70, 111, 111, 165, 118, 97, 108, 117, 101, 123,
];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
#[serde(tag = "t")]
enum Enum {
Foo { value: i32 },
Bar { value: u32 },
}
let mut de = Deserializer::new(cur);
let actual: Result<Enum, Error> = Deserialize::deserialize(&mut de);
assert!(actual.is_ok());
assert_eq!(Enum::Foo { value: 123 }, actual.unwrap())
}
#[test]
fn pass_enum_with_one_arg() {
// The encoded bytearray is: {0 => [1, 2]}.
let buf = [0x81, 0x0, 0x92, 0x01, 0x02];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
enum Enum {
V1(Vec<u32>),
}
let mut de = Deserializer::new(cur);
let actual: Enum = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(Enum::V1(vec![1, 2]), actual);
assert_eq!(buf.len() as u64, de.get_ref().position())
}
#[test]
fn pass_struct_with_nested_options() {
// The encoded bytearray is: [null, 13].
let buf = [0x92, 0xc0, 0x0D];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Struct {
f1: Option<Option<u32>>,
f2: Option<Option<u32>>,
}
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(
Struct {
f1: None,
f2: Some(Some(13))
},
actual
);
assert_eq!(buf.len() as u64, de.get_ref().position());
}
#[test]
fn pass_struct_with_flattened_map_field() {
use std::collections::BTreeMap;
// The encoded bytearray is: { "f1": 0, "f2": { "german": "Hallo Welt!" }, "english": "Hello World!" }.
let buf = [
0x83, 0xA2, 0x66, 0x31, 0x00, 0xA2, 0x66, 0x32, 0x81, 0xA6, 0x67, 0x65, 0x72, 0x6D, 0x61,
0x6E, 0xAB, 0x48, 0x61, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x65, 0x6C, 0x74, 0x21, 0xA7, 0x65,
0x6E, 0x67, 0x6C, 0x69, 0x73, 0x68, 0xAC, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F,
0x72, 0x6C, 0x64, 0x21,
];
let cur = Cursor::new(&buf[..]);
#[derive(Debug, PartialEq, Deserialize)]
struct Struct {
f1: u32,
// not flattend!
f2: BTreeMap<String, String>,
#[serde(flatten)]
f3: BTreeMap<String, String>,
}
let expected = Struct {
f1: 0,
f2: {
let mut map = BTreeMap::new();
map.insert("german".to_string(), "Hallo Welt!".to_string());
map
},
f3: {
let mut map = BTreeMap::new();
map.insert("english".to_string(), "Hello World!".to_string());
map
},
};
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(expected, actual);
assert_eq!(buf.len() as u64, de.get_ref().position());
}
#[test]
fn pass_struct_with_flattened_struct_field() {
#[derive(Debug, PartialEq, Deserialize)]
struct Struct {
f1: u32,
// not flattend!
f2: InnerStruct,
#[serde(flatten)]
f3: InnerStruct,
}
#[derive(Debug, PartialEq, Deserialize)]
struct InnerStruct {
f4: u32,
f5: u32,
}
let expected = Struct {
f1: 0,
f2: InnerStruct { f4: 8, f5: 13 },
f3: InnerStruct { f4: 21, f5: 34 },
};
// struct-as-tuple
{
// The encoded bytearray is: { "f1": 0, "f2": [8, 13], "f4": 21, "f5": 34 }.
let buf = [
0x84, 0xA2, 0x66, 0x31, 0x00, 0xA2, 0x66, 0x32, 0x92, 0x08, 0x0D, 0xA2, 0x66, 0x34,
0x15, 0xA2, 0x66, 0x35, 0x22,
];
let cur = Cursor::new(&buf[..]);
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(expected, actual);
assert_eq!(buf.len() as u64, de.get_ref().position());
}
// struct-as-map
{
// The encoded bytearray is: { "f1": 0, "f2": { "f4": 8, "f5": 13 }, "f4": 21, "f5": 34 }.
let buf = [
0x84, 0xA2, 0x66, 0x31, 0x00, 0xA2, 0x66, 0x32, 0x82, 0xA2, 0x66, 0x34, 0x08, 0xA2,
0x66, 0x35, 0x0D, 0xA2, 0x66, 0x34, 0x15, 0xA2, 0x66, 0x35, 0x22,
];
let cur = Cursor::new(&buf[..]);
let mut de = Deserializer::new(cur);
let actual: Struct = Deserialize::deserialize(&mut de).unwrap();
assert_eq!(expected, actual);
assert_eq!(buf.len() as u64, de.get_ref().position());
}
}
#[test]
fn pass_from_slice() {
let buf = [
0x93, 0xa4, 0x4a, 0x6f, 0x68, 0x6e, 0xa5, 0x53, 0x6d, 0x69, 0x74, 0x68, 0x2a,
];
#[derive(Debug, PartialEq, Deserialize)]
struct Person<'a> {
name: &'a str,
surname: &'a str,
age: u8,
}
assert_eq!(
Person {
name: "John",
surname: "Smith",
age: 42
},
rmps::from_slice(&buf[..]).unwrap()
);
}
#[test]
fn pass_from_ref() {
let buf = [0x92, 0xa5, 0x42, 0x6f, 0x62, 0x62, 0x79, 0x8];
#[derive(Debug, Deserialize, PartialEq)]
struct Dog<'a> {
name: &'a str,
age: u8,
}
assert_eq!(
Dog {
name: "Bobby",
age: 8
},
rmps::from_read_ref(&buf).unwrap()
);
}
|
use crate::test_struct::*;
pub fn connect(){
println!("this is connect");
test_struct();
} |
pub use VkDebugReportFlagsEXT::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkDebugReportFlagsEXT {
VK_DEBUG_REPORT_INFORMATION_BIT_EXT = 0x00000001,
VK_DEBUG_REPORT_WARNING_BIT_EXT = 0x00000002,
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT = 0x00000004,
VK_DEBUG_REPORT_ERROR_BIT_EXT = 0x00000008,
VK_DEBUG_REPORT_DEBUG_BIT_EXT = 0x00000010,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkDebugReportFlagBitsEXT(u32);
SetupVkFlags!(VkDebugReportFlagsEXT, VkDebugReportFlagBitsEXT);
|
use anyhow::Context;
use stark_hash::{stark_hash, Felt};
fn main() -> anyhow::Result<()> {
let mut args = std::env::args();
let myself = args
.next()
.unwrap_or_else(|| String::from("compute_contract_state_hash"));
let args = args
.map(|x| Felt::from_hex_str(&x).map(Some))
.chain(std::iter::repeat_with(|| Ok(None)));
let mut description = String::with_capacity(1 + 64 + 64 + 64 + 64 + 4);
description.push('#');
let res = args
.enumerate()
// was thinking this would be like a column value so start from 1
.map(|(nth, x)| (nth + 1, x))
// build the description up with an inspect
.inspect(|(_, x)| {
use std::fmt::Write;
if let Ok(x) = x {
write!(description, " {:x}", x.unwrap_or(Felt::ZERO)).unwrap();
}
})
.take(4)
.try_fold(None, |acc, next| {
let nth = next.0 + 1;
let next = next
.1
.with_context(|| format!("Failed to parse {nth} parameter"))?;
let next = if nth < 2 {
next.with_context(|| format!("Missing {nth} parameter"))?
} else {
next.unwrap_or(Felt::ZERO)
};
Ok::<_, anyhow::Error>(acc.map(|prev| stark_hash(prev, next)).or(Some(next)))
})
.with_context(|| {
format!("USAGE: {myself} class_hash tree_root [nonce [contract_version]]")
})?
.expect("there is always iterated over value");
println!("{description}");
println!("{res:x}");
Ok(())
}
|
use iced::{Sandbox, Element, Button, Column, Text, Settings, Container, Length, Align, HorizontalAlignment, Color, Background, button};
use iced::settings::Window;
pub fn main() {
Counter::run(Settings {
window: Window {
size: (300, 300), // (x, y)
resizable: false,
}
})
}
// state
struct Counter {
// counter value
value: i32,
// state of the two buttons
increment_button: button::State,
reset_button: button::State,
}
// message
#[derive(Debug, Clone, Copy)]
pub enum Message {
Increment,
Reset,
}
impl Sandbox for Counter {
type Message = Message;
fn new() -> Self {
Counter {
value: 0,
increment_button: button::State::default(),
reset_button: button::State::default(),
}
}
fn title(&self) -> String {
String::from("count up")
}
// update
fn update(&mut self, message: Message) {
match message {
Message::Increment => {
self.value += 1;
}
Message::Reset => {
self.value = 0;
}
}
}
// view logic
fn view(&mut self) -> Element<Message> {
Container::new(
Column::new()
.push(
Button::new(&mut self.increment_button, Text::new("+1"))
.on_press(Message::Increment)
.border_radius(5)
.background(Background::Color(Color{r: 0.8, g: 0.8, b: 0.8, a: 1.})),
)
.push(
Text::new(self.value.to_string()).size(50).horizontal_alignment(HorizontalAlignment::Center),
)
.push(
Button::new(&mut self.reset_button, Text::new("reset"))
.on_press(Message::Reset),
)
.align_items(Align::Center)
)
.width(Length::Fill)
.center_x()
.height(Length::Fill)
.center_y()
.into()
}
}
|
use actix_web::{http::StatusCode, FromRequest, HttpResponse, Json, Path};
use bigneon_api::controllers::ticket_types;
use bigneon_api::controllers::ticket_types::*;
use bigneon_api::models::{EventTicketPathParameters, PathParameters};
use bigneon_db::models::*;
use chrono::prelude::*;
use functional::base;
use serde_json;
use support;
use support::database::TestDatabase;
use support::test_request::TestRequest;
use uuid::Uuid;
#[cfg(test)]
mod create_tests {
use super::*;
#[test]
fn create_org_member() {
base::ticket_types::create(Roles::OrgMember, true);
}
#[test]
fn create_admin() {
base::ticket_types::create(Roles::Admin, true);
}
#[test]
fn create_user() {
base::ticket_types::create(Roles::User, false);
}
#[test]
fn create_org_owner() {
base::ticket_types::create(Roles::OrgOwner, true);
}
}
#[cfg(test)]
mod update_tests {
use super::*;
#[test]
fn update_org_member() {
base::ticket_types::update(Roles::OrgMember, true);
}
#[test]
fn update_admin() {
base::ticket_types::update(Roles::Admin, true);
}
#[test]
fn update_user() {
base::ticket_types::update(Roles::User, false);
}
#[test]
fn update_org_owner() {
base::ticket_types::update(Roles::OrgOwner, true);
}
}
#[cfg(test)]
mod index_tests {
use super::*;
#[test]
fn index_org_member() {
base::ticket_types::index(Roles::OrgMember, true);
}
#[test]
fn index_admin() {
base::ticket_types::index(Roles::Admin, true);
}
#[test]
fn index_user() {
base::ticket_types::index(Roles::User, false);
}
#[test]
fn index_org_owner() {
base::ticket_types::index(Roles::OrgOwner, true);
}
}
#[test]
pub fn create_with_overlapping_periods() {
let database = TestDatabase::new();
let user = database.create_user().finish();
let organization = database.create_organization().finish();
let auth_user = support::create_auth_user_from_user(&user, Roles::Admin, None, &database);
let event = database
.create_event()
.with_organization(&organization)
.finish();
//Construct Ticket creation and pricing request
let test_request = TestRequest::create();
let state = test_request.extract_state();
let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap();
path.id = event.id;
let mut ticket_pricing: Vec<CreateTicketPricingRequest> = Vec::new();
let start_date = NaiveDate::from_ymd(2018, 5, 1).and_hms(6, 20, 21);
let middle_date = NaiveDate::from_ymd(2018, 6, 2).and_hms(7, 45, 31);
let end_date = NaiveDate::from_ymd(2018, 7, 3).and_hms(9, 23, 23);
ticket_pricing.push(CreateTicketPricingRequest {
name: String::from("Early bird"),
price_in_cents: 10000,
start_date,
end_date: middle_date,
});
ticket_pricing.push(CreateTicketPricingRequest {
name: String::from("Base"),
price_in_cents: 20000,
start_date: start_date,
end_date,
});
let request_data = CreateTicketTypeRequest {
name: "VIP".into(),
capacity: 1000,
start_date,
end_date,
ticket_pricing,
increment: None,
};
let response: HttpResponse = ticket_types::create((
database.connection.into(),
path,
Json(request_data),
auth_user,
state,
)).into();
let body = support::unwrap_body_to_string(&response).unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert!(response.error().is_some());
#[derive(Deserialize)]
struct Response {
error: String,
}
let deserialized_response: Response = serde_json::from_str(&body).unwrap();
assert_eq!(deserialized_response.error, "Validation error");
}
#[test]
pub fn update_with_invalid_id() {
let database = TestDatabase::new();
let request = TestRequest::create();
let user = database.create_user().finish();
let organization = database.create_organization().finish();
let auth_user = support::create_auth_user_from_user(&user, Roles::Admin, None, &database);
let event = database
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
//Retrieve created ticket type and pricing
let created_ticket_type = &event.ticket_types(&database.connection).unwrap()[0];
let created_ticket_capacity = created_ticket_type
.ticket_capacity(&database.connection)
.unwrap();
created_ticket_type
.ticket_pricing(&database.connection)
.unwrap();
//Construct update request
let test_request = TestRequest::create_with_uri_event_ticket("/");
let mut path = Path::<EventTicketPathParameters>::extract(&test_request.request).unwrap();
path.event_id = event.id;
path.ticket_type_id = created_ticket_type.id;
let mut request_ticket_pricing: Vec<UpdateTicketPricingRequest> = Vec::new();
let start_date = Some(NaiveDate::from_ymd(2018, 5, 1).and_hms(6, 20, 21));
let end_date = Some(NaiveDate::from_ymd(2018, 7, 3).and_hms(9, 23, 23));
request_ticket_pricing.push(UpdateTicketPricingRequest {
id: Some(Uuid::new_v4()),
name: Some(String::from("Base")),
start_date,
end_date,
price_in_cents: Some(20000),
});
let request_data = UpdateTicketTypeRequest {
name: Some("Updated VIP".into()),
capacity: Some(created_ticket_capacity),
start_date,
end_date,
ticket_pricing: Some(request_ticket_pricing),
increment: None,
};
//Send update request
let response: HttpResponse = ticket_types::update((
database.connection.clone().into(),
path,
Json(request_data),
auth_user,
request.extract_state(),
)).into();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert!(response.error().is_some());
}
#[test]
pub fn update_with_overlapping_periods() {
let database = TestDatabase::new();
let request = TestRequest::create();
let user = database.create_user().finish();
let organization = database.create_organization().finish();
let auth_user = support::create_auth_user_from_user(&user, Roles::Admin, None, &database);
let event = database
.create_event()
.with_organization(&organization)
.with_tickets()
.with_ticket_pricing()
.finish();
//Retrieve created ticket type and pricing
let created_ticket_type = &event.ticket_types(&database.connection).unwrap()[0];
let created_ticket_capacity = created_ticket_type
.ticket_capacity(&database.connection)
.unwrap();
let created_ticket_pricing = created_ticket_type
.ticket_pricing(&database.connection)
.unwrap();
//Construct update request
let test_request = TestRequest::create_with_uri_event_ticket("/");
let mut path = Path::<EventTicketPathParameters>::extract(&test_request.request).unwrap();
path.event_id = event.id;
path.ticket_type_id = created_ticket_type.id;
let mut request_ticket_pricing: Vec<UpdateTicketPricingRequest> = Vec::new();
let start_date = Some(NaiveDate::from_ymd(2018, 5, 1).and_hms(6, 20, 21));
let middle_date = Some(NaiveDate::from_ymd(2018, 6, 2).and_hms(7, 45, 31));
let end_date = Some(NaiveDate::from_ymd(2018, 7, 3).and_hms(9, 23, 23));
let new_pricing_name = String::from("Online");
//Remove 1st pricing, modify 2nd pricing and add new additional pricing
request_ticket_pricing.push(UpdateTicketPricingRequest {
id: Some(created_ticket_pricing[1].id),
name: Some(String::from("Base")),
start_date: start_date,
end_date,
price_in_cents: Some(20000),
});
request_ticket_pricing.push(UpdateTicketPricingRequest {
id: None,
name: Some(new_pricing_name.clone()),
start_date,
end_date: middle_date,
price_in_cents: Some(15000),
});
let request_data = UpdateTicketTypeRequest {
name: Some("Updated VIP".into()),
capacity: Some(created_ticket_capacity),
start_date,
end_date,
ticket_pricing: Some(request_ticket_pricing),
increment: None,
};
//Send update request
let response: HttpResponse = ticket_types::update((
database.connection.clone().into(),
path,
Json(request_data),
auth_user,
request.extract_state(),
)).into();
let body = support::unwrap_body_to_string(&response).unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert!(response.error().is_some());
#[derive(Deserialize)]
struct Response {
error: String,
}
let deserialized_response: Response = serde_json::from_str(&body).unwrap();
assert_eq!(deserialized_response.error, "Validation error");
}
|
//use std::env;
fn add(matrix1: Vec<Vec<i32>>, matrix2: Vec<Vec<i32>>) -> Vec<Vec<i32>>{
let m1r = matrix1.capacity();
let m1c = matrix1[0].capacity();
let m2r = matrix2.capacity();
let m2c = matrix2[0].capacity();
return matrix1;
}
fn main() {
//let args: Vec<String> = env::args().collect();
let mut m: Vec<Vec<i32>> = vec![vec![0; 2]; 2];
println!("{}", m[0][0]);
}
|
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
fn square(size: u32) -> Rectangle {
Rectangle {width: size, height: size}
}
}
fn main() {
let user1 = build_user(String::from("sample@example.com"), String::from("sampleusername123"));
println!("{}, {}, {}, {}", user1.email, user1.username, user1.sign_in_count, user1.active);
let user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername456"),
..user1
};
println!("{}, {}, {}, {}", user2.email, user2.username, user2.sign_in_count, user2.active);
let rect1 = Rectangle {width: 30, height: 50};
println!("rect1 is {:#?}", rect1);
println!("The area of the rectangle is {} square pixels.", rect1.area());
let rect2 = Rectangle {width: 10, height: 40};
let rect3 = Rectangle {width: 60, height: 45};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
let square1 = Rectangle::square(3);
println!("square {:?}", square1);
}
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
|
use cderive::Derive;
use cderive::clang::*;
use std::fmt::Write;
pub struct CycleCollect;
macro_rules! try_opt {
($e:expr) => {
try_opt!($e, return None)
};
($e:expr, $other:expr) => {
match $e {
Some(x) => x,
None => $other,
}
};
}
// These flags control how we determine which fields need to be cycle collected.
const CC_REFCNT_TY: &'static str = "nsCycleCollectingAutoRefCnt";
const CC_CLASSNAME: &'static str = "cycleCollection";
// These are single-argument template types which, when seen, are considered to
// need to be cycle collected if their backing type is a potential CC target.
const REFPTR_TMPLS: [&'static str; 2] = [
"RefPtr",
"nsCOMPtr",
// XXX: nsCOMArray etc?
];
// These are single-argument template types which act as containers for their
// first template argument, and will be traversed if their first argument would
// be traversed.
const CONTAINER_TMPLS: [&'static str; 1] = [
"nsTArray",
];
// XXX: Handle objects with more than one template parameter?
// XXX: Walk up inheritence chains?
fn single_template_target<F>(ty: Type, mut matches: F) -> Option<Type>
where F: FnMut(&str) -> bool
{
// If any of these fail, we aren't looking at a template target
let decl = try_opt!(ty.get_declaration());
let template = try_opt!(decl.get_template());
let template_name = try_opt!(template.get_name());
if !matches(&template_name) {
return None;
}
let target = try_opt!(ty.get_template_argument_types());
if target.is_empty() {
return None;
}
let target = try_opt!(target[0]);
Some(target)
}
// None if not a refptr, otherwise get the target
fn refptr_target(ty: Type) -> Option<Type> {
single_template_target(ty, |s| REFPTR_TMPLS.iter().any(|&t| t == s))
}
// None if not a container, otherwise get the target
// XXX: Multi-template-argument containers (e.g. e.g. hashmap)
fn container_target(ty: Type) -> Option<Type> {
single_template_target(ty, |s| CONTAINER_TMPLS.iter().any(|&t| t == s))
}
fn fields(entity: Entity) -> Vec<Entity> {
let mut fields = Vec::new();
entity.visit_children(|entity, _| {
if entity.get_kind() == EntityKind::FieldDecl {
fields.push(entity);
}
EntityVisitResult::Continue
});
fields
}
fn defn_for_ty(ty: Type) -> Option<Entity> {
ty.get_declaration().and_then(|d| d.get_definition())
}
// Run pred on each base. If any of the preds return Some(v), return that value,
// otherwise return None.
fn base_matching<'a, F, T>(entity: Entity<'a>, pred: &mut F) -> Option<T>
where F: FnMut(Entity<'a>) -> Option<T>
{
if let Some(r) = pred(entity) {
return Some(r);
}
let mut result = None;
entity.visit_children(|child, _| {
if child.get_kind() == EntityKind::BaseSpecifier {
if let Some(base) = defn_for_ty(child.get_type().unwrap()) {
if let Some(r) = pred(base) {
result = Some(r);
return EntityVisitResult::Break;
}
result = base_matching(base, pred);
if result.is_some() {
return EntityVisitResult::Break;
}
}
}
EntityVisitResult::Continue
});
result
}
// Does Entity implement isupports?
fn is_isupports(entity: Entity) -> bool {
base_matching(entity, &mut |entity| match entity.get_display_name() {
Some(ref s) if s == "nsISupports" => Some(()),
_ => None,
}).is_some()
}
// Get the CC base of Entity. A base is a CC base if it has a CC_CLASSNAME inner
// class.
fn cc_base(orig: Entity) -> Option<Entity> {
base_matching(orig, &mut |entity| {
if orig == entity { return None; }
let mut result = None;
entity.visit_children(|child, _| {
if child.get_kind() == EntityKind::ClassDecl {
match child.get_display_name() {
Some(ref s) if s == CC_CLASSNAME => {
result = Some(entity);
return EntityVisitResult::Break;
}
_ => {}
}
}
EntityVisitResult::Continue
});
result
})
}
// Get the mRefCnt field of the given type, if it is present. Walk through base
// classes to find it.
fn refcnt_field(entity: Entity) -> Option<Entity> {
base_matching(entity, &mut |entity| {
for field in fields(entity) {
match field.get_display_name() {
Some(ref s) if s == "mRefCnt" => return Some(field),
_ => {},
}
}
None
})
}
// Check if this type should be CCed if behind a RefPtr or similar.
fn cc_ptr_target(ty: Type) -> bool {
let decl = try_opt!(ty.get_declaration(), return false);
let decl = try_opt!(decl.get_definition(), return false);
let rc_field = refcnt_field(decl);
let rc_field_type = rc_field
.and_then(|f| f.get_type())
.map(|t| t.get_display_name());
// If we see a cycle collecting refcnt, we know we're done!
match rc_field_type {
Some(ref ty) if ty == CC_REFCNT_TY => return true,
_ => {}
}
// If we're an nsISupports-base field, and have a rc field, it isn't
// CC_REFCNT_TY, so the target is not cycle collected.
is_isupports(decl) && !rc_field_type.is_some()
}
// Check if this type should be CCed
fn should_traverse_unlink(ty: Type) -> bool {
// Check if we're looking at a RefPtr<T> where T is a cc ptr target
if let Some(rt) = refptr_target(ty) {
return cc_ptr_target(rt);
}
// We should traverse/unlink a container if its elements can be
// traversed/unlinked.
if let Some(rt) = container_target(ty) {
return should_traverse_unlink(rt);
}
false
}
impl Derive for CycleCollect {
fn derive(&mut self, entity: Entity) -> Result<String, ()> {
let typename = entity.get_display_name().unwrap();
let cc_basename = cc_base(entity).and_then(|b| b.get_display_name());
let mut unlink = String::new();
let mut traverse = String::new();
// XXX: trace?
// Begin blocks
write!(unlink, "NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN({})\n",
typename);
if let Some(ref basename) = cc_basename {
write!(traverse,
"NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED({}, {})\n",
typename, basename);
} else {
write!(traverse, "NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN({})\n",
typename);
}
let fields = fields(entity);
for field in fields {
let name = try_opt!(field.get_display_name(), continue);
let ty = try_opt!(field.get_type(), continue);
if should_traverse_unlink(ty) {
use std::fmt::Write;
write!(unlink, " NS_IMPL_CYCLE_COLLECTION_UNLINK({})\n", name)
.unwrap();
write!(traverse, " NS_IMPL_CYCLE_COLLECTION_TRAVERSE({})\n", name)
.unwrap();
}
}
// End blocks
write!(traverse, "NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END\n");
if let Some(ref basename) = cc_basename {
write!(unlink, "NS_IMPL_CYCLE_COLLECTION_UNLINK_END_INHERITED({})\n",
basename);
} else {
write!(unlink, "NS_IMPL_CYCLE_COLLECTION_UNLINK_END\n");
}
let typename = entity.get_display_name().unwrap();
let res = format!("{unlink}\n{traverse}",
unlink = unlink,
traverse = traverse);
Ok(res)
}
}
|
use crate::record::cell::Cell;
use crate::SLKScanner;
use crate::slk_type::Record;
#[derive(Default, Debug)]
pub struct Document {
rows: u32,
columns: u32,
contents: Vec<Cell>,
}
impl Document {
pub fn load(&mut self, scanner: SLKScanner){
for record in scanner{
match record {
Record::Info(rows, columns) => {
self.rows = rows;
self.columns = columns;
},
Record::CellContent(cell) => self.contents.push(cell),
_ => ()
}
}
}
pub fn get_contents(&self) -> &Vec<Cell>{
&self.contents
}
pub fn row_count(&self) -> u32 {self.rows}
pub fn column_count(&self) -> u32 {self.columns}
pub fn debug(&self){
println!("{:#?}", self);
}
}
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkGeometryNV {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub geometryType: VkGeometryTypeNV,
pub geometry: VkGeometryDataNV,
pub flags: VkGeometryFlagBitsNV,
}
impl VkGeometryNV {
pub fn new<T>(geometry_type: VkGeometryTypeNV, geometry: VkGeometryDataNV, flags: T) -> Self
where
T: Into<VkGeometryFlagBitsNV>,
{
VkGeometryNV {
sType: VK_STRUCTURE_TYPE_GEOMETRY_NV,
pNext: ptr::null(),
geometryType: geometry_type,
geometry,
flags: flags.into(),
}
}
}
unsafe impl Sync for VkGeometryNV {}
unsafe impl Send for VkGeometryNV {}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::function(erlang:is_tuple/1)]
pub fn result(term: Term) -> Term {
match term.decode() {
Ok(TypedTerm::Tuple(_)) => true.into(),
_ => false.into(),
}
}
|
use core::alloc::Layout;
use core::cmp;
use core::mem;
use core::ops::DerefMut;
use core::ptr::NonNull;
use liblumen_core::sys::sysconf::MIN_ALIGN;
use liblumen_core::util::pointer::{distance_absolute, in_area};
use crate::erts::exception::AllocResult;
use crate::erts::term::prelude::Term;
/// The core trait for allocating on a heap
pub trait HeapAlloc {
/// Perform a heap allocation.
///
/// If space on the process heap is not immediately available, then the allocation
/// will be pushed into a heap fragment which will then be later moved on to the
/// process heap during garbage collection
unsafe fn alloc(&mut self, need: usize) -> AllocResult<NonNull<Term>> {
let align = cmp::max(mem::align_of::<Term>(), MIN_ALIGN);
let size = need * mem::size_of::<Term>();
let layout = Layout::from_size_align(size, align).unwrap();
self.alloc_layout(layout)
}
/// Same as `alloc`, but takes a `Layout` rather than the size in words
unsafe fn alloc_layout(&mut self, layout: Layout) -> AllocResult<NonNull<Term>>;
}
impl<T, H> HeapAlloc for T
where
H: HeapAlloc,
T: DerefMut<Target = H>,
{
#[inline]
unsafe fn alloc(&mut self, need: usize) -> AllocResult<NonNull<Term>> {
self.deref_mut().alloc(need)
}
#[inline]
unsafe fn alloc_layout(&mut self, layout: Layout) -> AllocResult<NonNull<Term>> {
self.deref_mut().alloc_layout(layout)
}
}
/// The base trait for heap implementations
///
/// Provides access to metadata about a heap above and beyond the low-level allocation functions
pub trait Heap: HeapAlloc {
fn is_corrupted(&self) -> bool;
/// Returns the lowest address that is part of the underlying heaps' range
fn heap_start(&self) -> *mut Term;
/// Returns the address immediately following the most recent
/// allocation in the underlying heap; it represents the position
/// at which the next allocation will begin, not accounting for
/// padding
fn heap_top(&self) -> *mut Term;
/// Returns the highest address that is part of the underlying heaps' range
fn heap_end(&self) -> *mut Term;
/// Returns the location on this heap where a collection cycle last stopped
///
/// Defaults to `heap_start`, and only requires implementation if this heap
/// supports distinguishing between mature and immature allocations
#[inline]
fn high_water_mark(&self) -> *mut Term {
self.heap_start()
}
/// Returns the total allocated size of the underlying heap
#[inline]
fn heap_size(&self) -> usize {
distance_absolute(self.heap_end(), self.heap_start())
}
/// Returns the total number of bytes that are used by
/// allocations in the underling heap
#[inline]
fn heap_used(&self) -> usize {
distance_absolute(self.heap_top(), self.heap_start())
}
/// Returns the total number of bytes that are available for
/// allocations in the underling heap
#[inline]
fn heap_available(&self) -> usize {
distance_absolute(self.heap_end(), self.heap_top())
}
/// Returns true if the underlying heap contains the address represented by `ptr`
#[inline]
fn contains<T: ?Sized>(&self, ptr: *const T) -> bool {
in_area(ptr, self.heap_start(), self.heap_end())
}
/// An alias for `contains` which better expresses intent in some places
///
/// Returns true if the given pointer is owned by this process/heap
#[inline(always)]
fn is_owner<T: ?Sized>(&self, ptr: *const T) -> bool {
self.contains(ptr)
}
#[cfg(debug_assertions)]
#[inline]
fn sanity_check(&self) {
let hb = self.heap_start();
let he = self.heap_end();
let size = self.heap_size() * mem::size_of::<Term>();
assert_eq!(size, (he as usize - hb as usize), "mismatch between heap size and the actual distance between the start of the heap and end of the stack");
let ht = self.heap_top();
assert!(
hb <= ht,
"bottom of the heap must be a lower address than or equal to the top of the heap"
);
}
#[cfg(not(debug_assertions))]
#[inline]
fn sanity_check(&self) {}
}
impl<T, H> Heap for T
where
H: Heap,
T: DerefMut<Target = H>,
{
fn is_corrupted(&self) -> bool {
self.deref().is_corrupted()
}
#[inline]
fn heap_start(&self) -> *mut Term {
self.deref().heap_start()
}
#[inline]
fn heap_top(&self) -> *mut Term {
self.deref().heap_top()
}
#[inline]
fn heap_end(&self) -> *mut Term {
self.deref().heap_end()
}
#[inline]
fn high_water_mark(&self) -> *mut Term {
self.deref().high_water_mark()
}
#[inline]
fn heap_size(&self) -> usize {
self.deref().heap_size()
}
#[inline]
fn heap_used(&self) -> usize {
self.deref().heap_used()
}
#[inline]
fn heap_available(&self) -> usize {
self.deref().heap_available()
}
#[inline]
fn contains<U: ?Sized>(&self, ptr: *const U) -> bool {
self.deref().contains(ptr)
}
#[inline(always)]
fn is_owner<U: ?Sized>(&self, ptr: *const U) -> bool {
self.deref().is_owner(ptr)
}
}
|
use std::{thread::sleep, time::Duration};
fn main() {
// Start the server and sleep for a bit.
println!("[rs consumer test] Starting the server.");
webviz_server_rs::start_server();
sleep(Duration::from_millis(1000));
// Check the server status and sleep again.
let is_server_running = webviz_server_rs::is_server_running();
if !is_server_running {
println!("Unexpectedly, server failed to run.");
return;
}
println!("[rs consumer test] Is the server running? {}", is_server_running);
println!("Server will run for 10 seconds.");
sleep(Duration::from_secs(10));
// Request server shutdown and wait again.
println!("[rs consumer test] Requesting server shutdown.");
webviz_server_rs::shutdown_server();
sleep(Duration::from_millis(1000));
println!("[rs consumer test] Is the server running now? {}", webviz_server_rs::is_server_running());
sleep(Duration::from_millis(1000));
println!("[rs consumer test] End of main().");
}
|
pub mod topic;
use self::topic::Topic;
use self::topic::elementary::Elementary;
use self::topic::lists_strings::ListStrings;
use std::collections::HashMap;
pub fn parse_input(s: &str) -> Result<(&str, u8), String> {
let mut iter = s.split(",");
match (iter.next(), iter.next()) {
(Some(topic), Some(n)) => Ok((topic, n)),
_ => Err(format!("Input '{}' didn't match required pattern", s))
}.and_then(parse_tuple)
}
fn parse_tuple<'a>(tuple: (&'a str, &str)) -> Result<(&'a str, u8), String> {
let (topic, n) = tuple;
n.trim()
.parse()
.map(|num| { (topic, num) })
.or_else(|e| { Err(format!("Failed to parse number from '{}': {}", n, e)) })
}
pub fn populate_map() -> HashMap<String, Box<Topic>> {
let mut map: HashMap<String, Box<Topic>> = HashMap::new();
map.insert(Elementary.describe(), Box::new(Elementary));
map.insert(ListStrings.describe(), Box::new(ListStrings));
map
}
#[test]
fn should_parse_valid_input() {
let (topic, num) = parse_input("Dance, 42").unwrap();
assert_eq!(num, 42);
assert_eq!(topic, "Dance");
}
#[test]
fn should_fail_to_parse_non_number(){
let result = parse_input("Comom, Lomom");
assert!(result.is_err());
}
#[test]
fn should_fail_to_parse_missing_comma(){
let result = parse_input("Toldom Acjdul");
assert!(result.is_err());
}
|
#[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::CHMAP0 {
#[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 UDMA_CHMAP0_CH0SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH0SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH0SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH0SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 0);
self.w.bits |= ((value as u32) & 15) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH1SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH1SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH1SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH1SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 4);
self.w.bits |= ((value as u32) & 15) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH2SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH2SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH2SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH2SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 8);
self.w.bits |= ((value as u32) & 15) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH3SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH3SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH3SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH3SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 12);
self.w.bits |= ((value as u32) & 15) << 12;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH4SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH4SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH4SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH4SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 16);
self.w.bits |= ((value as u32) & 15) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH5SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH5SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH5SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH5SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 20);
self.w.bits |= ((value as u32) & 15) << 20;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH6SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH6SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH6SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH6SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 24);
self.w.bits |= ((value as u32) & 15) << 24;
self.w
}
}
#[doc = r"Value of the field"]
pub struct UDMA_CHMAP0_CH7SELR {
bits: u8,
}
impl UDMA_CHMAP0_CH7SELR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _UDMA_CHMAP0_CH7SELW<'a> {
w: &'a mut W,
}
impl<'a> _UDMA_CHMAP0_CH7SELW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 28);
self.w.bits |= ((value as u32) & 15) << 28;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - uDMA Channel 0 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch0sel(&self) -> UDMA_CHMAP0_CH0SELR {
let bits = ((self.bits >> 0) & 15) as u8;
UDMA_CHMAP0_CH0SELR { bits }
}
#[doc = "Bits 4:7 - uDMA Channel 1 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch1sel(&self) -> UDMA_CHMAP0_CH1SELR {
let bits = ((self.bits >> 4) & 15) as u8;
UDMA_CHMAP0_CH1SELR { bits }
}
#[doc = "Bits 8:11 - uDMA Channel 2 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch2sel(&self) -> UDMA_CHMAP0_CH2SELR {
let bits = ((self.bits >> 8) & 15) as u8;
UDMA_CHMAP0_CH2SELR { bits }
}
#[doc = "Bits 12:15 - uDMA Channel 3 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch3sel(&self) -> UDMA_CHMAP0_CH3SELR {
let bits = ((self.bits >> 12) & 15) as u8;
UDMA_CHMAP0_CH3SELR { bits }
}
#[doc = "Bits 16:19 - uDMA Channel 4 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch4sel(&self) -> UDMA_CHMAP0_CH4SELR {
let bits = ((self.bits >> 16) & 15) as u8;
UDMA_CHMAP0_CH4SELR { bits }
}
#[doc = "Bits 20:23 - uDMA Channel 5 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch5sel(&self) -> UDMA_CHMAP0_CH5SELR {
let bits = ((self.bits >> 20) & 15) as u8;
UDMA_CHMAP0_CH5SELR { bits }
}
#[doc = "Bits 24:27 - uDMA Channel 6 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch6sel(&self) -> UDMA_CHMAP0_CH6SELR {
let bits = ((self.bits >> 24) & 15) as u8;
UDMA_CHMAP0_CH6SELR { bits }
}
#[doc = "Bits 28:31 - uDMA Channel 7 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch7sel(&self) -> UDMA_CHMAP0_CH7SELR {
let bits = ((self.bits >> 28) & 15) as u8;
UDMA_CHMAP0_CH7SELR { 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 = "Bits 0:3 - uDMA Channel 0 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch0sel(&mut self) -> _UDMA_CHMAP0_CH0SELW {
_UDMA_CHMAP0_CH0SELW { w: self }
}
#[doc = "Bits 4:7 - uDMA Channel 1 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch1sel(&mut self) -> _UDMA_CHMAP0_CH1SELW {
_UDMA_CHMAP0_CH1SELW { w: self }
}
#[doc = "Bits 8:11 - uDMA Channel 2 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch2sel(&mut self) -> _UDMA_CHMAP0_CH2SELW {
_UDMA_CHMAP0_CH2SELW { w: self }
}
#[doc = "Bits 12:15 - uDMA Channel 3 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch3sel(&mut self) -> _UDMA_CHMAP0_CH3SELW {
_UDMA_CHMAP0_CH3SELW { w: self }
}
#[doc = "Bits 16:19 - uDMA Channel 4 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch4sel(&mut self) -> _UDMA_CHMAP0_CH4SELW {
_UDMA_CHMAP0_CH4SELW { w: self }
}
#[doc = "Bits 20:23 - uDMA Channel 5 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch5sel(&mut self) -> _UDMA_CHMAP0_CH5SELW {
_UDMA_CHMAP0_CH5SELW { w: self }
}
#[doc = "Bits 24:27 - uDMA Channel 6 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch6sel(&mut self) -> _UDMA_CHMAP0_CH6SELW {
_UDMA_CHMAP0_CH6SELW { w: self }
}
#[doc = "Bits 28:31 - uDMA Channel 7 Source Select"]
#[inline(always)]
pub fn udma_chmap0_ch7sel(&mut self) -> _UDMA_CHMAP0_CH7SELW {
_UDMA_CHMAP0_CH7SELW { w: self }
}
}
|
use std::env;
use std::fs;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let perf_libs_dir = {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let mut path = Path::new(&manifest_dir);
path = path.parent().unwrap();
path.join(Path::new("target/perf-libs"))
};
let perf_libs_dir = perf_libs_dir.to_str().unwrap();
// Ensure `perf_libs_dir` exists. It's been observed that
// a cargo:rerun-if-changed= directive with a non-existent
// directory triggers a rebuild on every |cargo build| invocation
fs::create_dir_all(&perf_libs_dir).unwrap_or_else(|err| {
if err.kind() != std::io::ErrorKind::AlreadyExists {
panic!("Unable to create {}: {:?}", perf_libs_dir, err);
}
});
let chacha = !env::var("CARGO_FEATURE_CHACHA").is_err();
let cuda = !env::var("CARGO_FEATURE_CUDA").is_err();
if chacha || cuda {
println!("cargo:rerun-if-changed={}", perf_libs_dir);
println!("cargo:rustc-link-search=native={}", perf_libs_dir);
}
if chacha {
println!("cargo:rerun-if-changed={}/libcpu-crypt.a", perf_libs_dir);
}
if cuda {
let cuda_home = match env::var("CUDA_HOME") {
Ok(cuda_home) => cuda_home,
Err(_) => String::from("/usr/local/cuda"),
};
println!("cargo:rerun-if-changed={}/libcuda-crypt.a", perf_libs_dir);
println!("cargo:rustc-link-lib=static=cuda-crypt");
println!("cargo:rustc-link-search=native={}/lib64", cuda_home);
println!("cargo:rustc-link-lib=dylib=cudart");
println!("cargo:rustc-link-lib=dylib=cuda");
println!("cargo:rustc-link-lib=dylib=cudadevrt");
}
}
|
use front::stdlib::object::PROTOTYPE;
use front::stdlib::value::{Value, ResultValue, to_value};
use front::stdlib::function::Function;
/// Create a new error
pub fn make_error(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue {
if args.len() >= 1 {
this.set_field("message", args[0]);
}
Ok(Value::undefined())
}
/// Get the string representation of the error
pub fn to_string(_:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue {
let name = this.get_field("name");
let message = this.get_field("message");
Ok(to_value(format!("{}: {}", name, message).into_string()))
}
/// Create a new `Error` object
pub fn _create(global: Value) -> Value {
let prototype = js!(global, {
"message": "",
"name": "Error",
"toString": Function::make(to_string, [])
});
let error = Function::make(make_error, ["message"]);
error.set_field(PROTOTYPE, prototype);
error
}
/// Initialise the global object with the `Error` object
pub fn init(global:Value) {
js_extend!(global, {
"Error": _create(global)
});
} |
/*
Copyright 2020 Timo Saarinen
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::*;
// -------------------------------------------------------------------------------------------------
/// Type 4: Base Station Report
#[derive(Default, Clone, Debug, PartialEq)]
pub struct BaseStationReport {
/// True if the data is about own vessel, false if about other.
pub own_vessel: bool,
/// AIS station type.
pub station: Station,
/// User ID (30 bits)
pub mmsi: u32,
/// Timestamp
pub timestamp: Option<DateTime<Utc>>,
/// Position accuracy: true = high (<= 10 m), false = low (> 10 m)
pub high_position_accuracy: bool,
/// Latitude
pub latitude: Option<f64>,
/// Longitude
pub longitude: Option<f64>,
// Type of electronic position fixing device.
pub position_fix_type: Option<PositionFixType>,
/// Riverine And Inland Navigation systems blue sign:
/// RAIM (Receiver autonomous integrity monitoring) flag of electronic position
/// fixing device; false = RAIM not in use = default; true = RAIM in use
pub raim_flag: bool,
/// Communication state
/// Diagnostic information for the radio system.
/// https://www.itu.int/dms_pubrec/itu-r/rec/m/R-REC-M.1371-1-200108-S!!PDF-E.pdf
pub radio_status: u32,
}
impl LatLon for BaseStationReport {
fn latitude(&self) -> Option<f64> {
self.latitude
}
fn longitude(&self) -> Option<f64> {
self.longitude
}
}
// -------------------------------------------------------------------------------------------------
/// AIS VDM/VDO type 4: Base Station Report
pub(crate) fn handle(
bv: &BitVec,
station: Station,
own_vessel: bool,
) -> Result<ParsedMessage, ParseError> {
Ok(ParsedMessage::BaseStationReport(BaseStationReport {
own_vessel: { own_vessel },
station: { station },
mmsi: { pick_u64(&bv, 8, 30) as u32 },
timestamp: {
Some(parse_ymdhs(
pick_u64(&bv, 38, 14) as i32,
pick_u64(&bv, 52, 4) as u32,
pick_u64(&bv, 56, 5) as u32,
pick_u64(&bv, 61, 5) as u32,
pick_u64(&bv, 66, 6) as u32,
pick_u64(&bv, 72, 6) as u32,
)?)
},
high_position_accuracy: { pick_u64(&bv, 78, 1) != 0 },
latitude: {
let lat_raw = pick_i64(&bv, 107, 27) as i32;
if lat_raw != 0x3412140 {
Some((lat_raw as f64) / 600000.0)
} else {
None
}
},
longitude: {
let lon_raw = pick_i64(&bv, 79, 28) as i32;
if lon_raw != 0x6791AC0 {
Some((lon_raw as f64) / 600000.0)
} else {
None
}
},
position_fix_type: {
let raw = pick_u64(&bv, 134, 4) as u8;
match raw {
0 => None,
_ => Some(PositionFixType::new(raw)),
}
},
raim_flag: { pick_u64(&bv, 148, 1) != 0 },
radio_status: { pick_u64(&bv, 149, 19) as u32 },
}))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_vdm_type4() {
let mut p = NmeaParser::new();
match p.parse_sentence("!AIVDM,1,1,,A,403OviQuMGCqWrRO9>E6fE700@GO,0*4D") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::BaseStationReport(bsr) => {
assert_eq!(bsr.mmsi, 3669702);
assert_eq!(
bsr.timestamp,
Some(Utc.ymd(2007, 5, 14).and_hms(19, 57, 39))
);
assert_eq!(bsr.high_position_accuracy, true);
assert::close(bsr.latitude.unwrap_or(0.0), 36.884, 0.001);
assert::close(bsr.longitude.unwrap_or(0.0), -76.352, 0.001);
assert_eq!(bsr.position_fix_type, Some(PositionFixType::Surveyed));
assert_eq!(bsr.raim_flag, false);
assert_eq!(bsr.radio_status, 67039);
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
fn main() {
for (index, val) in (1..11).enumerate() {
println!("index= {}, value= {}", index, val);
}
} |
#[cfg(feature = "rayon")]
extern crate rayon;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
#[cfg(feature = "c_api")]
pub mod c_api;
const ROTATE: u32 = 'z' as u32 - 'a' as u32 + 1;
/// Encrypt the input using rot26.
#[inline(always)]
pub fn encrypt(input: &str) -> String {
encrypt_any(input, 26)
}
/// Decrypt the input using rot26.
#[inline(always)]
pub fn decrypt(input: &str) -> String {
decrypt_any(input, 26)
}
/// Encrypt the input using rot13.
/// Warning: Security researchers have managed to crack rot13.
/// New users are recommended to use rot26 for the best security.
#[inline(always)]
pub fn encrypt_rot13(input: &str) -> String {
encrypt_any(input, 13)
}
/// Decrypt the input using rot13.
/// Warning: Security researchers have managed to crack rot13.
/// New users are recommended to use rot26 for the best security.
#[inline(always)]
pub fn decrypt_rot13(input: &str) -> String {
decrypt_any(input, 13)
}
/// Encrypt using any amount.
/// Warning: Please carefully choose the right amount.
/// New users are recommended to use rot26 for the best security.
pub fn encrypt_any(input: &str, amount: u32) -> String {
let closure = |c| {
let base = match c {
'a'...'z' => 'a' as u32,
'A'...'Z' => 'A' as u32,
_ => return c
};
std::char::from_u32(((c as u32 - base + amount) % ROTATE) + base).unwrap()
};
#[cfg(not(feature = "rayon"))]
{ input.chars().map(closure).collect() }
#[cfg(feature = "rayon")]
{ input.par_chars().map(closure).collect() }
}
/// Decrypt using any amount.
/// Warning: Please carefully choose the right amount.
/// New users are recommended to use rot26 for the best security.
pub fn decrypt_any(input: &str, amount: u32) -> String {
let closure = |c| {
let base = match c {
'a'...'z' => 'a' as u32,
'A'...'Z' => 'A' as u32,
_ => return c
};
std::char::from_u32(((c as u32 - base + ROTATE - amount) % ROTATE) + base).unwrap()
};
#[cfg(not(feature = "rayon"))]
{ input.chars().map(closure).collect() }
#[cfg(feature = "rayon")]
{ input.par_chars().map(closure).collect() }
}
#[cfg(test)]
mod tests {
use ::*;
#[test]
fn test_rot26() {
let plain = "hello";
let encrypted = encrypt(plain);
assert_eq!(encrypted, "hello");
let decrypted = decrypt(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot13() {
let plain = "hello";
let encrypted = encrypt_rot13(plain);
assert_eq!(encrypted, "uryyb");
let decrypted = decrypt_rot13(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot13_all() {
let plain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let encrypted = encrypt_rot13(plain);
assert_eq!(encrypted, "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM");
let decrypted = decrypt_rot13(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot_any() {
let amount = 1;
let plain = "hello";
let encrypted = encrypt_any(plain, amount);
assert_eq!(encrypted, "ifmmp");
let decrypted = decrypt_any(&encrypted, amount);
assert_eq!(plain, decrypted);
}
}
|
use calculations::util::round_float;
pub fn change_by_percentage(n: f64, percent: f64) -> String {
/*
ChangeByPercentage:
Increase/Decrease a number by a percentage.
(n / 100) * p + n
First work out 1% of 250, 250 ÷ 100 = 2.5 then multiply the answer by 23,
because there was a 23% increase. 2.5 × 23 = 57.5.
*/
let one_percent: f64 = n / 100.0;
let addition_value: f64 = one_percent * percent;
let answer = n + addition_value;
let noun = || -> String {
if percent < 0.0 {
return "decrease".to_string();
} else {
return "increase".to_string();
}
}();
return json!({
"one_percent": round_float(one_percent, 2),
"addition_value": round_float(addition_value, 2),
"answer": round_float(answer, 2),
"noun": noun
}).to_string();
}
pub fn find_percentage_value(p: f64, n: f64) -> String {
/*
Find the value of the percentage of a number.
(p / 100) * n
*/
let divided = p / 100.0;
let answer = divided * n;
return json!({
"percentage": round_float(p, 2),
"number": round_float(n, 2),
"divided": round_float(divided, 2),
"answer": round_float(answer, 2)
}).to_string();
}
pub fn find_percentage_difference(n1: f64, n2: f64) -> String {
/*
Find the percentage change from one number to another.
(new_n - original_n) / original_n * 100
*/
let difference = n2 - n1;
let percentage_d = difference / n1;
let answer = percentage_d * 100.0;
return json!({
"n1": round_float(n1, 2),
"n2": round_float(n2, 2) ,
"difference": round_float(difference, 2) ,
"percentage_d": round_float(percentage_d, 2) ,
"answer": round_float(answer, 2) ,
}).to_string();
}
pub fn find_percentage(n1: f64, n2: f64) -> String {
/*
Find the percentage of a number of a total number.
(n / total_n) * 100
*/
let percentage_d = n1 / n2;
let answer = percentage_d * 100.0;
return json!({
"n1": n1,
"n2": n2,
"percentage_d": percentage_d,
"answer": answer
}).to_string();
}
|
#![feature(plugin, custom_derive, const_fn)]
#![plugin(rocket_codegen)]
extern crate rocket;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate diesel;
#[macro_use] extern crate diesel_codegen;
#[macro_use] extern crate serde_derive;
extern crate rocket_contrib;
extern crate r2d2;
extern crate r2d2_diesel;
extern crate dotenv;
mod static_files;
mod db;
mod robot;
mod routes;
mod schema;
use dotenv::dotenv;
use std::env;
use rocket::Rocket;
use routes::*;
fn rocket() -> Rocket {
dotenv().ok();
// Url to the database as set in the DATABASE_URL environment variable.
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
// Initializes database pool with r2d2.
let pool = db::init_pool(database_url);
rocket::ignite()
.manage(pool)
.mount("/api/v1/", routes![index, new, show, delete, department])
.mount("/", routes![static_files::index, static_files::all])
.catch(errors![not_found])
}
fn main() {
rocket().launch();
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
pub use libra_crypto::hash::HashValue;
pub use crypto_macro::CryptoHash;
pub use libra_crypto::hash::CryptoHash as LibraCryptoHash;
/// A type that implements `CryptoHash` can be hashed by a cryptographic hash function and produce
/// a `HashValue`.
pub trait CryptoHash {
/// Hashes the object and produces a `HashValue`.
fn crypto_hash(&self) -> HashValue;
}
// impl<T: serde::Serialize> CryptoHash for T {
// fn crypto_hash(&self) -> HashValue {
// HashValue::from_sha3_256(
// scs::to_bytes(self)
// .expect("Serialization should work.")
// .as_slice(),
// )
// }
// }
impl CryptoHash for &str {
fn crypto_hash(&self) -> HashValue {
HashValue::from_sha3_256(
scs::to_bytes(self)
.expect("Serialization should work.")
.as_slice(),
)
}
}
impl CryptoHash for String {
fn crypto_hash(&self) -> HashValue {
HashValue::from_sha3_256(
scs::to_bytes(self)
.expect("Serialization should work.")
.as_slice(),
)
}
}
impl CryptoHash for Vec<u8> {
fn crypto_hash(&self) -> HashValue {
HashValue::from_sha3_256(
scs::to_bytes(self)
.expect("Serialization should work.")
.as_slice(),
)
}
}
impl CryptoHash for &[u8] {
fn crypto_hash(&self) -> HashValue {
HashValue::from_sha3_256(
scs::to_bytes(self)
.expect("Serialization should work.")
.as_slice(),
)
}
}
pub fn create_literal_hash(word: &str) -> HashValue {
let mut s = word.as_bytes().to_vec();
assert!(s.len() <= HashValue::LENGTH);
s.resize(HashValue::LENGTH, 0);
HashValue::from_slice(&s).expect("Cannot fail")
}
|
extern crate chrono;
extern crate colored;
extern crate dotenv;
extern crate irc;
extern crate parking_lot;
extern crate regex;
extern crate serde;
extern crate termion;
extern crate textwrap;
extern crate toml;
extern crate tui;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate lazy_static;
pub mod config;
#[macro_use]
pub mod utils;
pub mod color;
#[macro_use]
pub mod client;
pub mod ui;
use config::Config;
use irc::{
client::prelude::{Client, Command, Config as IrcConfig, IrcReactor},
proto::command::CapSubCommand,
};
lazy_static! {
pub static ref PERSISTENT_CONFIG: Config =
config::load("tccconf.toml").expect("Unable to load Config");
}
fn main() -> Result<(), ::client::Error> {
dotenv::dotenv().ok();
let channels = &PERSISTENT_CONFIG.twitch.channel;
// Creating the reactor (event-loop) and initializing it with the config
let mut reactor = IrcReactor::new().expect("Unable to create IrcReactor");
let server = &PERSISTENT_CONFIG.twitch.connection.server;
let port = PERSISTENT_CONFIG.twitch.connection.port;
let ssl = PERSISTENT_CONFIG.twitch.connection.ssl;
let cfg = IrcConfig {
server: Some(server.clone()),
port: Some(port),
use_ssl: Some(ssl),
..IrcConfig::default()
};
let client = reactor
.prepare_client_and_connect(&cfg)
.expect("Unable to initialize client");
let (uu, snd) =
ui::UI::new(client.clone(), channels.iter().next().unwrap().to_owned()).unwrap();
uu.wait_on_init();
send!(snd | "# Authenticating...".to_owned())?;
send!(snd | "## PASS".to_owned())?;
// Sending auth and nick here. Twitch has a quirk and does not follow the IRCv3
// spec, so a raw command is needed here Sending OAUTH Code
let oauth = &PERSISTENT_CONFIG.twitch.oauth;
client
.send(Command::Raw("PASS".to_owned(), vec![oauth.clone()], None))
.expect("Unable to send PASS");
send!(snd | "## NICK".to_owned())?;
// Sending User Verification name
let nick = &PERSISTENT_CONFIG.twitch.username;
client
.send(Command::Raw("NICK".to_owned(), vec![nick.clone()], None))
.expect("Unable to send NICK");
send!(snd | "# Setting Capabilies".to_owned())?;
send!(snd | "## membership".to_owned())?;
// Command caps are pre
// Sending Membership Capability,
client
.send(Command::CAP(
None,
CapSubCommand::REQ,
Some(":twitch.tv/membership".to_owned()),
None,
))
.expect("Unable to set Membership Capability");
send!(snd | "## tags".to_owned())?;
// Sending Channel Capability
client
.send(Command::CAP(
None,
CapSubCommand::REQ,
Some(":twitch.tv/tags".to_owned()),
None,
))
.expect("Unable to set Channel Tag Capabilies");
// Sending command Capability
client
.send(Command::CAP(
None,
CapSubCommand::REQ,
Some(":twitch.tv/commands".to_owned()),
None,
))
.expect("Unable to set Channel Tag Capabilies");
send!(snd | "# Jointing all channels...".to_owned())?;
// Joining all channels
for chn in channels {
send!(snd | "## J C {}", chn)?;
client
.send(Command::JOIN(chn.clone(), None, None))
.expect(&format!("Unable to join channel {}", &chn));
}
let send = snd.clone();
reactor.register_client_with_handler(client, move |client, message| {
use client::Error;
use irc::error::IrcError;
let sender = send.clone();
match client::client_handler_fn(client, message, sender, uu.get_stop()) {
Ok(o) => Ok(o),
Err(Error::Irc(e)) => Err(e),
Err(Error::SendError(e)) => Err(IrcError::from(::std::io::Error::new(
::std::io::ErrorKind::Other,
e,
))),
Err(Error::OperationStopped) => Err(IrcError::from(::std::io::Error::new(
::std::io::ErrorKind::Other,
String::from("Operations Cancelled"),
))),
}
});
send!(snd | "# SERVING # SETUP COMPLETE".to_owned())?;
// Blocking SERVE Call
if let Err(e) = reactor.run() {
send!(snd | "E [{:?}] {}", e, e)?;
}
Ok(())
}
|
//! Contains various cameras and their projection matrices.
mod arcball;
pub use self::arcball::ArcBall;
use na::Matrix4;
use std::f32;
use window::Event;
/// Represents a camera in 3D space.
pub trait Camera {
fn get_position(&self) -> (f32, f32, f32);
fn handle_events(&mut self, event: &Event);
fn get_projection_matrix(&self) -> Matrix4<f32>;
fn move_camera(&mut self, dx: f32, dy: f32, dz: f32);
fn set_target_position(&mut self, p: (f32, f32, f32));
}
|
//! ```elixir
//! case Lumen.Web.Window.window() do
//! {:ok, window} -> ...
//! :error -> ...
//! end
//! ```
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::Term;
use crate::option_to_ok_tuple_or_error;
#[native_implemented::function(Elixir.Lumen.Web.Window:window/0)]
pub fn result(process: &Process) -> Term {
let option_window = web_sys::window();
option_to_ok_tuple_or_error(process, option_window)
}
|
use aoc_runner_derive::{aoc, aoc_generator};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
#[aoc_generator(day4)]
fn input_parse(input: &str) -> Vec<HashMap<String, String>> {
let mut passports = Vec::new();
let mut passport: HashMap<String, String> = HashMap::new();
for line in input.lines() {
if line.trim() == "" {
passports.push(passport);
passport = HashMap::new();
} else {
for kv in line.split(" ") {
let pair: Vec<&str> = kv.split(":").collect();
// println!("{:?}", pair);
passport.insert(pair[0].to_string(), pair[1].to_string());
}
}
}
passports.push(passport);
passports
}
fn validate_hgt(hgt: Option<&String>) -> bool {
lazy_static! {
static ref RE_HGT: Regex = Regex::new("(\\d+)(cm|in)").unwrap();
}
if hgt.is_none() {
return false;
}
let caps = RE_HGT.captures(hgt.unwrap());
match caps {
Some(caps) => {
let units = caps.get(2).unwrap().as_str();
let value = caps.get(1).unwrap().as_str().parse::<i32>();
match value {
Err(_) => false,
Ok(value) => match units {
"in" => value >= 59 && value <= 76,
"cm" => value >= 150 && value <= 193,
_ => false,
},
}
}
_ => false,
}
}
fn validate_hcl(hcl: Option<&String>) -> bool {
lazy_static! {
static ref RE_HCL: Regex = Regex::new("#[a-f0-9]{6}").unwrap();
}
match hcl {
None => false,
Some(v) => RE_HCL.is_match(v),
}
}
fn validate_pid(pid: Option<&String>) -> bool {
lazy_static! {
static ref RE_PID: Regex = Regex::new("^\\d{9}$").unwrap();
}
match pid {
None => false,
Some(v) => RE_PID.is_match(v),
}
}
fn validate_numstr(value: Option<&String>, min: i32, max: i32) -> bool {
let parsed = value.unwrap_or(&String::from("0")).parse::<i32>().unwrap();
parsed >= min && parsed <= max
}
fn validate(passport: &HashMap<String, String>) -> bool {
validate_numstr(passport.get("byr"), 1920, 2002)
&& validate_numstr(passport.get("iyr"), 2010, 2020)
&& validate_numstr(passport.get("eyr"), 2020, 2030)
&& validate_hgt(passport.get("hgt"))
&& validate_hcl(passport.get("hcl"))
&& vec![
String::from("amb"),
String::from("blu"),
String::from("brn"),
String::from("gry"),
String::from("grn"),
String::from("hzl"),
String::from("oth"),
]
.contains(passport.get("ecl").unwrap_or(&String::from("")))
&& validate_pid(passport.get("pid"))
}
#[aoc(day4, part1)]
fn solve_part1(passports: &Vec<HashMap<String, String>>) -> usize {
println!("{:#?} passports", passports.len());
passports
.iter()
.filter(|p| p.keys().len() == 8 || (p.keys().len() == 7 && !p.contains_key("cid")))
.count()
}
#[aoc(day4, part2)]
fn solve_part2(passports: &Vec<HashMap<String, String>>) -> usize {
passports
.iter()
.filter(|p| p.keys().len() == 8 || (p.keys().len() == 7 && !p.contains_key("cid")))
.filter(|p| validate(p))
.count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_hgt() {
assert_eq!(validate_hgt(Option::from(&String::from("169cm"))), true);
assert_eq!(validate_hgt(Option::from(&String::from("69in"))), true);
assert_eq!(validate_hgt(Option::from(&String::from("169in"))), false);
assert_eq!(validate_hgt(Option::from(&String::from("69cm"))), false);
assert_eq!(validate_hgt(Option::from(&String::from("garbage"))), false);
}
#[test]
fn test_validate_hcl() {
assert_eq!(validate_hcl(Option::None), false);
assert_eq!(validate_hcl(Option::from(&String::from("#abcdef"))), true);
assert_eq!(validate_hcl(Option::from(&String::from("#00ccff"))), true);
assert_eq!(validate_hcl(Option::from(&String::from("#996699"))), true);
assert_eq!(validate_hcl(Option::from(&String::from("#abcde"))), false);
}
#[test]
fn test_invalid_passports() {
let inp = "eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007";
assert_eq!(solve_part2(&input_parse(inp)), 0);
}
#[test]
fn test_valid_passports() {
let inp = "pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719";
assert_eq!(solve_part2(&input_parse(inp)), 4);
}
}
|
pub mod buffer_writer;
pub mod logger;
|
//mod chat;
extern crate serde_mcproto;
pub mod v1_7_10;
// pub mod v1_8;
pub use serde_mcproto::de::deserialize;
pub use serde_mcproto::ser::serialize;
pub use serde_mcproto::types;
pub use serde_mcproto::{de::MCProtoDeserializer, ser::MCProtoSerializer};
pub use serde_mcproto::read_varint;
pub use serde_mcproto::write_varint;
pub use serde_mcproto::error;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
use juniper::{GraphQLInputObject, GraphQLObject};
#[derive(GraphQLObject)]
struct ObjectA {
test: String,
}
#[derive(GraphQLInputObject)]
struct Object {
field: ObjectA,
}
fn main() {}
|
// Demonstration that you can't pass &T into functions that
// expect a trait implemented by T.
//
// If you implement a trait for type T, but all you have
// is a reference &T, you can still call trait methods, but
// you can't pass the &T to methods that expect the trait.
// That is, not without a hack like my TraitDereferencer!
use std::fmt::Debug;
use std::ops::Index;
fn main() {
let mut x = Vec::<u8>::new();
x.push(13);
try_to_print_first(&x);
}
fn try_to_print_first(x: &Vec<u8>) {
// Doesn't work:
//print_first(x);
// Works:
print_first(TraitDereferencer(x));
}
fn print_first<T: Index<usize>>(x: T) where T::Output: Debug + Sized {
println!("{:?}", x[0])
}
struct TraitDereferencer<'a, T: 'a + Index<usize>>(&'a T) where T::Output: Debug + Sized;
impl<'a, T: 'a + Index<usize>> Index<usize> for TraitDereferencer<'a, T>
where T::Output: Debug + Sized
{
type Output = T::Output;
fn index(&self, index: usize) -> &T::Output {
self.0.index(index)
}
}
|
// Notes:
// Varchar will not have a limit, in rust this means it will be hardcoded when compiled.
// This file contains meta command handling, CLI input and the high level while loop for the db.
use std::io::{self, Read, Write};
mod statements;
mod table;
mod data_structures;
use statements::ExecuteResult;
use statements::PrepareResult;
use statements::StatementType;
use statements::prepare_statement;
use statements::execute_statement;
use table::Table;
enum MetaCommandResult {
MetaCommandSuccess,
MetaCommandUnrecognizedCommand
}
struct InputBuffer {
buffer: String,
input_length: usize
}
impl InputBuffer{
fn update_length(&mut self, n: usize) {
self.input_length = n;
}
fn update_input(&mut self, input: String) {
self.buffer = input;
}
}
// TODO: Read up on the rust way of handling user inputs
fn read_input() -> String {
let mut input_buffer = InputBuffer {
buffer: String::new(),
input_length: 0
};
let mut input = String::new();
let mut bytes_read: usize = 0;
match io::stdin().read_line(&mut input) {
Ok(n) => {
bytes_read = n;
input = input;
}
Err(error) => println!("Error reading input: {}", error)
}
bytes_read -= 1;
input_buffer.update_length(bytes_read);
input_buffer.update_input(input);
input_buffer.buffer
}
// Responsible for meta commands such as exit, new db, ect
fn do_meta_command(command: &String) -> MetaCommandResult {
match command.trim() {
".exit" => {
println!("Exiting db");
std::process::exit(123);
}
_ => {
MetaCommandResult::MetaCommandUnrecognizedCommand
}
}
}
fn main() {
let dummy_btree = data_structures::build_btree();
let dummy_columns: Vec<String> = vec!["Username".to_string(), "Email".to_string()];
// Creating a test struct
let mut table = Table {
num_rows: 0,
pages: 0,
columns: dummy_columns,
rows: Vec::new(),
};
let done = false;
while !done {
print!("db > ");
std::io::stdout().flush().unwrap();
let command = read_input();
if command.trim().chars().next().unwrap() == '.' {
match do_meta_command(&command) {
MetaCommandResult::MetaCommandSuccess => {
continue;
}
MetaCommandResult::MetaCommandUnrecognizedCommand => {
println!("Unrecognized meta command {}", command);
continue;
}
}
}
let statement_status: (PrepareResult, StatementType) = prepare_statement(&command);
// Pattern matching PrepareResult enum
match statement_status.0 {
PrepareResult::PrepareSuccess => {
let statement = statement_status.1; // statement_status.1 == returned struct Statement
let new_row: ExecuteResult = execute_statement(&statement, &mut table);
match new_row {
ExecuteResult::ExecuteSuccess => {
println!("Command succeeded");
}
ExecuteResult::ExecuteFailed => {
println!("Command failed");
}
_ => {
println!(":thinking:");
}
}
}
PrepareResult::PrepareSyntaxError => {
println!("Syntax error. Could not parse statement: {}", command);
continue;
}
PrepareResult::PrepareUnrecognizedStatement => {
println!("Unrecognized keyword: {}", command);
continue;
}
};
// Might be redundant
// match execution_status. {
// ExecuteResult::ExecuteSuccess => {
// println!("Executed")
// break;
// }
// ExecuteResult::ExecuteTableFull => {
// println!("Error: Table full")
// break;
// }
// }
}
} |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::BTreeMap;
use arrow::datatypes::DataType;
use arrow::datatypes::Field;
use arrow::datatypes::Schema;
/// Project a [`Schema`] by picking the fields at the given indices.
pub fn project(schema: &Schema, indices: &[usize]) -> Schema {
let fields = indices
.iter()
.map(|idx| schema.fields[*idx].clone())
.collect::<Vec<_>>();
Schema::with_metadata(fields.into(), schema.metadata.clone())
}
/// Project a [`Schema`] with inner columns by path.
pub fn inner_project(schema: &Schema, path_indices: &BTreeMap<usize, Vec<usize>>) -> Schema {
let paths: Vec<Vec<usize>> = path_indices.values().cloned().collect();
let fields = paths
.iter()
.map(|path| traverse_paths(&schema.fields, path))
.collect::<Vec<_>>();
Schema::with_metadata(fields.into(), schema.metadata.clone())
}
fn traverse_paths(fields: &[Field], path: &[usize]) -> Field {
assert!(!path.is_empty());
let field = &fields[path[0]];
if path.len() == 1 {
return field.clone();
}
if let DataType::Struct(inner_fields) = field.data_type() {
let fields = inner_fields
.iter()
.map(|inner| {
let inner_name = format!("{}:{}", field.name, inner.name.to_lowercase());
Field {
name: inner_name,
..inner.clone()
}
})
.collect::<Vec<_>>();
return traverse_paths(&fields, &path[1..]);
}
unreachable!("Unable to get field paths. Fields: {:?}", fields);
}
|
// 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::super::qlib::common::*;
use super::super::super::qlib::linux_def::*;
use super::tty::*;
use super::util::*;
pub fn ioctlGetTermios(fd: i32, termios: &mut Termios) -> Result<()> {
let ret = Ioctl(fd, IoCtlCmd::TCGETS, termios as *mut Termios as u64);
if ret < 0 {
return Err(Error::SysError(-ret))
}
return Ok(())
}
pub fn ioctlSetTermios(fd: i32, req: u64, termios: &Termios) -> Result<()> {
let ret = Ioctl(fd, req, termios as *const Termios as u64);
if ret < 0 {
return Err(Error::SysError(-ret))
}
return Ok(())
}
pub fn ioctlGetWinsize(fd: i32, w: &mut Winsize) -> Result<()> {
let ret = Ioctl(fd, IoCtlCmd::TIOCGWINSZ, w as *mut Winsize as u64);
if ret < 0 {
return Err(Error::SysError(-ret))
}
return Ok(())
}
pub fn ioctlSetWinsize(fd: i32, w: &Winsize) -> Result<()> {
let ret = Ioctl(fd, IoCtlCmd::TIOCSWINSZ, w as *const Winsize as u64);
if ret < 0 {
return Err(Error::SysError(-ret))
}
return Ok(())
} |
//! Helper traits and types.
use super::types::Tag;
use super::traits::ToNbt;
/// Index trait for index operations where a result may not be available.
pub trait IndexOpt<Idx> {
type Output;
fn index_opt<'a>(&'a self, i: Idx) -> Option<&'a Self::Output>;
}
/// Index trait for mutable index operations where a result may not be
/// available.
pub trait IndexOptMut<Idx>: IndexOpt<Idx> {
fn index_opt_mut<'a>(&'a mut self, i: Idx) -> Option<&'a mut Self::Output>;
}
/// Wrapper type for generating byte arrays
pub struct ByteArrayWrapper<'a> {
data: &'a [u8]
}
impl<'a> ByteArrayWrapper<'a> {
pub fn new(d: &'a [u8]) -> ByteArrayWrapper<'a> {
ByteArrayWrapper {
data: d
}
}
}
impl<'a> ToNbt for ByteArrayWrapper<'a> {
fn to_nbt(&self) -> Tag {
let mut v = Vec::new();
v.extend(self.data.iter());
Tag::ByteArray(v)
}
}
/// Wrapper type for generating int arrays
pub struct IntArrayWrapper<'a> {
data: &'a [i32]
}
impl<'a> IntArrayWrapper<'a> {
pub fn new(d: &'a [i32]) -> IntArrayWrapper<'a> {
IntArrayWrapper {
data: d
}
}
}
impl<'a> ToNbt for IntArrayWrapper<'a> {
fn to_nbt(&self) -> Tag {
let mut v = Vec::new();
v.extend(self.data.iter());
Tag::IntArray(v)
}
}
|
use std::collections::HashMap;
use std::path::PathBuf;
use xdg::BaseDirectories;
#[derive(Debug, Clone)]
pub struct AutostartItem {
system_file: Option<PathBuf>,
system: bool,
local_file: Option<PathBuf>,
local_state: FileState,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileState {
StateTransient,
StateExists,
}
impl AutostartItem {
pub fn new() -> Self {
Self {
system_file: None,
system: false,
local_file: None,
local_state: FileState::StateExists,
}
}
pub fn with_system_file(file: &PathBuf) -> Self {
Self {
system_file: Some(file.clone()),
system: true,
local_file: None,
local_state: FileState::StateExists,
}
}
pub fn systemfile(&self) -> Option<PathBuf> {
self.system_file.clone()
}
pub fn file(&self) -> PathBuf {
// if let Some(system_file) = &self.system_file {
// system_file.clone()
// } else if let Some(local_file) = &self.local_file {
// local_file.clone()
// } else {
// PathBuf::new()
// }
if self.system {
self.system_file.clone().unwrap()
} else {
self.local_file.clone().unwrap()
}
}
pub fn set_local_from_file(&mut self, file: &PathBuf) {
self.local_file = Some(file.clone());
self.local_state = FileState::StateExists;
}
// !hard_code
pub fn remove_local(&self) -> bool {
false
}
pub fn overrides(&self) -> bool {
self.system && self.is_local()
}
// !hard_code
pub fn is_local(&self) -> bool {
false
}
pub fn is_transient(&self) -> bool {
self.local_state == FileState::StateTransient
}
pub fn create_item_map() -> HashMap<String, AutostartItem> {
let mut items = HashMap::new();
BaseDirectories::with_prefix("autostart").unwrap().get_config_dirs().into_iter().for_each(|config_dir| {
if let Ok(system_list) = list_of_desktop_files(config_dir) {
system_list.iter().for_each(|file| {
let name = file.file_stem().unwrap();
items.insert(name.to_str().unwrap().to_string(), AutostartItem::with_system_file(file));
})
}
});
if let Ok(local_list) = list_of_desktop_files(BaseDirectories::with_prefix("autostart").unwrap().get_config_home()) {
local_list.iter().for_each(|file| {
let name = file.file_stem().unwrap();
if items.contains_key(name.to_str().unwrap()) {
if let Some(item) = items.get_mut(name.to_str().unwrap()) {
item.set_local_from_file(file);
}
} else {
let mut item = AutostartItem::new();
item.set_local_from_file(file);
items.insert(name.to_str().unwrap().to_string(), item);
}
})
}
items
}
}
fn list_of_desktop_files(dir: PathBuf) -> std::io::Result<Vec<PathBuf>> {
let mut result = vec![];
for path in std::fs::read_dir(dir)? {
let path = path?.path();
if let Some("desktop") = path.extension().and_then(std::ffi::OsStr::to_str) {
result.push(path.to_owned());
}
}
Ok(result)
} |
pub const VENDOR: u16 = 0xDEAD;
pub const PRODUCT: u16 = 0xDEAD;
pub const VERSION: u16 = 0xDEAD;
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qcolordialog.h
// dst-file: /src/widgets/qcolordialog.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::qdialog::*; // 773
use std::ops::Deref;
use super::super::gui::qcolor::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::qwidget::*; // 773
use super::super::core::qobject::*; // 771
use super::super::core::qstring::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QColorDialog_Class_Size() -> c_int;
// proto: QColor QColorDialog::currentColor();
fn C_ZNK12QColorDialog12currentColorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QColor QColorDialog::customColor(int index);
fn C_ZN12QColorDialog11customColorEi(arg0: c_int) -> *mut c_void;
// proto: const QMetaObject * QColorDialog::metaObject();
fn C_ZNK12QColorDialog10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QColorDialog::QColorDialog(const QColor & initial, QWidget * parent);
fn C_ZN12QColorDialogC2ERK6QColorP7QWidget(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: static void QColorDialog::setStandardColor(int index, QColor color);
fn C_ZN12QColorDialog16setStandardColorEi6QColor(arg0: c_int, arg1: *mut c_void);
// proto: void QColorDialog::open(QObject * receiver, const char * member);
fn C_ZN12QColorDialog4openEP7QObjectPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_char);
// proto: QColor QColorDialog::selectedColor();
fn C_ZNK12QColorDialog13selectedColorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QColorDialog::~QColorDialog();
fn C_ZN12QColorDialogD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QColorDialog::setVisible(bool visible);
fn C_ZN12QColorDialog10setVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QColorDialog::setCurrentColor(const QColor & color);
fn C_ZN12QColorDialog15setCurrentColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QColor QColorDialog::standardColor(int index);
fn C_ZN12QColorDialog13standardColorEi(arg0: c_int) -> *mut c_void;
// proto: static QRgb QColorDialog::getRgba(QRgb rgba, bool * ok, QWidget * parent);
fn C_ZN12QColorDialog7getRgbaEjPbP7QWidget(arg0: c_uint, arg1: *mut c_char, arg2: *mut c_void) -> c_uint;
// proto: static void QColorDialog::setCustomColor(int index, QColor color);
fn C_ZN12QColorDialog14setCustomColorEi6QColor(arg0: c_int, arg1: *mut c_void);
// proto: void QColorDialog::QColorDialog(QWidget * parent);
fn C_ZN12QColorDialogC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: static int QColorDialog::customCount();
fn C_ZN12QColorDialog11customCountEv() -> c_int;
fn QColorDialog_SlotProxy_connect__ZN12QColorDialog19currentColorChangedERK6QColor(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QColorDialog_SlotProxy_connect__ZN12QColorDialog13colorSelectedERK6QColor(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QColorDialog)=1
#[derive(Default)]
pub struct QColorDialog {
qbase: QDialog,
pub qclsinst: u64 /* *mut c_void*/,
pub _colorSelected: QColorDialog_colorSelected_signal,
pub _currentColorChanged: QColorDialog_currentColorChanged_signal,
}
impl /*struct*/ QColorDialog {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QColorDialog {
return QColorDialog{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QColorDialog {
type Target = QDialog;
fn deref(&self) -> &QDialog {
return & self.qbase;
}
}
impl AsRef<QDialog> for QColorDialog {
fn as_ref(& self) -> & QDialog {
return & self.qbase;
}
}
// proto: QColor QColorDialog::currentColor();
impl /*struct*/ QColorDialog {
pub fn currentColor<RetType, T: QColorDialog_currentColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentColor(self);
// return 1;
}
}
pub trait QColorDialog_currentColor<RetType> {
fn currentColor(self , rsthis: & QColorDialog) -> RetType;
}
// proto: QColor QColorDialog::currentColor();
impl<'a> /*trait*/ QColorDialog_currentColor<QColor> for () {
fn currentColor(self , rsthis: & QColorDialog) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QColorDialog12currentColorEv()};
let mut ret = unsafe {C_ZNK12QColorDialog12currentColorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QColor QColorDialog::customColor(int index);
impl /*struct*/ QColorDialog {
pub fn customColor_s<RetType, T: QColorDialog_customColor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.customColor_s();
// return 1;
}
}
pub trait QColorDialog_customColor_s<RetType> {
fn customColor_s(self ) -> RetType;
}
// proto: static QColor QColorDialog::customColor(int index);
impl<'a> /*trait*/ QColorDialog_customColor_s<QColor> for (i32) {
fn customColor_s(self ) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog11customColorEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN12QColorDialog11customColorEi(arg0)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QColorDialog::metaObject();
impl /*struct*/ QColorDialog {
pub fn metaObject<RetType, T: QColorDialog_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QColorDialog_metaObject<RetType> {
fn metaObject(self , rsthis: & QColorDialog) -> RetType;
}
// proto: const QMetaObject * QColorDialog::metaObject();
impl<'a> /*trait*/ QColorDialog_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QColorDialog) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QColorDialog10metaObjectEv()};
let mut ret = unsafe {C_ZNK12QColorDialog10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QColorDialog::QColorDialog(const QColor & initial, QWidget * parent);
impl /*struct*/ QColorDialog {
pub fn new<T: QColorDialog_new>(value: T) -> QColorDialog {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QColorDialog_new {
fn new(self) -> QColorDialog;
}
// proto: void QColorDialog::QColorDialog(const QColor & initial, QWidget * parent);
impl<'a> /*trait*/ QColorDialog_new for (&'a QColor, Option<&'a QWidget>) {
fn new(self) -> QColorDialog {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialogC2ERK6QColorP7QWidget()};
let ctysz: c_int = unsafe{QColorDialog_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 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN12QColorDialogC2ERK6QColorP7QWidget(arg0, arg1)};
let rsthis = QColorDialog{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static void QColorDialog::setStandardColor(int index, QColor color);
impl /*struct*/ QColorDialog {
pub fn setStandardColor_s<RetType, T: QColorDialog_setStandardColor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setStandardColor_s();
// return 1;
}
}
pub trait QColorDialog_setStandardColor_s<RetType> {
fn setStandardColor_s(self ) -> RetType;
}
// proto: static void QColorDialog::setStandardColor(int index, QColor color);
impl<'a> /*trait*/ QColorDialog_setStandardColor_s<()> for (i32, QColor) {
fn setStandardColor_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog16setStandardColorEi6QColor()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN12QColorDialog16setStandardColorEi6QColor(arg0, arg1)};
// return 1;
}
}
// proto: void QColorDialog::open(QObject * receiver, const char * member);
impl /*struct*/ QColorDialog {
pub fn open<RetType, T: QColorDialog_open<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.open(self);
// return 1;
}
}
pub trait QColorDialog_open<RetType> {
fn open(self , rsthis: & QColorDialog) -> RetType;
}
// proto: void QColorDialog::open(QObject * receiver, const char * member);
impl<'a> /*trait*/ QColorDialog_open<()> for (&'a QObject, &'a String) {
fn open(self , rsthis: & QColorDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog4openEP7QObjectPKc()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.as_ptr() as *mut c_char;
unsafe {C_ZN12QColorDialog4openEP7QObjectPKc(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QColor QColorDialog::selectedColor();
impl /*struct*/ QColorDialog {
pub fn selectedColor<RetType, T: QColorDialog_selectedColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectedColor(self);
// return 1;
}
}
pub trait QColorDialog_selectedColor<RetType> {
fn selectedColor(self , rsthis: & QColorDialog) -> RetType;
}
// proto: QColor QColorDialog::selectedColor();
impl<'a> /*trait*/ QColorDialog_selectedColor<QColor> for () {
fn selectedColor(self , rsthis: & QColorDialog) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK12QColorDialog13selectedColorEv()};
let mut ret = unsafe {C_ZNK12QColorDialog13selectedColorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QColorDialog::~QColorDialog();
impl /*struct*/ QColorDialog {
pub fn free<RetType, T: QColorDialog_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QColorDialog_free<RetType> {
fn free(self , rsthis: & QColorDialog) -> RetType;
}
// proto: void QColorDialog::~QColorDialog();
impl<'a> /*trait*/ QColorDialog_free<()> for () {
fn free(self , rsthis: & QColorDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialogD2Ev()};
unsafe {C_ZN12QColorDialogD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QColorDialog::setVisible(bool visible);
impl /*struct*/ QColorDialog {
pub fn setVisible<RetType, T: QColorDialog_setVisible<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVisible(self);
// return 1;
}
}
pub trait QColorDialog_setVisible<RetType> {
fn setVisible(self , rsthis: & QColorDialog) -> RetType;
}
// proto: void QColorDialog::setVisible(bool visible);
impl<'a> /*trait*/ QColorDialog_setVisible<()> for (i8) {
fn setVisible(self , rsthis: & QColorDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog10setVisibleEb()};
let arg0 = self as c_char;
unsafe {C_ZN12QColorDialog10setVisibleEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QColorDialog::setCurrentColor(const QColor & color);
impl /*struct*/ QColorDialog {
pub fn setCurrentColor<RetType, T: QColorDialog_setCurrentColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCurrentColor(self);
// return 1;
}
}
pub trait QColorDialog_setCurrentColor<RetType> {
fn setCurrentColor(self , rsthis: & QColorDialog) -> RetType;
}
// proto: void QColorDialog::setCurrentColor(const QColor & color);
impl<'a> /*trait*/ QColorDialog_setCurrentColor<()> for (&'a QColor) {
fn setCurrentColor(self , rsthis: & QColorDialog) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog15setCurrentColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN12QColorDialog15setCurrentColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QColor QColorDialog::standardColor(int index);
impl /*struct*/ QColorDialog {
pub fn standardColor_s<RetType, T: QColorDialog_standardColor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.standardColor_s();
// return 1;
}
}
pub trait QColorDialog_standardColor_s<RetType> {
fn standardColor_s(self ) -> RetType;
}
// proto: static QColor QColorDialog::standardColor(int index);
impl<'a> /*trait*/ QColorDialog_standardColor_s<QColor> for (i32) {
fn standardColor_s(self ) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog13standardColorEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN12QColorDialog13standardColorEi(arg0)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QRgb QColorDialog::getRgba(QRgb rgba, bool * ok, QWidget * parent);
impl /*struct*/ QColorDialog {
pub fn getRgba_s<RetType, T: QColorDialog_getRgba_s<RetType>>( overload_args: T) -> RetType {
return overload_args.getRgba_s();
// return 1;
}
}
pub trait QColorDialog_getRgba_s<RetType> {
fn getRgba_s(self ) -> RetType;
}
// proto: static QRgb QColorDialog::getRgba(QRgb rgba, bool * ok, QWidget * parent);
impl<'a> /*trait*/ QColorDialog_getRgba_s<u32> for (Option<u32>, Option<&'a mut Vec<i8>>, Option<&'a QWidget>) {
fn getRgba_s(self ) -> u32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog7getRgbaEjPbP7QWidget()};
let arg0 = (if self.0.is_none() {0xffffffff} else {self.0.unwrap()}) as c_uint;
let arg1 = (if self.1.is_none() {0 as *const i8} else {self.1.unwrap().as_ptr()}) as *mut c_char;
let arg2 = (if self.2.is_none() {0} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN12QColorDialog7getRgbaEjPbP7QWidget(arg0, arg1, arg2)};
return ret as u32; // 1
// return 1;
}
}
// proto: static void QColorDialog::setCustomColor(int index, QColor color);
impl /*struct*/ QColorDialog {
pub fn setCustomColor_s<RetType, T: QColorDialog_setCustomColor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setCustomColor_s();
// return 1;
}
}
pub trait QColorDialog_setCustomColor_s<RetType> {
fn setCustomColor_s(self ) -> RetType;
}
// proto: static void QColorDialog::setCustomColor(int index, QColor color);
impl<'a> /*trait*/ QColorDialog_setCustomColor_s<()> for (i32, QColor) {
fn setCustomColor_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog14setCustomColorEi6QColor()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN12QColorDialog14setCustomColorEi6QColor(arg0, arg1)};
// return 1;
}
}
// proto: void QColorDialog::QColorDialog(QWidget * parent);
impl<'a> /*trait*/ QColorDialog_new for (Option<&'a QWidget>) {
fn new(self) -> QColorDialog {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialogC2EP7QWidget()};
let ctysz: c_int = unsafe{QColorDialog_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_ZN12QColorDialogC2EP7QWidget(arg0)};
let rsthis = QColorDialog{qbase: QDialog::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static int QColorDialog::customCount();
impl /*struct*/ QColorDialog {
pub fn customCount_s<RetType, T: QColorDialog_customCount_s<RetType>>( overload_args: T) -> RetType {
return overload_args.customCount_s();
// return 1;
}
}
pub trait QColorDialog_customCount_s<RetType> {
fn customCount_s(self ) -> RetType;
}
// proto: static int QColorDialog::customCount();
impl<'a> /*trait*/ QColorDialog_customCount_s<i32> for () {
fn customCount_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN12QColorDialog11customCountEv()};
let mut ret = unsafe {C_ZN12QColorDialog11customCountEv()};
return ret as i32; // 1
// return 1;
}
}
#[derive(Default)] // for QColorDialog_colorSelected
pub struct QColorDialog_colorSelected_signal{poi:u64}
impl /* struct */ QColorDialog {
pub fn colorSelected(&self) -> QColorDialog_colorSelected_signal {
return QColorDialog_colorSelected_signal{poi:self.qclsinst};
}
}
impl /* struct */ QColorDialog_colorSelected_signal {
pub fn connect<T: QColorDialog_colorSelected_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QColorDialog_colorSelected_signal_connect {
fn connect(self, sigthis: QColorDialog_colorSelected_signal);
}
#[derive(Default)] // for QColorDialog_currentColorChanged
pub struct QColorDialog_currentColorChanged_signal{poi:u64}
impl /* struct */ QColorDialog {
pub fn currentColorChanged(&self) -> QColorDialog_currentColorChanged_signal {
return QColorDialog_currentColorChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QColorDialog_currentColorChanged_signal {
pub fn connect<T: QColorDialog_currentColorChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QColorDialog_currentColorChanged_signal_connect {
fn connect(self, sigthis: QColorDialog_currentColorChanged_signal);
}
// currentColorChanged(const class QColor &)
extern fn QColorDialog_currentColorChanged_signal_connect_cb_0(rsfptr:fn(QColor), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QColor::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QColorDialog_currentColorChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QColor)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QColor::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QColorDialog_currentColorChanged_signal_connect for fn(QColor) {
fn connect(self, sigthis: QColorDialog_currentColorChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColorDialog_currentColorChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QColorDialog_SlotProxy_connect__ZN12QColorDialog19currentColorChangedERK6QColor(arg0, arg1, arg2)};
}
}
impl /* trait */ QColorDialog_currentColorChanged_signal_connect for Box<Fn(QColor)> {
fn connect(self, sigthis: QColorDialog_currentColorChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColorDialog_currentColorChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QColorDialog_SlotProxy_connect__ZN12QColorDialog19currentColorChangedERK6QColor(arg0, arg1, arg2)};
}
}
// colorSelected(const class QColor &)
extern fn QColorDialog_colorSelected_signal_connect_cb_1(rsfptr:fn(QColor), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QColor::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QColorDialog_colorSelected_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QColor)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QColor::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QColorDialog_colorSelected_signal_connect for fn(QColor) {
fn connect(self, sigthis: QColorDialog_colorSelected_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColorDialog_colorSelected_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QColorDialog_SlotProxy_connect__ZN12QColorDialog13colorSelectedERK6QColor(arg0, arg1, arg2)};
}
}
impl /* trait */ QColorDialog_colorSelected_signal_connect for Box<Fn(QColor)> {
fn connect(self, sigthis: QColorDialog_colorSelected_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QColorDialog_colorSelected_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QColorDialog_SlotProxy_connect__ZN12QColorDialog13colorSelectedERK6QColor(arg0, arg1, arg2)};
}
}
// <= body block end
|
use super::*;
#[derive(Clone)]
pub enum MapKey<K> {
Value(K),
/// This is a horrible hack.
Query(NonNull<MapQuery<'static, K>>),
}
impl<K> MapKey<K> {
#[inline]
pub fn into_inner(self) -> K {
match self {
MapKey::Value(v) => v,
_ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"),
}
}
#[inline]
pub fn as_ref(&self) -> &K {
match self {
MapKey::Value(v) => v,
_ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"),
}
}
}
impl<K> From<K> for MapKey<K> {
#[inline]
fn from(value: K) -> Self {
MapKey::Value(value)
}
}
impl<K> Debug for MapKey<K>
where
K: Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MapKey::Value(v) => Debug::fmt(v, f),
_ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"),
}
}
}
impl<K> Eq for MapKey<K> where K: Eq {}
impl<K> PartialEq for MapKey<K>
where
K: PartialEq,
{
fn eq<'a>(&'a self, other: &'a Self) -> bool {
match (self, other) {
(MapKey::Value(lhs), MapKey::Query(rhs)) | (MapKey::Query(rhs), MapKey::Value(lhs)) => unsafe {
rhs.as_ref().is_equal(lhs)
},
(MapKey::Value(lhs), MapKey::Value(rhs)) => lhs == rhs,
_ => {
unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
}
}
impl<K> Hash for MapKey<K>
where
K: Hash,
{
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
match self {
MapKey::Value(this) => {
this.hash(hasher);
}
MapKey::Query(this) => unsafe {
this.as_ref().hash(hasher);
},
}
}
}
impl<K> Borrow<K> for MapKey<K> {
fn borrow(&self) -> &K {
self.as_ref()
}
}
|
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::Read;
use anyhow::Result;
use digest::{Digest, DynDigest};
use crate::cmd_line::Algorithm;
use crate::error::AppError;
fn get_hasher(algorithm: Algorithm) -> Box<dyn DynDigest> {
match algorithm {
Algorithm::MD5 => Box::new(md5::Md5::new()),
Algorithm::SHA1 => Box::new(sha1::Sha1::new()),
Algorithm::SHA224 => Box::new(sha2::Sha224::new()),
Algorithm::SHA256 => Box::new(sha2::Sha256::new()),
Algorithm::SHA384 => Box::new(sha2::Sha384::new()),
Algorithm::SHA512 => Box::new(sha2::Sha512::new()),
}
}
fn guess_algorithm(hash_size: usize) -> Result<Algorithm> {
match hash_size {
16 => Ok(Algorithm::MD5),
20 => Ok(Algorithm::SHA1),
28 => Ok(Algorithm::SHA224),
32 => Ok(Algorithm::SHA256),
48 => Ok(Algorithm::SHA384),
64 => Ok(Algorithm::SHA512),
_ => Err(AppError::UnknownAlgorithmError(hash_size * 8))?
}
}
fn str_to_bytes(s: &str) -> Result<Vec<u8>> {
if s.len() / 2 * 2 != s.len() {
Err(AppError::InvalidHashValue(s.to_owned()))?;
}
let mut buf = Vec::<u8>::with_capacity(s.len() / 2);
for idx in (0..s.len()).step_by(2) {
let u8 = u8::from_str_radix(&s[idx..idx + 2], 16).or(Err(AppError::InvalidHashValue(s.to_owned())))?;
buf.push(u8);
}
Ok(buf)
}
pub fn calculate_checksum(path: &Path, algorithm: Algorithm) -> Result<Vec<u8>> {
let mut hasher = get_hasher(algorithm);
let mut buffer = [0; 4096];
let mut f = File::open(path)?;
loop {
let n = f.read(&mut buffer)?;
if n == 0 {
break;
}
hasher.update(&buffer[0..n]);
}
Ok(Vec::from(hasher.finalize()))
}
pub fn verify_checksum(path: &Path, checksum: &str, algorithm: Option<Algorithm>) -> Result<(PathBuf, bool)> {
let algorithm = algorithm.unwrap_or(guess_algorithm(checksum.len() / 2)?);
let calculated = calculate_checksum(path, algorithm);
Ok((path.to_owned(), str_to_bytes(checksum)? == calculated?))
}
#[cfg(test)]
mod test {
use tempfile::NamedTempFile;
use std::io::Write;
use crate::checksum::verify_checksum;
use crate::cmd_line::Algorithm;
#[test]
fn test_checksum() {
let mut file = NamedTempFile::new().unwrap();
file.write("abcdABCD1234".as_bytes()).unwrap();
file.flush().unwrap();
let path = file.path();
assert!(verify_checksum(path, "bb057481a1b7abc93ad5d70d52e3a55f", None).unwrap().1);
assert!(verify_checksum(path, "a9c0f8c056a19fdfd18db386039bdc90e680116c", None).unwrap().1);
assert!(verify_checksum(path, "1815e1f3522b385698aec88f13f880e838264fbd3f90f6e25f22fd8e", None).unwrap().1);
assert!(verify_checksum(path, "423df0dab6a97c46239d196ad6f610edf5484650e9e7085634045e8b3fc19d0b", None).unwrap().1);
assert!(verify_checksum(path, "9732f0a3c0a4cb8d834111224681e516534e74d5062e67bc5f652e5c5684d5b01795781bd5e51fdf0aeb1e13abd5004e", None).unwrap().1);
assert!(verify_checksum(path, "56e36f3eb1a36bef4d8665f17efe30a52f190bdbaff24be9f73ed18cdbab41b09eca3256967a1b5da04d2b501e7d3cd4b0fbe55a0e64ae905aefe8676a7aaa9d", None).unwrap().1);
assert!(verify_checksum(path, "bb057481a1b7abc93ad5d70d52e3a55f", Some(Algorithm::MD5)).unwrap().1);
assert!(verify_checksum(path, "a9c0f8c056a19fdfd18db386039bdc90e680116c", Some(Algorithm::SHA1)).unwrap().1);
assert!(verify_checksum(path, "1815e1f3522b385698aec88f13f880e838264fbd3f90f6e25f22fd8e", Some(Algorithm::SHA224)).unwrap().1);
assert!(verify_checksum(path, "423df0dab6a97c46239d196ad6f610edf5484650e9e7085634045e8b3fc19d0b", Some(Algorithm::SHA256)).unwrap().1);
assert!(verify_checksum(path, "9732f0a3c0a4cb8d834111224681e516534e74d5062e67bc5f652e5c5684d5b01795781bd5e51fdf0aeb1e13abd5004e", Some(Algorithm::SHA384)).unwrap().1);
assert!(verify_checksum(path, "56e36f3eb1a36bef4d8665f17efe30a52f190bdbaff24be9f73ed18cdbab41b09eca3256967a1b5da04d2b501e7d3cd4b0fbe55a0e64ae905aefe8676a7aaa9d", Some(Algorithm::SHA512)).unwrap().1);
assert!(!verify_checksum(path, "0b057481a1b7abc93ad5d70d52e3a55f", None).unwrap().1);
assert!(!verify_checksum(path, "09c0f8c056a19fdfd18db386039bdc90e680116c", None).unwrap().1);
assert!(!verify_checksum(path, "0815e1f3522b385698aec88f13f880e838264fbd3f90f6e25f22fd8e", None).unwrap().1);
assert!(!verify_checksum(path, "023df0dab6a97c46239d196ad6f610edf5484650e9e7085634045e8b3fc19d0b", None).unwrap().1);
assert!(!verify_checksum(path, "0732f0a3c0a4cb8d834111224681e516534e74d5062e67bc5f652e5c5684d5b01795781bd5e51fdf0aeb1e13abd5004e", None).unwrap().1);
assert!(!verify_checksum(path, "06e36f3eb1a36bef4d8665f17efe30a52f190bdbaff24be9f73ed18cdbab41b09eca3256967a1b5da04d2b501e7d3cd4b0fbe55a0e64ae905aefe8676a7aaa9d", None).unwrap().1);
}
}
|
use crate::erlang::self_0::result;
use crate::test::with_process;
#[test]
fn returns_process_pid() {
with_process(|process| {
assert_eq!(result(&process), process.pid_term());
});
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Global configuration register"]
pub gcr: GCR,
#[doc = "0x04 - Cluster CH%s, containing ?CR1, ?CR2, ?FRCR, ?SLOTR, ?IM, ?SR, ?CLRFR, ?DR"]
pub cha: CH,
#[doc = "0x24 - Cluster CH%s, containing ?CR1, ?CR2, ?FRCR, ?SLOTR, ?IM, ?SR, ?CLRFR, ?DR"]
pub chb: CH,
#[doc = "0x44 - PDM control register"]
pub pdmcr: PDMCR,
#[doc = "0x48 - PDM delay register"]
pub pdmdly: PDMDLY,
}
#[doc = r"Register block"]
#[repr(C)]
pub struct CH {
#[doc = "0x00 - Configuration register 1"]
pub cr1: self::ch::CR1,
#[doc = "0x04 - Configuration register 2"]
pub cr2: self::ch::CR2,
#[doc = "0x08 - This register has no meaning in AC97 and SPDIF audio protocol"]
pub frcr: self::ch::FRCR,
#[doc = "0x0c - This register has no meaning in AC97 and SPDIF audio protocol"]
pub slotr: self::ch::SLOTR,
#[doc = "0x10 - Interrupt mask register 2"]
pub im: self::ch::IM,
#[doc = "0x14 - Status register"]
pub sr: self::ch::SR,
#[doc = "0x18 - Clear flag register"]
pub clrfr: self::ch::CLRFR,
#[doc = "0x1c - Data register"]
pub dr: self::ch::DR,
}
#[doc = r"Register block"]
#[doc = "Cluster CH%s, containing ?CR1, ?CR2, ?FRCR, ?SLOTR, ?IM, ?SR, ?CLRFR, ?DR"]
pub mod ch;
#[doc = "Global 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 [gcr](gcr) module"]
pub type GCR = crate::Reg<u32, _GCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GCR;
#[doc = "`read()` method returns [gcr::R](gcr::R) reader structure"]
impl crate::Readable for GCR {}
#[doc = "`write(|w| ..)` method takes [gcr::W](gcr::W) writer structure"]
impl crate::Writable for GCR {}
#[doc = "Global configuration register"]
pub mod gcr;
#[doc = "PDM 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 [pdmcr](pdmcr) module"]
pub type PDMCR = crate::Reg<u32, _PDMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PDMCR;
#[doc = "`read()` method returns [pdmcr::R](pdmcr::R) reader structure"]
impl crate::Readable for PDMCR {}
#[doc = "`write(|w| ..)` method takes [pdmcr::W](pdmcr::W) writer structure"]
impl crate::Writable for PDMCR {}
#[doc = "PDM control register"]
pub mod pdmcr;
#[doc = "PDM delay 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 [pdmdly](pdmdly) module"]
pub type PDMDLY = crate::Reg<u32, _PDMDLY>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PDMDLY;
#[doc = "`read()` method returns [pdmdly::R](pdmdly::R) reader structure"]
impl crate::Readable for PDMDLY {}
#[doc = "`write(|w| ..)` method takes [pdmdly::W](pdmdly::W) writer structure"]
impl crate::Writable for PDMDLY {}
#[doc = "PDM delay register"]
pub mod pdmdly;
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::marker::PhantomData;
use std::ops::Range;
use common_arrow::arrow::bitmap::Bitmap;
use common_arrow::arrow::bitmap::MutableBitmap;
use common_arrow::arrow::trusted_len::TrustedLen;
use super::AnyType;
use crate::property::Domain;
use crate::types::ArgType;
use crate::types::DataType;
use crate::types::GenericMap;
use crate::types::ValueType;
use crate::utils::arrow::bitmap_into_mut;
use crate::values::Column;
use crate::values::Scalar;
use crate::ColumnBuilder;
use crate::ScalarRef;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NullableType<T: ValueType>(PhantomData<T>);
impl<T: ValueType> ValueType for NullableType<T> {
type Scalar = Option<T::Scalar>;
type ScalarRef<'a> = Option<T::ScalarRef<'a>>;
type Column = NullableColumn<T>;
type Domain = NullableDomain<T>;
type ColumnIterator<'a> = NullableIterator<'a, T>;
type ColumnBuilder = NullableColumnBuilder<T>;
#[inline]
fn upcast_gat<'short, 'long: 'short>(
long: Option<T::ScalarRef<'long>>,
) -> Option<T::ScalarRef<'short>> {
long.map(|long| T::upcast_gat(long))
}
fn to_owned_scalar<'a>(scalar: Self::ScalarRef<'a>) -> Self::Scalar {
scalar.map(T::to_owned_scalar)
}
fn to_scalar_ref<'a>(scalar: &'a Self::Scalar) -> Self::ScalarRef<'a> {
scalar.as_ref().map(T::to_scalar_ref)
}
fn try_downcast_scalar<'a>(scalar: &'a ScalarRef) -> Option<Self::ScalarRef<'a>> {
match scalar {
ScalarRef::Null => Some(None),
scalar => Some(Some(T::try_downcast_scalar(scalar)?)),
}
}
fn try_downcast_column<'a>(col: &'a Column) -> Option<Self::Column> {
NullableColumn::try_downcast(col.as_nullable()?)
}
fn try_downcast_domain(domain: &Domain) -> Option<Self::Domain> {
match domain {
Domain::Nullable(NullableDomain {
has_null,
value: Some(value),
}) => Some(NullableDomain {
has_null: *has_null,
value: Some(Box::new(T::try_downcast_domain(value)?)),
}),
Domain::Nullable(NullableDomain {
has_null,
value: None,
}) => Some(NullableDomain {
has_null: *has_null,
value: None,
}),
_ => None,
}
}
fn try_downcast_builder<'a>(
_builder: &'a mut ColumnBuilder,
) -> Option<&'a mut Self::ColumnBuilder> {
None
}
fn upcast_scalar(scalar: Self::Scalar) -> Scalar {
match scalar {
Some(scalar) => T::upcast_scalar(scalar),
None => Scalar::Null,
}
}
fn upcast_column(col: Self::Column) -> Column {
Column::Nullable(Box::new(col.upcast()))
}
fn upcast_domain(domain: Self::Domain) -> Domain {
Domain::Nullable(NullableDomain {
has_null: domain.has_null,
value: domain.value.map(|value| Box::new(T::upcast_domain(*value))),
})
}
fn column_len<'a>(col: &'a Self::Column) -> usize {
col.len()
}
fn index_column<'a>(col: &'a Self::Column, index: usize) -> Option<Self::ScalarRef<'a>> {
col.index(index)
}
unsafe fn index_column_unchecked<'a>(
col: &'a Self::Column,
index: usize,
) -> Self::ScalarRef<'a> {
col.index_unchecked(index)
}
fn slice_column<'a>(col: &'a Self::Column, range: Range<usize>) -> Self::Column {
col.slice(range)
}
fn iter_column<'a>(col: &'a Self::Column) -> Self::ColumnIterator<'a> {
col.iter()
}
fn column_to_builder(col: Self::Column) -> Self::ColumnBuilder {
NullableColumnBuilder::from_column(col)
}
fn builder_len(builder: &Self::ColumnBuilder) -> usize {
builder.len()
}
fn push_item(builder: &mut Self::ColumnBuilder, item: Self::ScalarRef<'_>) {
match item {
Some(item) => builder.push(item),
None => builder.push_null(),
}
}
fn push_default(builder: &mut Self::ColumnBuilder) {
builder.push_null();
}
fn append_column(builder: &mut Self::ColumnBuilder, other: &Self::Column) {
builder.append_column(other);
}
fn build_column(builder: Self::ColumnBuilder) -> Self::Column {
builder.build()
}
fn build_scalar(builder: Self::ColumnBuilder) -> Self::Scalar {
builder.build_scalar()
}
fn scalar_memory_size<'a>(scalar: &Self::ScalarRef<'a>) -> usize {
match scalar {
Some(scalar) => T::scalar_memory_size(scalar),
None => 0,
}
}
fn column_memory_size(col: &Self::Column) -> usize {
col.memory_size()
}
}
impl<T: ArgType> ArgType for NullableType<T> {
fn data_type() -> DataType {
DataType::Nullable(Box::new(T::data_type()))
}
fn full_domain() -> Self::Domain {
NullableDomain {
has_null: true,
value: Some(Box::new(T::full_domain())),
}
}
fn create_builder(capacity: usize, generics: &GenericMap) -> Self::ColumnBuilder {
NullableColumnBuilder::with_capacity(capacity, generics)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct NullableColumn<T: ValueType> {
pub column: T::Column,
pub validity: Bitmap,
}
impl<T: ValueType> NullableColumn<T> {
pub fn len(&self) -> usize {
self.validity.len()
}
pub fn index(&self, index: usize) -> Option<Option<T::ScalarRef<'_>>> {
match self.validity.get(index) {
Some(true) => Some(Some(T::index_column(&self.column, index).unwrap())),
Some(false) => Some(None),
None => None,
}
}
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined behavior]*
pub unsafe fn index_unchecked(&self, index: usize) -> Option<T::ScalarRef<'_>> {
match self.validity.get_bit_unchecked(index) {
true => Some(T::index_column(&self.column, index).unwrap()),
false => None,
}
}
pub fn slice(&self, range: Range<usize>) -> Self {
NullableColumn {
validity: self
.validity
.clone()
.sliced(range.start, range.end - range.start),
column: T::slice_column(&self.column, range),
}
}
pub fn iter(&self) -> NullableIterator<T> {
NullableIterator {
iter: T::iter_column(&self.column),
validity: self.validity.iter(),
}
}
pub fn upcast(self) -> NullableColumn<AnyType> {
NullableColumn {
column: T::upcast_column(self.column),
validity: self.validity,
}
}
pub fn memory_size(&self) -> usize {
T::column_memory_size(&self.column) + self.validity.as_slice().0.len()
}
}
impl NullableColumn<AnyType> {
pub fn try_downcast<T: ValueType>(&self) -> Option<NullableColumn<T>> {
Some(NullableColumn {
column: T::try_downcast_column(&self.column)?,
validity: self.validity.clone(),
})
}
}
pub struct NullableIterator<'a, T: ValueType> {
iter: T::ColumnIterator<'a>,
validity: common_arrow::arrow::bitmap::utils::BitmapIter<'a>,
}
impl<'a, T: ValueType> Iterator for NullableIterator<'a, T> {
type Item = Option<T::ScalarRef<'a>>;
fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()
.zip(self.validity.next())
.map(
|(scalar, is_not_null)| {
if is_not_null { Some(scalar) } else { None }
},
)
}
fn size_hint(&self) -> (usize, Option<usize>) {
assert_eq!(self.iter.size_hint(), self.validity.size_hint());
self.validity.size_hint()
}
}
unsafe impl<'a, T: ValueType> TrustedLen for NullableIterator<'a, T> {}
#[derive(Debug, Clone, PartialEq)]
pub struct NullableColumnBuilder<T: ValueType> {
pub builder: T::ColumnBuilder,
pub validity: MutableBitmap,
}
impl<T: ValueType> NullableColumnBuilder<T> {
pub fn from_column(col: NullableColumn<T>) -> Self {
NullableColumnBuilder {
builder: T::column_to_builder(col.column),
validity: bitmap_into_mut(col.validity),
}
}
pub fn len(&self) -> usize {
self.validity.len()
}
pub fn push(&mut self, item: T::ScalarRef<'_>) {
T::push_item(&mut self.builder, item);
self.validity.push(true);
}
pub fn push_null(&mut self) {
T::push_default(&mut self.builder);
self.validity.push(false);
}
pub fn append_column(&mut self, other: &NullableColumn<T>) {
T::append_column(&mut self.builder, &other.column);
self.validity.extend_from_bitmap(&other.validity)
}
pub fn build(self) -> NullableColumn<T> {
assert_eq!(self.validity.len(), T::builder_len(&self.builder));
NullableColumn {
column: T::build_column(self.builder),
validity: self.validity.into(),
}
}
pub fn build_scalar(self) -> Option<T::Scalar> {
assert_eq!(T::builder_len(&self.builder), 1);
assert_eq!(self.validity.len(), 1);
if self.validity.get(0) {
Some(T::build_scalar(self.builder))
} else {
None
}
}
}
impl<T: ArgType> NullableColumnBuilder<T> {
pub fn with_capacity(capacity: usize, generics: &GenericMap) -> Self {
NullableColumnBuilder {
builder: T::create_builder(capacity, generics),
validity: MutableBitmap::with_capacity(capacity),
}
}
}
impl NullableColumnBuilder<AnyType> {
pub fn pop(&mut self) -> Option<Option<Scalar>> {
if self.validity.pop()? {
Some(Some(self.builder.pop().unwrap()))
} else {
self.builder.pop().unwrap();
Some(None)
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct NullableDomain<T: ValueType> {
pub has_null: bool,
// `None` means all rows are `NULL`s.
//
// Invariant: `has_null` must be `true` when `value` is `None`.
pub value: Option<Box<T::Domain>>,
}
|
// Based on ws-addr.xsd
// targetNamespace="http://www.w3.org/2005/08/addressing"
// xmlns:xs="http://www.w3.org/2001/XMLSchema"
// xmlns:tns="http://www.w3.org/2005/08/addressing"
use std::io::{Read, Write};
use yaserde::{YaDeserialize, YaSerialize};
|
use super::parser::*;
use anyhow::{anyhow, Result};
use maplit::hashmap;
use std::collections::HashMap;
#[derive(Debug)]
pub struct CCommand {
pub dest: Dest,
pub comp: Comp,
pub jump: Jump,
pub addr: usize,
source: Source,
}
// C-Command dest operand
#[derive(PartialEq, Clone, Copy, Debug, enum_utils::FromStr)]
pub enum Dest {
Null = 0b000,
M = 0b001,
D = 0b010,
MD = 0b011,
A = 0b100,
AM = 0b101,
AD = 0b110,
AMD = 0b111,
}
// C-Command jump opreand
#[derive(PartialEq, Clone, Copy, Debug, enum_utils::FromStr)]
pub enum Jump {
Null = 0b000,
JGT = 0b001,
JEQ = 0b010,
JGE = 0b011,
JLT = 0b100,
JNE = 0b101,
JLE = 0b110,
JMP = 0b111,
}
// C-Command comp operand
#[derive(Debug, Copy, Clone)]
pub struct Comp {
exp: &'static str, // expression
pub mcode: i8, // machien code (7bit)
}
lazy_static! {
pub static ref COMP_MAP: HashMap<&'static str, Comp> = hashmap!(
"0" => Comp{ exp: "0", mcode: 0b0101010 },
"1" => Comp{ exp: "1", mcode: 0b0111111 },
"-1" => Comp{ exp: "-1", mcode: 0b0111010 },
"D" => Comp{ exp: "D", mcode: 0b0001100 },
"A" => Comp{ exp: "A", mcode: 0b0110000 },
"!D" => Comp{ exp: "!D", mcode: 0b0001101 },
"!A" => Comp{ exp: "!A", mcode: 0b0110001 },
"-D" => Comp{ exp: "-D", mcode: 0b0001111 },
"-A" => Comp{ exp: "-A", mcode: 0b0110011 },
"D+1" => Comp{ exp: "D+1", mcode: 0b0011111 },
"A+1" => Comp{ exp: "A+1", mcode: 0b0110111 },
"D-1" => Comp{ exp: "D-1", mcode: 0b0001110 },
"A-1" => Comp{ exp: "A-1", mcode: 0b0110010 },
"D+A" => Comp{ exp: "D+A", mcode: 0b0000010 },
"D-A" => Comp{ exp: "D-A", mcode: 0b0010011 },
"A-D" => Comp{ exp: "A-D", mcode: 0b0000111 },
"D&A" => Comp{ exp: "D&A", mcode: 0b0000000 },
"D|A" => Comp{ exp: "D|A", mcode: 0b0010101 },
"M" => Comp{ exp: "M", mcode: 0b1110000 },
"!M" => Comp{ exp: "!M", mcode: 0b1110001 },
"-M" => Comp{ exp: "-M", mcode: 0b1110011 },
"M+1" => Comp{ exp: "M+1", mcode: 0b1110111 },
"M-1" => Comp{ exp: "M-1", mcode: 0b1110010 },
"D+M" => Comp{ exp: "D+M", mcode: 0b1000010 },
"D-M" => Comp{ exp: "D-M", mcode: 0b1010011 },
"M-D" => Comp{ exp: "M-D", mcode: 0b1000111 },
"D&M" => Comp{ exp: "D&M", mcode: 0b1000000 },
"D|M" => Comp{ exp: "D|M", mcode: 0b1010101 },
);
}
pub fn parse(addr: usize, source: Source) -> Result<CCommand> {
let (dest, lhs) = split_code(&source.code, "=", true);
let dest = dest.unwrap_or("Null");
let dest = parse_dest(dest)?;
let lhs = lhs.ok_or(anyhow!(
"{:?} :lhs operand is missing: {}",
source,
source.code
))?;
let (comp, jump) = parse_comp_and_jmp(&source, lhs)?;
let cmd = CCommand {
dest,
comp,
jump,
addr,
source,
};
Ok(cmd)
}
fn parse_dest(dest: &str) -> Result<Dest> {
dest.parse::<Dest>()
.map_err(|()| anyhow!("invalid dest operand: {}", dest))
}
fn parse_comp_and_jmp(source: &Source, code: &str) -> Result<(Comp, Jump)> {
let (comp, jump) = split_code(&code, ";", false);
let comp = comp.ok_or(anyhow!("{:?} : comp operand is missing: {}", source, code))?;
let comp = COMP_MAP
.get(comp)
.ok_or(anyhow!("unnown comp operand : {}", comp))?;
let jump = jump.unwrap_or("Null");
let jump = parse_jump(source, jump)?;
Ok((*comp, jump))
}
fn parse_jump(source: &Source, jump: &str) -> Result<Jump> {
jump.parse::<Jump>()
.map_err(|()| anyhow!("{:?} : invalid jmp operand: {}", source, jump))
}
|
use abi_stable::{std_types::RCow, DynTrait};
use example_0_interface::CowStrIter;
use super::*;
/// This tests that a type coming from a dynamic library
/// cannot be converted back to its std-library equivalent
/// while reusing the heap allocation.
///
/// The reason why they can't reuse the heap allocation is because they might
/// be using a different global allocator that this binary is using.
///
/// There is no way that I am aware to check at compile-time what allocator
/// the type is using,so this is the best I can do while staying safe.
pub fn run_dynamic_library_tests(mods: TextOpsMod_Ref) {
test_reverse_lines(mods);
test_remove_words(mods);
println!();
println!(".-------------------------.");
println!("| tests succeeded! |");
println!("'-------------------------'");
}
fn test_reverse_lines(mods: TextOpsMod_Ref) {
let text_ops = mods;
let mut state = text_ops.new()();
assert_eq!(
&*text_ops.reverse_lines()(&mut state, "hello\nbig\nworld".into()),
"world\nbig\nhello\n"
);
}
fn test_remove_words(mods: TextOpsMod_Ref) {
let text_ops = mods;
let mut state = text_ops.new()();
{
let words = &mut vec!["burrito", "like", "a"].into_iter().map(RCow::from);
let param = RemoveWords {
string: "Monads are like a burrito wrapper.".into(),
words: DynTrait::from_borrowing_ptr(words),
};
assert_eq!(
&*text_ops.remove_words()(&mut state, param),
"Monads are wrapper."
);
}
{
let words = &mut vec!["largest", "is"].into_iter().map(RCow::from);
let param = RemoveWords {
string: "The largest planet is jupiter.".into(),
words: DynTrait::from_borrowing_ptr(words),
};
assert_eq!(
&*text_ops.remove_words()(&mut state, param),
"The planet jupiter."
);
}
}
|
extern crate wiring1;
use wiring1::*;
const PIN_LED: i32 = 0;
const PIN_INPUT: i32 = 3;
fn main() {
println!("Hello, world!");
wiringPiSetup();
pinMode(PIN_LED, cffi::OUTPUT);
pinMode(PIN_INPUT, cffi::INPUT);
loop {
digitalWrite(PIN_LED, cffi::HIGH);
println!("input = {}", digitalRead(PIN_INPUT));
delay(500);
digitalWrite(PIN_LED, cffi::LOW);
println!("input = {}", digitalRead(PIN_INPUT));
delay(500);
}
}
|
use std::{
any::TypeId,
fmt::{Debug, Formatter, Result},
};
use super::event_type::EventType;
/// An Event is a struct of data that can be sent and recreated on the connected
/// remote host
pub trait Event<T: EventType>: EventClone<T> {
/// Whether the Event is guaranteed for eventual delivery to the remote
/// host.
fn is_guaranteed(&self) -> bool;
/// Writes the current Event into an outgoing packet's byte stream
fn write(&self, out_bytes: &mut Vec<u8>);
/// Gets a copy of the Event, encapsulated within an EventType enum
fn get_typed_copy(&self) -> T;
/// Gets the TypeId of the Event
fn get_type_id(&self) -> TypeId;
}
/// A Boxed Event must be able to clone itself
pub trait EventClone<T: EventType> {
/// Clone the Boxed Event
fn clone_box(&self) -> Box<dyn Event<T>>;
}
impl<Z: EventType, T: 'static + Event<Z> + Clone> EventClone<Z> for T {
fn clone_box(&self) -> Box<dyn Event<Z>> {
Box::new(self.clone())
}
}
impl<T: EventType> Clone for Box<dyn Event<T>> {
fn clone(&self) -> Box<dyn Event<T>> {
EventClone::clone_box(self.as_ref())
}
}
impl<T: EventType> Debug for Box<dyn Event<T>> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.write_str("Boxed Event")
}
}
|
fn main() {
logging::init_logging().expect("Unable to initialize logging");
logging::test_logging();
}
|
pub mod bakerbird;
pub mod naive;
|
use itertools::Itertools as _;
use std::{
collections::VecDeque,
io::{self, Read},
};
const START_MSG_DISTINCT_CHARS_COUNT: usize = 14;
fn main() -> io::Result<()> {
let mut offset = START_MSG_DISTINCT_CHARS_COUNT;
let mut stream: VecDeque<u8> = VecDeque::default();
let mut buf = [0; 4096];
let mut stdin = io::stdin();
loop {
let read = stdin.read(&mut buf)?;
if read == 0 {
break;
}
stream.extend(&buf[..read]);
while stream.len() >= START_MSG_DISTINCT_CHARS_COUNT {
if stream
.iter()
.take(START_MSG_DISTINCT_CHARS_COUNT)
.unique()
.count()
== START_MSG_DISTINCT_CHARS_COUNT
{
break;
}
stream.pop_front();
offset += 1;
}
}
println!("{offset}");
Ok(())
}
|
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::AuthenticationKey;
use libra_crypto::{
ed25519::{Ed25519PublicKey, Ed25519Signature},
multi_ed25519::{MultiEd25519PublicKey, MultiEd25519Signature},
traits::Signature,
HashValue,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, fmt};
// TODO: in the future, can tie these to the enum with https://github.com/rust-lang/rust/issues/60553
const ED25519_SCHEME: u8 = 0;
const MULTI_ED25519_SCHEME: u8 = 1;
pub struct AuthenticationKeyPreimage(pub Vec<u8>);
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum TransactionAuthenticator {
/// Single signature
Ed25519 {
public_key: Ed25519PublicKey,
signature: Ed25519Signature,
},
/// K-of-N multisignature
MultiEd25519 {
public_key: MultiEd25519PublicKey,
signature: MultiEd25519Signature,
},
// ... add more schemes here
}
impl TransactionAuthenticator {
/// Unique identifier for the signature scheme
pub fn scheme_id(&self) -> u8 {
match self {
Self::Ed25519 { .. } => ED25519_SCHEME,
Self::MultiEd25519 { .. } => MULTI_ED25519_SCHEME,
}
}
/// Create a single-signature ed25519 authenticator
pub fn ed25519(public_key: Ed25519PublicKey, signature: Ed25519Signature) -> Self {
Self::Ed25519 {
public_key,
signature,
}
}
/// Create a multisignature ed25519 authenticator
pub fn multi_ed25519(
public_key: MultiEd25519PublicKey,
signature: MultiEd25519Signature,
) -> Self {
Self::MultiEd25519 {
public_key,
signature,
}
}
/// Return Ok if the authenticator's public key matches its signature, Err otherwise
pub fn verify_signature(&self, message: &HashValue) -> Result<()> {
match self {
Self::Ed25519 {
public_key,
signature,
} => signature.verify(message, public_key),
Self::MultiEd25519 {
public_key,
signature,
} => signature.verify(message, public_key),
}
}
pub fn public_key_bytes(&self) -> Vec<u8> {
match self {
Self::Ed25519 { public_key, .. } => public_key.to_bytes().to_vec(),
Self::MultiEd25519 { public_key, .. } => public_key.to_bytes().to_vec(),
}
}
pub fn signature_bytes(&self) -> Vec<u8> {
match self {
Self::Ed25519 { signature, .. } => signature.to_bytes().to_vec(),
Self::MultiEd25519 { signature, .. } => signature.to_bytes().to_vec(),
}
}
/// Return bytes for (self.public_key | self.scheme_id). To create an account authentication
/// key, sha3 these bytes
// TODO: move AuthenticationKey to this file and make this private
pub fn compute_authentication_key_preimage(
mut public_key_bytes: Vec<u8>,
scheme_id: u8,
) -> AuthenticationKeyPreimage {
public_key_bytes.push(scheme_id);
AuthenticationKeyPreimage(public_key_bytes)
}
// TODO: move AuthenticationKey to this file to avoid try_from
fn preimage_to_authentication_key(preimage: &AuthenticationKeyPreimage) -> AuthenticationKey {
AuthenticationKey::try_from(HashValue::from_sha3_256(&preimage.0).to_vec()).unwrap()
}
pub fn authentication_key_preimage(&self) -> AuthenticationKeyPreimage {
Self::compute_authentication_key_preimage(
self.public_key_bytes().to_vec(),
self.scheme_id(),
)
}
/// Return bytes for (self.public_key | self.scheme_id)
pub fn ed25519_authentication_key_preimage(
public_key: &Ed25519PublicKey,
) -> AuthenticationKeyPreimage {
Self::compute_authentication_key_preimage(public_key.to_bytes().to_vec(), ED25519_SCHEME)
}
/// Return bytes for (self.public_key | self.scheme_id)
pub fn multi_ed25519_authentication_key_preimage(
public_key: &MultiEd25519PublicKey,
) -> AuthenticationKeyPreimage {
Self::compute_authentication_key_preimage(public_key.to_bytes(), MULTI_ED25519_SCHEME)
}
/// Return an authentication derived from this public key
pub fn ed25519_authentication_key(public_key: &Ed25519PublicKey) -> AuthenticationKey {
Self::preimage_to_authentication_key(&Self::compute_authentication_key_preimage(
public_key.to_bytes().to_vec(),
ED25519_SCHEME,
))
}
/// Return an authentication derived from this public key
pub fn multi_ed25519_authentication_key(
public_key: &MultiEd25519PublicKey,
) -> AuthenticationKey {
Self::preimage_to_authentication_key(&Self::compute_authentication_key_preimage(
public_key.to_bytes(),
MULTI_ED25519_SCHEME,
))
}
}
impl fmt::Display for TransactionAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"TransactionAuthenticator[scheme id: {}, public key: {}, signature: {}]",
self.scheme_id(),
hex::encode(&self.public_key_bytes()),
hex::encode(&self.signature_bytes())
)
}
}
|
use std::fmt::Display;
use num_traits::AsPrimitive;
use crate::{InputType, InputValueError};
pub fn maximum<T, N>(value: &T, n: N) -> Result<(), InputValueError<T>>
where
T: AsPrimitive<N> + InputType,
N: PartialOrd + Display + Copy + 'static,
{
if value.as_() <= n {
Ok(())
} else {
Err(format!(
"the value is {}, must be less than or equal to {}",
value.as_(),
n
)
.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_maximum() {
assert!(maximum(&99, 100).is_ok());
assert!(maximum(&100, 100).is_ok());
assert!(maximum(&101, 100).is_err());
}
}
|
use diesel::{pg, prelude::*, r2d2::ConnectionManager};
use failure::{Fallible, ResultExt};
use r2d2::{Pool, PooledConnection};
pub mod dao;
pub mod model;
pub mod pagination;
mod schema;
pub use self::dao::ApiDao;
pub use self::model::*;
pub use self::pagination::*;
pub type DB = pg::Pg;
pub type DBConn = pg::PgConnection;
pub type DBConnManager = ConnectionManager<DBConn>;
pub type DBPool = Pool<DBConnManager>;
pub type DBPooledConn = PooledConnection<DBConnManager>;
pub fn new_pool<Str: Into<String>>(database_url: Str) -> Fallible<DBPool> {
let manager = DBConnManager::new(database_url);
let pool = r2d2::Pool::new(manager)?;
Ok(pool)
}
pub fn get_connection(pool: &DBPool) -> Fallible<DBPooledConn> {
let connection = pool.get().context("database_connection_failure")?;
Ok(connection)
}
|
pub use crate::song::{
artist::Artist,
hash::{HashMd5, HashSha256},
hash_converter::Converter,
include_features::IncludeFeatures,
level::{Level, Levels},
song::Song,
song_with_snap::SongWithSnap,
songs::{SongFormat, Songs, SongsBuilder},
title::Title,
};
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::BlockThresholds;
use opendal::Operator;
use storages_common_cache::LoadParams;
use storages_common_table_meta::meta::BlockMeta;
use storages_common_table_meta::meta::Location;
use storages_common_table_meta::meta::SegmentInfo;
use storages_common_table_meta::meta::Statistics;
use storages_common_table_meta::meta::TableSnapshot;
use super::AbortOperation;
use crate::io::MetaReaders;
use crate::io::SegmentWriter;
use crate::io::TableMetaLocationGenerator;
use crate::sessions::TableContext;
use crate::statistics::reducers::reduce_block_metas;
use crate::statistics::reducers::reduce_statistics;
#[derive(Clone)]
pub struct Replacement {
pub(crate) original_block_loc: Location,
pub(crate) new_block_meta: Option<BlockMeta>,
}
pub type SegmentIndex = usize;
pub type BlockIndex = usize;
#[derive(Clone)]
pub struct BaseMutator {
pub(crate) mutations: HashMap<SegmentIndex, Vec<Replacement>>,
pub(crate) ctx: Arc<dyn TableContext>,
pub(crate) location_generator: TableMetaLocationGenerator,
pub(crate) data_accessor: Operator,
pub(crate) base_snapshot: Arc<TableSnapshot>,
pub(crate) thresholds: BlockThresholds,
}
impl BaseMutator {
pub fn try_create(
ctx: Arc<dyn TableContext>,
op: Operator,
location_generator: TableMetaLocationGenerator,
base_snapshot: Arc<TableSnapshot>,
thresholds: BlockThresholds,
) -> Result<Self> {
Ok(Self {
mutations: HashMap::new(),
ctx,
location_generator,
data_accessor: op,
base_snapshot,
thresholds,
})
}
pub fn add_mutation(
&mut self,
seg_idx: SegmentIndex,
original_block_loc: Location,
new_block_meta: Option<BlockMeta>,
) {
self.mutations
.entry(seg_idx)
.or_default()
.push(Replacement {
original_block_loc,
new_block_meta,
});
}
pub async fn generate_segments(&self) -> Result<(Vec<Location>, Statistics, AbortOperation)> {
let mut abort_operation = AbortOperation::default();
let segments = self.base_snapshot.segments.clone();
let mut segments_editor =
HashMap::<_, _, RandomState>::from_iter(segments.clone().into_iter().enumerate());
let schema = Arc::new(self.base_snapshot.schema.clone());
let segment_reader = MetaReaders::segment_info_reader(self.data_accessor.clone(), schema);
let seg_writer = SegmentWriter::new(&self.data_accessor, &self.location_generator);
// apply mutations
for (seg_idx, replacements) in self.mutations.clone() {
let segment = {
let (path, version) = &segments[seg_idx];
// Keep in mind that segment_info_read must need a schema
let load_params = LoadParams {
location: path.clone(),
len_hint: None,
ver: *version,
put_cache: true,
};
segment_reader.read(&load_params).await?
};
// collects the block locations of the segment being modified
let block_positions = segment
.blocks
.iter()
.enumerate()
.map(|(idx, meta)| (&meta.location, idx))
.collect::<HashMap<_, _>>();
// prepare the new segment
let mut new_segment = SegmentInfo::new(segment.blocks.clone(), segment.summary.clone());
// take away the blocks, they are being mutated
let mut block_editor = HashMap::<_, _, RandomState>::from_iter(
std::mem::take(&mut new_segment.blocks)
.into_iter()
.enumerate(),
);
for replacement in replacements {
let position = block_positions
.get(&replacement.original_block_loc)
.ok_or_else(|| {
ErrorCode::Internal(format!(
"block location not found {:?}",
&replacement.original_block_loc
))
})?;
if let Some(block_meta) = replacement.new_block_meta {
abort_operation.add_block(&block_meta);
block_editor.insert(*position, Arc::new(block_meta));
} else {
block_editor.remove(position);
}
}
// assign back the mutated blocks to segment
new_segment.blocks = block_editor.into_values().collect();
if new_segment.blocks.is_empty() {
// remove the segment if no blocks there
segments_editor.remove(&seg_idx);
} else {
// re-calculate the segment statistics
let new_summary = reduce_block_metas(&new_segment.blocks, self.thresholds)?;
new_segment.summary = new_summary;
// write down new segment
let new_segment_location = seg_writer.write_segment(new_segment).await?;
segments_editor.insert(seg_idx, new_segment_location.clone());
abort_operation.add_segment(new_segment_location.0);
}
}
// assign back the mutated segments to snapshot
let new_segments = segments_editor.into_values().collect::<Vec<_>>();
let mut new_segment_summaries = Vec::with_capacity(new_segments.len());
for (loc, ver) in &new_segments {
let params = LoadParams {
location: loc.clone(),
len_hint: None,
ver: *ver,
put_cache: true,
};
let seg = segment_reader.read(¶ms).await?;
new_segment_summaries.push(seg.summary.clone())
}
// update the summary of new snapshot
let new_summary = reduce_statistics(&new_segment_summaries)?;
Ok((new_segments, new_summary, abort_operation))
}
}
|
// Copyright 2021 Datafuse Labs.
//
// 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 crate::procedures::systems::ClusteringInformationProcedure;
use crate::procedures::systems::FuseBlockProcedure;
use crate::procedures::systems::FuseSegmentProcedure;
use crate::procedures::systems::FuseSnapshotProcedure;
use crate::procedures::systems::SearchTablesProcedure;
use crate::procedures::ProcedureFactory;
pub struct SystemProcedure;
impl SystemProcedure {
pub fn register(factory: &mut ProcedureFactory) {
factory.register(
"system$clustering_information",
Box::new(ClusteringInformationProcedure::try_create),
);
factory.register(
"system$fuse_snapshot",
Box::new(FuseSnapshotProcedure::try_create),
);
factory.register(
"system$fuse_segment",
Box::new(FuseSegmentProcedure::try_create),
);
factory.register(
"system$fuse_block",
Box::new(FuseBlockProcedure::try_create),
);
factory.register(
"system$search_tables",
Box::new(SearchTablesProcedure::try_create),
);
}
}
|
/*
* Copyright (C) 2020 Zixiao Han
*/
mod bitboard;
mod bitmask;
mod def;
mod eval;
mod hashtable;
mod mov_table;
mod prng;
mod search;
mod state;
mod simple_rnd;
mod time_control;
mod uci;
mod util;
mod zob_keys;
use prng::XorshiftPrng;
use state::State;
use search::SearchEngine;
use time_control::TimeCapacity;
use uci::{UciCommand, Rawmov};
use std::io::{self, prelude::*};
use std::thread;
use std::sync::mpsc;
use std::time;
use std::u128;
const DEFAULT_MAX_TIME: TimeCapacity = TimeCapacity {
main_time_millis: u128::MAX,
extra_time_millis: 0,
};
const DEFAULT_MAX_DEPTH: u8 = 128;
fn main() {
if 1u8 != 0b01 {
println!("only litte-endian systems are supported");
std::process::exit(0);
}
zob_keys::init();
bitmask::init();
let (sender, receiver) = mpsc::channel();
thread::spawn(move || {
let mut search_engine = SearchEngine::new(def::DEFAULT_HASH_SIZE_UNIT);
let mut state = State::new(uci::FEN_START_POS);
loop {
let command: String = receiver.recv().unwrap();
let uci_cmd_process_result = uci::process_uci_cmd(command.trim());
match uci_cmd_process_result {
UciCommand::SetHashSize(hash_size) => {
search_engine.set_hash_size(hash_size);
},
UciCommand::Position(fen_str, mov_list) => {
state = State::new(&fen_str);
if mov_list.is_empty() {
continue
}
for Rawmov { from, to, promo, origin_mov_str } in mov_list {
if !promo.is_empty() {
let promo_piece_code = if state.player == def::PLAYER_W {
match promo.as_str() {
"q" => def::WQ,
"r" => def::WR,
"b" => def::WB,
"n" => def::WN,
_ => panic!("invalid promo piece"),
}
} else {
match promo.as_str() {
"q" => def::BQ,
"r" => def::BR,
"b" => def::BB,
"n" => def::BN,
_ => panic!("invalid promo piece"),
}
};
state.do_mov(from, to, def::MOV_PROMO, promo_piece_code);
continue
}
let moving_piece = state.squares[from];
if def::is_k(moving_piece) && ["e1g1", "e1c1", "e8g8", "e8c8"].contains(&origin_mov_str.as_str()) {
state.do_mov(from, to, def::MOV_CAS, 0);
continue
}
if def::is_p(moving_piece) {
if to == state.enp_square {
state.do_mov(from, to, def::MOV_ENP, 0);
continue
} else if (from as isize - to as isize).abs() == 16 {
state.do_mov(from, to, def::MOV_CR_ENP, 0);
continue
}
}
state.do_mov(from, to, def::MOV_REG, 0);
}
},
UciCommand::StartSearchWithTime(time_millis) => {
let best_mov = search_engine.search(&mut state, time_control::calculate_time_capacity(time_millis, 1, 0), DEFAULT_MAX_DEPTH);
print_best_mov(best_mov);
},
UciCommand::StartSearchWithComplextTimeControl((w_time_info, b_time_info)) => {
let time_capacity = if state.player == def::PLAYER_W {
time_control::calculate_time_capacity(w_time_info.all_time_millis, w_time_info.moves_to_go, w_time_info.increment_millis)
} else {
time_control::calculate_time_capacity(b_time_info.all_time_millis, b_time_info.moves_to_go, b_time_info.increment_millis)
};
let best_mov = search_engine.search(&mut state, time_capacity, DEFAULT_MAX_DEPTH);
print_best_mov(best_mov);
},
UciCommand::StartSearchToDepth(depth) => {
let best_mov = search_engine.search(&mut state, DEFAULT_MAX_TIME, depth);
print_best_mov(best_mov);
},
UciCommand::StartSearchInfinite => {
let best_mov = search_engine.search(&mut state, DEFAULT_MAX_TIME, DEFAULT_MAX_DEPTH);
print_best_mov(best_mov);
},
UciCommand::Perft(depth) => {
let start_time = time::Instant::now();
let perft_val = search_engine.perft(&mut state, depth);
println!("depth {} perft {} time {} milliseconds", depth, perft_val, start_time.elapsed().as_millis());
},
UciCommand::PrintDebugInfo => {
println!("{}", &state);
},
UciCommand::Reset => {
search_engine.reset();
},
UciCommand::IgnoredOption => {},
UciCommand::Noop => {},
}
}
});
loop {
let mut input = String::new();
match io::stdin().lock().read_line(&mut input) {
Ok(_) => {},
Err(error) => panic!("uable to read input {}", error),
}
match input.trim() {
"stop" => {
unsafe {
search::ABORT_SEARCH = true;
}
},
"quit" => {
std::process::exit(0);
},
_ => {
sender.send(input).unwrap();
}
}
}
}
fn print_best_mov(best_mov: u32) {
println!("bestmove {}", util::format_mov(best_mov));
io::stdout().flush().ok();
}
|
//! Futures integration.
use crate::stream::Stream;
use crate::sync::Mutex;
use std::future::Future;
use std::mem;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
/// The state a stream future.
#[derive(Debug)]
enum FutureValue<T> {
Pending,
Ready(T),
Finished,
}
/// The storage of a stream future.
#[derive(Debug)]
struct StreamFutureStorage<T> {
value: FutureValue<T>,
waker: Option<Waker>,
}
impl<T> Default for StreamFutureStorage<T> {
fn default() -> Self {
StreamFutureStorage {
value: FutureValue::Pending,
waker: None,
}
}
}
/// A future that waits for a stream value.
///
/// This is created by `Stream::next`.
#[derive(Debug)]
pub struct StreamFuture<T> {
storage: Arc<Mutex<StreamFutureStorage<T>>>,
stream: Stream<T>,
}
impl<T: Clone + Send + 'static> StreamFuture<T> {
/// Creates a future that returns the next value sent to this stream.
pub(crate) fn new(stream: Stream<T>) -> Self {
let this = StreamFuture {
storage: Default::default(),
stream,
};
this.register_callback();
this
}
/// Registers the stream observer that will update this future.
fn register_callback(&self) {
let weak = Arc::downgrade(&self.storage);
self.stream.observe(move |val| {
if let Some(st) = weak.upgrade() {
let mut storage = st.lock();
storage.value = FutureValue::Ready(val.into_owned());
if let Some(waker) = storage.waker.take() {
waker.wake();
}
}
false
});
}
/// Obtains the source stream.
#[inline]
pub fn get_source(&self) -> &Stream<T> {
&self.stream
}
/// Reuses a finished future so it can wait for another value.
///
/// Normally calling `poll` on a future after it returned `Poll::Ready` will panic.
/// This method will restart this future so it can be polled again for another value.
/// This allows awaiting for multiple values without having to create and allocate multiple
/// future objects.
///
/// Calling this on a pending (or ready but unread) future will have no effect.
pub fn reload(&self) {
let mut storage = self.storage.lock();
if let FutureValue::Finished = storage.value {
*storage = Default::default();
self.register_callback();
}
}
}
impl<T> Future for StreamFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
let mut storage = self.storage.lock();
match mem::replace(&mut storage.value, FutureValue::Pending) {
FutureValue::Ready(value) => {
storage.value = FutureValue::Finished;
Poll::Ready(value)
}
FutureValue::Pending => {
storage.waker = Some(ctx.waker().clone());
Poll::Pending
}
FutureValue::Finished => {
storage.value = FutureValue::Finished;
panic!("future polled again after completion");
}
}
}
}
impl<T> Unpin for StreamFuture<T> {}
#[cfg(test)]
mod tests {
use super::*;
use crate::stream::Sink;
use futures::executor::block_on;
#[test]
fn basic() {
let sink = Sink::new();
let future = StreamFuture::new(sink.stream());
sink.send(42);
sink.send(13);
assert_eq!(block_on(future), 42);
}
#[test]
#[should_panic]
fn invalid_poll() {
let sink = Sink::new();
let mut future = StreamFuture::new(sink.stream());
sink.send(42);
let _a = block_on(&mut future);
let _b = block_on(&mut future);
}
#[test]
fn reload() {
let sink = Sink::new();
let mut future = StreamFuture::new(sink.stream());
sink.send(42);
assert_eq!(block_on(&mut future), 42);
future.reload();
sink.send(13);
assert_eq!(block_on(&mut future), 13);
}
}
|
use idroid::geometry::plane::Plane;
use idroid::{node::ImageNodeBuilder, node::ImageViewNode, MVPUniformObj};
use nalgebra_glm as glm;
use wgpu::Extent3d;
use zerocopy::{AsBytes, FromBytes};
pub struct SDFRenderNode {
extent: Extent3d,
scale: f32,
view_node: ImageViewNode,
mvp_buf: MVPUniformObj,
}
#[repr(C)]
#[derive(Clone, Copy, AsBytes, FromBytes)]
pub struct DrawUniform {
stroke_color: [f32; 4],
mask_n_gamma: [f32; 2],
padding: [f32; 58],
}
impl SDFRenderNode {
pub fn new(
app_view: &idroid::AppView, device: &wgpu::Device, src_view: &wgpu::TextureView,
extent: Extent3d,
) -> Self {
let sampler = idroid::load_texture::bilinear_sampler(device);
let shader_stages =
[wgpu::ShaderStage::VERTEX, wgpu::ShaderStage::FRAGMENT, wgpu::ShaderStage::FRAGMENT]
.to_vec();
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
let mvp_buf = idroid::MVPUniformObj::new((&app_view.sc_desc).into(), device, &mut encoder);
// Create the vertex and index buffers
let (vertex_data, index_data) = Plane::new(1, 1).generate_vertices();
let dynamic_buf = idroid::BufferObj::create_uniforms_buffer(
device,
&[
DrawUniform {
stroke_color: [0.14, 0.14, 0.14, 1.0],
mask_n_gamma: [0.70, 0.0],
padding: [0.0; 58],
},
DrawUniform {
stroke_color: [0.97, 0.92, 0.80, 1.0],
mask_n_gamma: [0.75, 0.75],
padding: [0.0; 58],
},
],
Some("dynamic_buf")
);
let shader = idroid::shader2::create_shader_module(device, "text", None);
let builder =
ImageNodeBuilder::new(vec![(src_view, wgpu::TextureFormat::R32Float, None)], &shader)
.with_samplers(vec![&sampler])
.with_vertices_and_indices((vertex_data, index_data))
.with_shader_states(shader_stages)
.with_uniform_buffers(vec![&mvp_buf.buffer])
.with_dynamic_uniforms(vec![(&dynamic_buf, wgpu::ShaderStage::FRAGMENT)]);
let view_node = builder.build(device, &mut encoder);
app_view.queue.submit(Some(encoder.finish()));
SDFRenderNode { extent, scale: 1.0, view_node, mvp_buf }
}
pub fn update_scale(
&mut self, sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device,
encoder: &mut wgpu::CommandEncoder, scale: f32,
) {
let fovy: f32 = 75.0 / 180.0 * std::f32::consts::PI;
let radian: glm::TVec1<f32> = glm::vec1(fovy);
let p_matrix: glm::TMat4<f32> = glm::perspective_fov(
radian[0],
sc_desc.width as f32,
sc_desc.height as f32,
0.1,
100.0,
);
let mut vm_matrix = glm::TMat4::identity();
let sc_ratio = sc_desc.width as f32 / sc_desc.height as f32;
let tex_ratio = self.extent.width as f32 / self.extent.height as f32;
// maintain texture's aspect ratio
vm_matrix = glm::scale(&vm_matrix, &glm::vec3(1.0, 1.0 / tex_ratio, 1.0));
// when viewport's h > w, ratio = h / w, when w > h ,ratio = 1
let ratio = if sc_ratio < 1.0 { sc_desc.height as f32 / sc_desc.width as f32 } else { 1.0 };
// use fovy calculate z translate distance
let factor: f32 = (fovy / 2.0).tan();
// full fill viewport's width or height
let mut translate_z = -(ratio / factor);
if sc_ratio < tex_ratio {
if tex_ratio > 1.0 {
translate_z /= sc_ratio * ratio;
}
} else {
translate_z /= tex_ratio;
// when tex h > w and viewport h > w, need fill the viewport's height, and the height ration is not 1.0
if tex_ratio < 1.0 {
translate_z /= ratio;
};
}
vm_matrix = glm::translate(&vm_matrix, &glm::vec3(0.0, 0.0, translate_z));
self.scale *= scale;
vm_matrix = glm::scale(&vm_matrix, &glm::vec3(self.scale, self.scale, 1.0));
let mvp: [[f32; 4]; 4] = (p_matrix * vm_matrix).into();
self.mvp_buf.buffer.update_buffer(encoder, device, &mvp);
}
pub fn begin_render_pass(
&self, frame: &wgpu::SwapChainFrame, encoder: &mut wgpu::CommandEncoder,
) {
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &frame.output.view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(idroid::utils::clear_color()),
store: true,
},
}],
depth_stencil_attachment: None,
});
self.view_node.set_rpass(&mut rpass);
self.view_node.draw_rpass_by_offset(&mut rpass, 0, 1);
self.view_node.draw_rpass_by_offset(&mut rpass, 1, 1);
}
}
|
use crate::progenitor;
use crate::RoleAssignment;
use crate::ADMIN_ROLE_NAME;
use crate::AGENT_TO_ASSIGNMENT_LINK_TYPE;
use hdk::holochain_core_types::time::{Iso8601, Timeout};
use hdk::prelude::*;
use holochain_wasm_utils::api_serialization::get_entry::GetEntryResultItem;
use std::convert::TryFrom;
/**
* Validates that the agent that have signed this entry had the given role at the time they commited the entry
*/
pub fn validate_required_role(
validation_data: &hdk::ValidationData,
role_name: &String,
) -> Result<(), String> {
let agent_address = &validation_data.sources()[0];
let progenitor_address = progenitor::get_progenitor_address()?;
if role_name == crate::ADMIN_ROLE_NAME && progenitor_address == agent_address.clone() {
return Ok(());
}
let timestamp = &validation_data.package.chain_header.timestamp();
let entry_address = &validation_data.package.chain_header.entry_address();
match had_agent_role(&agent_address, &role_name, ×tamp)? {
true => Ok(()),
false => Err(format!(
"Agent {} did not have the role {} when committing entry {}",
agent_address, role_name, entry_address
)),
}
}
/**
* Returns whether the given agent had been assigned to a certain role in the given time
*/
pub fn had_agent_role(
agent_address: &Address,
role_name: &String,
timestamp: &Iso8601,
) -> ZomeApiResult<bool> {
let result_history = hdk::get_links_result(
&agent_address,
LinkMatch::Exactly(AGENT_TO_ASSIGNMENT_LINK_TYPE),
LinkMatch::Exactly(role_name),
GetLinksOptions::default(),
GetEntryOptions::new(StatusRequestKind::Initial, true, true, Timeout::default()),
)?;
let history: Vec<GetEntryResultItem> = result_history
.into_iter()
.filter_map(|item| match item {
Ok(i) => match i.result {
GetEntryResultType::Single(result) => Some(result),
_ => None,
},
_ => None,
})
.collect();
let maybe_item_index = history.iter().position(|item| {
let timestamps: Vec<&Iso8601> = item
.headers
.iter()
.map(|header| header.timestamp())
.collect();
let min = timestamps.iter().min();
match min {
Some(m) => m.clone() > timestamp,
None => false,
}
});
match maybe_item_index {
None => is_agent_assigned(history.last()),
Some(item_index) => {
let item = history.get(item_index - 1);
is_agent_assigned(item)
}
}
}
fn is_agent_assigned(maybe_item: Option<&GetEntryResultItem>) -> ZomeApiResult<bool> {
if let Some(item) = maybe_item {
if let Some(Entry::App(_, entry_content)) = item.clone().entry {
let role_assignment = RoleAssignment::try_from(entry_content)?;
return Ok(role_assignment.assigned);
}
}
return Ok(false);
}
/**
* Returns whether the given agent has been assigned to the given role
*/
pub fn has_agent_role(agent_address: &Address, role_name: &String) -> ZomeApiResult<bool> {
let role = RoleAssignment::initial(role_name.clone(), agent_address.clone());
let role_address = role.initial_address()?;
match hdk::get_entry(&role_address)? {
Some(Entry::App(_, entry_content)) => {
let role_assignment = RoleAssignment::try_from(entry_content)?;
Ok(role_assignment.assigned)
}
_ => Ok(false),
}
}
/**
* Returns whether the given agent is an administrator and, as such,
* can create, assign and unassign roles
*/
pub fn is_agent_admin(agent_address: &Address) -> ZomeApiResult<bool> {
let progenitor_address = progenitor::get_progenitor_address()?;
if progenitor_address == agent_address.clone() {
return Ok(true);
}
let result = has_agent_role(&agent_address, &String::from(ADMIN_ROLE_NAME))?;
Ok(result)
}
|
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CALLD0 {
#[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"Proxy"]
pub struct _HIB_CALLD0_SECW<'a> {
w: &'a mut W,
}
impl<'a> _HIB_CALLD0_SECW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(63 << 0);
self.w.bits |= ((value as u32) & 63) << 0;
self.w
}
}
#[doc = r"Proxy"]
pub struct _HIB_CALLD0_MINW<'a> {
w: &'a mut W,
}
impl<'a> _HIB_CALLD0_MINW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(63 << 8);
self.w.bits |= ((value as u32) & 63) << 8;
self.w
}
}
#[doc = r"Proxy"]
pub struct _HIB_CALLD0_HRW<'a> {
w: &'a mut W,
}
impl<'a> _HIB_CALLD0_HRW<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(31 << 16);
self.w.bits |= ((value as u32) & 31) << 16;
self.w
}
}
#[doc = r"Proxy"]
pub struct _HIB_CALLD0_AMPMW<'a> {
w: &'a mut W,
}
impl<'a> _HIB_CALLD0_AMPMW<'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 << 22);
self.w.bits |= ((value as u32) & 1) << 22;
self.w
}
}
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 = "Bits 0:5 - Seconds"]
#[inline(always)]
pub fn hib_calld0_sec(&mut self) -> _HIB_CALLD0_SECW {
_HIB_CALLD0_SECW { w: self }
}
#[doc = "Bits 8:13 - Minutes"]
#[inline(always)]
pub fn hib_calld0_min(&mut self) -> _HIB_CALLD0_MINW {
_HIB_CALLD0_MINW { w: self }
}
#[doc = "Bits 16:20 - Hours"]
#[inline(always)]
pub fn hib_calld0_hr(&mut self) -> _HIB_CALLD0_HRW {
_HIB_CALLD0_HRW { w: self }
}
#[doc = "Bit 22 - AM/PM Designation"]
#[inline(always)]
pub fn hib_calld0_ampm(&mut self) -> _HIB_CALLD0_AMPMW {
_HIB_CALLD0_AMPMW { w: self }
}
}
|
pub fn serve() {}
pub fn desk() {} |
// 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.
//! Helper builder for constructing a `CobaltEvent`.
use {
crate::traits::AsEventCodes,
fidl_fuchsia_cobalt::{CobaltEvent, CountEvent, EventPayload, HistogramBucket},
};
/// Adds the `builder()` method to `CobaltEvent`.
pub trait CobaltEventExt {
/// Returns a `CobaltEventBuilder` for the specified `metric_id`.
///
/// # Examples
///
/// ```
/// assert_eq!(CobaltEvent::builder(5).as_event().metric_id, 0);
/// ```
fn builder(metric_id: u32) -> CobaltEventBuilder;
}
impl CobaltEventExt for CobaltEvent {
fn builder(metric_id: u32) -> CobaltEventBuilder {
CobaltEventBuilder { metric_id, ..CobaltEventBuilder::default() }
}
}
/// CobaltEventBuilder allows for a chained construction of `CobaltEvent` objects.
#[derive(Debug, Default, Clone)]
pub struct CobaltEventBuilder {
metric_id: u32,
event_codes: Vec<u32>,
component: Option<String>,
}
impl CobaltEventBuilder {
/// Appends the provided `event_code` to the `event_codes` list.
///
/// # Examples
///
/// ```
/// assert_eq!(CobaltEvent::builder(6).with_event_code(10).as_event().event_codes, vec![10]);
/// ```
pub fn with_event_code(mut self, event_code: u32) -> CobaltEventBuilder {
self.event_codes.push(event_code);
self
}
/// Overrides the list of event_codes with the provided `event_codes`.
///
/// # Examples
///
/// ```
/// assert_eq!(
/// CobaltEvent::builder(7).with_event_codes([1, 2, 3]).as_event().event_codes,
/// vec![1,2,3]);
/// ```
pub fn with_event_codes<Codes: AsEventCodes>(
mut self,
event_codes: Codes,
) -> CobaltEventBuilder {
self.event_codes = event_codes.as_event_codes();
self
}
/// Writes an `event_code` to a particular `index`. This method is useful when not assigning
/// event codes in order.
///
/// # Examples
///
/// ```
/// assert_eq!(
/// CobaltEvent::builder(8).with_event_code_at(1, 10).as_event().event_codes,
/// vec![0, 10]);
/// ```
///
/// # Panics
///
/// Panics if the `value` is greater than or equal to 5.
pub fn with_event_code_at(mut self, index: usize, event_code: u32) -> CobaltEventBuilder {
assert!(
index < 5,
"Invalid index passed to CobaltEventBuilder::with_event_code. Cobalt events cannot support more than 5 event_codes."
);
while self.event_codes.len() <= index {
self.event_codes.push(0);
}
self.event_codes[index] = event_code;
self
}
/// Adds the provided `component` string to the resulting `CobaltEvent`.
///
/// # Examples
///
/// ```
/// assert_eq!(
/// CobaltEvent::builder(9).with_component("Comp").as_event.component,
/// Some("Comp".to_owned()));
/// ```
pub fn with_component<S: Into<String>>(mut self, component: S) -> CobaltEventBuilder {
self.component = Some(component.into());
self
}
/// Constructs a `CobaltEvent` with the provided `EventPayload`.
///
/// # Examples
/// ```
/// let payload = EventPayload::Event(fidl_fuchsia_cobalt::Event);
/// assert_eq!(CobaltEvent::builder(10).build(payload.clone()).payload, payload);
/// ```
pub fn build(self, payload: EventPayload) -> CobaltEvent {
CobaltEvent {
metric_id: self.metric_id,
event_codes: self.event_codes,
component: self.component,
payload,
}
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::Event`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(11).as_event().payload,
/// EventPayload::Event(fidl_fuchsia_cobalt::Event));
/// ```
pub fn as_event(self) -> CobaltEvent {
self.build(EventPayload::Event(fidl_fuchsia_cobalt::Event))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::EventCount`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(12).as_count_event(5, 10).payload,
/// EventPayload::EventCount(CountEvent { period_duration_micros: 5, count: 10 }));
/// ```
pub fn as_count_event(self, period_duration_micros: i64, count: i64) -> CobaltEvent {
self.build(EventPayload::EventCount(CountEvent { period_duration_micros, count }))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::ElapsedMicros`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(13).as_elapsed_time(30).payload,
/// EventPayload::ElapsedMicros(30));
/// ```
pub fn as_elapsed_time(self, elapsed_micros: i64) -> CobaltEvent {
self.build(EventPayload::ElapsedMicros(elapsed_micros))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::Fps`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(14).as_frame_rate(99.).payload,
/// EventPayload::Fps(99.));
/// ```
pub fn as_frame_rate(self, fps: f32) -> CobaltEvent {
self.build(EventPayload::Fps(fps))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::MemoryBytesUsed`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(15).as_memory_usage(1000).payload,
/// EventPayload::MemoryBytesUsed(1000));
/// ```
pub fn as_memory_usage(self, memory_bytes_used: i64) -> CobaltEvent {
self.build(EventPayload::MemoryBytesUsed(memory_bytes_used))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::StringEvent`.
///
/// # Examples
/// ```
/// asert_eq!(
/// CobaltEvent::builder(16).as_string_event("Event!").payload,
/// EventPayload::StringEvent("Event!".to_owned()));
/// ```
pub fn as_string_event<S: Into<String>>(self, string_event: S) -> CobaltEvent {
self.build(EventPayload::StringEvent(string_event.into()))
}
/// Constructs a `CobaltEvent` with a payload type of `EventPayload::IntHistogram`.
///
/// # Examples
/// ```
/// let histogram = vec![HistogramBucket { index: 0, count: 1 }];
/// asert_eq!(
/// CobaltEvent::builder(17).as_int_histogram(histogram.clone()).payload,
/// EventPayload::IntHistogram(histogram));
/// ```
pub fn as_int_histogram(self, int_histogram: Vec<HistogramBucket>) -> CobaltEvent {
self.build(EventPayload::IntHistogram(int_histogram))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_as_event() {
let event = CobaltEvent::builder(1).with_event_code(2).as_event();
let expected = CobaltEvent {
metric_id: 1,
event_codes: vec![2],
component: None,
payload: EventPayload::Event(fidl_fuchsia_cobalt::Event),
};
assert_eq!(event, expected);
}
#[test]
fn test_builder_as_count_event() {
let event =
CobaltEvent::builder(2).with_event_code(3).with_component("A").as_count_event(4, 5);
let expected = CobaltEvent {
metric_id: 2,
event_codes: vec![3],
component: Some("A".into()),
payload: EventPayload::EventCount(CountEvent { count: 5, period_duration_micros: 4 }),
};
assert_eq!(event, expected);
}
#[test]
fn test_as_elapsed_time() {
let event =
CobaltEvent::builder(3).with_event_code(4).with_component("B").as_elapsed_time(5);
let expected = CobaltEvent {
metric_id: 3,
event_codes: vec![4],
component: Some("B".into()),
payload: EventPayload::ElapsedMicros(5),
};
assert_eq!(event, expected);
}
#[test]
fn test_as_frame_rate() {
let event =
CobaltEvent::builder(4).with_event_code(5).with_component("C").as_frame_rate(6.);
let expected = CobaltEvent {
metric_id: 4,
event_codes: vec![5],
component: Some("C".into()),
payload: EventPayload::Fps(6.),
};
assert_eq!(event, expected);
}
#[test]
fn test_as_memory_usage() {
let event =
CobaltEvent::builder(5).with_event_code(6).with_component("D").as_memory_usage(7);
let expected = CobaltEvent {
metric_id: 5,
event_codes: vec![6],
component: Some("D".into()),
payload: EventPayload::MemoryBytesUsed(7),
};
assert_eq!(event, expected);
}
#[test]
fn test_as_string_event() {
let event = CobaltEvent::builder(6).as_string_event("String Value");
let expected = CobaltEvent {
metric_id: 6,
event_codes: vec![],
component: None,
payload: EventPayload::StringEvent("String Value".into()),
};
assert_eq!(event, expected);
}
#[test]
fn test_as_int_histogram() {
let event = CobaltEvent::builder(7)
.with_event_code(8)
.with_component("E")
.as_int_histogram(vec![HistogramBucket { index: 0, count: 1 }]);
let expected = CobaltEvent {
metric_id: 7,
event_codes: vec![8],
component: Some("E".into()),
payload: EventPayload::IntHistogram(vec![HistogramBucket { index: 0, count: 1 }]),
};
assert_eq!(event, expected);
}
#[test]
#[should_panic(expected = "Invalid index")]
fn test_bad_event_code_at_index() {
CobaltEvent::builder(8).with_event_code_at(5, 10).as_event();
}
#[test]
fn test_clone() {
let e = CobaltEvent::builder(102).with_event_code_at(1, 15);
assert_eq!(
e.clone().with_event_code_at(0, 10).as_string_event("Event 1"),
CobaltEvent {
metric_id: 102,
event_codes: vec![10, 15],
component: None,
payload: EventPayload::StringEvent("Event 1".to_owned())
}
);
assert_eq!(
e.with_event_code_at(0, 11).as_string_event("Event 2"),
CobaltEvent {
metric_id: 102,
event_codes: vec![11, 15],
component: None,
payload: EventPayload::StringEvent("Event 2".to_owned())
}
);
}
}
|
// 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 {
fidl_fuchsia_wlan_service::WlanMarker, fuchsia_component::client::connect_to_service,
wlan_common::mac::Bssid,
wlan_hw_sim::*,
};
/// Test a client can connect to a network protected by WPA2-PSK by simulating an AP that
/// authenticates, associates, as well as initiating and completing EAPOL exchange.
/// In this test, no data is being sent after the link becomes up.
#[fuchsia_async::run_singlethreaded(test)]
async fn connect_to_wpa2_network() {
const BSS: Bssid = Bssid(*b"wpa2ok");
const SSID: &[u8] = b"wpa2ssid";
let wlan_service = connect_to_service::<WlanMarker>().expect("Connect to WLAN service");
let mut helper = test_utils::TestHelper::begin_test(default_wlantap_config_client()).await;
let () = loop_until_iface_is_found().await;
let phy = helper.proxy();
let () = connect(&wlan_service, &phy, &mut helper, SSID, &BSS, Some(&"wpa2good")).await;
let status = wlan_service.status().await.expect("getting wlan status");
let is_protected = true;
assert_associated_state(status, &BSS, SSID, &CHANNEL, is_protected);
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use anyhow::*;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::iolist_or_binary;
#[native_implemented::function(erlang:list_to_binary/1)]
pub fn result(process: &Process, iolist: Term) -> exception::Result<Term> {
match iolist.decode()? {
TypedTerm::Nil | TypedTerm::List(_) => {
iolist_or_binary::to_binary(process, "iolist", iolist)
}
_ => Err(TypeError)
.context(format!("iolist ({}) is not a list", iolist))
.map_err(From::from),
}
}
|
use super::*;
use std::ops::{Deref, DerefMut};
pub(super) struct BinaryTree<L> {
pub(super) left: Option<L>,
pub(super) right: Option<L>
}
impl<L> BinaryTree<L>
{
fn make_fan(depth: usize) -> Self
where
L: NewLink<Self>
{
let mut fan = Self { left: None, right: None };
if depth > 0 {
fan.left = Some(L::new(Self::make_fan(depth.saturating_sub(1))));
fan.right = Some(L::new(Self::make_fan(depth.saturating_sub(1))));
}
fan
}
}
impl<L> DeepSafeDrop<L> for BinaryTree<L>
{
fn take_first_child(&mut self) -> Option<L> {
self.left.take()
}
fn replace_first_child_with_parent(&mut self, parent: L)
-> ReplacedFirstChild<L>
{
if let Some(child) = self.left.take() {
self.left = Some(parent);
ReplacedFirstChild::Yes { first_child: child }
} else {
ReplacedFirstChild::No { returned_parent: parent }
}
}
fn take_next_child(&mut self) -> Option<L> {
self.right.take()
}
}
#[test]
fn exercise()
{
use std::convert::TryInto;
struct BinaryTreeBox (Box<BinaryTree<Self>>);
impl NewLink<BinaryTree<Self>> for BinaryTreeBox {
fn new(tree: BinaryTree<Self>) -> Self {
Self(Box::new(tree))
}
}
impl Deref for BinaryTreeBox {
type Target = BinaryTree<Self>;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl DerefMut for BinaryTreeBox {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.0
}
}
impl Drop for BinaryTreeBox {
fn drop(&mut self) {
deep_safe_drop(&mut **self);
}
}
fn fan_depth(size: usize) -> usize {
fn log2(x: usize) -> u32 {
(usize::BITS - 1) - x.leading_zeros()
}
assert!(0 < size && size < usize::MAX);
#[allow(clippy::expect_used)]
(log2(size + 1) - 1).try_into().expect("impossible")
}
let fan = BinaryTree::<BinaryTreeBox>::make_fan(fan_depth(TREE_SIZE));
drop(fan);
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TXCSRL2 {
#[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() -> u8 {
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 USB_TXCSRL2_TXRDYR {
bits: bool,
}
impl USB_TXCSRL2_TXRDYR {
#[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 _USB_TXCSRL2_TXRDYW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_TXRDYW<'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 u8) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_FIFONER {
bits: bool,
}
impl USB_TXCSRL2_FIFONER {
#[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 _USB_TXCSRL2_FIFONEW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_FIFONEW<'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 u8) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_ERRORR {
bits: bool,
}
impl USB_TXCSRL2_ERRORR {
#[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 _USB_TXCSRL2_ERRORW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_ERRORW<'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 u8) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_FLUSHR {
bits: bool,
}
impl USB_TXCSRL2_FLUSHR {
#[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 _USB_TXCSRL2_FLUSHW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_FLUSHW<'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 u8) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_SETUPR {
bits: bool,
}
impl USB_TXCSRL2_SETUPR {
#[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 _USB_TXCSRL2_SETUPW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_SETUPW<'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 u8) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_STALLEDR {
bits: bool,
}
impl USB_TXCSRL2_STALLEDR {
#[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 _USB_TXCSRL2_STALLEDW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_STALLEDW<'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 u8) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_CLRDTR {
bits: bool,
}
impl USB_TXCSRL2_CLRDTR {
#[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 _USB_TXCSRL2_CLRDTW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_CLRDTW<'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 u8) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_NAKTOR {
bits: bool,
}
impl USB_TXCSRL2_NAKTOR {
#[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 _USB_TXCSRL2_NAKTOW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_NAKTOW<'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 u8) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_UNDRNR {
bits: bool,
}
impl USB_TXCSRL2_UNDRNR {
#[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 _USB_TXCSRL2_UNDRNW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_UNDRNW<'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 u8) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct USB_TXCSRL2_STALLR {
bits: bool,
}
impl USB_TXCSRL2_STALLR {
#[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 _USB_TXCSRL2_STALLW<'a> {
w: &'a mut W,
}
impl<'a> _USB_TXCSRL2_STALLW<'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 u8) & 1) << 4;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bit 0 - Transmit Packet Ready"]
#[inline(always)]
pub fn usb_txcsrl2_txrdy(&self) -> USB_TXCSRL2_TXRDYR {
let bits = ((self.bits >> 0) & 1) != 0;
USB_TXCSRL2_TXRDYR { bits }
}
#[doc = "Bit 1 - FIFO Not Empty"]
#[inline(always)]
pub fn usb_txcsrl2_fifone(&self) -> USB_TXCSRL2_FIFONER {
let bits = ((self.bits >> 1) & 1) != 0;
USB_TXCSRL2_FIFONER { bits }
}
#[doc = "Bit 2 - Error"]
#[inline(always)]
pub fn usb_txcsrl2_error(&self) -> USB_TXCSRL2_ERRORR {
let bits = ((self.bits >> 2) & 1) != 0;
USB_TXCSRL2_ERRORR { bits }
}
#[doc = "Bit 3 - Flush FIFO"]
#[inline(always)]
pub fn usb_txcsrl2_flush(&self) -> USB_TXCSRL2_FLUSHR {
let bits = ((self.bits >> 3) & 1) != 0;
USB_TXCSRL2_FLUSHR { bits }
}
#[doc = "Bit 4 - Setup Packet"]
#[inline(always)]
pub fn usb_txcsrl2_setup(&self) -> USB_TXCSRL2_SETUPR {
let bits = ((self.bits >> 4) & 1) != 0;
USB_TXCSRL2_SETUPR { bits }
}
#[doc = "Bit 5 - Endpoint Stalled"]
#[inline(always)]
pub fn usb_txcsrl2_stalled(&self) -> USB_TXCSRL2_STALLEDR {
let bits = ((self.bits >> 5) & 1) != 0;
USB_TXCSRL2_STALLEDR { bits }
}
#[doc = "Bit 6 - Clear Data Toggle"]
#[inline(always)]
pub fn usb_txcsrl2_clrdt(&self) -> USB_TXCSRL2_CLRDTR {
let bits = ((self.bits >> 6) & 1) != 0;
USB_TXCSRL2_CLRDTR { bits }
}
#[doc = "Bit 7 - NAK Timeout"]
#[inline(always)]
pub fn usb_txcsrl2_nakto(&self) -> USB_TXCSRL2_NAKTOR {
let bits = ((self.bits >> 7) & 1) != 0;
USB_TXCSRL2_NAKTOR { bits }
}
#[doc = "Bit 2 - Underrun"]
#[inline(always)]
pub fn usb_txcsrl2_undrn(&self) -> USB_TXCSRL2_UNDRNR {
let bits = ((self.bits >> 2) & 1) != 0;
USB_TXCSRL2_UNDRNR { bits }
}
#[doc = "Bit 4 - Send STALL"]
#[inline(always)]
pub fn usb_txcsrl2_stall(&self) -> USB_TXCSRL2_STALLR {
let bits = ((self.bits >> 4) & 1) != 0;
USB_TXCSRL2_STALLR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Transmit Packet Ready"]
#[inline(always)]
pub fn usb_txcsrl2_txrdy(&mut self) -> _USB_TXCSRL2_TXRDYW {
_USB_TXCSRL2_TXRDYW { w: self }
}
#[doc = "Bit 1 - FIFO Not Empty"]
#[inline(always)]
pub fn usb_txcsrl2_fifone(&mut self) -> _USB_TXCSRL2_FIFONEW {
_USB_TXCSRL2_FIFONEW { w: self }
}
#[doc = "Bit 2 - Error"]
#[inline(always)]
pub fn usb_txcsrl2_error(&mut self) -> _USB_TXCSRL2_ERRORW {
_USB_TXCSRL2_ERRORW { w: self }
}
#[doc = "Bit 3 - Flush FIFO"]
#[inline(always)]
pub fn usb_txcsrl2_flush(&mut self) -> _USB_TXCSRL2_FLUSHW {
_USB_TXCSRL2_FLUSHW { w: self }
}
#[doc = "Bit 4 - Setup Packet"]
#[inline(always)]
pub fn usb_txcsrl2_setup(&mut self) -> _USB_TXCSRL2_SETUPW {
_USB_TXCSRL2_SETUPW { w: self }
}
#[doc = "Bit 5 - Endpoint Stalled"]
#[inline(always)]
pub fn usb_txcsrl2_stalled(&mut self) -> _USB_TXCSRL2_STALLEDW {
_USB_TXCSRL2_STALLEDW { w: self }
}
#[doc = "Bit 6 - Clear Data Toggle"]
#[inline(always)]
pub fn usb_txcsrl2_clrdt(&mut self) -> _USB_TXCSRL2_CLRDTW {
_USB_TXCSRL2_CLRDTW { w: self }
}
#[doc = "Bit 7 - NAK Timeout"]
#[inline(always)]
pub fn usb_txcsrl2_nakto(&mut self) -> _USB_TXCSRL2_NAKTOW {
_USB_TXCSRL2_NAKTOW { w: self }
}
#[doc = "Bit 2 - Underrun"]
#[inline(always)]
pub fn usb_txcsrl2_undrn(&mut self) -> _USB_TXCSRL2_UNDRNW {
_USB_TXCSRL2_UNDRNW { w: self }
}
#[doc = "Bit 4 - Send STALL"]
#[inline(always)]
pub fn usb_txcsrl2_stall(&mut self) -> _USB_TXCSRL2_STALLW {
_USB_TXCSRL2_STALLW { w: self }
}
}
|
use crate::pesel_parsing_error::PeselError;
use std::str::FromStr;
use rand::Rng;
use rand::prelude::ThreadRng;
const PESEL_LENGTH: usize = 11;
/// Enum to represent Male/Female
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum PeselGender {
Male,
Female,
}
impl std::fmt::Display for PeselGender {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let gender_name = match *self {
PeselGender::Female => "female",
PeselGender::Male => "male",
};
write!(f, "{}", gender_name)
}
}
#[derive(Debug)]
pub struct PESEL {
raw: String, // raw PESEL as &str
yob: u8, // year of birth
mob: u8, // month of birth, codes century as well (could cover 5 centuries)
dob: u8, // day of birth
gender: PeselGender, // biological gender
checksum: u8, // checksum used for validation
is_valid: bool, // true if checksum == algorithmic PESEL validation?
}
impl PESEL {
/// Tries to create new PESEL strucutre based on:
/// - birth date (could be in the future!)
/// - biological gender
///
/// Returns Result<PESEL, PeselError>
/// When PeselError is returned it is mainly due to the fact that provided date of birth is invalid: for example 30th of February, 31st of April etc., or date is out range for PESEL (earlier than 1800 or after 2299)
///
/// Example:
/// ```rust
/// use pesel::pesel::{PESEL as PESEL, PeselGender};
///
/// // some code here...
///
/// let result = PESEL::new(1981, 05, 29, PeselGender::Female);
/// match result {
/// Ok(pesel) => println!("generated PESEL: {}", pesel),
/// _ => println!("unable to create PESEL for specified date"),
/// }
/// ```
/// Returned PESEL structure is valid (i.e. passes validation algorithm check - `new_pesel.is_valid` should always return `true`
pub fn new(year: u16, month: u8, day: u8, pesel_gender: PeselGender) -> Result<PESEL, PeselError> {
if ! PESEL::is_date_in_range(year as i32) {
return Err(PeselError::new(PeselError::DoBOutOfRange));
}
if ! PESEL::is_valid_date( year as i32, month as u32, day as u32) {
return Err(PeselError::new(PeselError::InvalidDoB));
}
let pesel_year = year % 100;
let pesel_month = month + PESEL::calc_month_century_offset(year);
let mut rng = rand::thread_rng();
let (random1, random2, random3) = PESEL::generate_random_values(&mut rng);
let gender = PESEL::generate_gender_digit(pesel_gender, &mut rng);
let pesel_string = format!("{:02}{:02}{:02}{:1}{:1}{:1}{:1}", pesel_year, pesel_month, day, random1, random2, random3, gender);
let checksum = PESEL::calc_checksum_from_pesel_string(&pesel_string);
PESEL::from_str(format!("{}{:1}", &pesel_string, checksum).as_str())
}
}
impl FromStr for PESEL {
type Err = PeselError;
/// This method implements parsing 11 character long string, containing only digits into PESEL number.
/// There are some checks performed:
/// - length of the string provided (11 characters)
/// - all characters have to be digits
/// - birth year must be between 1800 and 2299
/// - day should not exceed 31
/// - month should be of range 1..12
///
/// Important note: as this function could be used to build a PESEL structure retrieved from database - no algorithm validity check against PESEL number is performed. This is due to the fact that some PESEL numbers in use were not generated correctly (but are recognized by State as valid ones).
///
/// Example of use:
///
/// ```rust
/// use std::str::FromStr;
/// use pesel::pesel::{PESEL as PESEL, PeselGender};
///
/// // some code here...
///
/// let pesel_number ="44051401458".to_string();
/// let pesel = PESEL::from_str(pesel_number.as_str());
/// match pesel {
/// Ok(t) => println!("{}", t),
/// _ => panic!("invalid PESEL provided")
/// }
/// ```
///
/// In case an error occrus `PeselError` with apropriate message is being returned. This may happen when:
/// - string is not of expected length (11 characters)
/// - not all characters inside string are digits
/// - year of birth is out of range
/// - birth date is incorrect (i.e. 30th of February, 31st of April...
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != PESEL_LENGTH {
return Err(PeselError::new(PeselError::SizeError));
}
if s.chars().any(|f| !f.is_ascii_digit()) {
return Err(PeselError::new(PeselError::BadFormat));
}
// do not automatically validate PESEL struct and return Err if it doesn't pass validation check. Some PESEL numbers in Poland (still in use) have been generated incorrectly (probably database with exceptions is used).
let checksum = s[10..11].parse::<u8>().unwrap();
let gender = s[9..10].parse::<u8>().unwrap();
let yob = s[0..2].parse::<u8>().unwrap();
let mob = s[2..4].parse::<u8>().unwrap();
let dob = s[4..6].parse::<u8>().unwrap();
let real_year = PESEL::calc_year_from_pesel_encoded_month_and_year(yob, mob);
if ! PESEL::is_date_in_range(real_year) {
return Err(PeselError::new(PeselError::DoBOutOfRange));
}
if ! PESEL::is_valid_date( real_year, (mob % 20) as u32, dob as u32) {
return Err(PeselError::new(PeselError::InvalidDoB));
}
let calculated_checksum = PESEL::calc_checksum_from_pesel_string(&s);
let pesel_is_valid = calculated_checksum == checksum;
let real_gender = match gender %2 == 0 {
true => PeselGender::Female,
false => PeselGender::Male,
};
Ok(PESEL{
raw: s.clone().to_string(),
yob,
mob,
dob,
gender: real_gender,
checksum,
is_valid: pesel_is_valid,
})
}
}
impl std::fmt::Display for PESEL {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "PESEL: {}\n\
date of birth: {}\n\
gender: {}\n\
valid: {}", self.raw, self.date_of_birth(), self.gender_name(), self.is_valid())
}
}
impl PESEL {
/// Utility function - checks if date is within PESEL system range
fn is_date_in_range(year: i32) -> bool {
match year < 1800 || year > 2299 {
true => false,
false => true
}
}
/// Utility function - checks if date is valid
fn is_valid_date(year: i32, month: u32, day: u32) -> bool {
use chrono::prelude::*;
let date = Local.ymd_opt(year, month, day);
date != chrono::offset::LocalResult::None
}
/// Utility function - returns triple of random u8s (this is needed to fill some extra space being part of PESEL number
fn generate_random_values(rng: &mut ThreadRng) -> (u8, u8, u8) {
let random1 = rng.gen_range(0, 10) as u8;
let random2 = rng.gen_range(0, 10) as u8;
let random3 = rng.gen_range(0, 10) as u8;
(random1, random2, random3)
}
/// Utility function - calculates offset to be added to month to code a century person has been born in
fn calc_month_century_offset(year: u16) -> u8 {
let century = match year {
1800..=1899 => 80,
1900..=1999 => 0,
2000..=2099 => 20,
2100..=2199 => 40,
2200..=2299 => 60,
_ => 0,
};
century
}
fn calc_year_from_pesel_encoded_month_and_year(year: u8, month: u8) -> i32 {
year as i32 + match month {
1..=12 => 1900,
20..=32 => 2000,
40..=52 => 2100,
60..=72 => 2200,
80..=92 => 1800,
_ => 0,
}
}
/// Utility function - returns digit corresponding to biological gender.
/// Odd - represents man
/// Even - represents woman
fn generate_gender_digit(pesel_gender: PeselGender, rng: &mut ThreadRng) -> u8 {
let women = vec![0, 2, 4, 6, 8];
let men = vec![1, 3, 5, 7, 9];
let gender = match pesel_gender {
PeselGender::Male => men[rng.gen_range(0, 5)] as u8,
PeselGender::Female => women[rng.gen_range(0, 5)] as u8,
};
gender
}
/// Utility function - calculates checksum directly from PESEL string
fn calc_checksum_from_pesel_string(pesel_string: &str) -> u8 {
let (a, b, c, d, e, f, g, h, i, j) = PESEL::extract_pesel_factors(pesel_string);
PESEL::calc_checksum(a, b, c, d, e, f, g, h, i, j)
}
/// Utility function - calculates checksum when given all the factors as parameters
fn calc_checksum(a: u8, b: u8, c:u8, d:u8, e:u8, f:u8, g:u8, h:u8, i:u8, j:u8) -> u8 {
let sum:u16 = 9 * a as u16 +
7 * b as u16 +
3 * c as u16 +
d as u16 +
9 * e as u16 +
7 * f as u16 +
3 * g as u16 +
h as u16 +
9 * i as u16 +
7 * j as u16;
(sum % 10) as u8
}
/// Utility function - extracts all factors (a..j) from a string representing PESEL
fn extract_pesel_factors(pesel_string: &str) -> (u8, u8, u8, u8, u8, u8, u8, u8, u8, u8) {
let mut all_chars = pesel_string.chars();
let a = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let b = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let c = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let d = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let e = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let f = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let g = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let h = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let i = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
let j = all_chars.next().unwrap().to_digit(10).unwrap() as u8;
(a, b, c, d, e, f, g, h, i, j)
}
/// Checks if PESEL number is properly generated - i.e. if algorithmic check on all fields is equal to checksum (which is a part of PESEL number)
///
/// PESEL validation algorithm is as follows:
/// 1. PESEL number is 11 digits, last one is checksum. This gives 10 digits.
/// 2. The digits are usually called a, b, c, d, e, f, g, h, i, j
/// 3. First step is to calculate special sum of all digits except checksum as follows:
/// 9*a + 7*b + 3*c + d + 9*e + 7*f + 3*g + h + 9*i + 7*j
/// 4. The sum calculated above modulo 10 should be equal to checksum
///
/// Please note that some PESEL numbers that are in use in Poland are not properly generated, and thus this check may fail for a PESEL number that is officially used.
/// Note: this value is precomputed
pub fn is_valid(&self) -> bool {
self.is_valid
}
/// Returns biological gender as PeselGender enum
pub fn gender(&self) -> PeselGender {
self.gender
}
/// Returns date of birth as chrono::Date
pub fn date_of_birth(&self) -> chrono::Date<chrono::Local> {
let century:u16 = match self.mob {
0..=12 => 1900,
20..=32 => 2000,
40..=52 => 2100,
60..=72 => 2200,
80..=92 => 1800,
_ => panic!("invalid PESEL")
};
let year :u16 = self.yob as u16 + century;
let month = self.mob;
let day = self.dob;
use chrono::prelude::*;
Local.ymd_opt(year as i32, month as u32, day as u32).unwrap()
}
// Returns description of a biological gender of a person assigned PESEL number
pub fn gender_name(&self) -> String {
self.gender().to_string()
}
pub fn pesel_number(&self) -> String {
self.raw.clone()
}
}
#[cfg(test)]
mod pesel_parsing_tests {
use std::str::FromStr;
use crate::pesel_parsing_error::PeselError;
#[test]
fn zero_length_string_should_fail() {
let pesel = super::PESEL::from_str("");
assert_eq!(true, pesel.is_err());
assert_eq!(super::PeselError::new(PeselError::SizeError), pesel.err().unwrap());
}
#[test]
fn pesel_may_only_contain_digits() {
let pesel = super::PESEL::from_str("4405140145a");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::BadFormat), pesel.unwrap_err());
}
#[test]
fn input_longer_than_11_digits_should_fail() {
let pesel = super::PESEL::from_str("800526199869");
assert_eq!(true, pesel.is_err());
assert_eq!(super::PeselError::new(PeselError::SizeError), pesel.err().unwrap());
}
#[test]
fn input_shorter_than_11_digits_should_fail() {
let pesel = super::PESEL::from_str("8005261998");
assert_eq!(true, pesel.is_err());
assert_eq!(super::PeselError::new(PeselError::SizeError), pesel.err().unwrap());
}
}
#[cfg(test)]
mod pesel_base_tests {
use std::str::FromStr;
use crate::pesel::PeselGender;
#[test]
fn building_pesel_from_string() {
let pesel_input = "44051401458";
let pesel = super::PESEL::from_str(pesel_input).unwrap();
assert_eq!(pesel.raw, pesel_input);
assert_eq!(pesel.yob, 44);
assert_eq!(pesel.mob, 05);
assert_eq!(pesel.dob, 14);
}
#[test]
fn check_if_is_male() {
let pesel = super::PESEL::from_str("44051401458").unwrap();
assert_eq!("male", pesel.gender_name());
assert_eq!(super::PeselGender::Male, pesel.gender());
}
#[test]
fn check_if_is_female() {
let pesel = super::PESEL::from_str("44051401468").unwrap();
assert_eq!("female", pesel.gender_name());
assert_eq!(super::PeselGender::Female, pesel.gender());
}
#[test]
fn proper_pesel_should_be_validated() {
let pesel = super::PESEL::from_str("44051401458").unwrap();
assert_eq!(true, pesel.is_valid());
}
#[test]
fn invalid_pesel_should_not_be_validated() {
let pesel = super::PESEL::from_str("44051401459").unwrap();
assert_eq!(false, pesel.is_valid());
}
#[test]
fn pesel_from_number_that_fails_on_checksum_should_have_is_valid_set_to_false() {
let pesel = super::PESEL::from_str("44051401459");
let result = match pesel {
Ok(t) => Some(t),
Err(_e) => None,
};
assert_eq!(false, result.unwrap().is_valid());
}
#[test]
fn generated_pesel_should_be_valid() {
let pesel = super::PESEL::new(1981, 06, 27, PeselGender::Female).unwrap();
assert_eq!(true, pesel.is_valid());
}
#[test]
fn generated_pesel_should_have_proper_gender_set() {
let pesel = super::PESEL::new(1981, 06, 27, PeselGender::Female).unwrap();
assert_eq!("female", pesel.gender_name());
assert_eq!(PeselGender::Female, pesel.gender());
assert_ne!("male", pesel.gender_name());
assert_ne!(PeselGender::Male, pesel.gender());
}
#[test]
fn generated_pesel_should_have_proper_gender_set2() {
let pesel = super::PESEL::new(1981, 06, 27, PeselGender::Male).unwrap();
assert_eq!("male", pesel.gender_name());
assert_eq!(PeselGender::Male, pesel.gender());
assert_ne!("female", pesel.gender_name());
assert_ne!(PeselGender::Female, pesel.gender());
}
#[test]
fn pesel_number_stored_should_be_accessible() {
let input = "44051401468";
let pesel = super::PESEL::from_str(input).unwrap();
assert_eq!(input.to_string(), pesel.pesel_number());
}
}
#[cfg(test)]
mod pesel_date_tests {
use std::str::FromStr;
use crate::pesel::PeselGender;
use crate::pesel_parsing_error::PeselError;
#[test]
fn pesel_should_have_proper_century_coded() {
let pesel = super::PESEL::from_str("44951201458");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::DoBOutOfRange), pesel.unwrap_err());
}
#[test]
fn birth_day_should_not_exceed_31() {
let pesel = super::PESEL::from_str("44053201458");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.unwrap_err());
}
#[test]
fn birth_date_should_be_returned_as_yyyy_mm_dd() {
let pesel = super::PESEL::from_str("44051401458").unwrap();
assert_eq!("1944-05-14", pesel.date_of_birth().format("%Y-%m-%d").to_string());
}
#[test]
fn generated_pesel_should_print_proper_birth_date() {
let pesel = super::PESEL::new(1981, 06, 27, PeselGender::Female).unwrap();
assert_eq!("1981-06-27", pesel.date_of_birth().format("%Y-%m-%d").to_string());
}
#[test]
fn check_for_add_with_overflow() {
// This test is very specific. It makes sure, that generated pesel, containing many high values (digits) will not result in overflow when calculating checksum
let year = 2299;
let month = 12;
let day = 31;
let pesel = super::PESEL::new(year, month, day, PeselGender::Male).unwrap();
assert_eq!(true, pesel.is_valid());
}
#[test]
fn creating_pesel_from_invalid_date_should_result_in_error() {
// 1993 for sure was not a leap year...
let pesel = super::PESEL::new(1993, 02, 29, PeselGender::Female);
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn parsing_pesel_from_invalid_date_should_result_in_error() {
// 1993 for sure was not a leap year...
let pesel = super::PESEL::from_str("83022998790");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn creating_pesel_with_32nd_day_of_month_should_result_in_error() {
let pesel = super::PESEL::new(1982, 05, 32, PeselGender::Male);
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn parsing_pesel_day_out_of_range_should_result_in_error() {
let pesel = super::PESEL::from_str("97043289891");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn parsing_pesel_day_out_of_range_should_result_in_error2() {
let pesel = super::PESEL::from_str("97043189891");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn parsing_pesel_containing_invalid_date_should_result_in_error() {
let pesel = super::PESEL::from_str("80063144451");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::InvalidDoB), pesel.err().unwrap());
}
#[test]
fn creating_pesel_from_date_earlier_than_1800y_should_result_in_error() {
let pesel = super::PESEL::new(1799, 02, 06, PeselGender::Female);
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::DoBOutOfRange), pesel.err().unwrap());
}
#[test]
fn creating_pesel_from_date_after_2299y_should_result_in_error() {
let pesel = super::PESEL::new(2300, 01, 01, PeselGender::Female);
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::DoBOutOfRange), pesel.err().unwrap());
}
#[test]
fn parsing_pesel_from_date_out_of_range_should_result_in_error() {
let pesel = super::PESEL::from_str("99940656478");
assert_eq!(true, pesel.is_err());
assert_eq!(PeselError::new(PeselError::DoBOutOfRange), pesel.err().unwrap());
}
}
|
use crate::{
builtins::{PyBaseExceptionRef, PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef},
common::{ascii, lock::PyRwLock},
convert::ToPyObject,
function::PyMethodDef,
AsObject, Context, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
};
use std::{borrow::Cow, collections::HashMap, fmt::Write, ops::Range};
pub struct CodecsRegistry {
inner: PyRwLock<RegistryInner>,
}
struct RegistryInner {
search_path: Vec<PyObjectRef>,
search_cache: HashMap<String, PyCodec>,
errors: HashMap<String, PyObjectRef>,
}
pub const DEFAULT_ENCODING: &str = "utf-8";
#[derive(Clone)]
#[repr(transparent)]
pub struct PyCodec(PyTupleRef);
impl PyCodec {
#[inline]
pub fn from_tuple(tuple: PyTupleRef) -> Result<Self, PyTupleRef> {
if tuple.len() == 4 {
Ok(PyCodec(tuple))
} else {
Err(tuple)
}
}
#[inline]
pub fn into_tuple(self) -> PyTupleRef {
self.0
}
#[inline]
pub fn as_tuple(&self) -> &PyTupleRef {
&self.0
}
#[inline]
pub fn get_encode_func(&self) -> &PyObject {
&self.0[0]
}
#[inline]
pub fn get_decode_func(&self) -> &PyObject {
&self.0[1]
}
pub fn is_text_codec(&self, vm: &VirtualMachine) -> PyResult<bool> {
let is_text = vm.get_attribute_opt(self.0.clone().into(), "_is_text_encoding")?;
is_text.map_or(Ok(true), |is_text| is_text.try_to_bool(vm))
}
pub fn encode(
&self,
obj: PyObjectRef,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let args = match errors {
Some(errors) => vec![obj, errors.into()],
None => vec![obj],
};
let res = self.get_encode_func().call(args, vm)?;
let res = res
.downcast::<PyTuple>()
.ok()
.filter(|tuple| tuple.len() == 2)
.ok_or_else(|| {
vm.new_type_error("encoder must return a tuple (object, integer)".to_owned())
})?;
// we don't actually care about the integer
Ok(res[0].clone())
}
pub fn decode(
&self,
obj: PyObjectRef,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let args = match errors {
Some(errors) => vec![obj, errors.into()],
None => vec![obj],
};
let res = self.get_decode_func().call(args, vm)?;
let res = res
.downcast::<PyTuple>()
.ok()
.filter(|tuple| tuple.len() == 2)
.ok_or_else(|| {
vm.new_type_error("decoder must return a tuple (object,integer)".to_owned())
})?;
// we don't actually care about the integer
Ok(res[0].clone())
}
pub fn get_incremental_encoder(
&self,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let args = match errors {
Some(e) => vec![e.into()],
None => vec![],
};
vm.call_method(self.0.as_object(), "incrementalencoder", args)
}
pub fn get_incremental_decoder(
&self,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let args = match errors {
Some(e) => vec![e.into()],
None => vec![],
};
vm.call_method(self.0.as_object(), "incrementaldecoder", args)
}
}
impl TryFromObject for PyCodec {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
obj.downcast::<PyTuple>()
.ok()
.and_then(|tuple| PyCodec::from_tuple(tuple).ok())
.ok_or_else(|| {
vm.new_type_error("codec search functions must return 4-tuples".to_owned())
})
}
}
impl ToPyObject for PyCodec {
#[inline]
fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef {
self.0.into()
}
}
impl CodecsRegistry {
pub(crate) fn new(ctx: &Context) -> Self {
::rustpython_vm::common::static_cell! {
static METHODS: Box<[PyMethodDef]>;
}
let methods = METHODS.get_or_init(|| {
crate::define_methods![
"strict_errors" => strict_errors as EMPTY,
"ignore_errors" => ignore_errors as EMPTY,
"replace_errors" => replace_errors as EMPTY,
"xmlcharrefreplace_errors" => xmlcharrefreplace_errors as EMPTY,
"backslashreplace_errors" => backslashreplace_errors as EMPTY,
"namereplace_errors" => namereplace_errors as EMPTY,
"surrogatepass_errors" => surrogatepass_errors as EMPTY,
"surrogateescape_errors" => surrogateescape_errors as EMPTY
]
.into_boxed_slice()
});
let errors = [
("strict", methods[0].build_function(ctx)),
("ignore", methods[1].build_function(ctx)),
("replace", methods[2].build_function(ctx)),
("xmlcharrefreplace", methods[3].build_function(ctx)),
("backslashreplace", methods[4].build_function(ctx)),
("namereplace", methods[5].build_function(ctx)),
("surrogatepass", methods[6].build_function(ctx)),
("surrogateescape", methods[7].build_function(ctx)),
];
let errors = errors
.into_iter()
.map(|(name, f)| (name.to_owned(), f.into()))
.collect();
let inner = RegistryInner {
search_path: Vec::new(),
search_cache: HashMap::new(),
errors,
};
CodecsRegistry {
inner: PyRwLock::new(inner),
}
}
pub fn register(&self, search_function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if !search_function.is_callable() {
return Err(vm.new_type_error("argument must be callable".to_owned()));
}
self.inner.write().search_path.push(search_function);
Ok(())
}
pub fn unregister(&self, search_function: PyObjectRef) -> PyResult<()> {
let mut inner = self.inner.write();
// Do nothing if search_path is not created yet or was cleared.
if inner.search_path.is_empty() {
return Ok(());
}
for (i, item) in inner.search_path.iter().enumerate() {
if item.get_id() == search_function.get_id() {
if !inner.search_cache.is_empty() {
inner.search_cache.clear();
}
inner.search_path.remove(i);
return Ok(());
}
}
Ok(())
}
pub(crate) fn register_manual(&self, name: &str, codec: PyCodec) -> PyResult<()> {
self.inner
.write()
.search_cache
.insert(name.to_owned(), codec);
Ok(())
}
pub fn lookup(&self, encoding: &str, vm: &VirtualMachine) -> PyResult<PyCodec> {
let encoding = normalize_encoding_name(encoding);
let search_path = {
let inner = self.inner.read();
if let Some(codec) = inner.search_cache.get(encoding.as_ref()) {
// hit cache
return Ok(codec.clone());
}
inner.search_path.clone()
};
let encoding = PyStr::from(encoding.into_owned()).into_ref(&vm.ctx);
for func in search_path {
let res = func.call((encoding.clone(),), vm)?;
let res: Option<PyCodec> = res.try_into_value(vm)?;
if let Some(codec) = res {
let mut inner = self.inner.write();
// someone might have raced us to this, so use theirs
let codec = inner
.search_cache
.entry(encoding.as_str().to_owned())
.or_insert(codec);
return Ok(codec.clone());
}
}
Err(vm.new_lookup_error(format!("unknown encoding: {encoding}")))
}
fn _lookup_text_encoding(
&self,
encoding: &str,
generic_func: &str,
vm: &VirtualMachine,
) -> PyResult<PyCodec> {
let codec = self.lookup(encoding, vm)?;
if codec.is_text_codec(vm)? {
Ok(codec)
} else {
Err(vm.new_lookup_error(format!(
"'{encoding}' is not a text encoding; use {generic_func} to handle arbitrary codecs"
)))
}
}
pub fn forget(&self, encoding: &str) -> Option<PyCodec> {
let encoding = normalize_encoding_name(encoding);
self.inner.write().search_cache.remove(encoding.as_ref())
}
pub fn encode(
&self,
obj: PyObjectRef,
encoding: &str,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let codec = self.lookup(encoding, vm)?;
codec.encode(obj, errors, vm)
}
pub fn decode(
&self,
obj: PyObjectRef,
encoding: &str,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let codec = self.lookup(encoding, vm)?;
codec.decode(obj, errors, vm)
}
pub fn encode_text(
&self,
obj: PyStrRef,
encoding: &str,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
let codec = self._lookup_text_encoding(encoding, "codecs.encode()", vm)?;
codec
.encode(obj.into(), errors, vm)?
.downcast()
.map_err(|obj| {
vm.new_type_error(format!(
"'{}' encoder returned '{}' instead of 'bytes'; use codecs.encode() to \
encode arbitrary types",
encoding,
obj.class().name(),
))
})
}
pub fn decode_text(
&self,
obj: PyObjectRef,
encoding: &str,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<PyStrRef> {
let codec = self._lookup_text_encoding(encoding, "codecs.decode()", vm)?;
codec.decode(obj, errors, vm)?.downcast().map_err(|obj| {
vm.new_type_error(format!(
"'{}' decoder returned '{}' instead of 'str'; use codecs.decode() \
to encode arbitrary types",
encoding,
obj.class().name(),
))
})
}
pub fn register_error(&self, name: String, handler: PyObjectRef) -> Option<PyObjectRef> {
self.inner.write().errors.insert(name, handler)
}
pub fn lookup_error_opt(&self, name: &str) -> Option<PyObjectRef> {
self.inner.read().errors.get(name).cloned()
}
pub fn lookup_error(&self, name: &str, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
self.lookup_error_opt(name)
.ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{name}'")))
}
}
fn normalize_encoding_name(encoding: &str) -> Cow<'_, str> {
if let Some(i) = encoding.find(|c: char| c == ' ' || c.is_ascii_uppercase()) {
let mut out = encoding.as_bytes().to_owned();
for byte in &mut out[i..] {
if *byte == b' ' {
*byte = b'-';
} else {
byte.make_ascii_lowercase();
}
}
String::from_utf8(out).unwrap().into()
} else {
encoding.into()
}
}
// TODO: exceptions with custom payloads
fn extract_unicode_error_range(err: &PyObject, vm: &VirtualMachine) -> PyResult<Range<usize>> {
let start = err.get_attr("start", vm)?;
let start = start.try_into_value(vm)?;
let end = err.get_attr("end", vm)?;
let end = end.try_into_value(vm)?;
Ok(Range { start, end })
}
#[inline]
fn is_decode_err(err: &PyObject, vm: &VirtualMachine) -> bool {
err.fast_isinstance(vm.ctx.exceptions.unicode_decode_error)
}
#[inline]
fn is_encode_ish_err(err: &PyObject, vm: &VirtualMachine) -> bool {
err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error)
|| err.fast_isinstance(vm.ctx.exceptions.unicode_translate_error)
}
fn bad_err_type(err: PyObjectRef, vm: &VirtualMachine) -> PyBaseExceptionRef {
vm.new_type_error(format!(
"don't know how to handle {} in error callback",
err.class().name()
))
}
fn strict_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let err = err
.downcast()
.unwrap_or_else(|_| vm.new_type_error("codec must pass exception instance".to_owned()));
Err(err)
}
fn ignore_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef, usize)> {
if is_encode_ish_err(&err, vm) || is_decode_err(&err, vm) {
let range = extract_unicode_error_range(&err, vm)?;
Ok((vm.ctx.new_str(ascii!("")).into(), range.end))
} else {
Err(bad_err_type(err, vm))
}
}
fn replace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
// char::REPLACEMENT_CHARACTER as a str
let replacement_char = "\u{FFFD}";
let replace = if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
"?"
} else if err.fast_isinstance(vm.ctx.exceptions.unicode_decode_error) {
let range = extract_unicode_error_range(&err, vm)?;
return Ok((replacement_char.to_owned(), range.end));
} else if err.fast_isinstance(vm.ctx.exceptions.unicode_translate_error) {
replacement_char
} else {
return Err(bad_err_type(err, vm));
};
let range = extract_unicode_error_range(&err, vm)?;
let replace = replace.repeat(range.end - range.start);
Ok((replace, range.end))
}
fn xmlcharrefreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
if !is_encode_ish_err(&err, vm) {
return Err(bad_err_type(err, vm));
}
let range = extract_unicode_error_range(&err, vm)?;
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_after_start = crate::common::str::try_get_chars(s.as_str(), range.start..).unwrap_or("");
let num_chars = range.len();
// capacity rough guess; assuming that the codepoints are 3 digits in decimal + the &#;
let mut out = String::with_capacity(num_chars * 6);
for c in s_after_start.chars().take(num_chars) {
write!(out, "&#{};", c as u32).unwrap()
}
Ok((out, range.end))
}
fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
if is_decode_err(&err, vm) {
let range = extract_unicode_error_range(&err, vm)?;
let b = PyBytesRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let mut replace = String::with_capacity(4 * range.len());
for &c in &b[range.clone()] {
write!(replace, "\\x{c:02x}").unwrap();
}
return Ok((replace, range.end));
} else if !is_encode_ish_err(&err, vm) {
return Err(bad_err_type(err, vm));
}
let range = extract_unicode_error_range(&err, vm)?;
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_after_start = crate::common::str::try_get_chars(s.as_str(), range.start..).unwrap_or("");
let num_chars = range.len();
// minimum 4 output bytes per char: \xNN
let mut out = String::with_capacity(num_chars * 4);
for c in s_after_start.chars().take(num_chars) {
let c = c as u32;
if c >= 0x10000 {
write!(out, "\\U{c:08x}").unwrap();
} else if c >= 0x100 {
write!(out, "\\u{c:04x}").unwrap();
} else {
write!(out, "\\x{c:02x}").unwrap();
}
}
Ok((out, range.end))
}
fn namereplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(String, usize)> {
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
let range = extract_unicode_error_range(&err, vm)?;
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_after_start =
crate::common::str::try_get_chars(s.as_str(), range.start..).unwrap_or("");
let num_chars = range.len();
let mut out = String::with_capacity(num_chars * 4);
for c in s_after_start.chars().take(num_chars) {
let c_u32 = c as u32;
if let Some(c_name) = unicode_names2::name(c) {
write!(out, "\\N{{{c_name}}}").unwrap();
} else if c_u32 >= 0x10000 {
write!(out, "\\U{c_u32:08x}").unwrap();
} else if c_u32 >= 0x100 {
write!(out, "\\u{c_u32:04x}").unwrap();
} else {
write!(out, "\\x{c_u32:02x}").unwrap();
}
}
Ok((out, range.end))
} else {
Err(bad_err_type(err, vm))
}
}
#[derive(Eq, PartialEq)]
enum StandardEncoding {
Utf8,
Utf16Be,
Utf16Le,
Utf32Be,
Utf32Le,
Unknown,
}
fn get_standard_encoding(encoding: &str) -> (usize, StandardEncoding) {
if let Some(encoding) = encoding.to_lowercase().strip_prefix("utf") {
let mut byte_length: usize = 0;
let mut standard_encoding = StandardEncoding::Unknown;
let encoding = encoding
.strip_prefix(|c| ['-', '_'].contains(&c))
.unwrap_or(encoding);
if encoding == "8" {
byte_length = 3;
standard_encoding = StandardEncoding::Utf8;
} else if let Some(encoding) = encoding.strip_prefix("16") {
byte_length = 2;
if encoding.is_empty() {
if cfg!(target_endian = "little") {
standard_encoding = StandardEncoding::Utf16Le;
} else if cfg!(target_endian = "big") {
standard_encoding = StandardEncoding::Utf16Be;
}
if standard_encoding != StandardEncoding::Unknown {
return (byte_length, standard_encoding);
}
}
let encoding = encoding
.strip_prefix(|c| ['-', '_'].contains(&c))
.unwrap_or(encoding);
standard_encoding = match encoding {
"be" => StandardEncoding::Utf16Be,
"le" => StandardEncoding::Utf16Le,
_ => StandardEncoding::Unknown,
}
} else if let Some(encoding) = encoding.strip_prefix("32") {
byte_length = 4;
if encoding.is_empty() {
if cfg!(target_endian = "little") {
standard_encoding = StandardEncoding::Utf32Le;
} else if cfg!(target_endian = "big") {
standard_encoding = StandardEncoding::Utf32Be;
}
if standard_encoding != StandardEncoding::Unknown {
return (byte_length, standard_encoding);
}
}
let encoding = encoding
.strip_prefix(|c| ['-', '_'].contains(&c))
.unwrap_or(encoding);
standard_encoding = match encoding {
"be" => StandardEncoding::Utf32Be,
"le" => StandardEncoding::Utf32Le,
_ => StandardEncoding::Unknown,
}
}
return (byte_length, standard_encoding);
} else if encoding == "CP_UTF8" {
return (3, StandardEncoding::Utf8);
}
(0, StandardEncoding::Unknown)
}
fn surrogatepass_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef, usize)> {
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
let range = extract_unicode_error_range(&err, vm)?;
let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_encoding = PyStrRef::try_from_object(vm, err.get_attr("encoding", vm)?)?;
let (_, standard_encoding) = get_standard_encoding(s_encoding.as_str());
if let StandardEncoding::Unknown = standard_encoding {
// Not supported, fail with original exception
return Err(err.downcast().unwrap());
}
let s_after_start =
crate::common::str::try_get_chars(s.as_str(), range.start..).unwrap_or("");
let num_chars = range.len();
let mut out: Vec<u8> = Vec::with_capacity(num_chars * 4);
for c in s_after_start.chars().take(num_chars).map(|x| x as u32) {
if !(0xd800..=0xdfff).contains(&c) {
// Not a surrogate, fail with original exception
return Err(err.downcast().unwrap());
}
match standard_encoding {
StandardEncoding::Utf8 => {
out.push((0xe0 | (c >> 12)) as u8);
out.push((0x80 | ((c >> 6) & 0x3f)) as u8);
out.push((0x80 | (c & 0x3f)) as u8);
}
StandardEncoding::Utf16Le => {
out.push(c as u8);
out.push((c >> 8) as u8);
}
StandardEncoding::Utf16Be => {
out.push((c >> 8) as u8);
out.push(c as u8);
}
StandardEncoding::Utf32Le => {
out.push(c as u8);
out.push((c >> 8) as u8);
out.push((c >> 16) as u8);
out.push((c >> 24) as u8);
}
StandardEncoding::Utf32Be => {
out.push((c >> 24) as u8);
out.push((c >> 16) as u8);
out.push((c >> 8) as u8);
out.push(c as u8);
}
StandardEncoding::Unknown => {
unreachable!("NOTE: RUSTPYTHON, should've bailed out earlier")
}
}
}
Ok((vm.ctx.new_bytes(out).into(), range.end))
} else if is_decode_err(&err, vm) {
let range = extract_unicode_error_range(&err, vm)?;
let s = PyBytesRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_encoding = PyStrRef::try_from_object(vm, err.get_attr("encoding", vm)?)?;
let (byte_length, standard_encoding) = get_standard_encoding(s_encoding.as_str());
if let StandardEncoding::Unknown = standard_encoding {
// Not supported, fail with original exception
return Err(err.downcast().unwrap());
}
let mut c: u32 = 0;
// Try decoding a single surrogate character. If there are more,
// let the codec call us again.
let p = &s.as_bytes()[range.start..];
if p.len() - range.start >= byte_length {
match standard_encoding {
StandardEncoding::Utf8 => {
if (p[0] as u32 & 0xf0) == 0xe0
&& (p[1] as u32 & 0xc0) == 0x80
&& (p[2] as u32 & 0xc0) == 0x80
{
// it's a three-byte code
c = ((p[0] as u32 & 0x0f) << 12)
+ ((p[1] as u32 & 0x3f) << 6)
+ (p[2] as u32 & 0x3f);
}
}
StandardEncoding::Utf16Le => {
c = (p[1] as u32) << 8 | p[0] as u32;
}
StandardEncoding::Utf16Be => {
c = (p[0] as u32) << 8 | p[1] as u32;
}
StandardEncoding::Utf32Le => {
c = ((p[3] as u32) << 24)
| ((p[2] as u32) << 16)
| ((p[1] as u32) << 8)
| p[0] as u32;
}
StandardEncoding::Utf32Be => {
c = ((p[0] as u32) << 24)
| ((p[1] as u32) << 16)
| ((p[2] as u32) << 8)
| p[3] as u32;
}
StandardEncoding::Unknown => {
unreachable!("NOTE: RUSTPYTHON, should've bailed out earlier")
}
}
}
// !Py_UNICODE_IS_SURROGATE
if !(0xd800..=0xdfff).contains(&c) {
// Not a surrogate, fail with original exception
return Err(err.downcast().unwrap());
}
Ok((
vm.new_pyobj(format!("\\x{c:x?}")),
range.start + byte_length,
))
} else {
Err(bad_err_type(err, vm))
}
}
fn surrogateescape_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef, usize)> {
if err.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) {
let range = extract_unicode_error_range(&err, vm)?;
let object = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?;
let s_after_start =
crate::common::str::try_get_chars(object.as_str(), range.start..).unwrap_or("");
let mut out: Vec<u8> = Vec::with_capacity(range.len());
for ch in s_after_start.chars().take(range.len()) {
let ch = ch as u32;
if !(0xdc80..=0xdcff).contains(&ch) {
// Not a UTF-8b surrogate, fail with original exception
return Err(err.downcast().unwrap());
}
out.push((ch - 0xdc00) as u8);
}
let out = vm.ctx.new_bytes(out);
Ok((out.into(), range.end))
} else if is_decode_err(&err, vm) {
let range = extract_unicode_error_range(&err, vm)?;
let object = err.get_attr("object", vm)?;
let object = PyBytesRef::try_from_object(vm, object)?;
let p = &object.as_bytes()[range.clone()];
let mut consumed = 0;
let mut replace = String::with_capacity(4 * range.len());
while consumed < 4 && consumed < range.len() {
let c = p[consumed] as u32;
// Refuse to escape ASCII bytes
if c < 128 {
break;
}
write!(replace, "#{}", 0xdc00 + c).unwrap();
consumed += 1;
}
if consumed == 0 {
return Err(err.downcast().unwrap());
}
Ok((vm.new_pyobj(replace), range.start + consumed))
} else {
Err(bad_err_type(err, vm))
}
}
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A typesafe bitmask flag generator useful for sets of C-style flags.
//! It can be used for creating ergonomic wrappers around C APIs.
//!
//! The `bitflags!` macro generates `struct`s that manage a set of flags. The
//! type of those flags must be some primitive integer.
//!
//! # Examples
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! const C = 0b00000100;
//! const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
//! }
//! }
//!
//! fn main() {
//! let e1 = Flags::A | Flags::C;
//! let e2 = Flags::B | Flags::C;
//! assert_eq!((e1 | e2), Flags::ABC); // union
//! assert_eq!((e1 & e2), Flags::C); // intersection
//! assert_eq!((e1 - e2), Flags::A); // set difference
//! assert_eq!(!e2, Flags::A); // set complement
//! }
//! ```
//!
//! See [`example_generated::Flags`](./example_generated/struct.Flags.html) for documentation of code
//! generated by the above `bitflags!` expansion.
//!
//! # Visibility
//!
//! The `bitflags!` macro supports visibility, just like you'd expect when writing a normal
//! Rust `struct`:
//!
//! ```
//! mod example {
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! pub struct Flags1: u32 {
//! const A = 0b00000001;
//! }
//!
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! # pub
//! struct Flags2: u32 {
//! const B = 0b00000010;
//! }
//! }
//! }
//!
//! fn main() {
//! let flag1 = example::Flags1::A;
//! let flag2 = example::Flags2::B; // error: const `B` is private
//! }
//! ```
//!
//! # Attributes
//!
//! Attributes can be attached to the generated flags types and their constants as normal.
//!
//! # Representation
//!
//! It's valid to add a `#[repr(C)]` or `#[repr(transparent)]` attribute to a generated flags type.
//! The generated flags type is always guaranteed to be a newtype where its only field has the same
//! ABI as the underlying integer type.
//!
//! In this example, `Flags` has the same ABI as `u32`:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[repr(transparent)]
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! const C = 0b00000100;
//! }
//! }
//! ```
//!
//! # Extending
//!
//! Generated flags types belong to you, so you can add trait implementations to them outside
//! of what the `bitflags!` macro gives:
//!
//! ```
//! use std::fmt;
//!
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! }
//! }
//!
//! impl Flags {
//! pub fn clear(&mut self) {
//! *self.0.bits_mut() = 0;
//! }
//! }
//!
//! fn main() {
//! let mut flags = Flags::A | Flags::B;
//!
//! flags.clear();
//! assert!(flags.is_empty());
//!
//! assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)");
//! assert_eq!(format!("{:?}", Flags::B), "Flags(B)");
//! }
//! ```
//!
//! # What's implemented by `bitflags!`
//!
//! The `bitflags!` macro adds some trait implementations and inherent methods
//! to generated flags types, but leaves room for you to choose the semantics
//! of others.
//!
//! ## Iterators
//!
//! The following iterator traits are implemented for generated flags types:
//!
//! - `Extend`: adds the union of the instances iterated over.
//! - `FromIterator`: calculates the union.
//! - `IntoIterator`: iterates over set flag values.
//!
//! ## Formatting
//!
//! The following formatting traits are implemented for generated flags types:
//!
//! - `Binary`.
//! - `LowerHex` and `UpperHex`.
//! - `Octal`.
//!
//! Also see the _Debug and Display_ section for details about standard text
//! representations for flags types.
//!
//! ## Operators
//!
//! The following operator traits are implemented for the generated `struct`s:
//!
//! - `BitOr` and `BitOrAssign`: union
//! - `BitAnd` and `BitAndAssign`: intersection
//! - `BitXor` and `BitXorAssign`: toggle
//! - `Sub` and `SubAssign`: set difference
//! - `Not`: set complement
//!
//! ## Methods
//!
//! The following methods are defined for the generated `struct`s:
//!
//! - `empty`: an empty set of flags
//! - `all`: the set of all defined flags
//! - `bits`: the raw value of the flags currently stored
//! - `from_bits`: convert from underlying bit representation, unless that
//! representation contains bits that do not correspond to a
//! defined flag
//! - `from_bits_truncate`: convert from underlying bit representation, dropping
//! any bits that do not correspond to defined flags
//! - `from_bits_retain`: convert from underlying bit representation, keeping
//! all bits (even those not corresponding to defined
//! flags)
//! - `is_empty`: `true` if no flags are currently stored
//! - `is_all`: `true` if currently set flags exactly equal all defined flags
//! - `intersects`: `true` if there are flags common to both `self` and `other`
//! - `contains`: `true` if all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place
//! - `remove`: removes the specified flags in-place
//! - `toggle`: the specified flags will be inserted if not present, and removed
//! if they are.
//! - `set`: inserts or removes the specified flags depending on the passed value
//! - `intersection`: returns a new set of flags, containing only the flags present
//! in both `self` and `other` (the argument to the function).
//! - `union`: returns a new set of flags, containing any flags present in
//! either `self` or `other` (the argument to the function).
//! - `difference`: returns a new set of flags, containing all flags present in
//! `self` without any of the flags present in `other` (the
//! argument to the function).
//! - `symmetric_difference`: returns a new set of flags, containing all flags
//! present in either `self` or `other` (the argument
//! to the function), but not both.
//! - `complement`: returns a new set of flags, containing all flags which are
//! not set in `self`, but which are allowed for this type.
//!
//! # What's not implemented by `bitflags!`
//!
//! Some functionality is not automatically implemented for generated flags types
//! by the `bitflags!` macro, even when it reasonably could be. This is so callers
//! have more freedom to decide on the semantics of their flags types.
//!
//! ## `Clone` and `Copy`
//!
//! Generated flags types are not automatically copyable, even though they can always
//! derive both `Clone` and `Copy`.
//!
//! ## `Default`
//!
//! The `Default` trait is not automatically implemented for the generated structs.
//!
//! If your default value is equal to `0` (which is the same value as calling `empty()`
//! on the generated struct), you can simply derive `Default`:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! // Results in default value with bits: 0
//! #[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! const C = 0b00000100;
//! }
//! }
//!
//! fn main() {
//! let derived_default: Flags = Default::default();
//! assert_eq!(derived_default.bits(), 0);
//! }
//! ```
//!
//! If your default value is not equal to `0` you need to implement `Default` yourself:
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! const C = 0b00000100;
//! }
//! }
//!
//! // explicit `Default` implementation
//! impl Default for Flags {
//! fn default() -> Flags {
//! Flags::A | Flags::C
//! }
//! }
//!
//! fn main() {
//! let implemented_default: Flags = Default::default();
//! assert_eq!(implemented_default, (Flags::A | Flags::C));
//! }
//! ```
//!
//! ## `Debug` and `Display`
//!
//! The `Debug` trait can be derived for a reasonable implementation. This library defines a standard
//! text-based representation for flags that generated flags types can use. For details on the exact
//! grammar, see the [`parser`] module.
//!
//! To support formatting and parsing your generated flags types using that representation, you can implement
//! the standard `Display` and `FromStr` traits in this fashion:
//!
//! ```
//! use bitflags::bitflags;
//! use std::{fmt, str};
//!
//! bitflags! {
//! pub struct Flags: u32 {
//! const A = 1;
//! const B = 2;
//! const C = 4;
//! const D = 8;
//! }
//! }
//!
//! impl fmt::Debug for Flags {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! fmt::Debug::fmt(&self.0, f)
//! }
//! }
//!
//! impl fmt::Display for Flags {
//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! fmt::Display::fmt(&self.0, f)
//! }
//! }
//!
//! impl str::FromStr for Flags {
//! type Err = bitflags::parser::ParseError;
//!
//! fn from_str(flags: &str) -> Result<Self, Self::Err> {
//! Ok(Self(flags.parse()?))
//! }
//! }
//! ```
//!
//! ## `PartialEq` and `PartialOrd`
//!
//! Equality and ordering can be derived for a reasonable implementation, or implemented manually
//! for different semantics.
//!
//! # Edge cases
//!
//! ## Zero Flags
//!
//! Flags with a value equal to zero will have some strange behavior that one should be aware of.
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const NONE = 0b00000000;
//! const SOME = 0b00000001;
//! }
//! }
//!
//! fn main() {
//! let empty = Flags::empty();
//! let none = Flags::NONE;
//! let some = Flags::SOME;
//!
//! // Zero flags are treated as always present
//! assert!(empty.contains(Flags::NONE));
//! assert!(none.contains(Flags::NONE));
//! assert!(some.contains(Flags::NONE));
//!
//! // Zero flags will be ignored when testing for emptiness
//! assert!(none.is_empty());
//! }
//! ```
//!
//! Users should generally avoid defining a flag with a value of zero.
//!
//! ## Multi-bit Flags
//!
//! It is allowed to define a flag with multiple bits set, however such
//! flags are _not_ treated as a set where any of those bits is a valid
//! flag. Instead, each flag is treated as a unit when converting from
//! bits with [`from_bits`] or [`from_bits_truncate`].
//!
//! ```
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u8 {
//! const F3 = 0b00000011;
//! }
//! }
//!
//! fn main() {
//! // This bit pattern does not set all the bits in `F3`, so it is rejected.
//! assert!(Flags::from_bits(0b00000001).is_none());
//! assert!(Flags::from_bits_truncate(0b00000001).is_empty());
//! }
//! ```
//!
//! [`from_bits`]: Flags::from_bits
//! [`from_bits_truncate`]: Flags::from_bits_truncate
//!
//! # The `Flags` trait
//!
//! This library defines a `Flags` trait that's implemented by all generated flags types.
//! The trait makes it possible to work with flags types generically:
//!
//! ```
//! fn count_unset_flags<F: bitflags::Flags>(flags: &F) -> usize {
//! // Find out how many flags there are in total
//! let total = F::all().iter().count();
//!
//! // Find out how many flags are set
//! let set = flags.iter().count();
//!
//! total - set
//! }
//!
//! use bitflags::bitflags;
//!
//! bitflags! {
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
//! struct Flags: u32 {
//! const A = 0b00000001;
//! const B = 0b00000010;
//! const C = 0b00000100;
//! }
//! }
//!
//! assert_eq!(2, count_unset_flags(&Flags::B));
//! ```
//!
//! # The internal field
//!
//! This library generates newtypes like:
//!
//! ```
//! # pub struct Field0;
//! pub struct Flags(Field0);
//! ```
//!
//! You can freely use methods and trait implementations on this internal field as `.0`.
//! For details on exactly what's generated for it, see the [`Field0`](example_generated/struct.Field0.html)
//! example docs.
#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![cfg_attr(not(test), forbid(unsafe_code))]
#![cfg_attr(test, allow(mixed_script_confusables))]
#![doc(html_root_url = "https://docs.rs/bitflags/2.3.3")]
#[doc(inline)]
pub use traits::{Bits, Flag, Flags};
pub mod iter;
pub mod parser;
mod traits;
#[doc(hidden)]
pub mod __private {
pub use crate::{external::__private::*, traits::__private::*};
pub use core;
}
#[allow(unused_imports)]
pub use external::*;
#[allow(deprecated)]
pub use traits::BitFlags;
/*
How does the bitflags crate work?
This library generates a `struct` in the end-user's crate with a bunch of constants on it that represent flags.
The difference between `bitflags` and a lot of other libraries is that we don't actually control the generated `struct` in the end.
It's part of the end-user's crate, so it belongs to them. That makes it difficult to extend `bitflags` with new functionality
because we could end up breaking valid code that was already written.
Our solution is to split the type we generate into two: the public struct owned by the end-user, and an internal struct owned by `bitflags` (us).
To give you an example, let's say we had a crate that called `bitflags!`:
```rust
bitflags! {
pub struct MyFlags: u32 {
const A = 1;
const B = 2;
}
}
```
What they'd end up with looks something like this:
```rust
pub struct MyFlags(<MyFlags as PublicFlags>::InternalBitFlags);
const _: () = {
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MyInternalBitFlags {
bits: u32,
}
impl PublicFlags for MyFlags {
type Internal = InternalBitFlags;
}
};
```
If we want to expose something like a new trait impl for generated flags types, we add it to our generated `MyInternalBitFlags`,
and let `#[derive]` on `MyFlags` pick up that implementation, if an end-user chooses to add one.
The public API is generated in the `__impl_public_flags!` macro, and the internal API is generated in
the `__impl_internal_flags!` macro.
The macros are split into 3 modules:
- `public`: where the user-facing flags types are generated.
- `internal`: where the `bitflags`-facing flags types are generated.
- `external`: where external library traits are implemented conditionally.
*/
/// The macro used to generate the flag structure.
///
/// See the [crate level docs](../bitflags/index.html) for complete documentation.
///
/// # Example
///
/// ```
/// use bitflags::bitflags;
///
/// bitflags! {
/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
/// struct Flags: u32 {
/// const A = 0b00000001;
/// const B = 0b00000010;
/// const C = 0b00000100;
/// const ABC = Self::A.bits() | Self::B.bits() | Self::C.bits();
/// }
/// }
///
/// let e1 = Flags::A | Flags::C;
/// let e2 = Flags::B | Flags::C;
/// assert_eq!((e1 | e2), Flags::ABC); // union
/// assert_eq!((e1 & e2), Flags::C); // intersection
/// assert_eq!((e1 - e2), Flags::A); // set difference
/// assert_eq!(!e2, Flags::A); // set complement
/// ```
///
/// The generated `struct`s can also be extended with type and trait
/// implementations:
///
/// ```
/// use std::fmt;
///
/// use bitflags::bitflags;
///
/// bitflags! {
/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
/// struct Flags: u32 {
/// const A = 0b00000001;
/// const B = 0b00000010;
/// }
/// }
///
/// impl Flags {
/// pub fn clear(&mut self) {
/// *self.0.bits_mut() = 0;
/// }
/// }
///
/// let mut flags = Flags::A | Flags::B;
///
/// flags.clear();
/// assert!(flags.is_empty());
///
/// assert_eq!(format!("{:?}", Flags::A | Flags::B), "Flags(A | B)");
/// assert_eq!(format!("{:?}", Flags::B), "Flags(B)");
/// ```
#[macro_export(local_inner_macros)]
macro_rules! bitflags {
(
$(#[$outer:meta])*
$vis:vis struct $BitFlags:ident: $T:ty {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:ident = $value:expr;
)*
}
$($t:tt)*
) => {
// Declared in the scope of the `bitflags!` call
// This type appears in the end-user's API
__declare_public_bitflags! {
$(#[$outer])*
$vis struct $BitFlags
}
// Workaround for: https://github.com/bitflags/bitflags/issues/320
__impl_public_bitflags_consts! {
$BitFlags: $T {
$(
$(#[$inner $($args)*])*
$Flag = $value;
)*
}
}
#[allow(
dead_code,
deprecated,
unused_doc_comments,
unused_attributes,
unused_mut,
unused_imports,
non_upper_case_globals,
clippy::assign_op_pattern
)]
const _: () = {
// Declared in a "hidden" scope that can't be reached directly
// These types don't appear in the end-user's API
__declare_internal_bitflags! {
$vis struct InternalBitFlags: $T
}
__impl_internal_bitflags! {
InternalBitFlags: $T, $BitFlags {
$(
$(#[$inner $($args)*])*
$Flag = $value;
)*
}
}
// This is where new library trait implementations can be added
__impl_external_bitflags! {
InternalBitFlags: $T, $BitFlags {
$(
$(#[$inner $($args)*])*
$Flag;
)*
}
}
__impl_public_bitflags_forward! {
$BitFlags: $T, InternalBitFlags
}
__impl_public_bitflags_ops! {
$BitFlags
}
__impl_public_bitflags_iter! {
$BitFlags: $T, $BitFlags
}
};
bitflags! {
$($t)*
}
};
(
impl $BitFlags:ident: $T:ty {
$(
$(#[$inner:ident $($args:tt)*])*
const $Flag:ident = $value:expr;
)*
}
$($t:tt)*
) => {
__impl_public_bitflags_consts! {
$BitFlags: $T {
$(
$(#[$inner $($args)*])*
$Flag = $value;
)*
}
}
#[allow(
dead_code,
deprecated,
unused_doc_comments,
unused_attributes,
unused_mut,
unused_imports,
non_upper_case_globals,
clippy::assign_op_pattern
)]
const _: () = {
__impl_public_bitflags! {
$BitFlags: $T, $BitFlags {
$(
$(#[$inner $($args)*])*
$Flag;
)*
}
}
__impl_public_bitflags_ops! {
$BitFlags
}
__impl_public_bitflags_iter! {
$BitFlags: $T, $BitFlags
}
};
bitflags! {
$($t)*
}
};
() => {};
}
/// Implement functions on bitflags types.
///
/// We need to be careful about adding new methods and trait implementations here because they
/// could conflict with items added by the end-user.
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __impl_bitflags {
(
$PublicBitFlags:ident: $T:ty {
fn empty() $empty:block
fn all() $all:block
fn bits($bits0:ident) $bits:block
fn from_bits($from_bits0:ident) $from_bits:block
fn from_bits_truncate($from_bits_truncate0:ident) $from_bits_truncate:block
fn from_bits_retain($from_bits_retain0:ident) $from_bits_retain:block
fn from_name($from_name0:ident) $from_name:block
fn is_empty($is_empty0:ident) $is_empty:block
fn is_all($is_all0:ident) $is_all:block
fn intersects($intersects0:ident, $intersects1:ident) $intersects:block
fn contains($contains0:ident, $contains1:ident) $contains:block
fn insert($insert0:ident, $insert1:ident) $insert:block
fn remove($remove0:ident, $remove1:ident) $remove:block
fn toggle($toggle0:ident, $toggle1:ident) $toggle:block
fn set($set0:ident, $set1:ident, $set2:ident) $set:block
fn intersection($intersection0:ident, $intersection1:ident) $intersection:block
fn union($union0:ident, $union1:ident) $union:block
fn difference($difference0:ident, $difference1:ident) $difference:block
fn symmetric_difference($symmetric_difference0:ident, $symmetric_difference1:ident) $symmetric_difference:block
fn complement($complement0:ident) $complement:block
}
) => {
#[allow(dead_code, deprecated, unused_attributes)]
impl $PublicBitFlags {
/// Returns an empty set of flags.
#[inline]
pub const fn empty() -> Self {
$empty
}
/// Returns the set containing all flags.
#[inline]
pub const fn all() -> Self {
$all
}
/// Returns the raw value of the flags currently stored.
#[inline]
pub const fn bits(&self) -> $T {
let $bits0 = self;
$bits
}
/// Convert from underlying bit representation, unless that
/// representation contains bits that do not correspond to a flag.
#[inline]
pub const fn from_bits(bits: $T) -> $crate::__private::core::option::Option<Self> {
let $from_bits0 = bits;
$from_bits
}
/// Convert from underlying bit representation, dropping any bits
/// that do not correspond to flags.
#[inline]
pub const fn from_bits_truncate(bits: $T) -> Self {
let $from_bits_truncate0 = bits;
$from_bits_truncate
}
/// Convert from underlying bit representation, preserving all
/// bits (even those not corresponding to a defined flag).
#[inline]
pub const fn from_bits_retain(bits: $T) -> Self {
let $from_bits_retain0 = bits;
$from_bits_retain
}
/// Get the value for a flag from its stringified name.
///
/// Names are _case-sensitive_, so must correspond exactly to
/// the identifier given to the flag.
#[inline]
pub fn from_name(name: &str) -> $crate::__private::core::option::Option<Self> {
let $from_name0 = name;
$from_name
}
/// Returns `true` if no flags are currently stored.
#[inline]
pub const fn is_empty(&self) -> bool {
let $is_empty0 = self;
$is_empty
}
/// Returns `true` if all flags are currently set.
#[inline]
pub const fn is_all(&self) -> bool {
let $is_all0 = self;
$is_all
}
/// Returns `true` if there are flags common to both `self` and `other`.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
let $intersects0 = self;
let $intersects1 = other;
$intersects
}
/// Returns `true` if all of the flags in `other` are contained within `self`.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
let $contains0 = self;
let $contains1 = other;
$contains
}
/// Inserts the specified flags in-place.
///
/// This method is equivalent to `union`.
#[inline]
pub fn insert(&mut self, other: Self) {
let $insert0 = self;
let $insert1 = other;
$insert
}
/// Removes the specified flags in-place.
///
/// This method is equivalent to `difference`.
#[inline]
pub fn remove(&mut self, other: Self) {
let $remove0 = self;
let $remove1 = other;
$remove
}
/// Toggles the specified flags in-place.
///
/// This method is equivalent to `symmetric_difference`.
#[inline]
pub fn toggle(&mut self, other: Self) {
let $toggle0 = self;
let $toggle1 = other;
$toggle
}
/// Inserts or removes the specified flags depending on the passed value.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
let $set0 = self;
let $set1 = other;
let $set2 = value;
$set
}
/// Returns the intersection between the flags in `self` and
/// `other`.
///
/// Calculating `self` bitwise and (`&`) other, including
/// any bits that don't correspond to a defined flag.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
let $intersection0 = self;
let $intersection1 = other;
$intersection
}
/// Returns the union of between the flags in `self` and `other`.
///
/// Calculates `self` bitwise or (`|`) `other`, including
/// any bits that don't correspond to a defined flag.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
let $union0 = self;
let $union1 = other;
$union
}
/// Returns the difference between the flags in `self` and `other`.
///
/// Calculates `self` bitwise and (`&!`) the bitwise negation of `other`,
/// including any bits that don't correspond to a defined flag.
///
/// This method is _not_ equivalent to `a & !b` when there are bits set that
/// don't correspond to a defined flag. The `!` operator will unset any
/// bits that don't correspond to a flag, so they'll always be unset by `a &! b`,
/// but respected by `a.difference(b)`.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
let $difference0 = self;
let $difference1 = other;
$difference
}
/// Returns the symmetric difference between the flags
/// in `self` and `other`.
///
/// Calculates `self` bitwise exclusive or (`^`) `other`,
/// including any bits that don't correspond to a defined flag.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
let $symmetric_difference0 = self;
let $symmetric_difference1 = other;
$symmetric_difference
}
/// Returns the complement of this set of flags.
///
/// Calculates the bitwise negation (`!`) of `self`,
/// **unsetting** any bits that don't correspond to a defined flag.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
let $complement0 = self;
$complement
}
}
};
}
/// A macro that processed the input to `bitflags!` and shuffles attributes around
/// based on whether or not they're "expression-safe".
///
/// This macro is a token-tree muncher that works on 2 levels:
///
/// For each attribute, we explicitly match on its identifier, like `cfg` to determine
/// whether or not it should be considered expression-safe.
///
/// If you find yourself with an attribute that should be considered expression-safe
/// and isn't, it can be added here.
#[macro_export(local_inner_macros)]
#[doc(hidden)]
macro_rules! __bitflags_expr_safe_attrs {
// Entrypoint: Move all flags and all attributes into `unprocessed` lists
// where they'll be munched one-at-a-time
(
$(#[$inner:ident $($args:tt)*])*
{ $e:expr }
) => {
__bitflags_expr_safe_attrs! {
expr: { $e },
attrs: {
// All attributes start here
unprocessed: [$(#[$inner $($args)*])*],
// Attributes that are safe on expressions go here
processed: [],
},
}
};
// Process the next attribute on the current flag
// `cfg`: The next flag should be propagated to expressions
// NOTE: You can copy this rules block and replace `cfg` with
// your attribute name that should be considered expression-safe
(
expr: { $e:expr },
attrs: {
unprocessed: [
// cfg matched here
#[cfg $($args:tt)*]
$($attrs_rest:tt)*
],
processed: [$($expr:tt)*],
},
) => {
__bitflags_expr_safe_attrs! {
expr: { $e },
attrs: {
unprocessed: [
$($attrs_rest)*
],
processed: [
$($expr)*
// cfg added here
#[cfg $($args)*]
],
},
}
};
// Process the next attribute on the current flag
// `$other`: The next flag should not be propagated to expressions
(
expr: { $e:expr },
attrs: {
unprocessed: [
// $other matched here
#[$other:ident $($args:tt)*]
$($attrs_rest:tt)*
],
processed: [$($expr:tt)*],
},
) => {
__bitflags_expr_safe_attrs! {
expr: { $e },
attrs: {
unprocessed: [
$($attrs_rest)*
],
processed: [
// $other not added here
$($expr)*
],
},
}
};
// Once all attributes on all flags are processed, generate the actual code
(
expr: { $e:expr },
attrs: {
unprocessed: [],
processed: [$(#[$expr:ident $($exprargs:tt)*])*],
},
) => {
$(#[$expr $($exprargs)*])*
{ $e }
}
}
#[macro_use]
mod public;
#[macro_use]
mod internal;
#[macro_use]
mod external;
#[cfg(feature = "example_generated")]
pub mod example_generated;
#[cfg(test)]
mod tests;
|
use std::prelude::v1::*;
use gzip_header::*;
use std::io::Cursor;
fn roundtrip_inner(use_crc: bool) {
const COMMENT: &'static [u8] = b"Comment";
const FILENAME: &'static [u8] = b"Filename";
const MTIME: u32 = 12345;
const OS: FileSystemType = FileSystemType::NTFS;
const XFL: ExtraFlags = ExtraFlags::FastestCompression;
let header = GzBuilder::new()
.comment(COMMENT)
.filename(FILENAME)
.mtime(MTIME)
.os(OS)
.xfl(ExtraFlags::FastestCompression)
.into_header_inner(use_crc);
let mut reader = Cursor::new(header.clone());
let header_read = read_gz_header(&mut reader).unwrap();
assert_eq!(header_read.comment().unwrap(), COMMENT);
assert_eq!(header_read.filename().unwrap(), FILENAME);
assert_eq!(header_read.mtime(), MTIME);
assert_eq!(header_read.os(), OS.as_u8());
assert_eq!(header_read.xfl(), XFL.as_u8());
}
//#[test]
pub fn roundtrip() {
roundtrip_inner(false);
}
//#[test]
pub fn roundtrip_with_crc() {
roundtrip_inner(true);
}
//#[test]
pub fn filesystem_enum() {
for n in 0..20 {
assert_eq!(n, FileSystemType::from_u8(n).as_u8());
}
for n in 20..(u8::max_value() as u16) + 1 {
assert_eq!(FileSystemType::from_u8(n as u8), FileSystemType::Unknown);
}
}
|
extern crate cderive;
use cderive::clang::*;
use std::env;
struct CycleCollect;
macro_rules! try_opt {
($e:expr) => {
try_opt!($e, return None)
};
($e:expr, $other:expr) => {
match $e {
Some(x) => x,
None => $other,
}
};
}
// Gets the target type of a refptr. Returns None if the type is not a RefPtr or nsCOMPtr
fn refptr_target(ty: Type) -> Option<Type> {
// If any of these fail, we aren't looking at a RefPtr or nsCOMPtr
let decl = try_opt!(ty.get_declaration());
let template = try_opt!(decl.get_template());
let template_name = try_opt!(template.get_name());
// XXX: Handle more types?
if template_name != "RefPtr" && template_name != "nsCOMPtr" {
return None;
}
let target = try_opt!(ty.get_template_argument_types());
if target.is_empty() {
return None;
}
let target = try_opt!(target[0]);
Some(target)
}
fn fields(entity: Entity) -> Vec<Entity> {
let mut fields = Vec::new();
entity.visit_children(|entity, _| {
if entity.get_kind() == EntityKind::FieldDecl {
fields.push(entity);
}
EntityVisitResult::Continue
});
fields
}
impl cderive::Derive for CycleCollect {
fn derive(&mut self, entity: Entity) -> Result<String, ()> {
let fields = fields(entity);
eprintln!("{:?}", fields);
for field in fields {
let ty = try_opt!(field.get_type(), continue);
let target = try_opt!(refptr_target(ty), continue);
if let Some(decl) = target.get_declaration() {
}
}
let typename = entity.get_display_name().unwrap();
let res = format!("
{ty}::cycleCollection::Unlink(void* p) {{
{ty} *tmp = DowncastCCParticipant<{ty}>(p);
{body}
}}", ty = typename, body = "");
eprintln!("{}", res);
Ok("".to_owned())
/*
Ok(format!("
int {ty}::field_count() {{
return {count};
}}
const char** {ty}::field_names() {{
static const char* FIELD_NAMES[] = {{ {names} }};
return FIELD_NAMES;
}}
",
ty = entity.get_display_name().unwrap(),
count = fields.len(),
names = fields.join(", ")
))
*/
}
}
pub fn main() {
let mut cyclecollect = CycleCollect;
let mut deriver = cderive::Deriver::new();
deriver.register("CycleCollection", &mut cyclecollect);
let result = deriver.run(&env::args().skip(1).collect::<Vec<_>>()).unwrap();
println!("{}", result);
}
|
use crate::account::*;
use crate::asset::*;
use crate::rate::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use borsh::{BorshDeserialize, BorshSerialize};
#[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
pub struct Agent {
pub account: Account,
pub is_alive: bool,
}
impl Agent {
pub fn simulate(&mut self, rates: &HashMap<Exchange, Rate>, mission: &Account) {
// Every tick agent should be able to purchase 1 MissionTime.
// First it tries to purchase MissionTime with its Resource through Exchange::MissionTimeWithResource.
// If this fails, it will try to purchase through Exchange::MissionTimeWithTrust.
// If agent cannot purchase any more MissionTime it dies.
let Quantity(lifetime_before) = self.account.quantity(&Asset::MissionTime);
let exs = [Exchange::MissionTimeWithResource, Exchange::MissionTimeWithTrust];
if let Some(Tranx::Approved(buyer, _)) = exs.iter().find_map(|ex| {
match Account::exchange(rates.get(ex).unwrap(), Quantity(1), &self.account, mission) {
Tranx::Denied(_) => None,
tranx => Some(tranx),
}
}) {
self.account = buyer;
}
let Quantity(lifetime_after) = self.account.quantity(&Asset::MissionTime);
if lifetime_after <= lifetime_before {
self.is_alive = false;
}
}
}
|
use std::collections::HashSet;
use proconio::{input, marker::Bytes};
fn main() {
input! {
h: usize,
w: usize,
a: [Bytes; h],
};
let mut row = vec![vec![0; 26]; h];
for i in 0..h {
for j in 0..w {
row[i][(a[i][j] - b'a') as usize] += 1;
}
}
let mut column = vec![vec![0; 26]; w];
for j in 0..w {
for i in 0..h {
column[j][(a[i][j] - b'a') as usize] += 1;
}
}
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
enum T {
Row(usize),
Column(usize),
}
let mut row_x = vec![0; h];
let mut column_x = vec![0; w];
let mut erase = Vec::new();
let mut seen = HashSet::new();
for i in 0..h {
let x = row[i].iter().filter(|&&c| c >= 1).count();
row_x[i] = x;
if x == 1 {
erase.push(T::Row(i));
}
}
for j in 0..w {
let x = column[j].iter().filter(|&&c| c >= 1).count();
column_x[j] = x;
if x == 1 {
erase.push(T::Column(j));
}
}
let mut a = a;
while erase.len() >= 1 {
let mut mark = Vec::new();
let mut erase_next = Vec::new();
for t in erase {
match t {
T::Row(i) => {
let cookies = (0..w).filter(|&j| a[i][j] != b'.').count();
if cookies < 2 {
continue;
}
for j in 0..w {
if a[i][j] == b'.' {
continue;
}
let c = (a[i][j] - b'a') as usize;
mark.push((i, j));
assert!(column[j][c] >= 1);
column[j][c] -= 1;
if column[j][c] == 0 {
assert!(column_x[j] >= 1);
column_x[j] -= 1;
if column_x[j] == 1 {
let next = T::Column(j);
if seen.contains(&next) == false {
seen.insert(next);
erase_next.push(next);
continue;
}
}
}
}
}
T::Column(j) => {
let cookies = (0..h).filter(|&i| a[i][j] != b'.').count();
if cookies < 2 {
continue;
}
for i in 0..h {
if a[i][j] == b'.' {
continue;
}
let c = (a[i][j] - b'a') as usize;
mark.push((i, j));
assert!(row[i][c] >= 1);
row[i][c] -= 1;
if row[i][c] == 0 {
assert!(row_x[i] >= 1);
row_x[i] -= 1;
if row_x[i] == 1 {
let next = T::Row(i);
if seen.contains(&next) == false {
seen.insert(next);
erase_next.push(next);
continue;
}
}
}
}
}
}
}
for (i, j) in mark {
a[i][j] = b'.';
}
erase = erase_next;
}
let mut ans = 0;
for i in 0..h {
for j in 0..w {
if a[i][j] != b'.' {
ans += 1;
}
}
}
println!("{}", ans);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.