file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
circuit.rs | use ff::{Field, PrimeField, PrimeFieldRepr, BitIterator};
use bellman::{Circuit, ConstraintSystem, SynthesisError};
use zcash_primitives::jubjub::{FixedGenerators, JubjubEngine, edwards, PrimeOrder, JubjubParams};
use zcash_primitives::constants;
use zcash_primitives::primitives::{PaymentAddress, ProofGenerationKey, ValueCommitment};
use zcash_proofs::circuit::ecc;
use zcash_proofs::circuit::pedersen_hash;
use bellman::gadgets::blake2s;
use bellman::gadgets::boolean;
use bellman::gadgets::multipack;
use bellman::gadgets::num;
use bellman::gadgets::Assignment;
use bellman::gadgets::test::TestConstraintSystem;
use pairing::bls12_381::Bls12;
// A circuit for proving that the given vrf_output is valid for the given vrf_input under
// a key from the predefined set. It formalizes the following language:
// {(VRF_INPUT, VRF_OUTPUT, set) | VRF_OUTPUT = vrf(sk, VRF_INPUT), PK = derive(sk) and PK is in set }, where:
// - sk, PK is an elliptic curve keypair, thus PK is a point, sk is a scalar and derive(sk) = sk * B, for a predefined base pont B
// - VRF_INPUT and VRF_OUTPUT are elliptic curve points, and vrf(sk, VRF_INPUT) = sk * VRF_INPUT
// - set //TODO
// These are the values that are required to construct the circuit and populate all the wires.
// They are defined as Options as for CRS generation only circuit structure is relevant,
// not the wires' assignments, so knowing the types is enough.
pub struct Ring<'a, E: JubjubEngine> { // TODO: name
// Jubjub curve parameters.
pub params: &'a E::Params,
// The secret key, an element of Jubjub scalar field.
pub sk: Option<E::Fs>,
// The VRF input, a point in Jubjub prime order subgroup.
pub vrf_input: Option<edwards::Point<E, PrimeOrder>>,
// The authentication path of the public key x-coordinate in the Merkle tree,
// the element of Jubjub base field.
// This is enough to build the root as the base point is hardcoded in the circuit in the lookup tables,
// so we can restore the public key from the secret key.
pub auth_path: Vec<Option<(E::Fr, bool)>>,
}
impl<'a, E: JubjubEngine> Circuit<E> for Ring<'a, E> {
fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError> {
// Binary representation of the secret key, a prover's private input.
// fs_bits wires and fs_bits booleanity constraints, where fs_bits = 252 is Jubjub scalar field size.
// It isn't (range-)constrained to be an element of the field, so small values will have duplicate representations.
// That doesn't matter for the following reasons: // TODO: double-check
// 1. Knowledge of a congruence of the secret key is equivalent to the knowledge of the secret key,
// and the check sk * G = PK passes for a congruent (sk + n|fs|) * G = sk * G + n|fs| * G == PK + O
// 2. Multiplication by a congruent secret key results in the same VRF output:
// (sk + n|fs|) * H == sk * H, if ord(H) == |fs|
let sk_bits = boolean::field_into_boolean_vec_le(cs.namespace(|| "sk"), self.sk)?;
// Derives the public key from the secret key using the hardcoded generator,
// that is guaranteed to be in the primeorder subgroup,
// so no on-curve or subgroup checks are required //TODO: double-check
// 750 constraints according to Zcash spec A.3.3.7
let pk = ecc::fixed_base_multiplication(
cs.namespace(|| "PK = sk * G"),
FixedGenerators::SpendingKeyGenerator, //TODO: any NUMS point of full order
&sk_bits,
self.params,
)?;
//
// // Defines first 2 public input wires for the coordinates of the public key in Jubjub base field (~ BLS scalar field)
// // and assures their assignment matches the values calculated in the previous step in 2 constraints.
// // These 2 constraints are not strictly required, just Bellman is implemented this way.
// // TODO: x coordinate only
// pk.inputize(cs.namespace(|| "PK"))?;
// Allocates VRF_BASE on the circuit and checks that it is a point on the curve
// adds 4 constraints (A.3.3.1) to check that it is indeed a point on Jubjub
let vrf_input = ecc::EdwardsPoint::witness(
cs.namespace(|| "VRF_INPUT"),
self.vrf_input,
self.params,
)?;
// Checks that VRF_BASE lies in a proper subgroup of Jubjub. Not strictly required as it is the point provided
// externally as a public input, so MUST be previously checked by the verifier off-circuit.
// But why not double-check it in 16 = 3 * 5 (ec doubling) + 1 (!=0) constraints
// Moreover //TODO
vrf_input.assert_not_small_order(cs.namespace(|| "VRF_BASE not small order"), self.params)?;
// Defines the 3rd and the 4th input wires to be equal VRF_BASE coordinates,
// thus adding 2 more constraints
vrf_input.inputize(cs.namespace(|| "VRF_BASE input"))?;
// Produces VRF output = sk * VRF_BASE, it is a variable base multiplication, thus
// 3252 constraints (A.3.3.8)
// TODO: actually it is 13 more as it is full-length (252 bits) multiplication below
let vrf = vrf_input.mul(cs.namespace(|| "vrf = sk * VRF_BASE"), &sk_bits, self.params)?;
// And 2 more constraints to verify the output
vrf.inputize(cs.namespace(|| "vrf"))?;
// So the circuit is 6 (public inputs) + 252 (sk booleanity) + 750 (fixed-base mul)
// + 20 (on-curve + subgroup check) + 3252 (var-base mul)
// = 4280 constraints
// This is an injective encoding, as cur is a
// point in the prime order subgroup.
let mut cur = pk.get_x().clone();
// Ascend the merkle tree authentication path
for (i, e) in self.auth_path.into_iter().enumerate() {
let cs = &mut cs.namespace(|| format!("merkle tree hash {}", i));
// Determines if the current subtree is the "right" leaf at this
// depth of the tree.
let cur_is_right = boolean::Boolean::from(boolean::AllocatedBit::alloc(
cs.namespace(|| "position bit"),
e.map(|e| e.1),
)?);
// Witness the authentication path element adjacent
// at this depth.
let path_element =
num::AllocatedNum::alloc(cs.namespace(|| "path element"), || Ok(e.get()?.0))?;
// Swap the two if the current subtree is on the right
let (xl, xr) = num::AllocatedNum::conditionally_reverse(
cs.namespace(|| "conditional reversal of preimage"),
&cur,
&path_element,
&cur_is_right,
)?;
// We don't need to be strict, because the function is
// collision-resistant. If the prover witnesses a congruency,
// they will be unable to find an authentication path in the
// tree with high probability.
let mut preimage = vec![];
preimage.extend(xl.to_bits_le(cs.namespace(|| "xl into bits"))?);
preimage.extend(xr.to_bits_le(cs.namespace(|| "xr into bits"))?);
// Compute the new subtree value
cur = pedersen_hash::pedersen_hash(
cs.namespace(|| "computation of pedersen hash"),
pedersen_hash::Personalization::MerkleTree(i),
&preimage,
self.params,
)?
.get_x()
.clone(); // Injective encoding
}
cur.inputize(cs.namespace(|| "anchor"))?;
Ok(())
}
} | use zcash_primitives::pedersen_hash;
use zcash_primitives::jubjub::{JubjubBls12, fs, edwards,};
use rand_core::{RngCore, SeedableRng,};
use rand_xorshift::XorShiftRng;
let params = &JubjubBls12::new();
let rng = &mut XorShiftRng::from_seed([
0x58, 0x62, 0xbe, 0x3d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,
]);
let sk = fs::Fs::random(rng);
let vrf_base = edwards::Point::rand(rng, params).mul_by_cofactor(params);
let base_point = params.generator(FixedGenerators::SpendingKeyGenerator);
let pk = base_point.mul(sk, params).to_xy();
let tree_depth = 10;
let auth_path = vec![Some((Fr::random(rng), rng.next_u32() % 2!= 0)); tree_depth];
let mut cur = pk.0;
for (i, val) in auth_path.clone().into_iter().enumerate() {
let (uncle, b) = val.unwrap();
let mut lhs = cur;
let mut rhs = uncle;
if b {
::std::mem::swap(&mut lhs, &mut rhs);
}
let mut lhs: Vec<bool> = BitIterator::new(lhs.into_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::new(rhs.into_repr()).collect();
lhs.reverse();
rhs.reverse();
cur = pedersen_hash::pedersen_hash::<Bls12, _>(
pedersen_hash::Personalization::MerkleTree(i),
lhs.into_iter()
.take(Fr::NUM_BITS as usize)
.chain(rhs.into_iter().take(Fr::NUM_BITS as usize)),
params,
)
.to_xy()
.0;
}
let instance = Ring {
params,
sk: Some(sk),
vrf_input: Some(vrf_base.clone()),
auth_path: auth_path.clone(),
};
let mut cs = TestConstraintSystem::<Bls12>::new();
instance.synthesize(&mut cs).unwrap();
assert!(cs.is_satisfied());
assert_eq!(cs.num_inputs(), 5 + 1); // the 1st public input predefined to be = 1
// assert_eq!(cs.num_constraints(), 4280 + 13); //TODO: 13
println!("{}", cs.num_constraints() - 4293);
assert_eq!(cs.get_input(1, "VRF_BASE input/x/input variable"), vrf_base.to_xy().0);
assert_eq!(cs.get_input(2, "VRF_BASE input/y/input variable"), vrf_base.to_xy().1);
let vrf = vrf_base.mul(sk, params).to_xy();
assert_eq!(cs.get_input(3, "vrf/x/input variable"), vrf.0);
assert_eq!(cs.get_input(4, "vrf/y/input variable"), vrf.1);
assert_eq!(cs.get_input(5, "anchor/input variable"), cur);
} |
#[test]
fn test_ring() {
use bellman::gadgets::test::TestConstraintSystem;
use pairing::bls12_381::{Bls12, Fr,}; | random_line_split |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::{mpsc, RwLock};
use psrt::client;
use psrt::DEFAULT_PRIORITY;
const ERR_TOPIC_NOT_SPECIFIED: &str = "Topic not specified";
#[derive(Clap)]
#[clap(version = psrt::VERSION, author = psrt::AUTHOR)]
struct Opts {
#[clap(name = "host:port")]
path: String,
#[clap(short = 'u')]
user: Option<String>,
#[clap(short = 'p')]
password: Option<String>,
#[clap(long = "top", about = "monitor the most used topics")]
top: bool,
#[clap(short = 't')]
topic: Option<String>,
#[clap(short ='m', about = "==size to generate")]
message: Option<String>,
#[clap(long = "benchmark")]
benchmark: bool,
#[clap(long = "benchmark-iterations", default_value = "10000")]
benchmark_iterations: u32,
#[clap(long = "benchmark-workers", default_value = "4")]
benchmark_workers: u32,
#[clap(long = "benchmark-cluster-sub", about = "subscribe to another node")]
benchmark_cluster_sub: Option<String>,
#[clap(long = "timeout", default_value = "5")]
timeout: f64,
#[clap(long = "tls")]
tls: bool,
#[clap(long = "tls-ca")]
tls_ca: Option<String>,
}
struct BenchmarkWorker {
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: Arc<RwLock<mpsc::Receiver<psrt::Message>>>,
}
impl BenchmarkWorker {
fn new(
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: mpsc::Receiver<psrt::Message>,
) -> Self {
Self {
id,
client,
r_client,
data_channel: Arc::new(RwLock::new(data_channel)),
}
}
fn is_connected(&self) -> bool {
self.r_client.as_ref().map_or_else(
|| self.client.is_connected(),
|r| r.is_connected() && self.client.is_connected(),
)
}
async fn bye(&self) -> Result<(), psrt::Error> {
self.client.bye().await?;
if let Some(ref r) = self.r_client {
r.bye().await?;
}
Ok(())
}
}
#[allow(clippy::cast_possible_truncation)]
async fn benchmark_message(
name: &str,
message: &[u8],
workers: &[Arc<BenchmarkWorker>],
iterations: u32,
wait_read: bool,
) {
let mut futures = Vec::new();
let message = Arc::new(message.to_vec());
staged_benchmark_start!(name);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
let worker = wrk.clone();
let test_msg = message.clone();
if wait_read {
if let Some(ref r_client) = wrk.r_client {
r_client.subscribe(test_topic.clone()).await.unwrap();
} else {
wrk.client.subscribe(test_topic.clone()).await.unwrap();
}
let data_fut = tokio::spawn(async move {
let mut channel = worker.data_channel.write().await;
for _ in 0..iterations {
let msg = channel.recv().await.unwrap();
assert_eq!(msg.data(), *test_msg);
}
});
futures.push(data_fut);
}
let worker = wrk.clone();
let test_msg = message.clone();
let fut = tokio::spawn(async move {
for _ in 0..iterations {
worker
.client
.publish(DEFAULT_PRIORITY, test_topic.clone(), (*test_msg).clone())
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(workers.len() as u32 * iterations);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
wrk.client.unsubscribe(test_topic.clone()).await.unwrap();
}
}
fn prepare_stat_table() -> Table {
let mut table = Table::new();
let format = prettytable::format::FormatBuilder::new()
.column_separator(' ')
.borders(' ')
.separators(
&[prettytable::format::LinePosition::Title],
prettytable::format::LineSeparator::new('-', '-', '-', '-'),
)
.padding(0, 1)
.build();
table.set_format(format);
let titlevec: Vec<prettytable::Cell> = ["topic", "count", "bytes"]
.iter()
.map(|v| prettytable::Cell::new(v).style_spec("Fb"))
.collect();
table.set_titles(prettytable::Row::new(titlevec));
table
}
//#[derive(Eq)]
struct TopicStat {
topic: String,
count: u64,
bytes: u128,
}
impl TopicStat {
fn new(topic: &str) -> Self {
Self {
topic: topic.to_owned(),
count: 0,
bytes: 0,
}
}
fn count(&mut self, size: usize) {
self.bytes += size as u128;
self.count += 1;
}
}
//impl Ord for TopicStat {
//fn cmp(&self, other: &Self) -> core::cmp::Ordering {
//self.count.cmp(&other.count)
//}
//}
//impl PartialOrd for TopicStat {
//fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
//Some(self.cmp(other))
//}
//}
//impl PartialEq for TopicStat {
//fn eq(&self, other: &Self) -> bool {
//self.count == other.count
//}
//}
struct MessageTest {
name: String,
data: Vec<u8>,
iterations: u32,
}
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
impl MessageTest {
fn new(name: &str, iterations: u32) -> Self {
let mut data = Vec::new();
let size = byte_unit::Byte::from_str(name).unwrap().get_bytes();
for i in 0..size {
data.push(i as u8);
}
Self {
name: name.to_owned(),
data,
iterations,
}
}
}
#[allow(clippy::too_many_lines)]
async fn benchmark(
config: &client::Config,
benchmark_workers: u32,
iterations: u32,
sub_node: Option<&String>,
) {
let it_total = benchmark_workers * iterations;
info!(
"Benchmarking, {} workers, {} iterations per worker...",
benchmark_workers, iterations
);
let mut rng = rand::thread_rng();
let mut workers = Vec::new();
for i in 0..benchmark_workers {
let mut client = client::Client::connect(config).await.unwrap();
let (data_channel, r_client) = if let Some(p) = sub_node {
let mut r_config = config.clone();
r_config.update_path(p);
let mut r_client = client::Client::connect(&r_config).await.unwrap();
(r_client.take_data_channel().unwrap(), Some(r_client))
} else {
(client.take_data_channel().unwrap(), None)
};
assert!(client.is_connected());
let bi: u32 = rng.gen();
workers.push(Arc::new(BenchmarkWorker::new(
format!("{}/{}", bi, i),
client,
r_client,
data_channel,
)));
}
let mut futures = Vec::new();
staged_benchmark_start!("subscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
let message_tests = vec![
MessageTest::new("10b", iterations),
MessageTest::new("1kb", iterations),
MessageTest::new("10kb", iterations),
MessageTest::new("100kb", iterations / 10),
MessageTest::new("1mb", iterations / 100),
];
for test in message_tests {
benchmark_message(
&format!("pub-{}", test.name),
&test.data,
&workers,
test.iterations,
false,
)
.await;
benchmark_message(
&format!("pub-read-{}", test.name),
&test.data,
&workers,
test.iterations,
true,
)
.await;
}
let mut futures = Vec::new();
staged_benchmark_start!("unsubscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
for wrk in &workers {
wrk.bye().await.unwrap();
assert!(!wrk.is_connected());
}
staged_benchmark_print!();
}
#[inline]
fn parse_topics(topic: Option<&String>) -> Vec<String> {
topic
.expect(ERR_TOPIC_NOT_SPECIFIED)
.split(',')
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>()
}
#[tokio::main(worker_threads = 1)]
async fn main() {
let opts = Opts::parse();
env_logger::Builder::new()
.target(env_logger::Target::Stdout)
.filter_level(if opts.benchmark || opts.top {
log::LevelFilter::Info
} else {
log::LevelFilter::Trace
})
.init();
let queue_size = if opts.benchmark { 256_000 } else { 4_096 };
let user = opts.user.unwrap_or_else(|| "".to_owned());
let password = opts.password.unwrap_or_else(|| "".to_owned());
let tls_ca = if let Some(cafile) = opts.tls_ca {
Some(tokio::fs::read_to_string(cafile).await.unwrap())
} else {
None
};
let mut config = client::Config::new(&opts.path)
.set_auth(&user, &password)
.set_queue_size(queue_size)
.set_timeout(Duration::from_secs_f64(opts.timeout))
.set_tls(opts.tls)
.set_tls_ca(tls_ca)
.build();
if opts.benchmark {
benchmark(
&config,
opts.benchmark_workers,
opts.benchmark_iterations,
opts.benchmark_cluster_sub.as_ref(),
)
.await;
} else if opts.top {
static SORT_MODE: atomic::AtomicU8 = atomic::AtomicU8::new(0);
macro_rules! cls {
() => {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
};
}
let mut client = client::Client::connect(&config).await.unwrap();
let mut data_channel = client.take_data_channel().unwrap();
let mut topic_stats: BTreeMap<String, TopicStat> = BTreeMap::new();
client
.subscribe_bulk(parse_topics(opts.topic.as_ref()))
.await
.unwrap();
let client = Arc::new(client);
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
cls!();
client.bye().await.unwrap();
std::process::exit(0);
}
});
let mut last_refresh: Option<Instant> = None;
let show_step = Duration::from_secs(1);
let mut table = prepare_stat_table();
let getch = getch::Getch::new();
std::thread::spawn(move || loop {
let ch = getch.getch().unwrap();
match ch as char {
's' => {
let s = SORT_MODE.load(atomic::Ordering::SeqCst);
SORT_MODE.store(s ^ 1, atomic::Ordering::SeqCst);
}
_ => {}
}
});
table.add_row(row![' ','','']);
cls!();
table.printstd();
loop {
let message = data_channel.recv().await.unwrap();
let topic = message.topic();
if let Some(stat) = topic_stats.get_mut(topic) {
stat.count(message.data().len());
} else {
let mut stat = TopicStat::new(topic);
stat.count(message.data().len());
topic_stats.insert(topic.to_owned(), stat);
}
if let Some(last_refresh) = last_refresh {
if last_refresh.elapsed() < show_step {
continue;
}
}
last_refresh = Some(Instant::now());
let mut stats: Vec<&TopicStat> = topic_stats.values().collect();
stats.sort_by(|a, b| {
if SORT_MODE.load(atomic::Ordering::SeqCst) == 0 {
b.count.cmp(&a.count)
} else {
b.bytes.cmp(&a.bytes)
}
});
let (_, h) = term_size::dimensions().unwrap();
stats.truncate(h - 4);
let mut table = prepare_stat_table();
for s in stats {
let byte = byte_unit::Byte::from_bytes(s.bytes);
table.add_row(row![
s.topic,
s.count.to_formatted_string(&Locale::en).replace(',', "_"),
byte.get_appropriate_unit(false)
]);
}
cls!();
table.printstd();
}
} else {
if opts.message.is_some() {
config = config.disable_data_stream();
} | if let Some(ref msg) = opts.message {
let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED);
if let Some(message_size) = msg.strip_prefix("==") {
let mut m = Vec::new();
let size = byte_unit::Byte::from_str(&message_size)
.unwrap()
.get_bytes();
for i in 0..size {
#[allow(clippy::cast_possible_truncation)]
m.push(i as u8);
}
info!("msg.len = {}", m.len());
client.publish(DEFAULT_PRIORITY, topic, m).await.unwrap();
} else {
client
.publish(DEFAULT_PRIORITY, topic, msg.as_bytes().to_vec())
.await
.unwrap();
}
} else {
let mut data_channel = client.take_data_channel().unwrap();
let topics = parse_topics(opts.topic.as_ref());
info!("Listening to {}...", topics.join(", "));
client.subscribe_bulk(topics).await.unwrap();
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
info!("terminating");
client.bye().await.unwrap();
std::process::exit(0);
}
});
loop {
let message = data_channel.recv().await.unwrap();
println!(
"{}\n---\n\"{}\"",
message.topic(),
message
.data_as_str()
.map_or_else(|_| format!("{:x?}", message.data()), ToOwned::to_owned)
);
}
}
client.bye().await.unwrap();
}
} | let mut client = client::Client::connect(&config).await.unwrap(); | random_line_split |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::{mpsc, RwLock};
use psrt::client;
use psrt::DEFAULT_PRIORITY;
const ERR_TOPIC_NOT_SPECIFIED: &str = "Topic not specified";
#[derive(Clap)]
#[clap(version = psrt::VERSION, author = psrt::AUTHOR)]
struct Opts {
#[clap(name = "host:port")]
path: String,
#[clap(short = 'u')]
user: Option<String>,
#[clap(short = 'p')]
password: Option<String>,
#[clap(long = "top", about = "monitor the most used topics")]
top: bool,
#[clap(short = 't')]
topic: Option<String>,
#[clap(short ='m', about = "==size to generate")]
message: Option<String>,
#[clap(long = "benchmark")]
benchmark: bool,
#[clap(long = "benchmark-iterations", default_value = "10000")]
benchmark_iterations: u32,
#[clap(long = "benchmark-workers", default_value = "4")]
benchmark_workers: u32,
#[clap(long = "benchmark-cluster-sub", about = "subscribe to another node")]
benchmark_cluster_sub: Option<String>,
#[clap(long = "timeout", default_value = "5")]
timeout: f64,
#[clap(long = "tls")]
tls: bool,
#[clap(long = "tls-ca")]
tls_ca: Option<String>,
}
struct BenchmarkWorker {
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: Arc<RwLock<mpsc::Receiver<psrt::Message>>>,
}
impl BenchmarkWorker {
fn new(
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: mpsc::Receiver<psrt::Message>,
) -> Self {
Self {
id,
client,
r_client,
data_channel: Arc::new(RwLock::new(data_channel)),
}
}
fn is_connected(&self) -> bool {
self.r_client.as_ref().map_or_else(
|| self.client.is_connected(),
|r| r.is_connected() && self.client.is_connected(),
)
}
async fn bye(&self) -> Result<(), psrt::Error> {
self.client.bye().await?;
if let Some(ref r) = self.r_client {
r.bye().await?;
}
Ok(())
}
}
#[allow(clippy::cast_possible_truncation)]
async fn benchmark_message(
name: &str,
message: &[u8],
workers: &[Arc<BenchmarkWorker>],
iterations: u32,
wait_read: bool,
) {
let mut futures = Vec::new();
let message = Arc::new(message.to_vec());
staged_benchmark_start!(name);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
let worker = wrk.clone();
let test_msg = message.clone();
if wait_read {
if let Some(ref r_client) = wrk.r_client {
r_client.subscribe(test_topic.clone()).await.unwrap();
} else {
wrk.client.subscribe(test_topic.clone()).await.unwrap();
}
let data_fut = tokio::spawn(async move {
let mut channel = worker.data_channel.write().await;
for _ in 0..iterations {
let msg = channel.recv().await.unwrap();
assert_eq!(msg.data(), *test_msg);
}
});
futures.push(data_fut);
}
let worker = wrk.clone();
let test_msg = message.clone();
let fut = tokio::spawn(async move {
for _ in 0..iterations {
worker
.client
.publish(DEFAULT_PRIORITY, test_topic.clone(), (*test_msg).clone())
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(workers.len() as u32 * iterations);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
wrk.client.unsubscribe(test_topic.clone()).await.unwrap();
}
}
fn prepare_stat_table() -> Table {
let mut table = Table::new();
let format = prettytable::format::FormatBuilder::new()
.column_separator(' ')
.borders(' ')
.separators(
&[prettytable::format::LinePosition::Title],
prettytable::format::LineSeparator::new('-', '-', '-', '-'),
)
.padding(0, 1)
.build();
table.set_format(format);
let titlevec: Vec<prettytable::Cell> = ["topic", "count", "bytes"]
.iter()
.map(|v| prettytable::Cell::new(v).style_spec("Fb"))
.collect();
table.set_titles(prettytable::Row::new(titlevec));
table
}
//#[derive(Eq)]
struct TopicStat {
topic: String,
count: u64,
bytes: u128,
}
impl TopicStat {
fn new(topic: &str) -> Self {
Self {
topic: topic.to_owned(),
count: 0,
bytes: 0,
}
}
fn count(&mut self, size: usize) {
self.bytes += size as u128;
self.count += 1;
}
}
//impl Ord for TopicStat {
//fn cmp(&self, other: &Self) -> core::cmp::Ordering {
//self.count.cmp(&other.count)
//}
//}
//impl PartialOrd for TopicStat {
//fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
//Some(self.cmp(other))
//}
//}
//impl PartialEq for TopicStat {
//fn eq(&self, other: &Self) -> bool {
//self.count == other.count
//}
//}
struct MessageTest {
name: String,
data: Vec<u8>,
iterations: u32,
}
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
impl MessageTest {
fn new(name: &str, iterations: u32) -> Self {
let mut data = Vec::new();
let size = byte_unit::Byte::from_str(name).unwrap().get_bytes();
for i in 0..size {
data.push(i as u8);
}
Self {
name: name.to_owned(),
data,
iterations,
}
}
}
#[allow(clippy::too_many_lines)]
async fn benchmark(
config: &client::Config,
benchmark_workers: u32,
iterations: u32,
sub_node: Option<&String>,
) {
let it_total = benchmark_workers * iterations;
info!(
"Benchmarking, {} workers, {} iterations per worker...",
benchmark_workers, iterations
);
let mut rng = rand::thread_rng();
let mut workers = Vec::new();
for i in 0..benchmark_workers {
let mut client = client::Client::connect(config).await.unwrap();
let (data_channel, r_client) = if let Some(p) = sub_node {
let mut r_config = config.clone();
r_config.update_path(p);
let mut r_client = client::Client::connect(&r_config).await.unwrap();
(r_client.take_data_channel().unwrap(), Some(r_client))
} else {
(client.take_data_channel().unwrap(), None)
};
assert!(client.is_connected());
let bi: u32 = rng.gen();
workers.push(Arc::new(BenchmarkWorker::new(
format!("{}/{}", bi, i),
client,
r_client,
data_channel,
)));
}
let mut futures = Vec::new();
staged_benchmark_start!("subscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
let message_tests = vec![
MessageTest::new("10b", iterations),
MessageTest::new("1kb", iterations),
MessageTest::new("10kb", iterations),
MessageTest::new("100kb", iterations / 10),
MessageTest::new("1mb", iterations / 100),
];
for test in message_tests {
benchmark_message(
&format!("pub-{}", test.name),
&test.data,
&workers,
test.iterations,
false,
)
.await;
benchmark_message(
&format!("pub-read-{}", test.name),
&test.data,
&workers,
test.iterations,
true,
)
.await;
}
let mut futures = Vec::new();
staged_benchmark_start!("unsubscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
for wrk in &workers {
wrk.bye().await.unwrap();
assert!(!wrk.is_connected());
}
staged_benchmark_print!();
}
#[inline]
fn | (topic: Option<&String>) -> Vec<String> {
topic
.expect(ERR_TOPIC_NOT_SPECIFIED)
.split(',')
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>()
}
#[tokio::main(worker_threads = 1)]
async fn main() {
let opts = Opts::parse();
env_logger::Builder::new()
.target(env_logger::Target::Stdout)
.filter_level(if opts.benchmark || opts.top {
log::LevelFilter::Info
} else {
log::LevelFilter::Trace
})
.init();
let queue_size = if opts.benchmark { 256_000 } else { 4_096 };
let user = opts.user.unwrap_or_else(|| "".to_owned());
let password = opts.password.unwrap_or_else(|| "".to_owned());
let tls_ca = if let Some(cafile) = opts.tls_ca {
Some(tokio::fs::read_to_string(cafile).await.unwrap())
} else {
None
};
let mut config = client::Config::new(&opts.path)
.set_auth(&user, &password)
.set_queue_size(queue_size)
.set_timeout(Duration::from_secs_f64(opts.timeout))
.set_tls(opts.tls)
.set_tls_ca(tls_ca)
.build();
if opts.benchmark {
benchmark(
&config,
opts.benchmark_workers,
opts.benchmark_iterations,
opts.benchmark_cluster_sub.as_ref(),
)
.await;
} else if opts.top {
static SORT_MODE: atomic::AtomicU8 = atomic::AtomicU8::new(0);
macro_rules! cls {
() => {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
};
}
let mut client = client::Client::connect(&config).await.unwrap();
let mut data_channel = client.take_data_channel().unwrap();
let mut topic_stats: BTreeMap<String, TopicStat> = BTreeMap::new();
client
.subscribe_bulk(parse_topics(opts.topic.as_ref()))
.await
.unwrap();
let client = Arc::new(client);
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
cls!();
client.bye().await.unwrap();
std::process::exit(0);
}
});
let mut last_refresh: Option<Instant> = None;
let show_step = Duration::from_secs(1);
let mut table = prepare_stat_table();
let getch = getch::Getch::new();
std::thread::spawn(move || loop {
let ch = getch.getch().unwrap();
match ch as char {
's' => {
let s = SORT_MODE.load(atomic::Ordering::SeqCst);
SORT_MODE.store(s ^ 1, atomic::Ordering::SeqCst);
}
_ => {}
}
});
table.add_row(row![' ','','']);
cls!();
table.printstd();
loop {
let message = data_channel.recv().await.unwrap();
let topic = message.topic();
if let Some(stat) = topic_stats.get_mut(topic) {
stat.count(message.data().len());
} else {
let mut stat = TopicStat::new(topic);
stat.count(message.data().len());
topic_stats.insert(topic.to_owned(), stat);
}
if let Some(last_refresh) = last_refresh {
if last_refresh.elapsed() < show_step {
continue;
}
}
last_refresh = Some(Instant::now());
let mut stats: Vec<&TopicStat> = topic_stats.values().collect();
stats.sort_by(|a, b| {
if SORT_MODE.load(atomic::Ordering::SeqCst) == 0 {
b.count.cmp(&a.count)
} else {
b.bytes.cmp(&a.bytes)
}
});
let (_, h) = term_size::dimensions().unwrap();
stats.truncate(h - 4);
let mut table = prepare_stat_table();
for s in stats {
let byte = byte_unit::Byte::from_bytes(s.bytes);
table.add_row(row![
s.topic,
s.count.to_formatted_string(&Locale::en).replace(',', "_"),
byte.get_appropriate_unit(false)
]);
}
cls!();
table.printstd();
}
} else {
if opts.message.is_some() {
config = config.disable_data_stream();
}
let mut client = client::Client::connect(&config).await.unwrap();
if let Some(ref msg) = opts.message {
let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED);
if let Some(message_size) = msg.strip_prefix("==") {
let mut m = Vec::new();
let size = byte_unit::Byte::from_str(&message_size)
.unwrap()
.get_bytes();
for i in 0..size {
#[allow(clippy::cast_possible_truncation)]
m.push(i as u8);
}
info!("msg.len = {}", m.len());
client.publish(DEFAULT_PRIORITY, topic, m).await.unwrap();
} else {
client
.publish(DEFAULT_PRIORITY, topic, msg.as_bytes().to_vec())
.await
.unwrap();
}
} else {
let mut data_channel = client.take_data_channel().unwrap();
let topics = parse_topics(opts.topic.as_ref());
info!("Listening to {}...", topics.join(", "));
client.subscribe_bulk(topics).await.unwrap();
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
info!("terminating");
client.bye().await.unwrap();
std::process::exit(0);
}
});
loop {
let message = data_channel.recv().await.unwrap();
println!(
"{}\n---\n\"{}\"",
message.topic(),
message
.data_as_str()
.map_or_else(|_| format!("{:x?}", message.data()), ToOwned::to_owned)
);
}
}
client.bye().await.unwrap();
}
}
| parse_topics | identifier_name |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::{mpsc, RwLock};
use psrt::client;
use psrt::DEFAULT_PRIORITY;
const ERR_TOPIC_NOT_SPECIFIED: &str = "Topic not specified";
#[derive(Clap)]
#[clap(version = psrt::VERSION, author = psrt::AUTHOR)]
struct Opts {
#[clap(name = "host:port")]
path: String,
#[clap(short = 'u')]
user: Option<String>,
#[clap(short = 'p')]
password: Option<String>,
#[clap(long = "top", about = "monitor the most used topics")]
top: bool,
#[clap(short = 't')]
topic: Option<String>,
#[clap(short ='m', about = "==size to generate")]
message: Option<String>,
#[clap(long = "benchmark")]
benchmark: bool,
#[clap(long = "benchmark-iterations", default_value = "10000")]
benchmark_iterations: u32,
#[clap(long = "benchmark-workers", default_value = "4")]
benchmark_workers: u32,
#[clap(long = "benchmark-cluster-sub", about = "subscribe to another node")]
benchmark_cluster_sub: Option<String>,
#[clap(long = "timeout", default_value = "5")]
timeout: f64,
#[clap(long = "tls")]
tls: bool,
#[clap(long = "tls-ca")]
tls_ca: Option<String>,
}
struct BenchmarkWorker {
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: Arc<RwLock<mpsc::Receiver<psrt::Message>>>,
}
impl BenchmarkWorker {
fn new(
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: mpsc::Receiver<psrt::Message>,
) -> Self {
Self {
id,
client,
r_client,
data_channel: Arc::new(RwLock::new(data_channel)),
}
}
fn is_connected(&self) -> bool {
self.r_client.as_ref().map_or_else(
|| self.client.is_connected(),
|r| r.is_connected() && self.client.is_connected(),
)
}
async fn bye(&self) -> Result<(), psrt::Error> {
self.client.bye().await?;
if let Some(ref r) = self.r_client {
r.bye().await?;
}
Ok(())
}
}
#[allow(clippy::cast_possible_truncation)]
async fn benchmark_message(
name: &str,
message: &[u8],
workers: &[Arc<BenchmarkWorker>],
iterations: u32,
wait_read: bool,
) {
let mut futures = Vec::new();
let message = Arc::new(message.to_vec());
staged_benchmark_start!(name);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
let worker = wrk.clone();
let test_msg = message.clone();
if wait_read {
if let Some(ref r_client) = wrk.r_client {
r_client.subscribe(test_topic.clone()).await.unwrap();
} else {
wrk.client.subscribe(test_topic.clone()).await.unwrap();
}
let data_fut = tokio::spawn(async move {
let mut channel = worker.data_channel.write().await;
for _ in 0..iterations {
let msg = channel.recv().await.unwrap();
assert_eq!(msg.data(), *test_msg);
}
});
futures.push(data_fut);
}
let worker = wrk.clone();
let test_msg = message.clone();
let fut = tokio::spawn(async move {
for _ in 0..iterations {
worker
.client
.publish(DEFAULT_PRIORITY, test_topic.clone(), (*test_msg).clone())
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(workers.len() as u32 * iterations);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
wrk.client.unsubscribe(test_topic.clone()).await.unwrap();
}
}
fn prepare_stat_table() -> Table {
let mut table = Table::new();
let format = prettytable::format::FormatBuilder::new()
.column_separator(' ')
.borders(' ')
.separators(
&[prettytable::format::LinePosition::Title],
prettytable::format::LineSeparator::new('-', '-', '-', '-'),
)
.padding(0, 1)
.build();
table.set_format(format);
let titlevec: Vec<prettytable::Cell> = ["topic", "count", "bytes"]
.iter()
.map(|v| prettytable::Cell::new(v).style_spec("Fb"))
.collect();
table.set_titles(prettytable::Row::new(titlevec));
table
}
//#[derive(Eq)]
struct TopicStat {
topic: String,
count: u64,
bytes: u128,
}
impl TopicStat {
fn new(topic: &str) -> Self {
Self {
topic: topic.to_owned(),
count: 0,
bytes: 0,
}
}
fn count(&mut self, size: usize) {
self.bytes += size as u128;
self.count += 1;
}
}
//impl Ord for TopicStat {
//fn cmp(&self, other: &Self) -> core::cmp::Ordering {
//self.count.cmp(&other.count)
//}
//}
//impl PartialOrd for TopicStat {
//fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
//Some(self.cmp(other))
//}
//}
//impl PartialEq for TopicStat {
//fn eq(&self, other: &Self) -> bool {
//self.count == other.count
//}
//}
struct MessageTest {
name: String,
data: Vec<u8>,
iterations: u32,
}
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
impl MessageTest {
fn new(name: &str, iterations: u32) -> Self {
let mut data = Vec::new();
let size = byte_unit::Byte::from_str(name).unwrap().get_bytes();
for i in 0..size {
data.push(i as u8);
}
Self {
name: name.to_owned(),
data,
iterations,
}
}
}
#[allow(clippy::too_many_lines)]
async fn benchmark(
config: &client::Config,
benchmark_workers: u32,
iterations: u32,
sub_node: Option<&String>,
) {
let it_total = benchmark_workers * iterations;
info!(
"Benchmarking, {} workers, {} iterations per worker...",
benchmark_workers, iterations
);
let mut rng = rand::thread_rng();
let mut workers = Vec::new();
for i in 0..benchmark_workers {
let mut client = client::Client::connect(config).await.unwrap();
let (data_channel, r_client) = if let Some(p) = sub_node {
let mut r_config = config.clone();
r_config.update_path(p);
let mut r_client = client::Client::connect(&r_config).await.unwrap();
(r_client.take_data_channel().unwrap(), Some(r_client))
} else {
(client.take_data_channel().unwrap(), None)
};
assert!(client.is_connected());
let bi: u32 = rng.gen();
workers.push(Arc::new(BenchmarkWorker::new(
format!("{}/{}", bi, i),
client,
r_client,
data_channel,
)));
}
let mut futures = Vec::new();
staged_benchmark_start!("subscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
let message_tests = vec![
MessageTest::new("10b", iterations),
MessageTest::new("1kb", iterations),
MessageTest::new("10kb", iterations),
MessageTest::new("100kb", iterations / 10),
MessageTest::new("1mb", iterations / 100),
];
for test in message_tests {
benchmark_message(
&format!("pub-{}", test.name),
&test.data,
&workers,
test.iterations,
false,
)
.await;
benchmark_message(
&format!("pub-read-{}", test.name),
&test.data,
&workers,
test.iterations,
true,
)
.await;
}
let mut futures = Vec::new();
staged_benchmark_start!("unsubscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
for wrk in &workers {
wrk.bye().await.unwrap();
assert!(!wrk.is_connected());
}
staged_benchmark_print!();
}
#[inline]
fn parse_topics(topic: Option<&String>) -> Vec<String> {
topic
.expect(ERR_TOPIC_NOT_SPECIFIED)
.split(',')
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>()
}
#[tokio::main(worker_threads = 1)]
async fn main() | .set_queue_size(queue_size)
.set_timeout(Duration::from_secs_f64(opts.timeout))
.set_tls(opts.tls)
.set_tls_ca(tls_ca)
.build();
if opts.benchmark {
benchmark(
&config,
opts.benchmark_workers,
opts.benchmark_iterations,
opts.benchmark_cluster_sub.as_ref(),
)
.await;
} else if opts.top {
static SORT_MODE: atomic::AtomicU8 = atomic::AtomicU8::new(0);
macro_rules! cls {
() => {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
};
}
let mut client = client::Client::connect(&config).await.unwrap();
let mut data_channel = client.take_data_channel().unwrap();
let mut topic_stats: BTreeMap<String, TopicStat> = BTreeMap::new();
client
.subscribe_bulk(parse_topics(opts.topic.as_ref()))
.await
.unwrap();
let client = Arc::new(client);
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
cls!();
client.bye().await.unwrap();
std::process::exit(0);
}
});
let mut last_refresh: Option<Instant> = None;
let show_step = Duration::from_secs(1);
let mut table = prepare_stat_table();
let getch = getch::Getch::new();
std::thread::spawn(move || loop {
let ch = getch.getch().unwrap();
match ch as char {
's' => {
let s = SORT_MODE.load(atomic::Ordering::SeqCst);
SORT_MODE.store(s ^ 1, atomic::Ordering::SeqCst);
}
_ => {}
}
});
table.add_row(row![' ','','']);
cls!();
table.printstd();
loop {
let message = data_channel.recv().await.unwrap();
let topic = message.topic();
if let Some(stat) = topic_stats.get_mut(topic) {
stat.count(message.data().len());
} else {
let mut stat = TopicStat::new(topic);
stat.count(message.data().len());
topic_stats.insert(topic.to_owned(), stat);
}
if let Some(last_refresh) = last_refresh {
if last_refresh.elapsed() < show_step {
continue;
}
}
last_refresh = Some(Instant::now());
let mut stats: Vec<&TopicStat> = topic_stats.values().collect();
stats.sort_by(|a, b| {
if SORT_MODE.load(atomic::Ordering::SeqCst) == 0 {
b.count.cmp(&a.count)
} else {
b.bytes.cmp(&a.bytes)
}
});
let (_, h) = term_size::dimensions().unwrap();
stats.truncate(h - 4);
let mut table = prepare_stat_table();
for s in stats {
let byte = byte_unit::Byte::from_bytes(s.bytes);
table.add_row(row![
s.topic,
s.count.to_formatted_string(&Locale::en).replace(',', "_"),
byte.get_appropriate_unit(false)
]);
}
cls!();
table.printstd();
}
} else {
if opts.message.is_some() {
config = config.disable_data_stream();
}
let mut client = client::Client::connect(&config).await.unwrap();
if let Some(ref msg) = opts.message {
let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED);
if let Some(message_size) = msg.strip_prefix("==") {
let mut m = Vec::new();
let size = byte_unit::Byte::from_str(&message_size)
.unwrap()
.get_bytes();
for i in 0..size {
#[allow(clippy::cast_possible_truncation)]
m.push(i as u8);
}
info!("msg.len = {}", m.len());
client.publish(DEFAULT_PRIORITY, topic, m).await.unwrap();
} else {
client
.publish(DEFAULT_PRIORITY, topic, msg.as_bytes().to_vec())
.await
.unwrap();
}
} else {
let mut data_channel = client.take_data_channel().unwrap();
let topics = parse_topics(opts.topic.as_ref());
info!("Listening to {}...", topics.join(", "));
client.subscribe_bulk(topics).await.unwrap();
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
info!("terminating");
client.bye().await.unwrap();
std::process::exit(0);
}
});
loop {
let message = data_channel.recv().await.unwrap();
println!(
"{}\n---\n\"{}\"",
message.topic(),
message
.data_as_str()
.map_or_else(|_| format!("{:x?}", message.data()), ToOwned::to_owned)
);
}
}
client.bye().await.unwrap();
}
}
| {
let opts = Opts::parse();
env_logger::Builder::new()
.target(env_logger::Target::Stdout)
.filter_level(if opts.benchmark || opts.top {
log::LevelFilter::Info
} else {
log::LevelFilter::Trace
})
.init();
let queue_size = if opts.benchmark { 256_000 } else { 4_096 };
let user = opts.user.unwrap_or_else(|| "".to_owned());
let password = opts.password.unwrap_or_else(|| "".to_owned());
let tls_ca = if let Some(cafile) = opts.tls_ca {
Some(tokio::fs::read_to_string(cafile).await.unwrap())
} else {
None
};
let mut config = client::Config::new(&opts.path)
.set_auth(&user, &password) | identifier_body |
cli.rs | #[macro_use]
extern crate bma_benchmark;
#[macro_use]
extern crate prettytable;
use clap::Clap;
use log::info;
use num_format::{Locale, ToFormattedString};
use prettytable::Table;
use rand::prelude::*;
use std::collections::BTreeMap;
use std::sync::{atomic, Arc};
use std::time::{Duration, Instant};
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::{mpsc, RwLock};
use psrt::client;
use psrt::DEFAULT_PRIORITY;
const ERR_TOPIC_NOT_SPECIFIED: &str = "Topic not specified";
#[derive(Clap)]
#[clap(version = psrt::VERSION, author = psrt::AUTHOR)]
struct Opts {
#[clap(name = "host:port")]
path: String,
#[clap(short = 'u')]
user: Option<String>,
#[clap(short = 'p')]
password: Option<String>,
#[clap(long = "top", about = "monitor the most used topics")]
top: bool,
#[clap(short = 't')]
topic: Option<String>,
#[clap(short ='m', about = "==size to generate")]
message: Option<String>,
#[clap(long = "benchmark")]
benchmark: bool,
#[clap(long = "benchmark-iterations", default_value = "10000")]
benchmark_iterations: u32,
#[clap(long = "benchmark-workers", default_value = "4")]
benchmark_workers: u32,
#[clap(long = "benchmark-cluster-sub", about = "subscribe to another node")]
benchmark_cluster_sub: Option<String>,
#[clap(long = "timeout", default_value = "5")]
timeout: f64,
#[clap(long = "tls")]
tls: bool,
#[clap(long = "tls-ca")]
tls_ca: Option<String>,
}
struct BenchmarkWorker {
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: Arc<RwLock<mpsc::Receiver<psrt::Message>>>,
}
impl BenchmarkWorker {
fn new(
id: String,
client: client::Client,
r_client: Option<client::Client>,
data_channel: mpsc::Receiver<psrt::Message>,
) -> Self {
Self {
id,
client,
r_client,
data_channel: Arc::new(RwLock::new(data_channel)),
}
}
fn is_connected(&self) -> bool {
self.r_client.as_ref().map_or_else(
|| self.client.is_connected(),
|r| r.is_connected() && self.client.is_connected(),
)
}
async fn bye(&self) -> Result<(), psrt::Error> {
self.client.bye().await?;
if let Some(ref r) = self.r_client {
r.bye().await?;
}
Ok(())
}
}
#[allow(clippy::cast_possible_truncation)]
async fn benchmark_message(
name: &str,
message: &[u8],
workers: &[Arc<BenchmarkWorker>],
iterations: u32,
wait_read: bool,
) {
let mut futures = Vec::new();
let message = Arc::new(message.to_vec());
staged_benchmark_start!(name);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
let worker = wrk.clone();
let test_msg = message.clone();
if wait_read {
if let Some(ref r_client) = wrk.r_client {
r_client.subscribe(test_topic.clone()).await.unwrap();
} else {
wrk.client.subscribe(test_topic.clone()).await.unwrap();
}
let data_fut = tokio::spawn(async move {
let mut channel = worker.data_channel.write().await;
for _ in 0..iterations {
let msg = channel.recv().await.unwrap();
assert_eq!(msg.data(), *test_msg);
}
});
futures.push(data_fut);
}
let worker = wrk.clone();
let test_msg = message.clone();
let fut = tokio::spawn(async move {
for _ in 0..iterations {
worker
.client
.publish(DEFAULT_PRIORITY, test_topic.clone(), (*test_msg).clone())
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(workers.len() as u32 * iterations);
for wrk in workers {
assert!(wrk.is_connected());
let test_topic = format!("benchmark/{}/test/{}", wrk.id, name);
wrk.client.unsubscribe(test_topic.clone()).await.unwrap();
}
}
fn prepare_stat_table() -> Table {
let mut table = Table::new();
let format = prettytable::format::FormatBuilder::new()
.column_separator(' ')
.borders(' ')
.separators(
&[prettytable::format::LinePosition::Title],
prettytable::format::LineSeparator::new('-', '-', '-', '-'),
)
.padding(0, 1)
.build();
table.set_format(format);
let titlevec: Vec<prettytable::Cell> = ["topic", "count", "bytes"]
.iter()
.map(|v| prettytable::Cell::new(v).style_spec("Fb"))
.collect();
table.set_titles(prettytable::Row::new(titlevec));
table
}
//#[derive(Eq)]
struct TopicStat {
topic: String,
count: u64,
bytes: u128,
}
impl TopicStat {
fn new(topic: &str) -> Self {
Self {
topic: topic.to_owned(),
count: 0,
bytes: 0,
}
}
fn count(&mut self, size: usize) {
self.bytes += size as u128;
self.count += 1;
}
}
//impl Ord for TopicStat {
//fn cmp(&self, other: &Self) -> core::cmp::Ordering {
//self.count.cmp(&other.count)
//}
//}
//impl PartialOrd for TopicStat {
//fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
//Some(self.cmp(other))
//}
//}
//impl PartialEq for TopicStat {
//fn eq(&self, other: &Self) -> bool {
//self.count == other.count
//}
//}
struct MessageTest {
name: String,
data: Vec<u8>,
iterations: u32,
}
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_truncation)]
impl MessageTest {
fn new(name: &str, iterations: u32) -> Self {
let mut data = Vec::new();
let size = byte_unit::Byte::from_str(name).unwrap().get_bytes();
for i in 0..size {
data.push(i as u8);
}
Self {
name: name.to_owned(),
data,
iterations,
}
}
}
#[allow(clippy::too_many_lines)]
async fn benchmark(
config: &client::Config,
benchmark_workers: u32,
iterations: u32,
sub_node: Option<&String>,
) {
let it_total = benchmark_workers * iterations;
info!(
"Benchmarking, {} workers, {} iterations per worker...",
benchmark_workers, iterations
);
let mut rng = rand::thread_rng();
let mut workers = Vec::new();
for i in 0..benchmark_workers {
let mut client = client::Client::connect(config).await.unwrap();
let (data_channel, r_client) = if let Some(p) = sub_node {
let mut r_config = config.clone();
r_config.update_path(p);
let mut r_client = client::Client::connect(&r_config).await.unwrap();
(r_client.take_data_channel().unwrap(), Some(r_client))
} else | ;
assert!(client.is_connected());
let bi: u32 = rng.gen();
workers.push(Arc::new(BenchmarkWorker::new(
format!("{}/{}", bi, i),
client,
r_client,
data_channel,
)));
}
let mut futures = Vec::new();
staged_benchmark_start!("subscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
let message_tests = vec![
MessageTest::new("10b", iterations),
MessageTest::new("1kb", iterations),
MessageTest::new("10kb", iterations),
MessageTest::new("100kb", iterations / 10),
MessageTest::new("1mb", iterations / 100),
];
for test in message_tests {
benchmark_message(
&format!("pub-{}", test.name),
&test.data,
&workers,
test.iterations,
false,
)
.await;
benchmark_message(
&format!("pub-read-{}", test.name),
&test.data,
&workers,
test.iterations,
true,
)
.await;
}
let mut futures = Vec::new();
staged_benchmark_start!("unsubscribe");
for wrk in &workers {
assert!(wrk.is_connected());
let worker = wrk.clone();
let fut = tokio::spawn(async move {
for i in 0..iterations {
worker
.client
.subscribe(format!("benchmark/{}/{}", worker.id, i))
.await
.unwrap();
}
});
futures.push(fut);
}
for f in futures {
f.await.unwrap();
}
staged_benchmark_finish_current!(it_total);
for wrk in &workers {
wrk.bye().await.unwrap();
assert!(!wrk.is_connected());
}
staged_benchmark_print!();
}
#[inline]
fn parse_topics(topic: Option<&String>) -> Vec<String> {
topic
.expect(ERR_TOPIC_NOT_SPECIFIED)
.split(',')
.into_iter()
.map(ToOwned::to_owned)
.collect::<Vec<String>>()
}
#[tokio::main(worker_threads = 1)]
async fn main() {
let opts = Opts::parse();
env_logger::Builder::new()
.target(env_logger::Target::Stdout)
.filter_level(if opts.benchmark || opts.top {
log::LevelFilter::Info
} else {
log::LevelFilter::Trace
})
.init();
let queue_size = if opts.benchmark { 256_000 } else { 4_096 };
let user = opts.user.unwrap_or_else(|| "".to_owned());
let password = opts.password.unwrap_or_else(|| "".to_owned());
let tls_ca = if let Some(cafile) = opts.tls_ca {
Some(tokio::fs::read_to_string(cafile).await.unwrap())
} else {
None
};
let mut config = client::Config::new(&opts.path)
.set_auth(&user, &password)
.set_queue_size(queue_size)
.set_timeout(Duration::from_secs_f64(opts.timeout))
.set_tls(opts.tls)
.set_tls_ca(tls_ca)
.build();
if opts.benchmark {
benchmark(
&config,
opts.benchmark_workers,
opts.benchmark_iterations,
opts.benchmark_cluster_sub.as_ref(),
)
.await;
} else if opts.top {
static SORT_MODE: atomic::AtomicU8 = atomic::AtomicU8::new(0);
macro_rules! cls {
() => {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
};
}
let mut client = client::Client::connect(&config).await.unwrap();
let mut data_channel = client.take_data_channel().unwrap();
let mut topic_stats: BTreeMap<String, TopicStat> = BTreeMap::new();
client
.subscribe_bulk(parse_topics(opts.topic.as_ref()))
.await
.unwrap();
let client = Arc::new(client);
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
cls!();
client.bye().await.unwrap();
std::process::exit(0);
}
});
let mut last_refresh: Option<Instant> = None;
let show_step = Duration::from_secs(1);
let mut table = prepare_stat_table();
let getch = getch::Getch::new();
std::thread::spawn(move || loop {
let ch = getch.getch().unwrap();
match ch as char {
's' => {
let s = SORT_MODE.load(atomic::Ordering::SeqCst);
SORT_MODE.store(s ^ 1, atomic::Ordering::SeqCst);
}
_ => {}
}
});
table.add_row(row![' ','','']);
cls!();
table.printstd();
loop {
let message = data_channel.recv().await.unwrap();
let topic = message.topic();
if let Some(stat) = topic_stats.get_mut(topic) {
stat.count(message.data().len());
} else {
let mut stat = TopicStat::new(topic);
stat.count(message.data().len());
topic_stats.insert(topic.to_owned(), stat);
}
if let Some(last_refresh) = last_refresh {
if last_refresh.elapsed() < show_step {
continue;
}
}
last_refresh = Some(Instant::now());
let mut stats: Vec<&TopicStat> = topic_stats.values().collect();
stats.sort_by(|a, b| {
if SORT_MODE.load(atomic::Ordering::SeqCst) == 0 {
b.count.cmp(&a.count)
} else {
b.bytes.cmp(&a.bytes)
}
});
let (_, h) = term_size::dimensions().unwrap();
stats.truncate(h - 4);
let mut table = prepare_stat_table();
for s in stats {
let byte = byte_unit::Byte::from_bytes(s.bytes);
table.add_row(row![
s.topic,
s.count.to_formatted_string(&Locale::en).replace(',', "_"),
byte.get_appropriate_unit(false)
]);
}
cls!();
table.printstd();
}
} else {
if opts.message.is_some() {
config = config.disable_data_stream();
}
let mut client = client::Client::connect(&config).await.unwrap();
if let Some(ref msg) = opts.message {
let topic = opts.topic.expect(ERR_TOPIC_NOT_SPECIFIED);
if let Some(message_size) = msg.strip_prefix("==") {
let mut m = Vec::new();
let size = byte_unit::Byte::from_str(&message_size)
.unwrap()
.get_bytes();
for i in 0..size {
#[allow(clippy::cast_possible_truncation)]
m.push(i as u8);
}
info!("msg.len = {}", m.len());
client.publish(DEFAULT_PRIORITY, topic, m).await.unwrap();
} else {
client
.publish(DEFAULT_PRIORITY, topic, msg.as_bytes().to_vec())
.await
.unwrap();
}
} else {
let mut data_channel = client.take_data_channel().unwrap();
let topics = parse_topics(opts.topic.as_ref());
info!("Listening to {}...", topics.join(", "));
client.subscribe_bulk(topics).await.unwrap();
tokio::spawn(async move {
loop {
signal(SignalKind::interrupt()).unwrap().recv().await;
info!("terminating");
client.bye().await.unwrap();
std::process::exit(0);
}
});
loop {
let message = data_channel.recv().await.unwrap();
println!(
"{}\n---\n\"{}\"",
message.topic(),
message
.data_as_str()
.map_or_else(|_| format!("{:x?}", message.data()), ToOwned::to_owned)
);
}
}
client.bye().await.unwrap();
}
}
| {
(client.take_data_channel().unwrap(), None)
} | conditional_block |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueue, Step};
use hbbft::util;
use hbbft_testing::adversary::{Adversary, NodeOrderAdversary, ReorderingAdversary};
use hbbft_testing::proptest::{gen_seed, TestRng, TestRngSeed};
use hbbft_testing::{NetBuilder, NewNodeInfo, Node, VirtualNet};
use log::info;
use proptest::{prelude::ProptestConfig, proptest};
use rand::{Rng, SeedableRng};
type NodeId = u16;
type QHB = QueueingHoneyBadger<usize, NodeId, Vec<usize>>;
type SQ = SenderQueue<QHB>;
// Send the second half of the transactions to the specified node.
fn input_second_half<A>(
net: &mut VirtualNet<SQ, A>,
id: NodeId,
num_txs: usize,
mut rng: &mut TestRng,
) where
A: Adversary<SQ>,
{
for tx in (num_txs / 2)..num_txs {
let _ = net.send_input(id, Input::User(tx), &mut rng);
}
}
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(mut net: VirtualNet<SQ, A>, num_txs: usize, mut rng: &mut TestRng)
where
A: Adversary<SQ>,
{
// Make two copies of all public keys.
let pub_keys_add = net
.correct_nodes()
.nth(0)
.expect("At least one correct node needs to exist")
.algorithm()
.algo()
.dyn_hb()
.public_keys()
.clone();
let mut pub_keys_rm = pub_keys_add.clone();
// Get the first correct node id as candidate for removal/re-adding.
let first_correct_node = *net.correct_nodes().nth(0).unwrap().id();
// Remove the first correct node, which is to be removed.
Arc::make_mut(&mut pub_keys_rm).remove(&first_correct_node);
// Broadcast public keys of all nodes except for the node to be removed.
let _ = net.broadcast_input(
&Input::Change(Change::NodeChange(pub_keys_rm.clone())),
&mut rng,
);
// Broadcast the first half of the transactions.
for tx in 0..(num_txs / 2) {
let _ = net.broadcast_input(&Input::User(tx), &mut rng);
}
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes but the removed node.
let has_remove = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_rm,
_ => false,
})
};
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes, including the previously removed node.
let has_add = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_add,
_ => false,
})
};
// Returns `true` if the node has not output all changes or transactions yet.
let node_busy = |node: &Node<SQ>| {
!has_remove(node) ||!has_add(node) ||!node.algorithm().algo().queue().is_empty()
};
// All nodes await removal.
let mut awaiting_removal: BTreeSet<_> = net.correct_nodes().map(|node| *node.id()).collect();
// All nodes but the removed node await addition.
let mut awaiting_addition: BTreeSet<_> = net
.correct_nodes()
.map(|node| *node.id())
.filter(|id| *id!= first_correct_node)
.collect();
// All, including the previously removed node, await the second half of transactions.
let mut awaiting_second_half: BTreeSet<_> = awaiting_removal.clone();
// Whether the first correct node was rejoined as a validator.
let mut rejoined_first_correct = false;
// The removed first correct node which is to be restarted as soon as all remaining
// validators agreed to add it back.
let mut saved_first_correct: Option<Node<SQ>> = None;
// Handle messages in random order until all nodes have output all transactions.
while net.correct_nodes().any(node_busy) {
let stepped_id = net.crank_expect(&mut rng).0;
if awaiting_removal.contains(&stepped_id) && has_remove(&net.get(stepped_id).unwrap()) {
awaiting_removal.remove(&stepped_id);
info!(
"{:?} has finished waiting for node removal; still waiting: {:?}",
stepped_id, awaiting_removal
);
if awaiting_removal.is_empty() {
info!("Removing first correct node from the test network");
saved_first_correct = net.remove_node(&first_correct_node);
}
// Vote to add the first correct node back.
if stepped_id!= first_correct_node {
let _ = net.send_input(
stepped_id,
Input::Change(Change::NodeChange(pub_keys_add.clone())),
rng,
);
info!(
"Input the vote to add the first correct node into {:?} with netinfo {:?}",
stepped_id,
net.get(stepped_id).unwrap().algorithm().algo().netinfo()
);
}
}
if awaiting_removal.is_empty() && awaiting_addition.contains(&stepped_id) {
// If the stepped node started voting to add the first correct node back,
// take a note of that and rejoin it.
if let Some(join_plan) =
net.get(stepped_id)
.unwrap()
.outputs()
.iter()
.find_map(|batch| match batch.change() {
ChangeState::InProgress(Change::NodeChange(pub_keys))
if pub_keys == &pub_keys_add =>
{
batch.join_plan()
}
_ => None,
})
{
awaiting_addition.remove(&stepped_id);
info!(
"{:?} has finished waiting for node addition; still waiting: {:?}",
stepped_id, awaiting_addition
);
if awaiting_addition.is_empty() &&!rejoined_first_correct {
let node = saved_first_correct
.take()
.expect("first correct node wasn't saved");
let step = restart_node_for_add(&mut net, node, join_plan, &mut rng);
net.process_step(first_correct_node, &step)
.expect("processing a step failed");
rejoined_first_correct = true;
}
}
}
if rejoined_first_correct && awaiting_second_half.contains(&stepped_id) {
// Input the second half of user transactions into the stepped node.
input_second_half(&mut net, stepped_id, num_txs, &mut rng);
awaiting_second_half.remove(&stepped_id);
}
}
let node_1 = net
.correct_nodes()
.nth(1)
.expect("second correct node is missing");
net.verify_batches(node_1);
}
/// Restarts specified node on the test network for adding it back as a validator.
fn restart_node_for_add<R, A>(
net: &mut VirtualNet<SQ, A>,
mut node: Node<SQ>,
join_plan: JoinPlan<NodeId>,
mut rng: &mut R,
) -> Step<QueueingHoneyBadger<usize, NodeId, Vec<usize>>>
where
R: rand::Rng,
A: Adversary<SQ>,
{
let our_id = *node.id();
println!("Restarting node {} with {:?}", node.id(), join_plan);
// TODO: When an observer node is added to the network, it should also be added to peer_ids.
let peer_ids: Vec<_> = net
.nodes()
.map(Node::id)
.filter(|id| *id!= node.id())
.cloned()
.collect();
let secret_key = node.algorithm().algo().dyn_hb().secret_key().clone();
let (qhb, qhb_step) =
QueueingHoneyBadger::builder_joining(our_id, secret_key, join_plan, &mut rng)
.and_then(|builder| builder.batch_size(3).build(&mut rng))
.expect("failed to rebuild the node with a join plan");
let (sq, mut sq_step) = SenderQueue::builder(qhb, peer_ids.into_iter()).build(our_id);
*node.algorithm_mut() = sq;
sq_step.extend(qhb_step.map(|output| output, |fault| fault, Message::from));
net.insert_node(node);
sq_step
}
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[allow(clippy::needless_pass_by_value)]
fn | (node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) {
let mut rng: TestRng = TestRng::from_seed(seed);
let peer_ids = node_info.netinfo.other_ids().cloned();
let netinfo = node_info.netinfo.clone();
let dhb =
DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_info.pub_keys);
let (qhb, qhb_step) = QueueingHoneyBadger::builder(dhb)
.batch_size(3)
.build(&mut rng)
.expect("failed to build QueueingHoneyBadger");
let our_id = *node_info.netinfo.our_id();
let (sq, mut step) = SenderQueue::builder(qhb, peer_ids).build(our_id);
let output = step.extend_with(qhb_step, |fault| fault, Message::from);
assert!(output.is_empty());
(sq, step)
}
fn test_queueing_honey_badger_different_sizes<A, F>(
new_adversary: F,
num_txs: usize,
seed: TestRngSeed,
) where
A: Adversary<SQ>,
F: Fn() -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();
let mut rng: TestRng = TestRng::from_seed(seed);
let sizes = vec![3, 5, rng.gen_range(6, 10)];
for size in sizes {
// The test is removing one correct node, so we allow fewer faulty ones.
let num_adv_nodes = util::max_faulty(size - 1);
let num_good_nodes = size - num_adv_nodes;
info!(
"Network size: {} good nodes, {} faulty nodes",
num_good_nodes, num_adv_nodes
);
let (net, _) = NetBuilder::new(0..size as u16)
.num_faulty(num_adv_nodes)
.message_limit(20_000 * size)
.no_time_limit()
.adversary(new_adversary())
.using_step(move |node_info: NewNodeInfo<_>| {
// Note: The "seed" variable is implicitly copied by the move closure.
// The "Copy" trait is *not* implemented for TestRng, which additionally
// needs to be mutable, while we are in a function which captures immutably.
// To avoid convoluted clone/borrow constructs we pass a TestRngSeed
// rather than a TestRng instance.
new_queueing_hb(node_info, seed)
})
.build(&mut rng)
.expect("Could not construct test network.");
test_queueing_honey_badger(net, num_txs, &mut rng);
}
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 1,.. ProptestConfig::default()
})]
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_random_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_random_delivery_silent(seed)
}
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_first_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_first_delivery_silent(seed)
}
}
fn do_test_queueing_honey_badger_random_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed);
}
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed);
}
| new_queueing_hb | identifier_name |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueue, Step};
use hbbft::util;
use hbbft_testing::adversary::{Adversary, NodeOrderAdversary, ReorderingAdversary};
use hbbft_testing::proptest::{gen_seed, TestRng, TestRngSeed};
use hbbft_testing::{NetBuilder, NewNodeInfo, Node, VirtualNet};
use log::info;
use proptest::{prelude::ProptestConfig, proptest};
use rand::{Rng, SeedableRng};
type NodeId = u16;
type QHB = QueueingHoneyBadger<usize, NodeId, Vec<usize>>;
type SQ = SenderQueue<QHB>;
// Send the second half of the transactions to the specified node.
fn input_second_half<A>(
net: &mut VirtualNet<SQ, A>,
id: NodeId,
num_txs: usize,
mut rng: &mut TestRng,
) where
A: Adversary<SQ>,
{
for tx in (num_txs / 2)..num_txs {
let _ = net.send_input(id, Input::User(tx), &mut rng);
}
}
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(mut net: VirtualNet<SQ, A>, num_txs: usize, mut rng: &mut TestRng)
where
A: Adversary<SQ>,
{
// Make two copies of all public keys.
let pub_keys_add = net
.correct_nodes()
.nth(0)
.expect("At least one correct node needs to exist")
.algorithm()
.algo()
.dyn_hb()
.public_keys()
.clone();
let mut pub_keys_rm = pub_keys_add.clone();
// Get the first correct node id as candidate for removal/re-adding.
let first_correct_node = *net.correct_nodes().nth(0).unwrap().id();
// Remove the first correct node, which is to be removed.
Arc::make_mut(&mut pub_keys_rm).remove(&first_correct_node);
// Broadcast public keys of all nodes except for the node to be removed.
let _ = net.broadcast_input(
&Input::Change(Change::NodeChange(pub_keys_rm.clone())),
&mut rng,
);
// Broadcast the first half of the transactions.
for tx in 0..(num_txs / 2) {
let _ = net.broadcast_input(&Input::User(tx), &mut rng);
}
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes but the removed node.
let has_remove = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_rm,
_ => false,
})
};
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes, including the previously removed node.
let has_add = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_add,
_ => false,
})
};
// Returns `true` if the node has not output all changes or transactions yet.
let node_busy = |node: &Node<SQ>| {
!has_remove(node) ||!has_add(node) ||!node.algorithm().algo().queue().is_empty()
};
// All nodes await removal.
let mut awaiting_removal: BTreeSet<_> = net.correct_nodes().map(|node| *node.id()).collect();
// All nodes but the removed node await addition.
let mut awaiting_addition: BTreeSet<_> = net
.correct_nodes()
.map(|node| *node.id())
.filter(|id| *id!= first_correct_node)
.collect();
// All, including the previously removed node, await the second half of transactions.
let mut awaiting_second_half: BTreeSet<_> = awaiting_removal.clone();
// Whether the first correct node was rejoined as a validator.
let mut rejoined_first_correct = false;
// The removed first correct node which is to be restarted as soon as all remaining
// validators agreed to add it back.
let mut saved_first_correct: Option<Node<SQ>> = None;
// Handle messages in random order until all nodes have output all transactions.
while net.correct_nodes().any(node_busy) {
let stepped_id = net.crank_expect(&mut rng).0;
if awaiting_removal.contains(&stepped_id) && has_remove(&net.get(stepped_id).unwrap()) {
awaiting_removal.remove(&stepped_id); | info!(
"{:?} has finished waiting for node removal; still waiting: {:?}",
stepped_id, awaiting_removal
);
if awaiting_removal.is_empty() {
info!("Removing first correct node from the test network");
saved_first_correct = net.remove_node(&first_correct_node);
}
// Vote to add the first correct node back.
if stepped_id!= first_correct_node {
let _ = net.send_input(
stepped_id,
Input::Change(Change::NodeChange(pub_keys_add.clone())),
rng,
);
info!(
"Input the vote to add the first correct node into {:?} with netinfo {:?}",
stepped_id,
net.get(stepped_id).unwrap().algorithm().algo().netinfo()
);
}
}
if awaiting_removal.is_empty() && awaiting_addition.contains(&stepped_id) {
// If the stepped node started voting to add the first correct node back,
// take a note of that and rejoin it.
if let Some(join_plan) =
net.get(stepped_id)
.unwrap()
.outputs()
.iter()
.find_map(|batch| match batch.change() {
ChangeState::InProgress(Change::NodeChange(pub_keys))
if pub_keys == &pub_keys_add =>
{
batch.join_plan()
}
_ => None,
})
{
awaiting_addition.remove(&stepped_id);
info!(
"{:?} has finished waiting for node addition; still waiting: {:?}",
stepped_id, awaiting_addition
);
if awaiting_addition.is_empty() &&!rejoined_first_correct {
let node = saved_first_correct
.take()
.expect("first correct node wasn't saved");
let step = restart_node_for_add(&mut net, node, join_plan, &mut rng);
net.process_step(first_correct_node, &step)
.expect("processing a step failed");
rejoined_first_correct = true;
}
}
}
if rejoined_first_correct && awaiting_second_half.contains(&stepped_id) {
// Input the second half of user transactions into the stepped node.
input_second_half(&mut net, stepped_id, num_txs, &mut rng);
awaiting_second_half.remove(&stepped_id);
}
}
let node_1 = net
.correct_nodes()
.nth(1)
.expect("second correct node is missing");
net.verify_batches(node_1);
}
/// Restarts specified node on the test network for adding it back as a validator.
fn restart_node_for_add<R, A>(
net: &mut VirtualNet<SQ, A>,
mut node: Node<SQ>,
join_plan: JoinPlan<NodeId>,
mut rng: &mut R,
) -> Step<QueueingHoneyBadger<usize, NodeId, Vec<usize>>>
where
R: rand::Rng,
A: Adversary<SQ>,
{
let our_id = *node.id();
println!("Restarting node {} with {:?}", node.id(), join_plan);
// TODO: When an observer node is added to the network, it should also be added to peer_ids.
let peer_ids: Vec<_> = net
.nodes()
.map(Node::id)
.filter(|id| *id!= node.id())
.cloned()
.collect();
let secret_key = node.algorithm().algo().dyn_hb().secret_key().clone();
let (qhb, qhb_step) =
QueueingHoneyBadger::builder_joining(our_id, secret_key, join_plan, &mut rng)
.and_then(|builder| builder.batch_size(3).build(&mut rng))
.expect("failed to rebuild the node with a join plan");
let (sq, mut sq_step) = SenderQueue::builder(qhb, peer_ids.into_iter()).build(our_id);
*node.algorithm_mut() = sq;
sq_step.extend(qhb_step.map(|output| output, |fault| fault, Message::from));
net.insert_node(node);
sq_step
}
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[allow(clippy::needless_pass_by_value)]
fn new_queueing_hb(node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) {
let mut rng: TestRng = TestRng::from_seed(seed);
let peer_ids = node_info.netinfo.other_ids().cloned();
let netinfo = node_info.netinfo.clone();
let dhb =
DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_info.pub_keys);
let (qhb, qhb_step) = QueueingHoneyBadger::builder(dhb)
.batch_size(3)
.build(&mut rng)
.expect("failed to build QueueingHoneyBadger");
let our_id = *node_info.netinfo.our_id();
let (sq, mut step) = SenderQueue::builder(qhb, peer_ids).build(our_id);
let output = step.extend_with(qhb_step, |fault| fault, Message::from);
assert!(output.is_empty());
(sq, step)
}
fn test_queueing_honey_badger_different_sizes<A, F>(
new_adversary: F,
num_txs: usize,
seed: TestRngSeed,
) where
A: Adversary<SQ>,
F: Fn() -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();
let mut rng: TestRng = TestRng::from_seed(seed);
let sizes = vec![3, 5, rng.gen_range(6, 10)];
for size in sizes {
// The test is removing one correct node, so we allow fewer faulty ones.
let num_adv_nodes = util::max_faulty(size - 1);
let num_good_nodes = size - num_adv_nodes;
info!(
"Network size: {} good nodes, {} faulty nodes",
num_good_nodes, num_adv_nodes
);
let (net, _) = NetBuilder::new(0..size as u16)
.num_faulty(num_adv_nodes)
.message_limit(20_000 * size)
.no_time_limit()
.adversary(new_adversary())
.using_step(move |node_info: NewNodeInfo<_>| {
// Note: The "seed" variable is implicitly copied by the move closure.
// The "Copy" trait is *not* implemented for TestRng, which additionally
// needs to be mutable, while we are in a function which captures immutably.
// To avoid convoluted clone/borrow constructs we pass a TestRngSeed
// rather than a TestRng instance.
new_queueing_hb(node_info, seed)
})
.build(&mut rng)
.expect("Could not construct test network.");
test_queueing_honey_badger(net, num_txs, &mut rng);
}
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 1,.. ProptestConfig::default()
})]
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_random_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_random_delivery_silent(seed)
}
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_first_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_first_delivery_silent(seed)
}
}
fn do_test_queueing_honey_badger_random_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed);
}
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed);
} | random_line_split |
|
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueue, Step};
use hbbft::util;
use hbbft_testing::adversary::{Adversary, NodeOrderAdversary, ReorderingAdversary};
use hbbft_testing::proptest::{gen_seed, TestRng, TestRngSeed};
use hbbft_testing::{NetBuilder, NewNodeInfo, Node, VirtualNet};
use log::info;
use proptest::{prelude::ProptestConfig, proptest};
use rand::{Rng, SeedableRng};
type NodeId = u16;
type QHB = QueueingHoneyBadger<usize, NodeId, Vec<usize>>;
type SQ = SenderQueue<QHB>;
// Send the second half of the transactions to the specified node.
fn input_second_half<A>(
net: &mut VirtualNet<SQ, A>,
id: NodeId,
num_txs: usize,
mut rng: &mut TestRng,
) where
A: Adversary<SQ>,
{
for tx in (num_txs / 2)..num_txs {
let _ = net.send_input(id, Input::User(tx), &mut rng);
}
}
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(mut net: VirtualNet<SQ, A>, num_txs: usize, mut rng: &mut TestRng)
where
A: Adversary<SQ>,
{
// Make two copies of all public keys.
let pub_keys_add = net
.correct_nodes()
.nth(0)
.expect("At least one correct node needs to exist")
.algorithm()
.algo()
.dyn_hb()
.public_keys()
.clone();
let mut pub_keys_rm = pub_keys_add.clone();
// Get the first correct node id as candidate for removal/re-adding.
let first_correct_node = *net.correct_nodes().nth(0).unwrap().id();
// Remove the first correct node, which is to be removed.
Arc::make_mut(&mut pub_keys_rm).remove(&first_correct_node);
// Broadcast public keys of all nodes except for the node to be removed.
let _ = net.broadcast_input(
&Input::Change(Change::NodeChange(pub_keys_rm.clone())),
&mut rng,
);
// Broadcast the first half of the transactions.
for tx in 0..(num_txs / 2) {
let _ = net.broadcast_input(&Input::User(tx), &mut rng);
}
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes but the removed node.
let has_remove = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_rm,
_ => false,
})
};
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes, including the previously removed node.
let has_add = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_add,
_ => false,
})
};
// Returns `true` if the node has not output all changes or transactions yet.
let node_busy = |node: &Node<SQ>| {
!has_remove(node) ||!has_add(node) ||!node.algorithm().algo().queue().is_empty()
};
// All nodes await removal.
let mut awaiting_removal: BTreeSet<_> = net.correct_nodes().map(|node| *node.id()).collect();
// All nodes but the removed node await addition.
let mut awaiting_addition: BTreeSet<_> = net
.correct_nodes()
.map(|node| *node.id())
.filter(|id| *id!= first_correct_node)
.collect();
// All, including the previously removed node, await the second half of transactions.
let mut awaiting_second_half: BTreeSet<_> = awaiting_removal.clone();
// Whether the first correct node was rejoined as a validator.
let mut rejoined_first_correct = false;
// The removed first correct node which is to be restarted as soon as all remaining
// validators agreed to add it back.
let mut saved_first_correct: Option<Node<SQ>> = None;
// Handle messages in random order until all nodes have output all transactions.
while net.correct_nodes().any(node_busy) {
let stepped_id = net.crank_expect(&mut rng).0;
if awaiting_removal.contains(&stepped_id) && has_remove(&net.get(stepped_id).unwrap()) {
awaiting_removal.remove(&stepped_id);
info!(
"{:?} has finished waiting for node removal; still waiting: {:?}",
stepped_id, awaiting_removal
);
if awaiting_removal.is_empty() {
info!("Removing first correct node from the test network");
saved_first_correct = net.remove_node(&first_correct_node);
}
// Vote to add the first correct node back.
if stepped_id!= first_correct_node {
let _ = net.send_input(
stepped_id,
Input::Change(Change::NodeChange(pub_keys_add.clone())),
rng,
);
info!(
"Input the vote to add the first correct node into {:?} with netinfo {:?}",
stepped_id,
net.get(stepped_id).unwrap().algorithm().algo().netinfo()
);
}
}
if awaiting_removal.is_empty() && awaiting_addition.contains(&stepped_id) {
// If the stepped node started voting to add the first correct node back,
// take a note of that and rejoin it.
if let Some(join_plan) =
net.get(stepped_id)
.unwrap()
.outputs()
.iter()
.find_map(|batch| match batch.change() {
ChangeState::InProgress(Change::NodeChange(pub_keys))
if pub_keys == &pub_keys_add =>
{
batch.join_plan()
}
_ => None,
})
{
awaiting_addition.remove(&stepped_id);
info!(
"{:?} has finished waiting for node addition; still waiting: {:?}",
stepped_id, awaiting_addition
);
if awaiting_addition.is_empty() &&!rejoined_first_correct {
let node = saved_first_correct
.take()
.expect("first correct node wasn't saved");
let step = restart_node_for_add(&mut net, node, join_plan, &mut rng);
net.process_step(first_correct_node, &step)
.expect("processing a step failed");
rejoined_first_correct = true;
}
}
}
if rejoined_first_correct && awaiting_second_half.contains(&stepped_id) {
// Input the second half of user transactions into the stepped node.
input_second_half(&mut net, stepped_id, num_txs, &mut rng);
awaiting_second_half.remove(&stepped_id);
}
}
let node_1 = net
.correct_nodes()
.nth(1)
.expect("second correct node is missing");
net.verify_batches(node_1);
}
/// Restarts specified node on the test network for adding it back as a validator.
fn restart_node_for_add<R, A>(
net: &mut VirtualNet<SQ, A>,
mut node: Node<SQ>,
join_plan: JoinPlan<NodeId>,
mut rng: &mut R,
) -> Step<QueueingHoneyBadger<usize, NodeId, Vec<usize>>>
where
R: rand::Rng,
A: Adversary<SQ>,
{
let our_id = *node.id();
println!("Restarting node {} with {:?}", node.id(), join_plan);
// TODO: When an observer node is added to the network, it should also be added to peer_ids.
let peer_ids: Vec<_> = net
.nodes()
.map(Node::id)
.filter(|id| *id!= node.id())
.cloned()
.collect();
let secret_key = node.algorithm().algo().dyn_hb().secret_key().clone();
let (qhb, qhb_step) =
QueueingHoneyBadger::builder_joining(our_id, secret_key, join_plan, &mut rng)
.and_then(|builder| builder.batch_size(3).build(&mut rng))
.expect("failed to rebuild the node with a join plan");
let (sq, mut sq_step) = SenderQueue::builder(qhb, peer_ids.into_iter()).build(our_id);
*node.algorithm_mut() = sq;
sq_step.extend(qhb_step.map(|output| output, |fault| fault, Message::from));
net.insert_node(node);
sq_step
}
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[allow(clippy::needless_pass_by_value)]
fn new_queueing_hb(node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) {
let mut rng: TestRng = TestRng::from_seed(seed);
let peer_ids = node_info.netinfo.other_ids().cloned();
let netinfo = node_info.netinfo.clone();
let dhb =
DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_info.pub_keys);
let (qhb, qhb_step) = QueueingHoneyBadger::builder(dhb)
.batch_size(3)
.build(&mut rng)
.expect("failed to build QueueingHoneyBadger");
let our_id = *node_info.netinfo.our_id();
let (sq, mut step) = SenderQueue::builder(qhb, peer_ids).build(our_id);
let output = step.extend_with(qhb_step, |fault| fault, Message::from);
assert!(output.is_empty());
(sq, step)
}
fn test_queueing_honey_badger_different_sizes<A, F>(
new_adversary: F,
num_txs: usize,
seed: TestRngSeed,
) where
A: Adversary<SQ>,
F: Fn() -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();
let mut rng: TestRng = TestRng::from_seed(seed);
let sizes = vec![3, 5, rng.gen_range(6, 10)];
for size in sizes {
// The test is removing one correct node, so we allow fewer faulty ones.
let num_adv_nodes = util::max_faulty(size - 1);
let num_good_nodes = size - num_adv_nodes;
info!(
"Network size: {} good nodes, {} faulty nodes",
num_good_nodes, num_adv_nodes
);
let (net, _) = NetBuilder::new(0..size as u16)
.num_faulty(num_adv_nodes)
.message_limit(20_000 * size)
.no_time_limit()
.adversary(new_adversary())
.using_step(move |node_info: NewNodeInfo<_>| {
// Note: The "seed" variable is implicitly copied by the move closure.
// The "Copy" trait is *not* implemented for TestRng, which additionally
// needs to be mutable, while we are in a function which captures immutably.
// To avoid convoluted clone/borrow constructs we pass a TestRngSeed
// rather than a TestRng instance.
new_queueing_hb(node_info, seed)
})
.build(&mut rng)
.expect("Could not construct test network.");
test_queueing_honey_badger(net, num_txs, &mut rng);
}
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 1,.. ProptestConfig::default()
})]
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_random_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_random_delivery_silent(seed)
}
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_first_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_first_delivery_silent(seed)
}
}
fn do_test_queueing_honey_badger_random_delivery_silent(seed: TestRngSeed) |
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed);
}
| {
test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed);
} | identifier_body |
queueing_honey_badger.rs | #![deny(unused_must_use)]
//! Network tests for Queueing Honey Badger.
use std::collections::BTreeSet;
use std::sync::Arc;
use hbbft::dynamic_honey_badger::{DynamicHoneyBadger, JoinPlan};
use hbbft::queueing_honey_badger::{Change, ChangeState, Input, QueueingHoneyBadger};
use hbbft::sender_queue::{Message, SenderQueue, Step};
use hbbft::util;
use hbbft_testing::adversary::{Adversary, NodeOrderAdversary, ReorderingAdversary};
use hbbft_testing::proptest::{gen_seed, TestRng, TestRngSeed};
use hbbft_testing::{NetBuilder, NewNodeInfo, Node, VirtualNet};
use log::info;
use proptest::{prelude::ProptestConfig, proptest};
use rand::{Rng, SeedableRng};
type NodeId = u16;
type QHB = QueueingHoneyBadger<usize, NodeId, Vec<usize>>;
type SQ = SenderQueue<QHB>;
// Send the second half of the transactions to the specified node.
fn input_second_half<A>(
net: &mut VirtualNet<SQ, A>,
id: NodeId,
num_txs: usize,
mut rng: &mut TestRng,
) where
A: Adversary<SQ>,
{
for tx in (num_txs / 2)..num_txs {
let _ = net.send_input(id, Input::User(tx), &mut rng);
}
}
/// Proposes `num_txs` values and expects nodes to output and order them.
fn test_queueing_honey_badger<A>(mut net: VirtualNet<SQ, A>, num_txs: usize, mut rng: &mut TestRng)
where
A: Adversary<SQ>,
{
// Make two copies of all public keys.
let pub_keys_add = net
.correct_nodes()
.nth(0)
.expect("At least one correct node needs to exist")
.algorithm()
.algo()
.dyn_hb()
.public_keys()
.clone();
let mut pub_keys_rm = pub_keys_add.clone();
// Get the first correct node id as candidate for removal/re-adding.
let first_correct_node = *net.correct_nodes().nth(0).unwrap().id();
// Remove the first correct node, which is to be removed.
Arc::make_mut(&mut pub_keys_rm).remove(&first_correct_node);
// Broadcast public keys of all nodes except for the node to be removed.
let _ = net.broadcast_input(
&Input::Change(Change::NodeChange(pub_keys_rm.clone())),
&mut rng,
);
// Broadcast the first half of the transactions.
for tx in 0..(num_txs / 2) {
let _ = net.broadcast_input(&Input::User(tx), &mut rng);
}
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes but the removed node.
let has_remove = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_rm,
_ => false,
})
};
// Closure for checking the output of a node for ChangeSet completion containing
// all nodes, including the previously removed node.
let has_add = |node: &Node<SQ>| {
node.outputs().iter().any(|batch| match batch.change() {
ChangeState::Complete(Change::NodeChange(pub_keys)) => pub_keys == &pub_keys_add,
_ => false,
})
};
// Returns `true` if the node has not output all changes or transactions yet.
let node_busy = |node: &Node<SQ>| {
!has_remove(node) ||!has_add(node) ||!node.algorithm().algo().queue().is_empty()
};
// All nodes await removal.
let mut awaiting_removal: BTreeSet<_> = net.correct_nodes().map(|node| *node.id()).collect();
// All nodes but the removed node await addition.
let mut awaiting_addition: BTreeSet<_> = net
.correct_nodes()
.map(|node| *node.id())
.filter(|id| *id!= first_correct_node)
.collect();
// All, including the previously removed node, await the second half of transactions.
let mut awaiting_second_half: BTreeSet<_> = awaiting_removal.clone();
// Whether the first correct node was rejoined as a validator.
let mut rejoined_first_correct = false;
// The removed first correct node which is to be restarted as soon as all remaining
// validators agreed to add it back.
let mut saved_first_correct: Option<Node<SQ>> = None;
// Handle messages in random order until all nodes have output all transactions.
while net.correct_nodes().any(node_busy) {
let stepped_id = net.crank_expect(&mut rng).0;
if awaiting_removal.contains(&stepped_id) && has_remove(&net.get(stepped_id).unwrap()) {
awaiting_removal.remove(&stepped_id);
info!(
"{:?} has finished waiting for node removal; still waiting: {:?}",
stepped_id, awaiting_removal
);
if awaiting_removal.is_empty() {
info!("Removing first correct node from the test network");
saved_first_correct = net.remove_node(&first_correct_node);
}
// Vote to add the first correct node back.
if stepped_id!= first_correct_node {
let _ = net.send_input(
stepped_id,
Input::Change(Change::NodeChange(pub_keys_add.clone())),
rng,
);
info!(
"Input the vote to add the first correct node into {:?} with netinfo {:?}",
stepped_id,
net.get(stepped_id).unwrap().algorithm().algo().netinfo()
);
}
}
if awaiting_removal.is_empty() && awaiting_addition.contains(&stepped_id) | stepped_id, awaiting_addition
);
if awaiting_addition.is_empty() &&!rejoined_first_correct {
let node = saved_first_correct
.take()
.expect("first correct node wasn't saved");
let step = restart_node_for_add(&mut net, node, join_plan, &mut rng);
net.process_step(first_correct_node, &step)
.expect("processing a step failed");
rejoined_first_correct = true;
}
}
}
if rejoined_first_correct && awaiting_second_half.contains(&stepped_id) {
// Input the second half of user transactions into the stepped node.
input_second_half(&mut net, stepped_id, num_txs, &mut rng);
awaiting_second_half.remove(&stepped_id);
}
}
let node_1 = net
.correct_nodes()
.nth(1)
.expect("second correct node is missing");
net.verify_batches(node_1);
}
/// Restarts specified node on the test network for adding it back as a validator.
fn restart_node_for_add<R, A>(
net: &mut VirtualNet<SQ, A>,
mut node: Node<SQ>,
join_plan: JoinPlan<NodeId>,
mut rng: &mut R,
) -> Step<QueueingHoneyBadger<usize, NodeId, Vec<usize>>>
where
R: rand::Rng,
A: Adversary<SQ>,
{
let our_id = *node.id();
println!("Restarting node {} with {:?}", node.id(), join_plan);
// TODO: When an observer node is added to the network, it should also be added to peer_ids.
let peer_ids: Vec<_> = net
.nodes()
.map(Node::id)
.filter(|id| *id!= node.id())
.cloned()
.collect();
let secret_key = node.algorithm().algo().dyn_hb().secret_key().clone();
let (qhb, qhb_step) =
QueueingHoneyBadger::builder_joining(our_id, secret_key, join_plan, &mut rng)
.and_then(|builder| builder.batch_size(3).build(&mut rng))
.expect("failed to rebuild the node with a join plan");
let (sq, mut sq_step) = SenderQueue::builder(qhb, peer_ids.into_iter()).build(our_id);
*node.algorithm_mut() = sq;
sq_step.extend(qhb_step.map(|output| output, |fault| fault, Message::from));
net.insert_node(node);
sq_step
}
// Allow passing `netinfo` by value. `TestNetwork` expects this function signature.
#[allow(clippy::needless_pass_by_value)]
fn new_queueing_hb(node_info: NewNodeInfo<SQ>, seed: TestRngSeed) -> (SQ, Step<QHB>) {
let mut rng: TestRng = TestRng::from_seed(seed);
let peer_ids = node_info.netinfo.other_ids().cloned();
let netinfo = node_info.netinfo.clone();
let dhb =
DynamicHoneyBadger::builder().build(netinfo, node_info.secret_key, node_info.pub_keys);
let (qhb, qhb_step) = QueueingHoneyBadger::builder(dhb)
.batch_size(3)
.build(&mut rng)
.expect("failed to build QueueingHoneyBadger");
let our_id = *node_info.netinfo.our_id();
let (sq, mut step) = SenderQueue::builder(qhb, peer_ids).build(our_id);
let output = step.extend_with(qhb_step, |fault| fault, Message::from);
assert!(output.is_empty());
(sq, step)
}
fn test_queueing_honey_badger_different_sizes<A, F>(
new_adversary: F,
num_txs: usize,
seed: TestRngSeed,
) where
A: Adversary<SQ>,
F: Fn() -> A,
{
// This returns an error in all but the first test.
let _ = env_logger::try_init();
let mut rng: TestRng = TestRng::from_seed(seed);
let sizes = vec![3, 5, rng.gen_range(6, 10)];
for size in sizes {
// The test is removing one correct node, so we allow fewer faulty ones.
let num_adv_nodes = util::max_faulty(size - 1);
let num_good_nodes = size - num_adv_nodes;
info!(
"Network size: {} good nodes, {} faulty nodes",
num_good_nodes, num_adv_nodes
);
let (net, _) = NetBuilder::new(0..size as u16)
.num_faulty(num_adv_nodes)
.message_limit(20_000 * size)
.no_time_limit()
.adversary(new_adversary())
.using_step(move |node_info: NewNodeInfo<_>| {
// Note: The "seed" variable is implicitly copied by the move closure.
// The "Copy" trait is *not* implemented for TestRng, which additionally
// needs to be mutable, while we are in a function which captures immutably.
// To avoid convoluted clone/borrow constructs we pass a TestRngSeed
// rather than a TestRng instance.
new_queueing_hb(node_info, seed)
})
.build(&mut rng)
.expect("Could not construct test network.");
test_queueing_honey_badger(net, num_txs, &mut rng);
}
}
proptest! {
#![proptest_config(ProptestConfig {
cases: 1,.. ProptestConfig::default()
})]
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_random_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_random_delivery_silent(seed)
}
#[test]
#[allow(clippy::unnecessary_operation)]
fn test_queueing_honey_badger_first_delivery_silent(seed in gen_seed()) {
do_test_queueing_honey_badger_first_delivery_silent(seed)
}
}
fn do_test_queueing_honey_badger_random_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(ReorderingAdversary::new, 30, seed);
}
fn do_test_queueing_honey_badger_first_delivery_silent(seed: TestRngSeed) {
test_queueing_honey_badger_different_sizes(NodeOrderAdversary::new, 30, seed);
}
| {
// If the stepped node started voting to add the first correct node back,
// take a note of that and rejoin it.
if let Some(join_plan) =
net.get(stepped_id)
.unwrap()
.outputs()
.iter()
.find_map(|batch| match batch.change() {
ChangeState::InProgress(Change::NodeChange(pub_keys))
if pub_keys == &pub_keys_add =>
{
batch.join_plan()
}
_ => None,
})
{
awaiting_addition.remove(&stepped_id);
info!(
"{:?} has finished waiting for node addition; still waiting: {:?}", | conditional_block |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A cache that holds a limited number of key-value pairs. When the
//! capacity of the cache is exceeded, the least-recently-used
//! (where "used" means a look-up or putting the pair into the cache)
//! pair is automatically removed.
//!
//! # Example
//!
//! ```rust
//! use collections::LruCache;
//!
//! let mut cache: LruCache<int, int> = LruCache::new(2);
//! cache.put(1, 10);
//! cache.put(2, 20);
//! cache.put(3, 30);
//! assert!(cache.get(&1).is_none());
//! assert_eq!(*cache.get(&2).unwrap(), 20);
//! assert_eq!(*cache.get(&3).unwrap(), 30);
//!
//! cache.put(2, 22);
//! assert_eq!(*cache.get(&2).unwrap(), 22);
//!
//! cache.put(6, 60);
//! assert!(cache.get(&3).is_none());
//!
//! cache.change_capacity(1);
//! assert!(cache.get(&2).is_none());
//! ```
use std::cast;
use std::container::Container;
use std::hash::Hash;
use std::fmt;
use std::ptr;
use HashMap;
struct KeyRef<K> { k: *K }
struct LruEntry<K, V> {
key: Option<K>,
value: Option<V>,
next: *mut LruEntry<K, V>,
prev: *mut LruEntry<K, V>,
}
/// An LRU Cache.
pub struct LruCache<K, V> {
map: HashMap<KeyRef<K>, ~LruEntry<K, V>>,
max_size: uint,
head: *mut LruEntry<K, V>,
tail: *mut LruEntry<K, V>,
}
impl<S, K: Hash<S>> Hash<S> for KeyRef<K> {
fn hash(&self, state: &mut S) {
unsafe { (*self.k).hash(state) }
}
}
impl<K: Eq> Eq for KeyRef<K> {
fn eq(&self, other: &KeyRef<K>) -> bool {
unsafe{ (*self.k).eq(&*other.k) }
}
}
impl<K: TotalEq> TotalEq for KeyRef<K> {}
impl<K, V> LruEntry<K, V> {
fn new() -> LruEntry<K, V> {
LruEntry {
key: None,
value: None,
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
fn with_key_value(k: K, v: V) -> LruEntry<K, V> {
LruEntry {
key: Some(k),
value: Some(v),
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
}
impl<K: Hash + TotalEq, V> LruCache<K, V> {
/// Create an LRU Cache that holds at most `capacity` items.
pub fn new(capacity: uint) -> LruCache<K, V> {
let cache = LruCache {
map: HashMap::new(),
max_size: capacity,
head: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
tail: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
};
unsafe {
(*cache.head).next = cache.tail;
(*cache.tail).prev = cache.head;
}
return cache;
}
/// Put a key-value pair into cache.
pub fn put(&mut self, k: K, v: V) {
let mut key_existed = false;
let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) {
Some(node) => {
key_existed = true;
node.value = Some(v);
let node_ptr: *mut LruEntry<K, V> = &mut **node;
(node_ptr, None)
}
None => {
let mut node = ~LruEntry::with_key_value(k, v);
let node_ptr: *mut LruEntry<K, V> = &mut *node;
(node_ptr, Some(node))
}
};
if key_existed {
self.detach(node_ptr);
self.attach(node_ptr);
} else {
let keyref = unsafe { (*node_ptr).key.as_ref().unwrap() };
self.map.swap(KeyRef{k: keyref}, node_opt.unwrap());
self.attach(node_ptr);
if self.len() > self.capacity() {
self.remove_lru();
}
}
}
/// Return a value corresponding to the key in the cache.
pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> {
let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) {
None => (None, None),
Some(node) => {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
unsafe {
match (*node_ptr).value {
None => (None, None),
Some(ref value) => (Some(value), Some(node_ptr))
}
}
}
};
match node_ptr_opt {
None => (),
Some(node_ptr) => {
self.detach(node_ptr);
self.attach(node_ptr);
}
}
return value;
}
/// Remove and return a value corresponding to the key from the cache.
pub fn pop(&mut self, k: &K) -> Option<V> {
match self.map.pop(&KeyRef{k: k}) {
None => None,
Some(lru_entry) => lru_entry.value
}
}
/// Return the maximum number of key-value pairs the cache can hold.
pub fn capacity(&self) -> uint {
self.max_size
}
/// Change the number of key-value pairs the cache can hold. Remove
/// least-recently-used key-value pairs if necessary.
pub fn change_capacity(&mut self, capacity: uint) {
for _ in range(capacity, self.len()) {
self.remove_lru();
}
self.max_size = capacity;
}
#[inline]
fn remove_lru(&mut self) {
if self.len() > 0 {
let lru = unsafe { (*self.tail).prev };
self.detach(lru);
unsafe {
match (*lru).key {
None => (),
Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
}
}
}
}
#[inline]
fn detach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*(*node).prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
}
}
#[inline]
fn attach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = (*self.head).next;
(*node).prev = self.head;
(*self.head).next = node;
(*(*node).next).prev = node;
}
}
}
impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// Return a string that lists the key-value pairs from most-recently
/// used to least-recently used.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
let mut cur = self.head;
for i in range(0, self.len()) {
if i > 0 { try!(write!(f.buf, ", ")) }
unsafe {
cur = (*cur).next;
match (*cur).key {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref k) => try!(write!(f.buf, "{}", *k)),
}
}
try!(write!(f.buf, ": "));
unsafe {
match (*cur).value {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref value) => try!(write!(f.buf, "{}", *value)),
}
}
}
write!(f.buf, r"\}")
}
}
impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
}
}
#[unsafe_destructor]
impl<K, V> Drop for LruCache<K, V> {
fn | (&mut self) {
unsafe {
let _: ~LruEntry<K, V> = cast::transmute(self.head);
let _: ~LruEntry<K, V> = cast::transmute(self.tail);
}
}
}
#[cfg(test)]
mod tests {
use super::LruCache;
fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
assert!(opt.is_some());
assert!(opt.unwrap() == &v);
}
#[test]
fn test_put_and_get() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_opt_eq(cache.get(&1), 10);
assert_opt_eq(cache.get(&2), 20);
assert_eq!(cache.len(), 2);
}
#[test]
fn test_put_update() {
let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1);
cache.put(~"1", vec![10, 10]);
cache.put(~"1", vec![10, 19]);
assert_opt_eq(cache.get(&~"1"), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<~str, ~str> = LruCache::new(2);
cache.put(~"foo1", ~"bar1");
cache.put(~"foo2", ~"bar2");
cache.put(~"foo3", ~"bar3");
assert!(cache.get(&~"foo1").is_none());
cache.put(~"foo2", ~"bar2update");
cache.put(~"foo4", ~"bar4");
assert!(cache.get(&~"foo3").is_none());
}
#[test]
fn test_pop() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_eq!(cache.len(), 2);
let opt1 = cache.pop(&1);
assert!(opt1.is_some());
assert_eq!(opt1.unwrap(), 10);
assert!(cache.get(&1).is_none());
assert_eq!(cache.len(), 1);
}
#[test]
fn test_change_capacity() {
let mut cache: LruCache<int, int> = LruCache::new(2);
assert_eq!(cache.capacity(), 2);
cache.put(1, 10);
cache.put(2, 20);
cache.change_capacity(1);
assert!(cache.get(&1).is_none());
assert_eq!(cache.capacity(), 1);
}
#[test]
fn test_to_str() {
let mut cache: LruCache<int, int> = LruCache::new(3);
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
cache.put(2, 22);
assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
cache.put(6, 60);
assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
cache.get(&3);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
cache.change_capacity(2);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
}
#[test]
fn test_clear() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
assert_eq!(cache.to_str(), ~"{}");
}
}
| drop | identifier_name |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A cache that holds a limited number of key-value pairs. When the
//! capacity of the cache is exceeded, the least-recently-used
//! (where "used" means a look-up or putting the pair into the cache)
//! pair is automatically removed.
//!
//! # Example
//!
//! ```rust
//! use collections::LruCache;
//!
//! let mut cache: LruCache<int, int> = LruCache::new(2);
//! cache.put(1, 10);
//! cache.put(2, 20);
//! cache.put(3, 30);
//! assert!(cache.get(&1).is_none());
//! assert_eq!(*cache.get(&2).unwrap(), 20);
//! assert_eq!(*cache.get(&3).unwrap(), 30);
//!
//! cache.put(2, 22);
//! assert_eq!(*cache.get(&2).unwrap(), 22);
//!
//! cache.put(6, 60);
//! assert!(cache.get(&3).is_none());
//!
//! cache.change_capacity(1);
//! assert!(cache.get(&2).is_none());
//! ```
use std::cast;
use std::container::Container;
use std::hash::Hash;
use std::fmt;
use std::ptr;
use HashMap;
struct KeyRef<K> { k: *K }
struct LruEntry<K, V> {
key: Option<K>,
value: Option<V>,
next: *mut LruEntry<K, V>,
prev: *mut LruEntry<K, V>,
}
/// An LRU Cache.
pub struct LruCache<K, V> {
map: HashMap<KeyRef<K>, ~LruEntry<K, V>>,
max_size: uint,
head: *mut LruEntry<K, V>,
tail: *mut LruEntry<K, V>,
}
impl<S, K: Hash<S>> Hash<S> for KeyRef<K> {
fn hash(&self, state: &mut S) {
unsafe { (*self.k).hash(state) }
}
}
impl<K: Eq> Eq for KeyRef<K> {
fn eq(&self, other: &KeyRef<K>) -> bool {
unsafe{ (*self.k).eq(&*other.k) }
}
}
impl<K: TotalEq> TotalEq for KeyRef<K> {}
impl<K, V> LruEntry<K, V> {
fn new() -> LruEntry<K, V> {
LruEntry {
key: None,
value: None,
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
fn with_key_value(k: K, v: V) -> LruEntry<K, V> {
LruEntry {
key: Some(k),
value: Some(v),
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
}
impl<K: Hash + TotalEq, V> LruCache<K, V> {
/// Create an LRU Cache that holds at most `capacity` items.
pub fn new(capacity: uint) -> LruCache<K, V> {
let cache = LruCache {
map: HashMap::new(),
max_size: capacity,
head: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
tail: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
};
unsafe {
(*cache.head).next = cache.tail;
(*cache.tail).prev = cache.head;
}
return cache;
}
/// Put a key-value pair into cache.
pub fn put(&mut self, k: K, v: V) {
let mut key_existed = false;
let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) {
Some(node) => {
key_existed = true;
node.value = Some(v);
let node_ptr: *mut LruEntry<K, V> = &mut **node;
(node_ptr, None)
}
None => {
let mut node = ~LruEntry::with_key_value(k, v);
let node_ptr: *mut LruEntry<K, V> = &mut *node;
(node_ptr, Some(node))
}
};
if key_existed {
self.detach(node_ptr);
self.attach(node_ptr);
} else {
let keyref = unsafe { (*node_ptr).key.as_ref().unwrap() };
self.map.swap(KeyRef{k: keyref}, node_opt.unwrap());
self.attach(node_ptr);
if self.len() > self.capacity() {
self.remove_lru();
}
}
}
/// Return a value corresponding to the key in the cache.
pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> {
let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) {
None => (None, None),
Some(node) => {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
unsafe {
match (*node_ptr).value {
None => (None, None),
Some(ref value) => (Some(value), Some(node_ptr))
}
}
}
};
match node_ptr_opt {
None => (),
Some(node_ptr) => {
self.detach(node_ptr);
self.attach(node_ptr);
}
}
return value;
}
/// Remove and return a value corresponding to the key from the cache.
pub fn pop(&mut self, k: &K) -> Option<V> {
match self.map.pop(&KeyRef{k: k}) {
None => None,
Some(lru_entry) => lru_entry.value
}
}
/// Return the maximum number of key-value pairs the cache can hold.
pub fn capacity(&self) -> uint {
self.max_size
}
/// Change the number of key-value pairs the cache can hold. Remove
/// least-recently-used key-value pairs if necessary.
pub fn change_capacity(&mut self, capacity: uint) {
for _ in range(capacity, self.len()) {
self.remove_lru();
}
self.max_size = capacity;
}
#[inline]
fn remove_lru(&mut self) {
if self.len() > 0 {
let lru = unsafe { (*self.tail).prev };
self.detach(lru);
unsafe {
match (*lru).key {
None => (),
Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
}
}
}
}
#[inline]
fn detach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*(*node).prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
}
}
#[inline]
fn attach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = (*self.head).next;
(*node).prev = self.head;
(*self.head).next = node;
(*(*node).next).prev = node;
}
}
}
impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// Return a string that lists the key-value pairs from most-recently
/// used to least-recently used.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
let mut cur = self.head;
for i in range(0, self.len()) {
if i > 0 |
unsafe {
cur = (*cur).next;
match (*cur).key {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref k) => try!(write!(f.buf, "{}", *k)),
}
}
try!(write!(f.buf, ": "));
unsafe {
match (*cur).value {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref value) => try!(write!(f.buf, "{}", *value)),
}
}
}
write!(f.buf, r"\}")
}
}
impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
}
}
#[unsafe_destructor]
impl<K, V> Drop for LruCache<K, V> {
fn drop(&mut self) {
unsafe {
let _: ~LruEntry<K, V> = cast::transmute(self.head);
let _: ~LruEntry<K, V> = cast::transmute(self.tail);
}
}
}
#[cfg(test)]
mod tests {
use super::LruCache;
fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
assert!(opt.is_some());
assert!(opt.unwrap() == &v);
}
#[test]
fn test_put_and_get() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_opt_eq(cache.get(&1), 10);
assert_opt_eq(cache.get(&2), 20);
assert_eq!(cache.len(), 2);
}
#[test]
fn test_put_update() {
let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1);
cache.put(~"1", vec![10, 10]);
cache.put(~"1", vec![10, 19]);
assert_opt_eq(cache.get(&~"1"), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<~str, ~str> = LruCache::new(2);
cache.put(~"foo1", ~"bar1");
cache.put(~"foo2", ~"bar2");
cache.put(~"foo3", ~"bar3");
assert!(cache.get(&~"foo1").is_none());
cache.put(~"foo2", ~"bar2update");
cache.put(~"foo4", ~"bar4");
assert!(cache.get(&~"foo3").is_none());
}
#[test]
fn test_pop() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_eq!(cache.len(), 2);
let opt1 = cache.pop(&1);
assert!(opt1.is_some());
assert_eq!(opt1.unwrap(), 10);
assert!(cache.get(&1).is_none());
assert_eq!(cache.len(), 1);
}
#[test]
fn test_change_capacity() {
let mut cache: LruCache<int, int> = LruCache::new(2);
assert_eq!(cache.capacity(), 2);
cache.put(1, 10);
cache.put(2, 20);
cache.change_capacity(1);
assert!(cache.get(&1).is_none());
assert_eq!(cache.capacity(), 1);
}
#[test]
fn test_to_str() {
let mut cache: LruCache<int, int> = LruCache::new(3);
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
cache.put(2, 22);
assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
cache.put(6, 60);
assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
cache.get(&3);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
cache.change_capacity(2);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
}
#[test]
fn test_clear() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
assert_eq!(cache.to_str(), ~"{}");
}
}
| { try!(write!(f.buf, ", ")) } | conditional_block |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A cache that holds a limited number of key-value pairs. When the
//! capacity of the cache is exceeded, the least-recently-used
//! (where "used" means a look-up or putting the pair into the cache)
//! pair is automatically removed.
//!
//! # Example
//!
//! ```rust
//! use collections::LruCache;
//!
//! let mut cache: LruCache<int, int> = LruCache::new(2);
//! cache.put(1, 10);
//! cache.put(2, 20);
//! cache.put(3, 30);
//! assert!(cache.get(&1).is_none());
//! assert_eq!(*cache.get(&2).unwrap(), 20);
//! assert_eq!(*cache.get(&3).unwrap(), 30);
//!
//! cache.put(2, 22);
//! assert_eq!(*cache.get(&2).unwrap(), 22);
//!
//! cache.put(6, 60);
//! assert!(cache.get(&3).is_none());
//!
//! cache.change_capacity(1);
//! assert!(cache.get(&2).is_none());
//! ```
use std::cast;
use std::container::Container;
use std::hash::Hash;
use std::fmt;
use std::ptr;
use HashMap;
struct KeyRef<K> { k: *K }
struct LruEntry<K, V> {
key: Option<K>,
value: Option<V>,
next: *mut LruEntry<K, V>,
prev: *mut LruEntry<K, V>,
}
/// An LRU Cache.
pub struct LruCache<K, V> {
map: HashMap<KeyRef<K>, ~LruEntry<K, V>>,
max_size: uint,
head: *mut LruEntry<K, V>,
tail: *mut LruEntry<K, V>,
}
impl<S, K: Hash<S>> Hash<S> for KeyRef<K> {
fn hash(&self, state: &mut S) {
unsafe { (*self.k).hash(state) }
}
}
impl<K: Eq> Eq for KeyRef<K> {
fn eq(&self, other: &KeyRef<K>) -> bool {
unsafe{ (*self.k).eq(&*other.k) }
}
}
impl<K: TotalEq> TotalEq for KeyRef<K> {}
impl<K, V> LruEntry<K, V> {
fn new() -> LruEntry<K, V> {
LruEntry {
key: None,
value: None,
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
fn with_key_value(k: K, v: V) -> LruEntry<K, V> {
LruEntry {
key: Some(k),
value: Some(v),
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
}
impl<K: Hash + TotalEq, V> LruCache<K, V> {
/// Create an LRU Cache that holds at most `capacity` items.
pub fn new(capacity: uint) -> LruCache<K, V> {
let cache = LruCache {
map: HashMap::new(),
max_size: capacity,
head: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
tail: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
};
unsafe {
(*cache.head).next = cache.tail;
(*cache.tail).prev = cache.head;
}
return cache;
}
/// Put a key-value pair into cache.
pub fn put(&mut self, k: K, v: V) {
let mut key_existed = false;
let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) {
Some(node) => {
key_existed = true;
node.value = Some(v);
let node_ptr: *mut LruEntry<K, V> = &mut **node;
(node_ptr, None)
}
None => {
let mut node = ~LruEntry::with_key_value(k, v);
let node_ptr: *mut LruEntry<K, V> = &mut *node;
(node_ptr, Some(node))
}
};
if key_existed {
self.detach(node_ptr);
self.attach(node_ptr);
} else {
let keyref = unsafe { (*node_ptr).key.as_ref().unwrap() };
self.map.swap(KeyRef{k: keyref}, node_opt.unwrap());
self.attach(node_ptr);
if self.len() > self.capacity() {
self.remove_lru();
}
}
}
/// Return a value corresponding to the key in the cache.
pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> {
let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) {
None => (None, None),
Some(node) => {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
unsafe {
match (*node_ptr).value {
None => (None, None),
Some(ref value) => (Some(value), Some(node_ptr))
}
}
}
};
match node_ptr_opt {
None => (),
Some(node_ptr) => {
self.detach(node_ptr);
self.attach(node_ptr);
}
}
return value;
}
/// Remove and return a value corresponding to the key from the cache.
pub fn pop(&mut self, k: &K) -> Option<V> {
match self.map.pop(&KeyRef{k: k}) {
None => None,
Some(lru_entry) => lru_entry.value
}
}
/// Return the maximum number of key-value pairs the cache can hold.
pub fn capacity(&self) -> uint {
self.max_size
}
/// Change the number of key-value pairs the cache can hold. Remove
/// least-recently-used key-value pairs if necessary.
pub fn change_capacity(&mut self, capacity: uint) {
for _ in range(capacity, self.len()) {
self.remove_lru();
}
self.max_size = capacity;
}
#[inline]
fn remove_lru(&mut self) {
if self.len() > 0 {
let lru = unsafe { (*self.tail).prev };
self.detach(lru);
unsafe {
match (*lru).key {
None => (),
Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
}
}
}
}
#[inline]
fn detach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*(*node).prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
}
}
#[inline]
fn attach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = (*self.head).next;
(*node).prev = self.head;
(*self.head).next = node;
(*(*node).next).prev = node;
}
}
}
impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// Return a string that lists the key-value pairs from most-recently
/// used to least-recently used.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
let mut cur = self.head;
for i in range(0, self.len()) {
if i > 0 { try!(write!(f.buf, ", ")) }
unsafe {
cur = (*cur).next;
match (*cur).key {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref k) => try!(write!(f.buf, "{}", *k)),
}
}
try!(write!(f.buf, ": "));
unsafe {
match (*cur).value {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref value) => try!(write!(f.buf, "{}", *value)),
}
}
} | write!(f.buf, r"\}")
}
}
impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
}
}
#[unsafe_destructor]
impl<K, V> Drop for LruCache<K, V> {
fn drop(&mut self) {
unsafe {
let _: ~LruEntry<K, V> = cast::transmute(self.head);
let _: ~LruEntry<K, V> = cast::transmute(self.tail);
}
}
}
#[cfg(test)]
mod tests {
use super::LruCache;
fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
assert!(opt.is_some());
assert!(opt.unwrap() == &v);
}
#[test]
fn test_put_and_get() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_opt_eq(cache.get(&1), 10);
assert_opt_eq(cache.get(&2), 20);
assert_eq!(cache.len(), 2);
}
#[test]
fn test_put_update() {
let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1);
cache.put(~"1", vec![10, 10]);
cache.put(~"1", vec![10, 19]);
assert_opt_eq(cache.get(&~"1"), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<~str, ~str> = LruCache::new(2);
cache.put(~"foo1", ~"bar1");
cache.put(~"foo2", ~"bar2");
cache.put(~"foo3", ~"bar3");
assert!(cache.get(&~"foo1").is_none());
cache.put(~"foo2", ~"bar2update");
cache.put(~"foo4", ~"bar4");
assert!(cache.get(&~"foo3").is_none());
}
#[test]
fn test_pop() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_eq!(cache.len(), 2);
let opt1 = cache.pop(&1);
assert!(opt1.is_some());
assert_eq!(opt1.unwrap(), 10);
assert!(cache.get(&1).is_none());
assert_eq!(cache.len(), 1);
}
#[test]
fn test_change_capacity() {
let mut cache: LruCache<int, int> = LruCache::new(2);
assert_eq!(cache.capacity(), 2);
cache.put(1, 10);
cache.put(2, 20);
cache.change_capacity(1);
assert!(cache.get(&1).is_none());
assert_eq!(cache.capacity(), 1);
}
#[test]
fn test_to_str() {
let mut cache: LruCache<int, int> = LruCache::new(3);
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
cache.put(2, 22);
assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
cache.put(6, 60);
assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
cache.get(&3);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
cache.change_capacity(2);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
}
#[test]
fn test_clear() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
assert_eq!(cache.to_str(), ~"{}");
}
} | random_line_split |
|
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A cache that holds a limited number of key-value pairs. When the
//! capacity of the cache is exceeded, the least-recently-used
//! (where "used" means a look-up or putting the pair into the cache)
//! pair is automatically removed.
//!
//! # Example
//!
//! ```rust
//! use collections::LruCache;
//!
//! let mut cache: LruCache<int, int> = LruCache::new(2);
//! cache.put(1, 10);
//! cache.put(2, 20);
//! cache.put(3, 30);
//! assert!(cache.get(&1).is_none());
//! assert_eq!(*cache.get(&2).unwrap(), 20);
//! assert_eq!(*cache.get(&3).unwrap(), 30);
//!
//! cache.put(2, 22);
//! assert_eq!(*cache.get(&2).unwrap(), 22);
//!
//! cache.put(6, 60);
//! assert!(cache.get(&3).is_none());
//!
//! cache.change_capacity(1);
//! assert!(cache.get(&2).is_none());
//! ```
use std::cast;
use std::container::Container;
use std::hash::Hash;
use std::fmt;
use std::ptr;
use HashMap;
struct KeyRef<K> { k: *K }
struct LruEntry<K, V> {
key: Option<K>,
value: Option<V>,
next: *mut LruEntry<K, V>,
prev: *mut LruEntry<K, V>,
}
/// An LRU Cache.
pub struct LruCache<K, V> {
map: HashMap<KeyRef<K>, ~LruEntry<K, V>>,
max_size: uint,
head: *mut LruEntry<K, V>,
tail: *mut LruEntry<K, V>,
}
impl<S, K: Hash<S>> Hash<S> for KeyRef<K> {
fn hash(&self, state: &mut S) {
unsafe { (*self.k).hash(state) }
}
}
impl<K: Eq> Eq for KeyRef<K> {
fn eq(&self, other: &KeyRef<K>) -> bool {
unsafe{ (*self.k).eq(&*other.k) }
}
}
impl<K: TotalEq> TotalEq for KeyRef<K> {}
impl<K, V> LruEntry<K, V> {
fn new() -> LruEntry<K, V> {
LruEntry {
key: None,
value: None,
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
fn with_key_value(k: K, v: V) -> LruEntry<K, V> {
LruEntry {
key: Some(k),
value: Some(v),
next: ptr::mut_null(),
prev: ptr::mut_null(),
}
}
}
impl<K: Hash + TotalEq, V> LruCache<K, V> {
/// Create an LRU Cache that holds at most `capacity` items.
pub fn new(capacity: uint) -> LruCache<K, V> {
let cache = LruCache {
map: HashMap::new(),
max_size: capacity,
head: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
tail: unsafe{ cast::transmute(~LruEntry::<K, V>::new()) },
};
unsafe {
(*cache.head).next = cache.tail;
(*cache.tail).prev = cache.head;
}
return cache;
}
/// Put a key-value pair into cache.
pub fn put(&mut self, k: K, v: V) {
let mut key_existed = false;
let (node_ptr, node_opt) = match self.map.find_mut(&KeyRef{k: &k}) {
Some(node) => {
key_existed = true;
node.value = Some(v);
let node_ptr: *mut LruEntry<K, V> = &mut **node;
(node_ptr, None)
}
None => {
let mut node = ~LruEntry::with_key_value(k, v);
let node_ptr: *mut LruEntry<K, V> = &mut *node;
(node_ptr, Some(node))
}
};
if key_existed {
self.detach(node_ptr);
self.attach(node_ptr);
} else {
let keyref = unsafe { (*node_ptr).key.as_ref().unwrap() };
self.map.swap(KeyRef{k: keyref}, node_opt.unwrap());
self.attach(node_ptr);
if self.len() > self.capacity() {
self.remove_lru();
}
}
}
/// Return a value corresponding to the key in the cache.
pub fn get<'a>(&'a mut self, k: &K) -> Option<&'a V> {
let (value, node_ptr_opt) = match self.map.find_mut(&KeyRef{k: k}) {
None => (None, None),
Some(node) => {
let node_ptr: *mut LruEntry<K, V> = &mut **node;
unsafe {
match (*node_ptr).value {
None => (None, None),
Some(ref value) => (Some(value), Some(node_ptr))
}
}
}
};
match node_ptr_opt {
None => (),
Some(node_ptr) => {
self.detach(node_ptr);
self.attach(node_ptr);
}
}
return value;
}
/// Remove and return a value corresponding to the key from the cache.
pub fn pop(&mut self, k: &K) -> Option<V> {
match self.map.pop(&KeyRef{k: k}) {
None => None,
Some(lru_entry) => lru_entry.value
}
}
/// Return the maximum number of key-value pairs the cache can hold.
pub fn capacity(&self) -> uint {
self.max_size
}
/// Change the number of key-value pairs the cache can hold. Remove
/// least-recently-used key-value pairs if necessary.
pub fn change_capacity(&mut self, capacity: uint) {
for _ in range(capacity, self.len()) {
self.remove_lru();
}
self.max_size = capacity;
}
#[inline]
fn remove_lru(&mut self) |
#[inline]
fn detach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*(*node).prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
}
}
#[inline]
fn attach(&mut self, node: *mut LruEntry<K, V>) {
unsafe {
(*node).next = (*self.head).next;
(*node).prev = self.head;
(*self.head).next = node;
(*(*node).next).prev = node;
}
}
}
impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// Return a string that lists the key-value pairs from most-recently
/// used to least-recently used.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
let mut cur = self.head;
for i in range(0, self.len()) {
if i > 0 { try!(write!(f.buf, ", ")) }
unsafe {
cur = (*cur).next;
match (*cur).key {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref k) => try!(write!(f.buf, "{}", *k)),
}
}
try!(write!(f.buf, ": "));
unsafe {
match (*cur).value {
// should never print nil
None => try!(write!(f.buf, "nil")),
Some(ref value) => try!(write!(f.buf, "{}", *value)),
}
}
}
write!(f.buf, r"\}")
}
}
impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
}
}
#[unsafe_destructor]
impl<K, V> Drop for LruCache<K, V> {
fn drop(&mut self) {
unsafe {
let _: ~LruEntry<K, V> = cast::transmute(self.head);
let _: ~LruEntry<K, V> = cast::transmute(self.tail);
}
}
}
#[cfg(test)]
mod tests {
use super::LruCache;
fn assert_opt_eq<V: Eq>(opt: Option<&V>, v: V) {
assert!(opt.is_some());
assert!(opt.unwrap() == &v);
}
#[test]
fn test_put_and_get() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_opt_eq(cache.get(&1), 10);
assert_opt_eq(cache.get(&2), 20);
assert_eq!(cache.len(), 2);
}
#[test]
fn test_put_update() {
let mut cache: LruCache<~str, Vec<u8>> = LruCache::new(1);
cache.put(~"1", vec![10, 10]);
cache.put(~"1", vec![10, 19]);
assert_opt_eq(cache.get(&~"1"), vec![10, 19]);
assert_eq!(cache.len(), 1);
}
#[test]
fn test_expire_lru() {
let mut cache: LruCache<~str, ~str> = LruCache::new(2);
cache.put(~"foo1", ~"bar1");
cache.put(~"foo2", ~"bar2");
cache.put(~"foo3", ~"bar3");
assert!(cache.get(&~"foo1").is_none());
cache.put(~"foo2", ~"bar2update");
cache.put(~"foo4", ~"bar4");
assert!(cache.get(&~"foo3").is_none());
}
#[test]
fn test_pop() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
assert_eq!(cache.len(), 2);
let opt1 = cache.pop(&1);
assert!(opt1.is_some());
assert_eq!(opt1.unwrap(), 10);
assert!(cache.get(&1).is_none());
assert_eq!(cache.len(), 1);
}
#[test]
fn test_change_capacity() {
let mut cache: LruCache<int, int> = LruCache::new(2);
assert_eq!(cache.capacity(), 2);
cache.put(1, 10);
cache.put(2, 20);
cache.change_capacity(1);
assert!(cache.get(&1).is_none());
assert_eq!(cache.capacity(), 1);
}
#[test]
fn test_to_str() {
let mut cache: LruCache<int, int> = LruCache::new(3);
cache.put(1, 10);
cache.put(2, 20);
cache.put(3, 30);
assert_eq!(cache.to_str(), ~"{3: 30, 2: 20, 1: 10}");
cache.put(2, 22);
assert_eq!(cache.to_str(), ~"{2: 22, 3: 30, 1: 10}");
cache.put(6, 60);
assert_eq!(cache.to_str(), ~"{6: 60, 2: 22, 3: 30}");
cache.get(&3);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60, 2: 22}");
cache.change_capacity(2);
assert_eq!(cache.to_str(), ~"{3: 30, 6: 60}");
}
#[test]
fn test_clear() {
let mut cache: LruCache<int, int> = LruCache::new(2);
cache.put(1, 10);
cache.put(2, 20);
cache.clear();
assert!(cache.get(&1).is_none());
assert!(cache.get(&2).is_none());
assert_eq!(cache.to_str(), ~"{}");
}
}
| {
if self.len() > 0 {
let lru = unsafe { (*self.tail).prev };
self.detach(lru);
unsafe {
match (*lru).key {
None => (),
Some(ref k) => { self.map.pop(&KeyRef{k: k}); }
}
}
}
} | identifier_body |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct Fetchplaces {
#[structopt(flatten)]
db: DbOpt,
#[structopt(flatten)]
overpass: OverpassOpt,
/// Max number of photos to use for --auto
#[structopt(long, short, default_value = "5")]
limit: i64,
/// Fetch data for photos with position but lacking places.
#[structopt(long, short)]
auto: bool,
/// Image ids to fetch place data for
photos: Vec<i32>,
}
impl Fetchplaces {
pub fn run(&self) -> Result<(), super::adm::result::Error> {
let db = self.db.connect()?;
if self.auto {
println!("Should find {} photos to fetch places for", self.limit);
use crate::schema::photo_places::dsl as place;
use crate::schema::positions::dsl as pos;
let result = pos::positions
.select((pos::photo_id, (pos::latitude, pos::longitude)))
.filter(pos::photo_id.ne_all(
place::photo_places.select(place::photo_id).distinct(),
))
.order(pos::photo_id.desc())
.limit(self.limit)
.load::<(i32, Coord)>(&db)?;
for (photo_id, coord) in result {
println!("Find places for #{}, {:?}", photo_id, coord);
self.overpass.update_image_places(&db, photo_id)?;
}
} else {
for photo in &self.photos {
self.overpass.update_image_places(&db, *photo)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct OverpassOpt {
/// How to connect to the overpass API.
///
/// See https://wiki.openstreetmap.org/wiki/Overpass_API for
/// available servers and policies.
#[structopt(long, env = "OVERPASS_URL")]
overpass_url: String,
}
impl OverpassOpt {
pub fn update_image_places(
&self,
c: &PgConnection,
image: i32,
) -> Result<(), Error> {
use crate::schema::positions::dsl::*;
let coord = positions
.filter(photo_id.eq(image))
.select((latitude, longitude))
.first::<Coord>(c)
.optional()
.map_err(|e| Error::Db(image, e))?
.ok_or_else(|| Error::NoPosition(image))?;
debug!("Should get places for #{} at {:?}", image, coord);
let data = Client::new()
.post(&self.overpass_url)
.body(format!("[out:json];is_in({},{});out;", coord.x, coord.y))
.send()
.and_then(Response::error_for_status)
.and_then(|mut r| r.json::<Value>())
.map_err(|e| Error::Server(image, e))?;
if let Some(elements) = data
.as_object()
.and_then(|o| o.get("elements"))
.and_then(Value::as_array)
{
for obj in elements {
if let (Some(t_osm_id), Some((name, level))) =
(osm_id(obj), name_and_level(obj))
{
debug!("{}: {} (level {})", t_osm_id, name, level);
let place = get_or_create_place(c, t_osm_id, name, level)
.map_err(|e| Error::Db(image, e))?;
if place.osm_id.is_none() {
debug!("Matched {:?} by name, update osm info", place);
use crate::schema::places::dsl::*;
diesel::update(places)
.filter(id.eq(place.id))
.set((
osm_id.eq(Some(t_osm_id)),
osm_level.eq(level),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
use crate::models::PhotoPlace;
use crate::schema::photo_places::dsl::*;
let q = photo_places
.filter(photo_id.eq(image))
.filter(place_id.eq(place.id));
if q.first::<PhotoPlace>(c).is_ok() {
debug!(
"Photo #{} already has {} ({})",
image, place.id, place.place_name
);
} else {
diesel::insert_into(photo_places)
.values((
photo_id.eq(image),
place_id.eq(place.id),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
} else {
info!("Unused area: {}", obj);
}
}
}
Ok(())
}
}
fn osm_id(obj: &Value) -> Option<i64> {
obj.get("id").and_then(Value::as_i64)
}
fn name_and_level(obj: &Value) -> Option<(&str, i16)> {
if let Some(tags) = obj.get("tags") {
let name = tags
.get("name:sv")
//.or_else(|| tags.get("name:en"))
.or_else(|| tags.get("name"))
.and_then(Value::as_str);
let level = tags
.get("admin_level")
.and_then(Value::as_str)
.and_then(|l| l.parse().ok())
.or_else(|| match tag_str(tags, "leisure") {
Some("garden") => Some(18),
Some("nature_reserve") => Some(12),
Some("park") => Some(14),
Some("pitch") => Some(15),
Some("playground") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "tourism") {
Some("attraction") => Some(16),
Some("theme_park") | Some("zoo") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "boundary") {
Some("national_park") => Some(14),
Some("historic") => Some(7), // Seems to be mainly "Landskap"
_ => None,
})
.or_else(|| match tag_str(tags, "landuse") {
Some("allotments") => Some(14),
Some("commercial") => Some(12),
Some("grass") => Some(13),
Some("industrial") => Some(11),
Some("residential") => Some(11),
Some("retail") => Some(13),
_ => None,
})
.or_else(|| match tag_str(tags, "highway") { | Some("station") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "amenity") {
Some("bus_station") => Some(16),
Some("exhibition_center") => Some(20),
Some("kindergarten") => Some(15),
Some("place_of_worship") => Some(15),
Some("school") => Some(14),
Some("university") => Some(12),
_ => None,
})
.or_else(|| match tag_str(tags, "aeroway") {
Some("aerodrome") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "water") {
Some("lake") => Some(15),
_ => None,
})
.or_else(|| match tag_str(tags, "waterway") {
Some("riverbank") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "man_made") {
Some("bridge") => Some(17),
_ => None,
})
.or_else(|| match tag_str(tags, "place") {
Some("city_block") => Some(17),
Some("island") => Some(13),
Some("islet") => Some(17),
Some("penisula") => Some(13),
Some("region") => Some(8),
Some("square") => Some(18),
Some("suburb") => Some(11),
_ => None,
})
.or_else(|| match tag_str(tags, "natural") {
Some("bay") => Some(14),
Some("wood") => Some(14),
Some("scrub") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "building") {
Some("exhibition_center") => Some(19),
Some("sports_hall") => Some(19),
Some(_) => Some(20),
_ => None,
})
.or_else(|| match tag_str(tags, "political_division") {
Some("canton") => Some(9),
_ => None,
});
if let (Some(name), Some(level)) = (name, level) {
debug!("{} is level {}", name, level);
Some((name, level))
} else {
None
}
} else {
warn!("Tag-less object {:?}", obj);
None
}
}
fn tag_str<'a>(tags: &'a Value, name: &str) -> Option<&'a str> {
tags.get(name).and_then(Value::as_str)
}
fn get_or_create_place(
c: &PgConnection,
t_osm_id: i64,
name: &str,
level: i16,
) -> Result<Place, diesel::result::Error> {
use crate::schema::places::dsl::*;
places
.filter(
osm_id
.eq(Some(t_osm_id))
.or(place_name.eq(name).and(osm_id.is_null())),
)
.first::<Place>(c)
.or_else(|_| {
let mut result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
let mut attempt = 1;
while is_duplicate(&result) && attempt < 25 {
info!("Attempt #{} got {:?}, trying again", attempt, result);
attempt += 1;
let name = format!("{} ({})", name, attempt);
result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
}
result
})
}
fn is_duplicate<T>(r: &Result<T, DieselError>) -> bool {
match r {
Err(DieselError::DatabaseError(
DatabaseErrorKind::UniqueViolation,
_,
)) => true,
_ => false,
}
}
#[derive(Debug)]
pub enum Error {
NoPosition(i32),
Db(i32, diesel::result::Error),
Server(i32, reqwest::Error),
} | Some("pedestrian") => Some(15), // torg
Some("rest_area") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "public_transport") { | random_line_split |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct Fetchplaces {
#[structopt(flatten)]
db: DbOpt,
#[structopt(flatten)]
overpass: OverpassOpt,
/// Max number of photos to use for --auto
#[structopt(long, short, default_value = "5")]
limit: i64,
/// Fetch data for photos with position but lacking places.
#[structopt(long, short)]
auto: bool,
/// Image ids to fetch place data for
photos: Vec<i32>,
}
impl Fetchplaces {
pub fn run(&self) -> Result<(), super::adm::result::Error> {
let db = self.db.connect()?;
if self.auto {
println!("Should find {} photos to fetch places for", self.limit);
use crate::schema::photo_places::dsl as place;
use crate::schema::positions::dsl as pos;
let result = pos::positions
.select((pos::photo_id, (pos::latitude, pos::longitude)))
.filter(pos::photo_id.ne_all(
place::photo_places.select(place::photo_id).distinct(),
))
.order(pos::photo_id.desc())
.limit(self.limit)
.load::<(i32, Coord)>(&db)?;
for (photo_id, coord) in result {
println!("Find places for #{}, {:?}", photo_id, coord);
self.overpass.update_image_places(&db, photo_id)?;
}
} else {
for photo in &self.photos {
self.overpass.update_image_places(&db, *photo)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct OverpassOpt {
/// How to connect to the overpass API.
///
/// See https://wiki.openstreetmap.org/wiki/Overpass_API for
/// available servers and policies.
#[structopt(long, env = "OVERPASS_URL")]
overpass_url: String,
}
impl OverpassOpt {
pub fn update_image_places(
&self,
c: &PgConnection,
image: i32,
) -> Result<(), Error> {
use crate::schema::positions::dsl::*;
let coord = positions
.filter(photo_id.eq(image))
.select((latitude, longitude))
.first::<Coord>(c)
.optional()
.map_err(|e| Error::Db(image, e))?
.ok_or_else(|| Error::NoPosition(image))?;
debug!("Should get places for #{} at {:?}", image, coord);
let data = Client::new()
.post(&self.overpass_url)
.body(format!("[out:json];is_in({},{});out;", coord.x, coord.y))
.send()
.and_then(Response::error_for_status)
.and_then(|mut r| r.json::<Value>())
.map_err(|e| Error::Server(image, e))?;
if let Some(elements) = data
.as_object()
.and_then(|o| o.get("elements"))
.and_then(Value::as_array)
{
for obj in elements {
if let (Some(t_osm_id), Some((name, level))) =
(osm_id(obj), name_and_level(obj))
{
debug!("{}: {} (level {})", t_osm_id, name, level);
let place = get_or_create_place(c, t_osm_id, name, level)
.map_err(|e| Error::Db(image, e))?;
if place.osm_id.is_none() {
debug!("Matched {:?} by name, update osm info", place);
use crate::schema::places::dsl::*;
diesel::update(places)
.filter(id.eq(place.id))
.set((
osm_id.eq(Some(t_osm_id)),
osm_level.eq(level),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
use crate::models::PhotoPlace;
use crate::schema::photo_places::dsl::*;
let q = photo_places
.filter(photo_id.eq(image))
.filter(place_id.eq(place.id));
if q.first::<PhotoPlace>(c).is_ok() {
debug!(
"Photo #{} already has {} ({})",
image, place.id, place.place_name
);
} else {
diesel::insert_into(photo_places)
.values((
photo_id.eq(image),
place_id.eq(place.id),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
} else {
info!("Unused area: {}", obj);
}
}
}
Ok(())
}
}
fn osm_id(obj: &Value) -> Option<i64> {
obj.get("id").and_then(Value::as_i64)
}
fn name_and_level(obj: &Value) -> Option<(&str, i16)> | Some("attraction") => Some(16),
Some("theme_park") | Some("zoo") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "boundary") {
Some("national_park") => Some(14),
Some("historic") => Some(7), // Seems to be mainly "Landskap"
_ => None,
})
.or_else(|| match tag_str(tags, "landuse") {
Some("allotments") => Some(14),
Some("commercial") => Some(12),
Some("grass") => Some(13),
Some("industrial") => Some(11),
Some("residential") => Some(11),
Some("retail") => Some(13),
_ => None,
})
.or_else(|| match tag_str(tags, "highway") {
Some("pedestrian") => Some(15), // torg
Some("rest_area") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "public_transport") {
Some("station") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "amenity") {
Some("bus_station") => Some(16),
Some("exhibition_center") => Some(20),
Some("kindergarten") => Some(15),
Some("place_of_worship") => Some(15),
Some("school") => Some(14),
Some("university") => Some(12),
_ => None,
})
.or_else(|| match tag_str(tags, "aeroway") {
Some("aerodrome") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "water") {
Some("lake") => Some(15),
_ => None,
})
.or_else(|| match tag_str(tags, "waterway") {
Some("riverbank") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "man_made") {
Some("bridge") => Some(17),
_ => None,
})
.or_else(|| match tag_str(tags, "place") {
Some("city_block") => Some(17),
Some("island") => Some(13),
Some("islet") => Some(17),
Some("penisula") => Some(13),
Some("region") => Some(8),
Some("square") => Some(18),
Some("suburb") => Some(11),
_ => None,
})
.or_else(|| match tag_str(tags, "natural") {
Some("bay") => Some(14),
Some("wood") => Some(14),
Some("scrub") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "building") {
Some("exhibition_center") => Some(19),
Some("sports_hall") => Some(19),
Some(_) => Some(20),
_ => None,
})
.or_else(|| match tag_str(tags, "political_division") {
Some("canton") => Some(9),
_ => None,
});
if let (Some(name), Some(level)) = (name, level) {
debug!("{} is level {}", name, level);
Some((name, level))
} else {
None
}
} else {
warn!("Tag-less object {:?}", obj);
None
}
}
fn tag_str<'a>(tags: &'a Value, name: &str) -> Option<&'a str> {
tags.get(name).and_then(Value::as_str)
}
fn get_or_create_place(
c: &PgConnection,
t_osm_id: i64,
name: &str,
level: i16,
) -> Result<Place, diesel::result::Error> {
use crate::schema::places::dsl::*;
places
.filter(
osm_id
.eq(Some(t_osm_id))
.or(place_name.eq(name).and(osm_id.is_null())),
)
.first::<Place>(c)
.or_else(|_| {
let mut result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
let mut attempt = 1;
while is_duplicate(&result) && attempt < 25 {
info!("Attempt #{} got {:?}, trying again", attempt, result);
attempt += 1;
let name = format!("{} ({})", name, attempt);
result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
}
result
})
}
fn is_duplicate<T>(r: &Result<T, DieselError>) -> bool {
match r {
Err(DieselError::DatabaseError(
DatabaseErrorKind::UniqueViolation,
_,
)) => true,
_ => false,
}
}
#[derive(Debug)]
pub enum Error {
NoPosition(i32),
Db(i32, diesel::result::Error),
Server(i32, reqwest::Error),
}
| {
if let Some(tags) = obj.get("tags") {
let name = tags
.get("name:sv")
//.or_else(|| tags.get("name:en"))
.or_else(|| tags.get("name"))
.and_then(Value::as_str);
let level = tags
.get("admin_level")
.and_then(Value::as_str)
.and_then(|l| l.parse().ok())
.or_else(|| match tag_str(tags, "leisure") {
Some("garden") => Some(18),
Some("nature_reserve") => Some(12),
Some("park") => Some(14),
Some("pitch") => Some(15),
Some("playground") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "tourism") { | identifier_body |
fetch_places.rs | use crate::models::{Coord, Place};
use crate::DbOpt;
use diesel;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error as DieselError};
use log::{debug, info, warn};
use reqwest::{self, Client, Response};
use serde_json::Value;
use slug::slugify;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct Fetchplaces {
#[structopt(flatten)]
db: DbOpt,
#[structopt(flatten)]
overpass: OverpassOpt,
/// Max number of photos to use for --auto
#[structopt(long, short, default_value = "5")]
limit: i64,
/// Fetch data for photos with position but lacking places.
#[structopt(long, short)]
auto: bool,
/// Image ids to fetch place data for
photos: Vec<i32>,
}
impl Fetchplaces {
pub fn run(&self) -> Result<(), super::adm::result::Error> {
let db = self.db.connect()?;
if self.auto {
println!("Should find {} photos to fetch places for", self.limit);
use crate::schema::photo_places::dsl as place;
use crate::schema::positions::dsl as pos;
let result = pos::positions
.select((pos::photo_id, (pos::latitude, pos::longitude)))
.filter(pos::photo_id.ne_all(
place::photo_places.select(place::photo_id).distinct(),
))
.order(pos::photo_id.desc())
.limit(self.limit)
.load::<(i32, Coord)>(&db)?;
for (photo_id, coord) in result {
println!("Find places for #{}, {:?}", photo_id, coord);
self.overpass.update_image_places(&db, photo_id)?;
}
} else {
for photo in &self.photos {
self.overpass.update_image_places(&db, *photo)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
pub struct OverpassOpt {
/// How to connect to the overpass API.
///
/// See https://wiki.openstreetmap.org/wiki/Overpass_API for
/// available servers and policies.
#[structopt(long, env = "OVERPASS_URL")]
overpass_url: String,
}
impl OverpassOpt {
pub fn update_image_places(
&self,
c: &PgConnection,
image: i32,
) -> Result<(), Error> {
use crate::schema::positions::dsl::*;
let coord = positions
.filter(photo_id.eq(image))
.select((latitude, longitude))
.first::<Coord>(c)
.optional()
.map_err(|e| Error::Db(image, e))?
.ok_or_else(|| Error::NoPosition(image))?;
debug!("Should get places for #{} at {:?}", image, coord);
let data = Client::new()
.post(&self.overpass_url)
.body(format!("[out:json];is_in({},{});out;", coord.x, coord.y))
.send()
.and_then(Response::error_for_status)
.and_then(|mut r| r.json::<Value>())
.map_err(|e| Error::Server(image, e))?;
if let Some(elements) = data
.as_object()
.and_then(|o| o.get("elements"))
.and_then(Value::as_array)
{
for obj in elements {
if let (Some(t_osm_id), Some((name, level))) =
(osm_id(obj), name_and_level(obj))
{
debug!("{}: {} (level {})", t_osm_id, name, level);
let place = get_or_create_place(c, t_osm_id, name, level)
.map_err(|e| Error::Db(image, e))?;
if place.osm_id.is_none() {
debug!("Matched {:?} by name, update osm info", place);
use crate::schema::places::dsl::*;
diesel::update(places)
.filter(id.eq(place.id))
.set((
osm_id.eq(Some(t_osm_id)),
osm_level.eq(level),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
use crate::models::PhotoPlace;
use crate::schema::photo_places::dsl::*;
let q = photo_places
.filter(photo_id.eq(image))
.filter(place_id.eq(place.id));
if q.first::<PhotoPlace>(c).is_ok() {
debug!(
"Photo #{} already has {} ({})",
image, place.id, place.place_name
);
} else {
diesel::insert_into(photo_places)
.values((
photo_id.eq(image),
place_id.eq(place.id),
))
.execute(c)
.map_err(|e| Error::Db(image, e))?;
}
} else {
info!("Unused area: {}", obj);
}
}
}
Ok(())
}
}
fn osm_id(obj: &Value) -> Option<i64> {
obj.get("id").and_then(Value::as_i64)
}
fn name_and_level(obj: &Value) -> Option<(&str, i16)> {
if let Some(tags) = obj.get("tags") {
let name = tags
.get("name:sv")
//.or_else(|| tags.get("name:en"))
.or_else(|| tags.get("name"))
.and_then(Value::as_str);
let level = tags
.get("admin_level")
.and_then(Value::as_str)
.and_then(|l| l.parse().ok())
.or_else(|| match tag_str(tags, "leisure") {
Some("garden") => Some(18),
Some("nature_reserve") => Some(12),
Some("park") => Some(14),
Some("pitch") => Some(15),
Some("playground") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "tourism") {
Some("attraction") => Some(16),
Some("theme_park") | Some("zoo") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "boundary") {
Some("national_park") => Some(14),
Some("historic") => Some(7), // Seems to be mainly "Landskap"
_ => None,
})
.or_else(|| match tag_str(tags, "landuse") {
Some("allotments") => Some(14),
Some("commercial") => Some(12),
Some("grass") => Some(13),
Some("industrial") => Some(11),
Some("residential") => Some(11),
Some("retail") => Some(13),
_ => None,
})
.or_else(|| match tag_str(tags, "highway") {
Some("pedestrian") => Some(15), // torg
Some("rest_area") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "public_transport") {
Some("station") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "amenity") {
Some("bus_station") => Some(16),
Some("exhibition_center") => Some(20),
Some("kindergarten") => Some(15),
Some("place_of_worship") => Some(15),
Some("school") => Some(14),
Some("university") => Some(12),
_ => None,
})
.or_else(|| match tag_str(tags, "aeroway") {
Some("aerodrome") => Some(14),
_ => None,
})
.or_else(|| match tag_str(tags, "water") {
Some("lake") => Some(15),
_ => None,
})
.or_else(|| match tag_str(tags, "waterway") {
Some("riverbank") => Some(16),
_ => None,
})
.or_else(|| match tag_str(tags, "man_made") {
Some("bridge") => Some(17),
_ => None,
})
.or_else(|| match tag_str(tags, "place") {
Some("city_block") => Some(17),
Some("island") => Some(13),
Some("islet") => Some(17),
Some("penisula") => Some(13),
Some("region") => Some(8),
Some("square") => Some(18),
Some("suburb") => Some(11),
_ => None,
})
.or_else(|| match tag_str(tags, "natural") {
Some("bay") => Some(14),
Some("wood") => Some(14),
Some("scrub") => Some(18),
_ => None,
})
.or_else(|| match tag_str(tags, "building") {
Some("exhibition_center") => Some(19),
Some("sports_hall") => Some(19),
Some(_) => Some(20),
_ => None,
})
.or_else(|| match tag_str(tags, "political_division") {
Some("canton") => Some(9),
_ => None,
});
if let (Some(name), Some(level)) = (name, level) {
debug!("{} is level {}", name, level);
Some((name, level))
} else {
None
}
} else {
warn!("Tag-less object {:?}", obj);
None
}
}
fn | <'a>(tags: &'a Value, name: &str) -> Option<&'a str> {
tags.get(name).and_then(Value::as_str)
}
fn get_or_create_place(
c: &PgConnection,
t_osm_id: i64,
name: &str,
level: i16,
) -> Result<Place, diesel::result::Error> {
use crate::schema::places::dsl::*;
places
.filter(
osm_id
.eq(Some(t_osm_id))
.or(place_name.eq(name).and(osm_id.is_null())),
)
.first::<Place>(c)
.or_else(|_| {
let mut result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
let mut attempt = 1;
while is_duplicate(&result) && attempt < 25 {
info!("Attempt #{} got {:?}, trying again", attempt, result);
attempt += 1;
let name = format!("{} ({})", name, attempt);
result = diesel::insert_into(places)
.values((
place_name.eq(&name),
slug.eq(&slugify(&name)),
osm_id.eq(Some(t_osm_id)),
osm_level.eq(Some(level)),
))
.get_result::<Place>(c);
}
result
})
}
fn is_duplicate<T>(r: &Result<T, DieselError>) -> bool {
match r {
Err(DieselError::DatabaseError(
DatabaseErrorKind::UniqueViolation,
_,
)) => true,
_ => false,
}
}
#[derive(Debug)]
pub enum Error {
NoPosition(i32),
Db(i32, diesel::result::Error),
Server(i32, reqwest::Error),
}
| tag_str | identifier_name |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
SwimKind}};
use habitat_common::liveliness_checker;
use habitat_core::util::ToI64;
use lazy_static::lazy_static;
use log::{debug,
error,
trace};
use prometheus::{register_int_counter_vec,
register_int_gauge_vec,
IntCounterVec,
IntGaugeVec};
use std::{net::{SocketAddr,
UdpSocket},
thread,
time::Duration};
lazy_static! {
static ref SWIM_MESSAGES_RECEIVED: IntCounterVec =
register_int_counter_vec!("hab_butterfly_swim_messages_received_total",
"Total number of SWIM messages received",
&["type", "mode"]).unwrap();
static ref SWIM_BYTES_RECEIVED: IntGaugeVec =
register_int_gauge_vec!("hab_butterfly_swim_received_bytes",
"SWIM message size received in bytes",
&["type", "mode"]).unwrap();
}
pub fn spawn_thread(name: String,
server: Server,
socket: UdpSocket,
tx_outbound: AckSender)
-> std::io::Result<()> {
thread::Builder::new().name(name)
.spawn(move || ->! { run_loop(&server, &socket, &tx_outbound) })
.map(|_| ())
}
/// Run the thread. Listens for messages up to 1k in size, and then processes them accordingly.
/// Takes the Server and a channel to send received Acks to the outbound thread.
pub fn run_loop(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender) ->! {
let mut recv_buffer: Vec<u8> = vec![0; 1024];
loop {
liveliness_checker::mark_thread_alive().and_divergent();
if server.paused() {
thread::sleep(Duration::from_millis(100));
continue;
}
match socket.recv_from(&mut recv_buffer[..]) {
Ok((length, addr)) => {
let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) {
Ok(swim_payload) => swim_payload,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error unwrapping protocol message, {}", e);
let label_values = &["unwrap_wire", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(length.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
let bytes_received = swim_payload.len();
let msg = match Swim::decode(&swim_payload) {
Ok(msg) => msg,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error decoding protocol message, {}", e);
let label_values = &["undecodable", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
// Setting a label_values variable here throws errors about moving borrowed
// content that I couldn't solve w/o clones. Leaving this for now. I'm sure
// there's a better way.
SWIM_BYTES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.inc();
trace!("SWIM Message: {:?}", msg);
match msg.kind {
SwimKind::Ping(ping) => {
if server.is_member_blocked_sblr(&ping.from.id) {
debug!("Not processing message from {} - it is blocked",
ping.from.id);
continue;
}
process_ping_mlw_smw_rhw(server, socket, addr, ping);
}
SwimKind::Ack(ack) => {
if server.is_member_blocked_sblr(&ack.from.id) && ack.forward_to.is_none() {
debug!("Not processing message from {} - it is blocked",
ack.from.id);
continue;
}
process_ack_mlw_smw_rhw(server, socket, tx_outbound, addr, ack);
}
SwimKind::PingReq(pingreq) => {
if server.is_member_blocked_sblr(&pingreq.from.id) {
debug!("Not processing message from {} - it is blocked",
pingreq.from.id);
continue;
}
process_pingreq_mlr_smr_rhw(server, socket, addr, pingreq);
}
}
}
Err(e) => {
// TODO: We can't use magic numbers here because the Supervisor runs on more
// than one platform. I'm sure these were added as specific OS errors for Linux
// but we need to also handle Windows & Mac.
match e.raw_os_error() {
Some(35) | Some(11) | Some(10035) | Some(10060) => {
// This is the normal non-blocking result, or a timeout
}
Some(_) => {
error!("UDP Receive error: {}", e);
debug!("UDP Receive error debug: {:?}", e);
}
None => {
error!("UDP Receive error: {}", e);
}
}
}
}
}
}
/// Process pingreq messages.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (read)
/// * `Server::member` (read)
/// * `RumorHeat::inner` (write)
fn process_pingreq_mlr_smr_rhw(server: &Server,
socket: &UdpSocket,
addr: SocketAddr,
mut msg: PingReq) {
if let Some(target) = server.member_list.get_cloned_mlr(&msg.target.id) {
msg.from.address = addr.ip().to_string();
let ping_msg = Ping { membership: vec![],
from: server.myself.lock_smr().to_member(),
forward_to: Some(msg.from.clone()), };
let swim = outbound::populate_membership_rumors_mlr_rhw(server, &target, ping_msg);
// Set the route-back address to the one we received the
// pingreq from
outbound::ping(server,
socket,
target.swim_socket_address(),
Some(&msg.from),
&swim);
} else {
error!("PingReq request {:?} for invalid target", msg);
}
}
/// Process ack messages; forwards to the outbound thread.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn | (server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender,
addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id!= msg.forward_to.as_ref().unwrap().id {
let (forward_to_addr, from_addr) = {
let forward_to = msg.forward_to.as_ref().unwrap();
let forward_addr_str = format!("{}:{}", forward_to.address, forward_to.swim_port);
let forward_to_addr = match forward_addr_str.parse() {
Ok(addr) => addr,
Err(e) => {
error!("Abandoning Ack forward: cannot parse member address: {}:{}, {}",
forward_to.address, forward_to.swim_port, e);
return;
}
};
trace!("Forwarding Ack from {}@{} to {}@{}",
msg.from.id,
addr,
forward_to.id,
forward_to.address,);
(forward_to_addr, addr.ip().to_string())
};
msg.from.address = from_addr;
outbound::forward_ack(server, socket, forward_to_addr, msg);
return;
}
let memberships = msg.membership.clone();
match tx_outbound.send((addr, msg)) {
Ok(()) => {
for membership in memberships {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
Err(e) => panic!("Outbound thread has died - this shouldn't happen: #{:?}", e),
}
}
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ping_mlw_smw_rhw(server: &Server, socket: &UdpSocket, addr: SocketAddr, mut msg: Ping) {
outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to);
// Populate the member for this sender with its remote address
msg.from.address = addr.ip().to_string();
trace!("Ping from {}@{}", msg.from.id, addr);
if msg.from.departed {
server.insert_member_mlw_rhw(msg.from, Health::Departed);
} else {
server.insert_member_mlw_rhw(msg.from, Health::Alive);
}
for membership in msg.membership {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
| process_ack_mlw_smw_rhw | identifier_name |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
SwimKind}};
use habitat_common::liveliness_checker;
use habitat_core::util::ToI64;
use lazy_static::lazy_static;
use log::{debug,
error,
trace};
use prometheus::{register_int_counter_vec,
register_int_gauge_vec,
IntCounterVec,
IntGaugeVec};
use std::{net::{SocketAddr,
UdpSocket},
thread,
time::Duration};
lazy_static! {
static ref SWIM_MESSAGES_RECEIVED: IntCounterVec =
register_int_counter_vec!("hab_butterfly_swim_messages_received_total",
"Total number of SWIM messages received",
&["type", "mode"]).unwrap();
static ref SWIM_BYTES_RECEIVED: IntGaugeVec =
register_int_gauge_vec!("hab_butterfly_swim_received_bytes",
"SWIM message size received in bytes",
&["type", "mode"]).unwrap();
}
pub fn spawn_thread(name: String,
server: Server,
socket: UdpSocket,
tx_outbound: AckSender)
-> std::io::Result<()> {
thread::Builder::new().name(name)
.spawn(move || ->! { run_loop(&server, &socket, &tx_outbound) })
.map(|_| ())
}
/// Run the thread. Listens for messages up to 1k in size, and then processes them accordingly.
/// Takes the Server and a channel to send received Acks to the outbound thread.
pub fn run_loop(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender) ->! {
let mut recv_buffer: Vec<u8> = vec![0; 1024];
loop {
liveliness_checker::mark_thread_alive().and_divergent();
if server.paused() |
match socket.recv_from(&mut recv_buffer[..]) {
Ok((length, addr)) => {
let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) {
Ok(swim_payload) => swim_payload,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error unwrapping protocol message, {}", e);
let label_values = &["unwrap_wire", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(length.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
let bytes_received = swim_payload.len();
let msg = match Swim::decode(&swim_payload) {
Ok(msg) => msg,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error decoding protocol message, {}", e);
let label_values = &["undecodable", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
// Setting a label_values variable here throws errors about moving borrowed
// content that I couldn't solve w/o clones. Leaving this for now. I'm sure
// there's a better way.
SWIM_BYTES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.inc();
trace!("SWIM Message: {:?}", msg);
match msg.kind {
SwimKind::Ping(ping) => {
if server.is_member_blocked_sblr(&ping.from.id) {
debug!("Not processing message from {} - it is blocked",
ping.from.id);
continue;
}
process_ping_mlw_smw_rhw(server, socket, addr, ping);
}
SwimKind::Ack(ack) => {
if server.is_member_blocked_sblr(&ack.from.id) && ack.forward_to.is_none() {
debug!("Not processing message from {} - it is blocked",
ack.from.id);
continue;
}
process_ack_mlw_smw_rhw(server, socket, tx_outbound, addr, ack);
}
SwimKind::PingReq(pingreq) => {
if server.is_member_blocked_sblr(&pingreq.from.id) {
debug!("Not processing message from {} - it is blocked",
pingreq.from.id);
continue;
}
process_pingreq_mlr_smr_rhw(server, socket, addr, pingreq);
}
}
}
Err(e) => {
// TODO: We can't use magic numbers here because the Supervisor runs on more
// than one platform. I'm sure these were added as specific OS errors for Linux
// but we need to also handle Windows & Mac.
match e.raw_os_error() {
Some(35) | Some(11) | Some(10035) | Some(10060) => {
// This is the normal non-blocking result, or a timeout
}
Some(_) => {
error!("UDP Receive error: {}", e);
debug!("UDP Receive error debug: {:?}", e);
}
None => {
error!("UDP Receive error: {}", e);
}
}
}
}
}
}
/// Process pingreq messages.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (read)
/// * `Server::member` (read)
/// * `RumorHeat::inner` (write)
fn process_pingreq_mlr_smr_rhw(server: &Server,
socket: &UdpSocket,
addr: SocketAddr,
mut msg: PingReq) {
if let Some(target) = server.member_list.get_cloned_mlr(&msg.target.id) {
msg.from.address = addr.ip().to_string();
let ping_msg = Ping { membership: vec![],
from: server.myself.lock_smr().to_member(),
forward_to: Some(msg.from.clone()), };
let swim = outbound::populate_membership_rumors_mlr_rhw(server, &target, ping_msg);
// Set the route-back address to the one we received the
// pingreq from
outbound::ping(server,
socket,
target.swim_socket_address(),
Some(&msg.from),
&swim);
} else {
error!("PingReq request {:?} for invalid target", msg);
}
}
/// Process ack messages; forwards to the outbound thread.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ack_mlw_smw_rhw(server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender,
addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id!= msg.forward_to.as_ref().unwrap().id {
let (forward_to_addr, from_addr) = {
let forward_to = msg.forward_to.as_ref().unwrap();
let forward_addr_str = format!("{}:{}", forward_to.address, forward_to.swim_port);
let forward_to_addr = match forward_addr_str.parse() {
Ok(addr) => addr,
Err(e) => {
error!("Abandoning Ack forward: cannot parse member address: {}:{}, {}",
forward_to.address, forward_to.swim_port, e);
return;
}
};
trace!("Forwarding Ack from {}@{} to {}@{}",
msg.from.id,
addr,
forward_to.id,
forward_to.address,);
(forward_to_addr, addr.ip().to_string())
};
msg.from.address = from_addr;
outbound::forward_ack(server, socket, forward_to_addr, msg);
return;
}
let memberships = msg.membership.clone();
match tx_outbound.send((addr, msg)) {
Ok(()) => {
for membership in memberships {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
Err(e) => panic!("Outbound thread has died - this shouldn't happen: #{:?}", e),
}
}
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ping_mlw_smw_rhw(server: &Server, socket: &UdpSocket, addr: SocketAddr, mut msg: Ping) {
outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to);
// Populate the member for this sender with its remote address
msg.from.address = addr.ip().to_string();
trace!("Ping from {}@{}", msg.from.id, addr);
if msg.from.departed {
server.insert_member_mlw_rhw(msg.from, Health::Departed);
} else {
server.insert_member_mlw_rhw(msg.from, Health::Alive);
}
for membership in msg.membership {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
| {
thread::sleep(Duration::from_millis(100));
continue;
} | conditional_block |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
SwimKind}};
use habitat_common::liveliness_checker;
use habitat_core::util::ToI64;
use lazy_static::lazy_static;
use log::{debug,
error,
trace};
use prometheus::{register_int_counter_vec,
register_int_gauge_vec,
IntCounterVec,
IntGaugeVec};
use std::{net::{SocketAddr,
UdpSocket},
thread,
time::Duration};
lazy_static! {
static ref SWIM_MESSAGES_RECEIVED: IntCounterVec =
register_int_counter_vec!("hab_butterfly_swim_messages_received_total",
"Total number of SWIM messages received",
&["type", "mode"]).unwrap();
static ref SWIM_BYTES_RECEIVED: IntGaugeVec =
register_int_gauge_vec!("hab_butterfly_swim_received_bytes",
"SWIM message size received in bytes",
&["type", "mode"]).unwrap();
}
pub fn spawn_thread(name: String,
server: Server,
socket: UdpSocket,
tx_outbound: AckSender)
-> std::io::Result<()> {
thread::Builder::new().name(name)
.spawn(move || ->! { run_loop(&server, &socket, &tx_outbound) })
.map(|_| ())
}
/// Run the thread. Listens for messages up to 1k in size, and then processes them accordingly.
/// Takes the Server and a channel to send received Acks to the outbound thread.
pub fn run_loop(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender) ->! {
let mut recv_buffer: Vec<u8> = vec![0; 1024];
loop {
liveliness_checker::mark_thread_alive().and_divergent();
if server.paused() {
thread::sleep(Duration::from_millis(100));
continue;
}
match socket.recv_from(&mut recv_buffer[..]) {
Ok((length, addr)) => {
let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) {
Ok(swim_payload) => swim_payload,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error unwrapping protocol message, {}", e);
let label_values = &["unwrap_wire", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(length.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
let bytes_received = swim_payload.len();
let msg = match Swim::decode(&swim_payload) {
Ok(msg) => msg,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error decoding protocol message, {}", e);
let label_values = &["undecodable", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
// Setting a label_values variable here throws errors about moving borrowed
// content that I couldn't solve w/o clones. Leaving this for now. I'm sure
// there's a better way.
SWIM_BYTES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.inc();
trace!("SWIM Message: {:?}", msg);
match msg.kind {
SwimKind::Ping(ping) => {
if server.is_member_blocked_sblr(&ping.from.id) {
debug!("Not processing message from {} - it is blocked",
ping.from.id);
continue;
}
process_ping_mlw_smw_rhw(server, socket, addr, ping);
}
SwimKind::Ack(ack) => {
if server.is_member_blocked_sblr(&ack.from.id) && ack.forward_to.is_none() {
debug!("Not processing message from {} - it is blocked",
ack.from.id);
continue;
}
process_ack_mlw_smw_rhw(server, socket, tx_outbound, addr, ack);
}
SwimKind::PingReq(pingreq) => {
if server.is_member_blocked_sblr(&pingreq.from.id) {
debug!("Not processing message from {} - it is blocked",
pingreq.from.id);
continue;
}
process_pingreq_mlr_smr_rhw(server, socket, addr, pingreq);
}
}
}
Err(e) => {
// TODO: We can't use magic numbers here because the Supervisor runs on more
// than one platform. I'm sure these were added as specific OS errors for Linux
// but we need to also handle Windows & Mac.
match e.raw_os_error() {
Some(35) | Some(11) | Some(10035) | Some(10060) => {
// This is the normal non-blocking result, or a timeout
}
Some(_) => {
error!("UDP Receive error: {}", e);
debug!("UDP Receive error debug: {:?}", e);
}
None => {
error!("UDP Receive error: {}", e);
}
}
}
}
}
}
/// Process pingreq messages.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (read)
/// * `Server::member` (read)
/// * `RumorHeat::inner` (write)
fn process_pingreq_mlr_smr_rhw(server: &Server,
socket: &UdpSocket,
addr: SocketAddr,
mut msg: PingReq) {
if let Some(target) = server.member_list.get_cloned_mlr(&msg.target.id) {
msg.from.address = addr.ip().to_string();
let ping_msg = Ping { membership: vec![],
from: server.myself.lock_smr().to_member(),
forward_to: Some(msg.from.clone()), };
let swim = outbound::populate_membership_rumors_mlr_rhw(server, &target, ping_msg);
// Set the route-back address to the one we received the
// pingreq from
outbound::ping(server,
socket,
target.swim_socket_address(),
Some(&msg.from),
&swim);
} else {
error!("PingReq request {:?} for invalid target", msg);
}
}
/// Process ack messages; forwards to the outbound thread.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write) | addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id!= msg.forward_to.as_ref().unwrap().id {
let (forward_to_addr, from_addr) = {
let forward_to = msg.forward_to.as_ref().unwrap();
let forward_addr_str = format!("{}:{}", forward_to.address, forward_to.swim_port);
let forward_to_addr = match forward_addr_str.parse() {
Ok(addr) => addr,
Err(e) => {
error!("Abandoning Ack forward: cannot parse member address: {}:{}, {}",
forward_to.address, forward_to.swim_port, e);
return;
}
};
trace!("Forwarding Ack from {}@{} to {}@{}",
msg.from.id,
addr,
forward_to.id,
forward_to.address,);
(forward_to_addr, addr.ip().to_string())
};
msg.from.address = from_addr;
outbound::forward_ack(server, socket, forward_to_addr, msg);
return;
}
let memberships = msg.membership.clone();
match tx_outbound.send((addr, msg)) {
Ok(()) => {
for membership in memberships {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
Err(e) => panic!("Outbound thread has died - this shouldn't happen: #{:?}", e),
}
}
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ping_mlw_smw_rhw(server: &Server, socket: &UdpSocket, addr: SocketAddr, mut msg: Ping) {
outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to);
// Populate the member for this sender with its remote address
msg.from.address = addr.ip().to_string();
trace!("Ping from {}@{}", msg.from.id, addr);
if msg.from.departed {
server.insert_member_mlw_rhw(msg.from, Health::Departed);
} else {
server.insert_member_mlw_rhw(msg.from, Health::Alive);
}
for membership in msg.membership {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
} | fn process_ack_mlw_smw_rhw(server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender, | random_line_split |
inbound.rs | //! The inbound thread.
//!
//! This module handles all the inbound SWIM messages.
use super::AckSender;
use crate::{member::Health,
server::{outbound,
Server},
swim::{Ack,
Ping,
PingReq,
Swim,
SwimKind}};
use habitat_common::liveliness_checker;
use habitat_core::util::ToI64;
use lazy_static::lazy_static;
use log::{debug,
error,
trace};
use prometheus::{register_int_counter_vec,
register_int_gauge_vec,
IntCounterVec,
IntGaugeVec};
use std::{net::{SocketAddr,
UdpSocket},
thread,
time::Duration};
lazy_static! {
static ref SWIM_MESSAGES_RECEIVED: IntCounterVec =
register_int_counter_vec!("hab_butterfly_swim_messages_received_total",
"Total number of SWIM messages received",
&["type", "mode"]).unwrap();
static ref SWIM_BYTES_RECEIVED: IntGaugeVec =
register_int_gauge_vec!("hab_butterfly_swim_received_bytes",
"SWIM message size received in bytes",
&["type", "mode"]).unwrap();
}
pub fn spawn_thread(name: String,
server: Server,
socket: UdpSocket,
tx_outbound: AckSender)
-> std::io::Result<()> {
thread::Builder::new().name(name)
.spawn(move || ->! { run_loop(&server, &socket, &tx_outbound) })
.map(|_| ())
}
/// Run the thread. Listens for messages up to 1k in size, and then processes them accordingly.
/// Takes the Server and a channel to send received Acks to the outbound thread.
pub fn run_loop(server: &Server, socket: &UdpSocket, tx_outbound: &AckSender) ->! {
let mut recv_buffer: Vec<u8> = vec![0; 1024];
loop {
liveliness_checker::mark_thread_alive().and_divergent();
if server.paused() {
thread::sleep(Duration::from_millis(100));
continue;
}
match socket.recv_from(&mut recv_buffer[..]) {
Ok((length, addr)) => {
let swim_payload = match server.unwrap_wire(&recv_buffer[0..length]) {
Ok(swim_payload) => swim_payload,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error unwrapping protocol message, {}", e);
let label_values = &["unwrap_wire", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(length.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
let bytes_received = swim_payload.len();
let msg = match Swim::decode(&swim_payload) {
Ok(msg) => msg,
Err(e) => {
// NOTE: In the future, we might want to block people who send us
// garbage all the time.
error!("Error decoding protocol message, {}", e);
let label_values = &["undecodable", "failure"];
SWIM_BYTES_RECEIVED.with_label_values(label_values)
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(label_values).inc();
continue;
}
};
// Setting a label_values variable here throws errors about moving borrowed
// content that I couldn't solve w/o clones. Leaving this for now. I'm sure
// there's a better way.
SWIM_BYTES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.set(bytes_received.to_i64());
SWIM_MESSAGES_RECEIVED.with_label_values(&[msg.kind.as_str(), "success"])
.inc();
trace!("SWIM Message: {:?}", msg);
match msg.kind {
SwimKind::Ping(ping) => {
if server.is_member_blocked_sblr(&ping.from.id) {
debug!("Not processing message from {} - it is blocked",
ping.from.id);
continue;
}
process_ping_mlw_smw_rhw(server, socket, addr, ping);
}
SwimKind::Ack(ack) => {
if server.is_member_blocked_sblr(&ack.from.id) && ack.forward_to.is_none() {
debug!("Not processing message from {} - it is blocked",
ack.from.id);
continue;
}
process_ack_mlw_smw_rhw(server, socket, tx_outbound, addr, ack);
}
SwimKind::PingReq(pingreq) => {
if server.is_member_blocked_sblr(&pingreq.from.id) {
debug!("Not processing message from {} - it is blocked",
pingreq.from.id);
continue;
}
process_pingreq_mlr_smr_rhw(server, socket, addr, pingreq);
}
}
}
Err(e) => {
// TODO: We can't use magic numbers here because the Supervisor runs on more
// than one platform. I'm sure these were added as specific OS errors for Linux
// but we need to also handle Windows & Mac.
match e.raw_os_error() {
Some(35) | Some(11) | Some(10035) | Some(10060) => {
// This is the normal non-blocking result, or a timeout
}
Some(_) => {
error!("UDP Receive error: {}", e);
debug!("UDP Receive error debug: {:?}", e);
}
None => {
error!("UDP Receive error: {}", e);
}
}
}
}
}
}
/// Process pingreq messages.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (read)
/// * `Server::member` (read)
/// * `RumorHeat::inner` (write)
fn process_pingreq_mlr_smr_rhw(server: &Server,
socket: &UdpSocket,
addr: SocketAddr,
mut msg: PingReq) {
if let Some(target) = server.member_list.get_cloned_mlr(&msg.target.id) {
msg.from.address = addr.ip().to_string();
let ping_msg = Ping { membership: vec![],
from: server.myself.lock_smr().to_member(),
forward_to: Some(msg.from.clone()), };
let swim = outbound::populate_membership_rumors_mlr_rhw(server, &target, ping_msg);
// Set the route-back address to the one we received the
// pingreq from
outbound::ping(server,
socket,
target.swim_socket_address(),
Some(&msg.from),
&swim);
} else {
error!("PingReq request {:?} for invalid target", msg);
}
}
/// Process ack messages; forwards to the outbound thread.
///
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ack_mlw_smw_rhw(server: &Server,
socket: &UdpSocket,
tx_outbound: &AckSender,
addr: SocketAddr,
mut msg: Ack) {
trace!("Ack from {}@{}", msg.from.id, addr);
if msg.forward_to.is_some() && *server.member_id!= msg.forward_to.as_ref().unwrap().id {
let (forward_to_addr, from_addr) = {
let forward_to = msg.forward_to.as_ref().unwrap();
let forward_addr_str = format!("{}:{}", forward_to.address, forward_to.swim_port);
let forward_to_addr = match forward_addr_str.parse() {
Ok(addr) => addr,
Err(e) => {
error!("Abandoning Ack forward: cannot parse member address: {}:{}, {}",
forward_to.address, forward_to.swim_port, e);
return;
}
};
trace!("Forwarding Ack from {}@{} to {}@{}",
msg.from.id,
addr,
forward_to.id,
forward_to.address,);
(forward_to_addr, addr.ip().to_string())
};
msg.from.address = from_addr;
outbound::forward_ack(server, socket, forward_to_addr, msg);
return;
}
let memberships = msg.membership.clone();
match tx_outbound.send((addr, msg)) {
Ok(()) => {
for membership in memberships {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
}
Err(e) => panic!("Outbound thread has died - this shouldn't happen: #{:?}", e),
}
}
/// # Locking (see locking.md)
/// * `MemberList::entries` (write)
/// * `Server::member` (write)
/// * `RumorHeat::inner` (write)
fn process_ping_mlw_smw_rhw(server: &Server, socket: &UdpSocket, addr: SocketAddr, mut msg: Ping) | {
outbound::ack_mlr_smr_rhw(server, socket, &msg.from, addr, msg.forward_to);
// Populate the member for this sender with its remote address
msg.from.address = addr.ip().to_string();
trace!("Ping from {}@{}", msg.from.id, addr);
if msg.from.departed {
server.insert_member_mlw_rhw(msg.from, Health::Departed);
} else {
server.insert_member_mlw_rhw(msg.from, Health::Alive);
}
for membership in msg.membership {
server.insert_member_from_rumor_mlw_smw_rhw(membership.member, membership.health);
}
} | identifier_body |
|
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data" images
Linear,
/// Used for color maps and other "visual" images
Srgb,
}
/// Parameters that are used to configure a [Compressor]
pub struct CompressorParams(pub *mut sys::CompressorParams);
impl Default for CompressorParams {
fn default() -> Self {
Self::new()
}
}
impl CompressorParams {
/// Create a compressor with default options
pub fn new() -> Self {
unsafe {
let mut params = CompressorParams(sys::compressor_params_new());
params.set_default_options();
params
}
}
/// Resets the compressor params to default state
pub fn reset(&mut self) |
// The default options that are applied when creating a new compressor or calling reset() on it
fn set_default_options(&mut self) {
// Set a default quality level. Leaving this unset results in undefined behavior, so we set
// it to a working value by default
self.set_etc1s_quality_level(crate::ETC1S_QUALITY_DEFAULT);
self.set_uastc_quality_level(crate::UASTC_QUALITY_DEFAULT);
// The library by default prints to stdout, but since this is a library we should disable
// that by default
self.set_print_status_to_stdout(false);
}
//
// These function are used to load image data into the compressor
//
/// Get a reference to the source index. The internal list of source images is resized as needed
/// such that the image will exist
pub fn source_image_mut(
&mut self,
image_index: u32,
) -> CompressorImageRef {
unsafe {
CompressorImageRef(sys::compressor_params_get_or_create_source_image(
self.0,
image_index,
))
}
}
/// Resizes the source image list. If the provided length is shorter than the list, the data
/// beyond the provided length is truncated.
pub fn resize_source_image_list(
&mut self,
size: u32,
) {
unsafe {
sys::compressor_params_resize_source_image_list(self.0, size as _);
}
}
/// Resets the image list to be zero-length
pub fn clear_source_image_list(&mut self) {
unsafe {
sys::compressor_params_clear_source_image_list(self.0);
}
}
//
// These set parameters for compression
//
/// Enable stdout logging
pub fn set_print_status_to_stdout(
&mut self,
print_status_to_stdout: bool,
) {
unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) }
}
/// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN)
/// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX).
pub fn set_etc1s_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::ETC1S_QUALITY_MIN);
assert!(quality_level <= crate::ETC1S_QUALITY_MAX);
unsafe {
sys::compressor_params_set_quality_level(self.0, quality_level as i32);
}
}
/// Sets UASTC quality level. The value MUST be >= [UASTC_QUALITY_MIN](crate::UASTC_QUALITY_MIN)
/// and <= [UASTC_QUALITY_MAX](crate::UASTC_QUALITY_MAX).
pub fn set_uastc_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::UASTC_QUALITY_MIN);
assert!(quality_level <= crate::UASTC_QUALITY_MAX);
unsafe {
let mut flags = sys::compressor_params_get_pack_uastc_flags(self.0);
flags |= quality_level;
sys::compressor_params_set_pack_uastc_flags(self.0, flags);
}
}
/// Use the global codebook to compress the image. slightly smaller files, but lower quality,
/// slower encoding
pub fn set_use_global_codebook(
&mut self,
use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_global_sel_pal(self.0, use_global_codebook);
}
}
/// Automatically use virtual selector palettes on small images for slightly smaller files
/// (defaults to off for faster encoding time)
pub fn set_auto_use_global_codebook(
&mut self,
auto_use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_auto_global_sel_pal(self.0, auto_use_global_codebook);
}
}
/// Set the basis format we will compress to. See basis documentation for details. This
/// corresponds to the -uastc flag in the basisu command line tool and the m_uastc boolean param
/// on `basis_compressor_params` in the original library
///
/// UASTC encoding result in significantly higher texture quality, but larger files.
pub fn set_basis_format(
&mut self,
basis_format: BasisTextureFormat,
) {
let is_uastc = match basis_format {
BasisTextureFormat::ETC1S => false,
BasisTextureFormat::UASTC4x4 => true,
};
unsafe {
sys::compressor_params_set_uastc(self.0, is_uastc);
}
}
/// Sets the color space the images to be compressed is encoded in
///
/// Setting a linear color space will:
/// * Use linear colorspace metrics (instead of the default sRGB)
/// * By default use linear (not sRGB) mipmap filtering
pub fn set_color_space(
&mut self,
color_space: ColorSpace,
) {
let perceptual = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_perceptual(self.0, perceptual);
}
}
/// Override the mipmap generation color space behavior. This function is not necessary to call
/// if you call [set_color_space] with the correct value.
///
/// * If the color space is sRGB, convert image to linear before filtering, then back to sRGB
/// * If the color space is linear, we keep the image in linear during mipmap filtering
/// (i.e. do not convert to/from sRGB for filtering purposes)
pub fn set_mip_color_space(
&mut self,
color_space: ColorSpace,
) {
let mip_srgb = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_mip_srgb(self.0, mip_srgb);
}
}
/// Disable backend's selector rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_selector_rdo(
&mut self,
no_selector_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_selector_rdo(self.0, no_selector_rdo);
}
}
/// Disable backend's endpoint rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_endpoint_rdo(
&mut self,
no_endpoint_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_endpoint_rdo(self.0, no_endpoint_rdo);
}
}
/// Enable/disable UASTC RDO post-processing and set UASTC RDO quality scalar to X. Lower
/// values=higher quality/larger LZ compressed files, higher values=lower quality/smaller LZ
/// compressed files. Good range to try is [.2-4]
pub fn set_rdo_uastc(
&mut self,
rdo_uastc_quality_scalar: Option<f32>,
) {
unsafe {
match rdo_uastc_quality_scalar {
Some(quality_scalar) => {
sys::compressor_params_set_rdo_uastc(self.0, true);
sys::compressor_params_set_rdo_uastc_quality_scalar(self.0, quality_scalar);
}
None => {
sys::compressor_params_set_rdo_uastc(self.0, false);
}
}
}
}
/// Generate mipmaps for each source image
///
/// By default, sRGB textures will be converted from sRGB to linear before mipmap filtering.
/// This can be changed by calling [set_color_space] or [set_mip_color_space]
pub fn set_generate_mipmaps(
&mut self,
generate_mipmaps: bool,
) {
unsafe {
sys::compressor_params_set_generate_mipmaps(self.0, generate_mipmaps);
}
}
/// Sets the smallest dimension mipmap that will be generated
pub fn set_mipmap_smallest_dimension(
&mut self,
smallest_dimension: u32,
) {
unsafe {
sys::compressor_params_set_mip_smallest_dimension(self.0, smallest_dimension as _);
}
}
/// Set arbitrary userdata to be included with the basis-universal binary data
pub fn set_userdata(
&mut self,
userdata: UserData,
) {
unsafe {
sys::compressor_params_set_userdata(self.0, userdata.userdata0, userdata.userdata1);
}
}
/// The `basisu` command line compressor offers a -normal_map parameter that sets several
/// values automatically. This convenience function mimics that parameter.
///
/// * linear colorspace metrics
/// * linear mipmap filtering
/// * no selector RDO
/// * no sRGB
pub fn tune_for_normal_maps(&mut self) {
//TODO
unsafe {
sys::compressor_params_set_perceptual(self.0, false);
sys::compressor_params_set_mip_srgb(self.0, false);
sys::compressor_params_set_no_selector_rdo(self.0, true);
sys::compressor_params_set_no_endpoint_rdo(self.0, true);
}
}
// set_multithreaded not implemented here as this is controlled by thread count passed to
// `Compressor::new()`
}
impl Drop for CompressorParams {
fn drop(&mut self) {
unsafe {
sys::compressor_params_delete(self.0);
}
}
}
| {
unsafe {
sys::compressor_params_clear(self.0);
self.set_default_options();
self.clear_source_image_list();
}
} | identifier_body |
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data" images
Linear,
/// Used for color maps and other "visual" images
Srgb,
}
/// Parameters that are used to configure a [Compressor]
pub struct CompressorParams(pub *mut sys::CompressorParams);
impl Default for CompressorParams {
fn default() -> Self {
Self::new()
}
}
impl CompressorParams {
/// Create a compressor with default options
pub fn new() -> Self {
unsafe {
let mut params = CompressorParams(sys::compressor_params_new());
params.set_default_options();
params
}
}
/// Resets the compressor params to default state
pub fn reset(&mut self) {
unsafe {
sys::compressor_params_clear(self.0);
self.set_default_options();
self.clear_source_image_list();
}
}
// The default options that are applied when creating a new compressor or calling reset() on it
fn set_default_options(&mut self) {
// Set a default quality level. Leaving this unset results in undefined behavior, so we set
// it to a working value by default
self.set_etc1s_quality_level(crate::ETC1S_QUALITY_DEFAULT);
self.set_uastc_quality_level(crate::UASTC_QUALITY_DEFAULT);
// The library by default prints to stdout, but since this is a library we should disable
// that by default
self.set_print_status_to_stdout(false);
}
//
// These function are used to load image data into the compressor
//
/// Get a reference to the source index. The internal list of source images is resized as needed
/// such that the image will exist
pub fn source_image_mut(
&mut self,
image_index: u32,
) -> CompressorImageRef {
unsafe {
CompressorImageRef(sys::compressor_params_get_or_create_source_image(
self.0,
image_index,
))
}
}
/// Resizes the source image list. If the provided length is shorter than the list, the data
/// beyond the provided length is truncated.
pub fn resize_source_image_list(
&mut self,
size: u32,
) {
unsafe {
sys::compressor_params_resize_source_image_list(self.0, size as _);
}
}
/// Resets the image list to be zero-length
pub fn clear_source_image_list(&mut self) {
unsafe {
sys::compressor_params_clear_source_image_list(self.0);
}
}
//
// These set parameters for compression
//
/// Enable stdout logging
pub fn | (
&mut self,
print_status_to_stdout: bool,
) {
unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) }
}
/// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN)
/// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX).
pub fn set_etc1s_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::ETC1S_QUALITY_MIN);
assert!(quality_level <= crate::ETC1S_QUALITY_MAX);
unsafe {
sys::compressor_params_set_quality_level(self.0, quality_level as i32);
}
}
/// Sets UASTC quality level. The value MUST be >= [UASTC_QUALITY_MIN](crate::UASTC_QUALITY_MIN)
/// and <= [UASTC_QUALITY_MAX](crate::UASTC_QUALITY_MAX).
pub fn set_uastc_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::UASTC_QUALITY_MIN);
assert!(quality_level <= crate::UASTC_QUALITY_MAX);
unsafe {
let mut flags = sys::compressor_params_get_pack_uastc_flags(self.0);
flags |= quality_level;
sys::compressor_params_set_pack_uastc_flags(self.0, flags);
}
}
/// Use the global codebook to compress the image. slightly smaller files, but lower quality,
/// slower encoding
pub fn set_use_global_codebook(
&mut self,
use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_global_sel_pal(self.0, use_global_codebook);
}
}
/// Automatically use virtual selector palettes on small images for slightly smaller files
/// (defaults to off for faster encoding time)
pub fn set_auto_use_global_codebook(
&mut self,
auto_use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_auto_global_sel_pal(self.0, auto_use_global_codebook);
}
}
/// Set the basis format we will compress to. See basis documentation for details. This
/// corresponds to the -uastc flag in the basisu command line tool and the m_uastc boolean param
/// on `basis_compressor_params` in the original library
///
/// UASTC encoding result in significantly higher texture quality, but larger files.
pub fn set_basis_format(
&mut self,
basis_format: BasisTextureFormat,
) {
let is_uastc = match basis_format {
BasisTextureFormat::ETC1S => false,
BasisTextureFormat::UASTC4x4 => true,
};
unsafe {
sys::compressor_params_set_uastc(self.0, is_uastc);
}
}
/// Sets the color space the images to be compressed is encoded in
///
/// Setting a linear color space will:
/// * Use linear colorspace metrics (instead of the default sRGB)
/// * By default use linear (not sRGB) mipmap filtering
pub fn set_color_space(
&mut self,
color_space: ColorSpace,
) {
let perceptual = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_perceptual(self.0, perceptual);
}
}
/// Override the mipmap generation color space behavior. This function is not necessary to call
/// if you call [set_color_space] with the correct value.
///
/// * If the color space is sRGB, convert image to linear before filtering, then back to sRGB
/// * If the color space is linear, we keep the image in linear during mipmap filtering
/// (i.e. do not convert to/from sRGB for filtering purposes)
pub fn set_mip_color_space(
&mut self,
color_space: ColorSpace,
) {
let mip_srgb = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_mip_srgb(self.0, mip_srgb);
}
}
/// Disable backend's selector rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_selector_rdo(
&mut self,
no_selector_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_selector_rdo(self.0, no_selector_rdo);
}
}
/// Disable backend's endpoint rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_endpoint_rdo(
&mut self,
no_endpoint_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_endpoint_rdo(self.0, no_endpoint_rdo);
}
}
/// Enable/disable UASTC RDO post-processing and set UASTC RDO quality scalar to X. Lower
/// values=higher quality/larger LZ compressed files, higher values=lower quality/smaller LZ
/// compressed files. Good range to try is [.2-4]
pub fn set_rdo_uastc(
&mut self,
rdo_uastc_quality_scalar: Option<f32>,
) {
unsafe {
match rdo_uastc_quality_scalar {
Some(quality_scalar) => {
sys::compressor_params_set_rdo_uastc(self.0, true);
sys::compressor_params_set_rdo_uastc_quality_scalar(self.0, quality_scalar);
}
None => {
sys::compressor_params_set_rdo_uastc(self.0, false);
}
}
}
}
/// Generate mipmaps for each source image
///
/// By default, sRGB textures will be converted from sRGB to linear before mipmap filtering.
/// This can be changed by calling [set_color_space] or [set_mip_color_space]
pub fn set_generate_mipmaps(
&mut self,
generate_mipmaps: bool,
) {
unsafe {
sys::compressor_params_set_generate_mipmaps(self.0, generate_mipmaps);
}
}
/// Sets the smallest dimension mipmap that will be generated
pub fn set_mipmap_smallest_dimension(
&mut self,
smallest_dimension: u32,
) {
unsafe {
sys::compressor_params_set_mip_smallest_dimension(self.0, smallest_dimension as _);
}
}
/// Set arbitrary userdata to be included with the basis-universal binary data
pub fn set_userdata(
&mut self,
userdata: UserData,
) {
unsafe {
sys::compressor_params_set_userdata(self.0, userdata.userdata0, userdata.userdata1);
}
}
/// The `basisu` command line compressor offers a -normal_map parameter that sets several
/// values automatically. This convenience function mimics that parameter.
///
/// * linear colorspace metrics
/// * linear mipmap filtering
/// * no selector RDO
/// * no sRGB
pub fn tune_for_normal_maps(&mut self) {
//TODO
unsafe {
sys::compressor_params_set_perceptual(self.0, false);
sys::compressor_params_set_mip_srgb(self.0, false);
sys::compressor_params_set_no_selector_rdo(self.0, true);
sys::compressor_params_set_no_endpoint_rdo(self.0, true);
}
}
// set_multithreaded not implemented here as this is controlled by thread count passed to
// `Compressor::new()`
}
impl Drop for CompressorParams {
fn drop(&mut self) {
unsafe {
sys::compressor_params_delete(self.0);
}
}
}
| set_print_status_to_stdout | identifier_name |
compressor_params.rs | use super::*;
use crate::{BasisTextureFormat, UserData};
use basis_universal_sys as sys;
pub use basis_universal_sys::ColorU8;
/// The color space the image to be compressed is encoded in. Using the correct color space will
#[derive(Debug, Copy, Clone)]
pub enum ColorSpace {
/// Used for normal maps or other "data" images
Linear,
/// Used for color maps and other "visual" images
Srgb,
}
/// Parameters that are used to configure a [Compressor]
pub struct CompressorParams(pub *mut sys::CompressorParams);
impl Default for CompressorParams {
fn default() -> Self {
Self::new()
}
}
impl CompressorParams {
/// Create a compressor with default options
pub fn new() -> Self {
unsafe {
let mut params = CompressorParams(sys::compressor_params_new());
params.set_default_options();
params
}
}
/// Resets the compressor params to default state
pub fn reset(&mut self) {
unsafe {
sys::compressor_params_clear(self.0);
self.set_default_options();
self.clear_source_image_list();
}
}
// The default options that are applied when creating a new compressor or calling reset() on it
fn set_default_options(&mut self) {
// Set a default quality level. Leaving this unset results in undefined behavior, so we set
// it to a working value by default
self.set_etc1s_quality_level(crate::ETC1S_QUALITY_DEFAULT);
self.set_uastc_quality_level(crate::UASTC_QUALITY_DEFAULT);
// The library by default prints to stdout, but since this is a library we should disable
// that by default
self.set_print_status_to_stdout(false);
}
//
// These function are used to load image data into the compressor
//
/// Get a reference to the source index. The internal list of source images is resized as needed
/// such that the image will exist
pub fn source_image_mut(
&mut self,
image_index: u32,
) -> CompressorImageRef {
unsafe {
CompressorImageRef(sys::compressor_params_get_or_create_source_image(
self.0,
image_index,
))
}
}
/// Resizes the source image list. If the provided length is shorter than the list, the data
/// beyond the provided length is truncated.
pub fn resize_source_image_list(
&mut self,
size: u32,
) {
unsafe {
sys::compressor_params_resize_source_image_list(self.0, size as _);
}
}
/// Resets the image list to be zero-length
pub fn clear_source_image_list(&mut self) {
unsafe {
sys::compressor_params_clear_source_image_list(self.0);
}
}
//
// These set parameters for compression
//
/// Enable stdout logging
pub fn set_print_status_to_stdout(
&mut self, | }
/// Set ETC1S quality level. The value MUST be >= [ETC1S_QUALITY_MIN](crate::ETC1S_QUALITY_MIN)
/// and <= [ETC1S_QUALITY_MAX](crate::ETC1S_QUALITY_MAX).
pub fn set_etc1s_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::ETC1S_QUALITY_MIN);
assert!(quality_level <= crate::ETC1S_QUALITY_MAX);
unsafe {
sys::compressor_params_set_quality_level(self.0, quality_level as i32);
}
}
/// Sets UASTC quality level. The value MUST be >= [UASTC_QUALITY_MIN](crate::UASTC_QUALITY_MIN)
/// and <= [UASTC_QUALITY_MAX](crate::UASTC_QUALITY_MAX).
pub fn set_uastc_quality_level(
&mut self,
quality_level: u32,
) {
assert!(quality_level >= crate::UASTC_QUALITY_MIN);
assert!(quality_level <= crate::UASTC_QUALITY_MAX);
unsafe {
let mut flags = sys::compressor_params_get_pack_uastc_flags(self.0);
flags |= quality_level;
sys::compressor_params_set_pack_uastc_flags(self.0, flags);
}
}
/// Use the global codebook to compress the image. slightly smaller files, but lower quality,
/// slower encoding
pub fn set_use_global_codebook(
&mut self,
use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_global_sel_pal(self.0, use_global_codebook);
}
}
/// Automatically use virtual selector palettes on small images for slightly smaller files
/// (defaults to off for faster encoding time)
pub fn set_auto_use_global_codebook(
&mut self,
auto_use_global_codebook: bool,
) {
unsafe {
sys::compressor_params_set_auto_global_sel_pal(self.0, auto_use_global_codebook);
}
}
/// Set the basis format we will compress to. See basis documentation for details. This
/// corresponds to the -uastc flag in the basisu command line tool and the m_uastc boolean param
/// on `basis_compressor_params` in the original library
///
/// UASTC encoding result in significantly higher texture quality, but larger files.
pub fn set_basis_format(
&mut self,
basis_format: BasisTextureFormat,
) {
let is_uastc = match basis_format {
BasisTextureFormat::ETC1S => false,
BasisTextureFormat::UASTC4x4 => true,
};
unsafe {
sys::compressor_params_set_uastc(self.0, is_uastc);
}
}
/// Sets the color space the images to be compressed is encoded in
///
/// Setting a linear color space will:
/// * Use linear colorspace metrics (instead of the default sRGB)
/// * By default use linear (not sRGB) mipmap filtering
pub fn set_color_space(
&mut self,
color_space: ColorSpace,
) {
let perceptual = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_perceptual(self.0, perceptual);
}
}
/// Override the mipmap generation color space behavior. This function is not necessary to call
/// if you call [set_color_space] with the correct value.
///
/// * If the color space is sRGB, convert image to linear before filtering, then back to sRGB
/// * If the color space is linear, we keep the image in linear during mipmap filtering
/// (i.e. do not convert to/from sRGB for filtering purposes)
pub fn set_mip_color_space(
&mut self,
color_space: ColorSpace,
) {
let mip_srgb = match color_space {
ColorSpace::Linear => false,
ColorSpace::Srgb => true,
};
unsafe {
sys::compressor_params_set_mip_srgb(self.0, mip_srgb);
}
}
/// Disable backend's selector rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_selector_rdo(
&mut self,
no_selector_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_selector_rdo(self.0, no_selector_rdo);
}
}
/// Disable backend's endpoint rate distortion optimizations (slightly faster, less noisy
/// output, but lower quality per output bit)
pub fn set_no_endpoint_rdo(
&mut self,
no_endpoint_rdo: bool,
) {
unsafe {
sys::compressor_params_set_no_endpoint_rdo(self.0, no_endpoint_rdo);
}
}
/// Enable/disable UASTC RDO post-processing and set UASTC RDO quality scalar to X. Lower
/// values=higher quality/larger LZ compressed files, higher values=lower quality/smaller LZ
/// compressed files. Good range to try is [.2-4]
pub fn set_rdo_uastc(
&mut self,
rdo_uastc_quality_scalar: Option<f32>,
) {
unsafe {
match rdo_uastc_quality_scalar {
Some(quality_scalar) => {
sys::compressor_params_set_rdo_uastc(self.0, true);
sys::compressor_params_set_rdo_uastc_quality_scalar(self.0, quality_scalar);
}
None => {
sys::compressor_params_set_rdo_uastc(self.0, false);
}
}
}
}
/// Generate mipmaps for each source image
///
/// By default, sRGB textures will be converted from sRGB to linear before mipmap filtering.
/// This can be changed by calling [set_color_space] or [set_mip_color_space]
pub fn set_generate_mipmaps(
&mut self,
generate_mipmaps: bool,
) {
unsafe {
sys::compressor_params_set_generate_mipmaps(self.0, generate_mipmaps);
}
}
/// Sets the smallest dimension mipmap that will be generated
pub fn set_mipmap_smallest_dimension(
&mut self,
smallest_dimension: u32,
) {
unsafe {
sys::compressor_params_set_mip_smallest_dimension(self.0, smallest_dimension as _);
}
}
/// Set arbitrary userdata to be included with the basis-universal binary data
pub fn set_userdata(
&mut self,
userdata: UserData,
) {
unsafe {
sys::compressor_params_set_userdata(self.0, userdata.userdata0, userdata.userdata1);
}
}
/// The `basisu` command line compressor offers a -normal_map parameter that sets several
/// values automatically. This convenience function mimics that parameter.
///
/// * linear colorspace metrics
/// * linear mipmap filtering
/// * no selector RDO
/// * no sRGB
pub fn tune_for_normal_maps(&mut self) {
//TODO
unsafe {
sys::compressor_params_set_perceptual(self.0, false);
sys::compressor_params_set_mip_srgb(self.0, false);
sys::compressor_params_set_no_selector_rdo(self.0, true);
sys::compressor_params_set_no_endpoint_rdo(self.0, true);
}
}
// set_multithreaded not implemented here as this is controlled by thread count passed to
// `Compressor::new()`
}
impl Drop for CompressorParams {
fn drop(&mut self) {
unsafe {
sys::compressor_params_delete(self.0);
}
}
} | print_status_to_stdout: bool,
) {
unsafe { sys::compressor_params_set_status_output(self.0, print_status_to_stdout) } | random_line_split |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use clippy_utils::{
can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
peel_hir_expr_refs, peel_hir_expr_while, CaptureKind,
};
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome};
use rustc_hir::{
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, SyntaxContext};
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of `match` which could be implemented using `map`
///
/// ### Why is this bad?
/// Using the `map` method is clearer and more concise.
///
/// ### Example
/// ```rust
/// match Some(0) {
/// Some(x) => Some(x + 1),
/// None => None,
/// };
/// ```
/// Use instead:
/// ```rust
/// Some(0).map(|x| x + 1);
/// ```
#[clippy::version = "1.52.0"]
pub MANUAL_MAP,
style,
"reimplementation of `map`"
}
declare_lint_pass!(ManualMap => [MANUAL_MAP]);
impl LateLintPass<'_> for ManualMap {
#[allow(clippy::too_many_lines)]
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let (scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else),
Some(IfLetOrMatch::Match(
scrutinee,
[arm1 @ Arm { guard: None,.. }, arm2 @ Arm { guard: None,.. }],
_,
)) => (scrutinee, arm1.pat, arm1.body, Some(arm2.pat), arm2.body),
_ => return,
};
if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
return;
}
let (scrutinee_ty, ty_ref_count, ty_mutability) =
peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
if!(is_type_diagnostic_item(cx, scrutinee_ty, sym::Option)
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Option))
{
return;
}
let expr_ctxt = expr.span.ctxt();
let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
try_parse_pattern(cx, then_pat, expr_ctxt),
else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),
) {
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, true)
},
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, false)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, true)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, false)
},
_ => return,
};
// Top level or patterns aren't allowed in closures.
if matches!(some_pat.kind, PatKind::Or(_)) {
return;
}
let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
Some(expr) => expr,
None => return,
};
// These two lints will go back and forth with each other.
if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
&&!is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
{
return;
}
// `map` won't perform any adjustments.
if!cx.typeck_results().expr_adjustments(some_expr).is_empty() {
return;
}
// Determine which binding mode to use.
let explicit_ref = some_pat.contains_explicit_ref_binding();
let binding_ref = explicit_ref.or_else(|| (ty_ref_count!= pat_ref_count).then(|| ty_mutability));
let as_ref_str = match binding_ref {
Some(Mutability::Mut) => ".as_mut()",
Some(Mutability::Not) => ".as_ref()",
None => "",
};
match can_move_expr_to_closure(cx, some_expr) {
Some(captures) => {
// Check if captures the closure will need conflict with borrows made in the scrutinee.
// TODO: check all the references made in the scrutinee expression. This will require interacting
// with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
if let Some(binding_ref_mutability) = binding_ref {
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
_ => None,
});
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l),.. })) = e.kind {
match captures.get(l) {
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {
return;
},
Some(CaptureKind::Ref(Mutability::Not)) | None => (),
}
}
}
},
None => return,
};
let mut app = Applicability::MachineApplicable;
// Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
// it's being passed by value.
let scrutinee = peel_hir_expr_refs(scrutinee).0;
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
let scrutinee_str =
if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
format!("({})", scrutinee_str)
} else {
scrutinee_str.into()
};
let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
match can_pass_as_func(cx, id, some_expr) {
Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
},
_ => {
if path_to_local_id(some_expr, id)
&&!is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
&& binding_ref.is_some()
{
return;
}
// `ref` and `ref mut` annotations were handled earlier.
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
"mut "
} else {
""
};
format!(
"|{}{}| {}",
annotation,
some_binding,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
},
}
} else if!is_wild_none && explicit_ref.is_none() {
// TODO: handle explicit reference annotations.
format!(
"|{}| {}",
snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
} else {
// Refutable bindings and mixed reference annotations can't be handled by `map`.
return;
};
span_lint_and_sugg(
cx,
MANUAL_MAP,
expr.span,
"manual implementation of `Option::map`",
"try this",
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
} else {
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
},
app,
);
}
}
// Checks whether the expression could be passed as a function, or whether a closure is needed.
// Returns the function to be passed to `map` if it exists.
fn can_pass_as_func(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
match expr.kind {
ExprKind::Call(func, [arg])
if path_to_local_id(arg, binding) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
{
Some(func)
},
_ => None,
}
}
enum OptionPat<'a> {
Wild,
None,
Some {
// The pattern contained in the `Some` tuple.
pattern: &'a Pat<'a>,
// The number of references before the `Some` tuple.
// e.g. `&&Some(_)` has a ref count of 2.
ref_count: usize,
},
}
// Try to parse into a recognized `Option` pattern.
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> |
f(cx, pat, 0, ctxt)
}
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
// TODO: Allow more complex expressions.
match expr.kind {
ExprKind::Call(
Expr {
kind: ExprKind::Path(ref qpath),
..
},
[arg],
) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => get_some_expr(cx, expr, ctxt),
_ => None,
}
}
// Checks for the `None` value.
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
match expr.kind {
ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => is_none_expr(cx, expr),
_ => false,
}
}
| {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
PatKind::TupleStruct(ref qpath, [pattern], _)
if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
{
Some(OptionPat::Some { pattern, ref_count })
},
_ => None,
}
} | identifier_body |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use clippy_utils::{
can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
peel_hir_expr_refs, peel_hir_expr_while, CaptureKind,
};
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome};
use rustc_hir::{
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, SyntaxContext};
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of `match` which could be implemented using `map`
///
/// ### Why is this bad?
/// Using the `map` method is clearer and more concise.
///
/// ### Example
/// ```rust
/// match Some(0) {
/// Some(x) => Some(x + 1),
/// None => None,
/// };
/// ```
/// Use instead:
/// ```rust
/// Some(0).map(|x| x + 1);
/// ```
#[clippy::version = "1.52.0"]
pub MANUAL_MAP,
style,
"reimplementation of `map`"
}
declare_lint_pass!(ManualMap => [MANUAL_MAP]);
impl LateLintPass<'_> for ManualMap {
#[allow(clippy::too_many_lines)]
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let (scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else),
Some(IfLetOrMatch::Match(
scrutinee,
[arm1 @ Arm { guard: None,.. }, arm2 @ Arm { guard: None,.. }],
_,
)) => (scrutinee, arm1.pat, arm1.body, Some(arm2.pat), arm2.body),
_ => return,
};
if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
return;
}
let (scrutinee_ty, ty_ref_count, ty_mutability) =
peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
if!(is_type_diagnostic_item(cx, scrutinee_ty, sym::Option)
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Option))
{
return;
}
let expr_ctxt = expr.span.ctxt();
let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
try_parse_pattern(cx, then_pat, expr_ctxt),
else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),
) {
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, true)
},
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, false)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, true)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, false)
},
_ => return,
};
// Top level or patterns aren't allowed in closures.
if matches!(some_pat.kind, PatKind::Or(_)) {
return;
}
let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
Some(expr) => expr,
None => return,
};
// These two lints will go back and forth with each other.
if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
&&!is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
{
return;
}
// `map` won't perform any adjustments.
if!cx.typeck_results().expr_adjustments(some_expr).is_empty() {
return;
}
// Determine which binding mode to use.
let explicit_ref = some_pat.contains_explicit_ref_binding();
let binding_ref = explicit_ref.or_else(|| (ty_ref_count!= pat_ref_count).then(|| ty_mutability));
let as_ref_str = match binding_ref {
Some(Mutability::Mut) => ".as_mut()",
Some(Mutability::Not) => ".as_ref()",
None => "",
};
match can_move_expr_to_closure(cx, some_expr) {
Some(captures) => {
// Check if captures the closure will need conflict with borrows made in the scrutinee.
// TODO: check all the references made in the scrutinee expression. This will require interacting
// with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
if let Some(binding_ref_mutability) = binding_ref {
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
_ => None,
});
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l),.. })) = e.kind {
match captures.get(l) {
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {
return;
},
Some(CaptureKind::Ref(Mutability::Not)) | None => (),
}
}
}
},
None => return,
};
let mut app = Applicability::MachineApplicable;
// Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
// it's being passed by value.
let scrutinee = peel_hir_expr_refs(scrutinee).0;
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
let scrutinee_str =
if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
format!("({})", scrutinee_str)
} else {
scrutinee_str.into()
};
let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
match can_pass_as_func(cx, id, some_expr) {
Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
},
_ => {
if path_to_local_id(some_expr, id)
&&!is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
&& binding_ref.is_some()
{
return;
}
// `ref` and `ref mut` annotations were handled earlier.
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
"mut "
} else {
""
};
format!(
"|{}{}| {}",
annotation,
some_binding,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
},
}
} else if!is_wild_none && explicit_ref.is_none() {
// TODO: handle explicit reference annotations.
format!(
"|{}| {}",
snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
} else {
// Refutable bindings and mixed reference annotations can't be handled by `map`.
return;
};
span_lint_and_sugg(
cx,
MANUAL_MAP,
expr.span,
"manual implementation of `Option::map`",
"try this",
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
} else {
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
},
app,
);
}
}
// Checks whether the expression could be passed as a function, or whether a closure is needed.
// Returns the function to be passed to `map` if it exists.
fn can_pass_as_func(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
match expr.kind {
ExprKind::Call(func, [arg])
if path_to_local_id(arg, binding) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
{
Some(func)
},
_ => None,
}
}
enum OptionPat<'a> {
Wild,
None,
Some {
// The pattern contained in the `Some` tuple.
pattern: &'a Pat<'a>,
// The number of references before the `Some` tuple.
// e.g. `&&Some(_)` has a ref count of 2.
ref_count: usize,
},
}
// Try to parse into a recognized `Option` pattern.
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
fn | (cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
PatKind::TupleStruct(ref qpath, [pattern], _)
if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
{
Some(OptionPat::Some { pattern, ref_count })
},
_ => None,
}
}
f(cx, pat, 0, ctxt)
}
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
// TODO: Allow more complex expressions.
match expr.kind {
ExprKind::Call(
Expr {
kind: ExprKind::Path(ref qpath),
..
},
[arg],
) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => get_some_expr(cx, expr, ctxt),
_ => None,
}
}
// Checks for the `None` value.
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
match expr.kind {
ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => is_none_expr(cx, expr),
_ => false,
}
}
| f | identifier_name |
manual_map.rs | use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::higher::IfLetOrMatch;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
use clippy_utils::ty::{is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
use clippy_utils::{
can_move_expr_to_closure, in_constant, is_else_clause, is_lang_ctor, is_lint_allowed, path_to_local_id,
peel_hir_expr_refs, peel_hir_expr_while, CaptureKind, | use rustc_hir::{
def::Res, Arm, BindingAnnotation, Block, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath,
};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, SyntaxContext};
declare_clippy_lint! {
/// ### What it does
/// Checks for usages of `match` which could be implemented using `map`
///
/// ### Why is this bad?
/// Using the `map` method is clearer and more concise.
///
/// ### Example
/// ```rust
/// match Some(0) {
/// Some(x) => Some(x + 1),
/// None => None,
/// };
/// ```
/// Use instead:
/// ```rust
/// Some(0).map(|x| x + 1);
/// ```
#[clippy::version = "1.52.0"]
pub MANUAL_MAP,
style,
"reimplementation of `map`"
}
declare_lint_pass!(ManualMap => [MANUAL_MAP]);
impl LateLintPass<'_> for ManualMap {
#[allow(clippy::too_many_lines)]
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
let (scrutinee, then_pat, then_body, else_pat, else_body) = match IfLetOrMatch::parse(cx, expr) {
Some(IfLetOrMatch::IfLet(scrutinee, pat, body, Some(r#else))) => (scrutinee, pat, body, None, r#else),
Some(IfLetOrMatch::Match(
scrutinee,
[arm1 @ Arm { guard: None,.. }, arm2 @ Arm { guard: None,.. }],
_,
)) => (scrutinee, arm1.pat, arm1.body, Some(arm2.pat), arm2.body),
_ => return,
};
if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
return;
}
let (scrutinee_ty, ty_ref_count, ty_mutability) =
peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
if!(is_type_diagnostic_item(cx, scrutinee_ty, sym::Option)
&& is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::Option))
{
return;
}
let expr_ctxt = expr.span.ctxt();
let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
try_parse_pattern(cx, then_pat, expr_ctxt),
else_pat.map_or(Some(OptionPat::Wild), |p| try_parse_pattern(cx, p, expr_ctxt)),
) {
(Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, true)
},
(Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) if is_none_expr(cx, then_body) => {
(else_body, pattern, ref_count, false)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, true)
},
(Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) if is_none_expr(cx, else_body) => {
(then_body, pattern, ref_count, false)
},
_ => return,
};
// Top level or patterns aren't allowed in closures.
if matches!(some_pat.kind, PatKind::Or(_)) {
return;
}
let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
Some(expr) => expr,
None => return,
};
// These two lints will go back and forth with each other.
if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
&&!is_lint_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
{
return;
}
// `map` won't perform any adjustments.
if!cx.typeck_results().expr_adjustments(some_expr).is_empty() {
return;
}
// Determine which binding mode to use.
let explicit_ref = some_pat.contains_explicit_ref_binding();
let binding_ref = explicit_ref.or_else(|| (ty_ref_count!= pat_ref_count).then(|| ty_mutability));
let as_ref_str = match binding_ref {
Some(Mutability::Mut) => ".as_mut()",
Some(Mutability::Not) => ".as_ref()",
None => "",
};
match can_move_expr_to_closure(cx, some_expr) {
Some(captures) => {
// Check if captures the closure will need conflict with borrows made in the scrutinee.
// TODO: check all the references made in the scrutinee expression. This will require interacting
// with the borrow checker. Currently only `<local>[.<field>]*` is checked for.
if let Some(binding_ref_mutability) = binding_ref {
let e = peel_hir_expr_while(scrutinee, |e| match e.kind {
ExprKind::Field(e, _) | ExprKind::AddrOf(_, _, e) => Some(e),
_ => None,
});
if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l),.. })) = e.kind {
match captures.get(l) {
Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return,
Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => {
return;
},
Some(CaptureKind::Ref(Mutability::Not)) | None => (),
}
}
}
},
None => return,
};
let mut app = Applicability::MachineApplicable;
// Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
// it's being passed by value.
let scrutinee = peel_hir_expr_refs(scrutinee).0;
let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
let scrutinee_str =
if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
format!("({})", scrutinee_str)
} else {
scrutinee_str.into()
};
let body_str = if let PatKind::Binding(annotation, id, some_binding, None) = some_pat.kind {
match can_pass_as_func(cx, id, some_expr) {
Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
},
_ => {
if path_to_local_id(some_expr, id)
&&!is_lint_allowed(cx, MATCH_AS_REF, expr.hir_id)
&& binding_ref.is_some()
{
return;
}
// `ref` and `ref mut` annotations were handled earlier.
let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
"mut "
} else {
""
};
format!(
"|{}{}| {}",
annotation,
some_binding,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
},
}
} else if!is_wild_none && explicit_ref.is_none() {
// TODO: handle explicit reference annotations.
format!(
"|{}| {}",
snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
)
} else {
// Refutable bindings and mixed reference annotations can't be handled by `map`.
return;
};
span_lint_and_sugg(
cx,
MANUAL_MAP,
expr.span,
"manual implementation of `Option::map`",
"try this",
if else_pat.is_none() && is_else_clause(cx.tcx, expr) {
format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
} else {
format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
},
app,
);
}
}
// Checks whether the expression could be passed as a function, or whether a closure is needed.
// Returns the function to be passed to `map` if it exists.
fn can_pass_as_func(cx: &LateContext<'tcx>, binding: HirId, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
match expr.kind {
ExprKind::Call(func, [arg])
if path_to_local_id(arg, binding) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
{
Some(func)
},
_ => None,
}
}
enum OptionPat<'a> {
Wild,
None,
Some {
// The pattern contained in the `Some` tuple.
pattern: &'a Pat<'a>,
// The number of references before the `Some` tuple.
// e.g. `&&Some(_)` has a ref count of 2.
ref_count: usize,
},
}
// Try to parse into a recognized `Option` pattern.
// i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
match pat.kind {
PatKind::Wild => Some(OptionPat::Wild),
PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
PatKind::TupleStruct(ref qpath, [pattern], _)
if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
{
Some(OptionPat::Some { pattern, ref_count })
},
_ => None,
}
}
f(cx, pat, 0, ctxt)
}
// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
// TODO: Allow more complex expressions.
match expr.kind {
ExprKind::Call(
Expr {
kind: ExprKind::Path(ref qpath),
..
},
[arg],
) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => get_some_expr(cx, expr, ctxt),
_ => None,
}
}
// Checks for the `None` value.
fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
match expr.kind {
ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
ExprKind::Block(
Block {
stmts: [],
expr: Some(expr),
..
},
_,
) => is_none_expr(cx, expr),
_ => false,
}
} | };
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome}; | random_line_split |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use walkdir::WalkDir;
use libc;
use crate::{Result, util};
pub fn is_valid_name(name: &str, maxsize: usize) -> bool {
name.len() <= maxsize &&
// Also false on empty string
is_first_char_alphabetic(name) &&
name.chars().all(is_alphanum_or_dash)
}
fn is_alphanum_or_dash(c: char) -> bool {
is_ascii(c) && (c.is_alphanumeric() || c == '-')
}
fn is_ascii(c: char) -> bool {
c as u32 <= 0x7F
}
pub fn is_first_char_alphabetic(s: &str) -> bool {
if let Some(c) = s.chars().next() {
return is_ascii(c) && c.is_alphabetic()
}
false
}
fn search_path(filename: &str) -> Result<PathBuf> {
let path_var = env::var("PATH").unwrap_or("".into());
for mut path in env::split_paths(&path_var) {
path.push(filename);
if path.exists() {
return Ok(path);
}
}
bail!("could not find {} in $PATH", filename)
}
pub fn ensure_command_exists(cmd: &str) -> Result<()> {
let path = Path::new(cmd);
if!path.is_absolute() {
search_path(cmd)?;
return Ok(())
} else if path.exists() {
return Ok(())
}
bail!("cannot execute '{}': command does not exist", cmd)
}
pub fn sha256<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let output = cmd_with_output!("/usr/bin/sha256sum", "{}", path.display())
.map_err(context!("failed to calculate sha256 on {:?}", path))?;
let v: Vec<&str> = output.split_whitespace().collect();
Ok(v[0].trim().to_owned())
}
#[derive(Copy,Clone)]
pub enum FileRange {
All,
Offset(usize),
Range{offset: usize, len: usize},
}
fn ranged_reader<P: AsRef<Path>>(path: P, range: FileRange) -> Result<Box<dyn Read>> {
let path = path.as_ref();
let mut f = File::open(path)
.map_err(context!("error opening input file {:?}", path))?;
let offset = match range {
FileRange::All => 0,
FileRange::Offset(n) => n,
FileRange::Range {offset,.. } => offset,
};
if offset > 0 {
f.seek(SeekFrom::Start(offset as u64))
.map_err(context!("error seeking to offset {} in input file {:?}", offset, path))?;
}
let r = BufReader::new(f);
if let FileRange::Range {len,..} = range {
Ok(Box::new(r.take(len as u64)))
} else {
Ok(Box::new(r))
}
}
///
/// Execute a command, pipe the contents of a file to stdin, return the output as a `String`
///
pub fn exec_cmdline_pipe_input<S,P>(cmd_path: &str, args: S, input: P, range: FileRange) -> Result<String>
where S: AsRef<str>, P: AsRef<Path>
{
let mut r = ranged_reader(input.as_ref(), range)?;
ensure_command_exists(cmd_path)?;
let args: Vec<&str> = args.as_ref().split_whitespace().collect::<Vec<_>>();
let mut child = Command::new(cmd_path)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(context!("unable to execute {}", cmd_path))?;
let stdin = child.stdin.as_mut().unwrap();
io::copy(&mut r, stdin)
.map_err(context!("error copying input to stdin"))?;
let output = child.wait_with_output()
.map_err(context!("error waiting for command {} to exit", cmd_path))?;
Ok(String::from_utf8(output.stdout).unwrap().trim().to_owned())
}
pub fn xz_compress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-T0 {}", path.display())
.map_err(context!("failed to compress {:?}", path))
}
pub fn xz_decompress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-d {}", path.display())
.map_err(context!("failed to decompress {:?}", path))
}
pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> {
let source = source.as_ref();
let target = target.as_ref();
if let Some(options) = options {
cmd!("/usr/bin/mount", "{} {} {}", options, source, target.display())
} else {
cmd!("/usr/bin/mount", "{} {}", source, target.display())
}.map_err(context!("failed to mount {} to {:?}", source, target))
}
pub fn umount<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/umount", "{}", path.display())
.map_err(context!("failed to unmount {:?}", path))
}
pub fn chown_user<P: AsRef<Path>>(path: P) -> Result<()> {
chown(path.as_ref(), 1000, 1000)
}
pub fn chown(path: &Path, uid: u32, gid: u32) -> Result<()> {
let cstr = CString::new(path.as_os_str().as_bytes())
.expect("path contains null byte");
unsafe {
if libc::chown(cstr.as_ptr(), uid, gid) == -1 {
let err = io::Error::last_os_error();
bail!("failed to chown({},{}) {:?}: {}", uid, gid, path, err);
}
}
Ok(())
}
pub fn chmod(path: &Path, mode: u32) -> Result<()> {
let meta = path.metadata()
.map_err(context!("Failed to read metadata from path {:?}", path))?;
meta.permissions().set_mode(mode);
Ok(())
}
/// Rename or move file at `from` to file path `to`
///
/// A wrapper around `fs::rename()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::rename(from, to)
.map_err(context!("error renaming {:?} to {:?}", from, to))
}
/// Create a symlink at path `dst` which points to `src`
///
/// A wrapper around `fs::symlink()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
unixfs::symlink(src, dst)
.map_err(context!("failed to create symlink {:?} to {:?}", dst, src))
}
/// Read directory `dir` and call closure `f` on each `DirEntry`
pub fn read_directory<F>(dir: impl AsRef<Path>, mut f: F) -> Result<()>
where
F: FnMut(&DirEntry) -> Result<()>
{
let dir = dir.as_ref();
let entries = fs::read_dir(dir)
.map_err(context!("failed to read directory {:?}", dir))?;
for dent in entries {
let dent = dent.map_err(context!("error reading entry from directory {:?}", dir))?;
f(&dent)?;
}
Ok(())
}
/// Remove file at `path` if it exists.
///
/// A wrapper around `fs::remove_file()` which on failure returns an error indicating the path of
/// the file which failed to be removed.
///
pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if path.exists() {
fs::remove_file(path)
.map_err(context!("failed to remove file {:?}", path))?;
}
Ok(())
}
/// Create directory `path` if it does not already exist.
///
/// A wrapper around `fs::create_dir_all()` which on failure returns an error indicating the path
/// of the directory which failed to be created.
///
pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if!path.exists() {
fs::create_dir_all(path)
.map_err(context!("failed to create directory {:?}", path))?;
}
Ok(())
}
/// Write `contents` to file `path`
///
/// A wrapper around `fs::write()` which on failure returns an error indicating the path
/// of the file which failed to be written.
///
pub fn write_file(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
let path = path.as_ref();
fs::write(path, contents)
.map_err(context!("failed to write to file {:?}", path))
}
/// Read content of file `path` into a `String`
///
/// A wrapper around `fs::read_to_string()` which on failure returns an error indicating the path
/// of the file which failed to be read.
///
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
let path = path.as_ref();
fs::read_to_string(path)
.map_err(context!("failed to read file {:?}", path))
}
/// Copy file at path `from` to a new file at path `to`
///
/// A wrapper around `fs::copy()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::copy(from, to)
.map_err(context!("failed to copy file {:?} to {:?}", from, to))?;
Ok(())
}
fn copy_path(from: &Path, to: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
if to.exists() {
bail!("destination path {} already exists which is not expected", to.display());
}
let meta = from.metadata()
.map_err(context!("failed to read metadata from source file {:?}", from))?;
if from.is_dir() {
util::create_dir(to)?;
} else {
util::copy_file(&from, &to)?;
}
if let Some((uid,gid)) = chown_to {
chown(to, uid, gid)?;
} else {
chown(to, meta.uid(), meta.gid())?;
}
Ok(())
}
pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> {
_copy_tree(from_base, to_base, None)
}
pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> {
_copy_tree(from_base, to_base, Some(chown_to))
}
fn _copy_tree(from_base: &Path, to_base: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
for entry in WalkDir::new(from_base) {
let entry = entry.map_err(|e| format_err!("Error walking directory tree: {}", e))?;
let path = entry.path();
let suffix = path.strip_prefix(from_base)
.map_err(|_| format_err!("Failed to strip prefix from {:?}", path))?;
let to = to_base.join(suffix);
if &to!= to_base |
}
Ok(())
}
pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> {
for entry in WalkDir::new(base) {
let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?;
if entry.path()!= base || include_base {
chown(entry.path(), chown_to.0, chown_to.1)
.map_err(context!("failed to chown {:?}", entry.path()))?;
}
}
Ok(())
}
pub fn is_euid_root() -> bool {
unsafe {
libc::geteuid() == 0
}
}
| {
copy_path(path, &to, chown_to)
.map_err(context!("failed to copy {:?} to {:?}", path, to))?;
} | conditional_block |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use walkdir::WalkDir;
use libc;
use crate::{Result, util};
pub fn is_valid_name(name: &str, maxsize: usize) -> bool {
name.len() <= maxsize &&
// Also false on empty string
is_first_char_alphabetic(name) &&
name.chars().all(is_alphanum_or_dash)
}
fn is_alphanum_or_dash(c: char) -> bool {
is_ascii(c) && (c.is_alphanumeric() || c == '-')
}
fn is_ascii(c: char) -> bool {
c as u32 <= 0x7F
}
pub fn is_first_char_alphabetic(s: &str) -> bool {
if let Some(c) = s.chars().next() {
return is_ascii(c) && c.is_alphabetic()
}
false
}
fn search_path(filename: &str) -> Result<PathBuf> {
let path_var = env::var("PATH").unwrap_or("".into());
for mut path in env::split_paths(&path_var) {
path.push(filename);
if path.exists() {
return Ok(path);
}
}
bail!("could not find {} in $PATH", filename)
}
pub fn ensure_command_exists(cmd: &str) -> Result<()> {
let path = Path::new(cmd);
if!path.is_absolute() {
search_path(cmd)?;
return Ok(())
} else if path.exists() {
return Ok(())
}
bail!("cannot execute '{}': command does not exist", cmd)
}
pub fn sha256<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let output = cmd_with_output!("/usr/bin/sha256sum", "{}", path.display())
.map_err(context!("failed to calculate sha256 on {:?}", path))?;
let v: Vec<&str> = output.split_whitespace().collect();
Ok(v[0].trim().to_owned())
}
#[derive(Copy,Clone)]
pub enum FileRange {
All,
Offset(usize),
Range{offset: usize, len: usize},
}
fn ranged_reader<P: AsRef<Path>>(path: P, range: FileRange) -> Result<Box<dyn Read>> {
let path = path.as_ref();
let mut f = File::open(path)
.map_err(context!("error opening input file {:?}", path))?;
let offset = match range {
FileRange::All => 0,
FileRange::Offset(n) => n,
FileRange::Range {offset,.. } => offset,
};
if offset > 0 {
f.seek(SeekFrom::Start(offset as u64))
.map_err(context!("error seeking to offset {} in input file {:?}", offset, path))?;
}
let r = BufReader::new(f);
if let FileRange::Range {len,..} = range {
Ok(Box::new(r.take(len as u64)))
} else {
Ok(Box::new(r))
}
}
///
/// Execute a command, pipe the contents of a file to stdin, return the output as a `String`
///
pub fn exec_cmdline_pipe_input<S,P>(cmd_path: &str, args: S, input: P, range: FileRange) -> Result<String>
where S: AsRef<str>, P: AsRef<Path>
{
let mut r = ranged_reader(input.as_ref(), range)?;
ensure_command_exists(cmd_path)?;
let args: Vec<&str> = args.as_ref().split_whitespace().collect::<Vec<_>>();
let mut child = Command::new(cmd_path)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(context!("unable to execute {}", cmd_path))?;
let stdin = child.stdin.as_mut().unwrap();
io::copy(&mut r, stdin)
.map_err(context!("error copying input to stdin"))?;
let output = child.wait_with_output()
.map_err(context!("error waiting for command {} to exit", cmd_path))?;
Ok(String::from_utf8(output.stdout).unwrap().trim().to_owned())
}
pub fn xz_compress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-T0 {}", path.display())
.map_err(context!("failed to compress {:?}", path))
}
pub fn | <P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-d {}", path.display())
.map_err(context!("failed to decompress {:?}", path))
}
pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> {
let source = source.as_ref();
let target = target.as_ref();
if let Some(options) = options {
cmd!("/usr/bin/mount", "{} {} {}", options, source, target.display())
} else {
cmd!("/usr/bin/mount", "{} {}", source, target.display())
}.map_err(context!("failed to mount {} to {:?}", source, target))
}
pub fn umount<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/umount", "{}", path.display())
.map_err(context!("failed to unmount {:?}", path))
}
pub fn chown_user<P: AsRef<Path>>(path: P) -> Result<()> {
chown(path.as_ref(), 1000, 1000)
}
pub fn chown(path: &Path, uid: u32, gid: u32) -> Result<()> {
let cstr = CString::new(path.as_os_str().as_bytes())
.expect("path contains null byte");
unsafe {
if libc::chown(cstr.as_ptr(), uid, gid) == -1 {
let err = io::Error::last_os_error();
bail!("failed to chown({},{}) {:?}: {}", uid, gid, path, err);
}
}
Ok(())
}
pub fn chmod(path: &Path, mode: u32) -> Result<()> {
let meta = path.metadata()
.map_err(context!("Failed to read metadata from path {:?}", path))?;
meta.permissions().set_mode(mode);
Ok(())
}
/// Rename or move file at `from` to file path `to`
///
/// A wrapper around `fs::rename()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::rename(from, to)
.map_err(context!("error renaming {:?} to {:?}", from, to))
}
/// Create a symlink at path `dst` which points to `src`
///
/// A wrapper around `fs::symlink()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
unixfs::symlink(src, dst)
.map_err(context!("failed to create symlink {:?} to {:?}", dst, src))
}
/// Read directory `dir` and call closure `f` on each `DirEntry`
pub fn read_directory<F>(dir: impl AsRef<Path>, mut f: F) -> Result<()>
where
F: FnMut(&DirEntry) -> Result<()>
{
let dir = dir.as_ref();
let entries = fs::read_dir(dir)
.map_err(context!("failed to read directory {:?}", dir))?;
for dent in entries {
let dent = dent.map_err(context!("error reading entry from directory {:?}", dir))?;
f(&dent)?;
}
Ok(())
}
/// Remove file at `path` if it exists.
///
/// A wrapper around `fs::remove_file()` which on failure returns an error indicating the path of
/// the file which failed to be removed.
///
pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if path.exists() {
fs::remove_file(path)
.map_err(context!("failed to remove file {:?}", path))?;
}
Ok(())
}
/// Create directory `path` if it does not already exist.
///
/// A wrapper around `fs::create_dir_all()` which on failure returns an error indicating the path
/// of the directory which failed to be created.
///
pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if!path.exists() {
fs::create_dir_all(path)
.map_err(context!("failed to create directory {:?}", path))?;
}
Ok(())
}
/// Write `contents` to file `path`
///
/// A wrapper around `fs::write()` which on failure returns an error indicating the path
/// of the file which failed to be written.
///
pub fn write_file(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
let path = path.as_ref();
fs::write(path, contents)
.map_err(context!("failed to write to file {:?}", path))
}
/// Read content of file `path` into a `String`
///
/// A wrapper around `fs::read_to_string()` which on failure returns an error indicating the path
/// of the file which failed to be read.
///
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
let path = path.as_ref();
fs::read_to_string(path)
.map_err(context!("failed to read file {:?}", path))
}
/// Copy file at path `from` to a new file at path `to`
///
/// A wrapper around `fs::copy()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::copy(from, to)
.map_err(context!("failed to copy file {:?} to {:?}", from, to))?;
Ok(())
}
fn copy_path(from: &Path, to: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
if to.exists() {
bail!("destination path {} already exists which is not expected", to.display());
}
let meta = from.metadata()
.map_err(context!("failed to read metadata from source file {:?}", from))?;
if from.is_dir() {
util::create_dir(to)?;
} else {
util::copy_file(&from, &to)?;
}
if let Some((uid,gid)) = chown_to {
chown(to, uid, gid)?;
} else {
chown(to, meta.uid(), meta.gid())?;
}
Ok(())
}
pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> {
_copy_tree(from_base, to_base, None)
}
pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> {
_copy_tree(from_base, to_base, Some(chown_to))
}
fn _copy_tree(from_base: &Path, to_base: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
for entry in WalkDir::new(from_base) {
let entry = entry.map_err(|e| format_err!("Error walking directory tree: {}", e))?;
let path = entry.path();
let suffix = path.strip_prefix(from_base)
.map_err(|_| format_err!("Failed to strip prefix from {:?}", path))?;
let to = to_base.join(suffix);
if &to!= to_base {
copy_path(path, &to, chown_to)
.map_err(context!("failed to copy {:?} to {:?}", path, to))?;
}
}
Ok(())
}
pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> {
for entry in WalkDir::new(base) {
let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?;
if entry.path()!= base || include_base {
chown(entry.path(), chown_to.0, chown_to.1)
.map_err(context!("failed to chown {:?}", entry.path()))?;
}
}
Ok(())
}
pub fn is_euid_root() -> bool {
unsafe {
libc::geteuid() == 0
}
}
| xz_decompress | identifier_name |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use walkdir::WalkDir;
use libc;
use crate::{Result, util};
pub fn is_valid_name(name: &str, maxsize: usize) -> bool {
name.len() <= maxsize &&
// Also false on empty string
is_first_char_alphabetic(name) &&
name.chars().all(is_alphanum_or_dash)
}
fn is_alphanum_or_dash(c: char) -> bool {
is_ascii(c) && (c.is_alphanumeric() || c == '-')
}
fn is_ascii(c: char) -> bool {
c as u32 <= 0x7F
}
pub fn is_first_char_alphabetic(s: &str) -> bool {
if let Some(c) = s.chars().next() {
return is_ascii(c) && c.is_alphabetic()
}
false
}
fn search_path(filename: &str) -> Result<PathBuf> {
let path_var = env::var("PATH").unwrap_or("".into());
for mut path in env::split_paths(&path_var) {
path.push(filename);
if path.exists() {
return Ok(path);
}
}
bail!("could not find {} in $PATH", filename)
}
pub fn ensure_command_exists(cmd: &str) -> Result<()> {
let path = Path::new(cmd);
if!path.is_absolute() {
search_path(cmd)?;
return Ok(())
} else if path.exists() {
return Ok(())
}
bail!("cannot execute '{}': command does not exist", cmd)
}
pub fn sha256<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let output = cmd_with_output!("/usr/bin/sha256sum", "{}", path.display())
.map_err(context!("failed to calculate sha256 on {:?}", path))?;
let v: Vec<&str> = output.split_whitespace().collect();
Ok(v[0].trim().to_owned())
}
#[derive(Copy,Clone)]
pub enum FileRange {
All,
Offset(usize),
Range{offset: usize, len: usize},
}
fn ranged_reader<P: AsRef<Path>>(path: P, range: FileRange) -> Result<Box<dyn Read>> {
let path = path.as_ref();
let mut f = File::open(path)
.map_err(context!("error opening input file {:?}", path))?;
let offset = match range {
FileRange::All => 0,
FileRange::Offset(n) => n,
FileRange::Range {offset,.. } => offset,
};
if offset > 0 {
f.seek(SeekFrom::Start(offset as u64))
.map_err(context!("error seeking to offset {} in input file {:?}", offset, path))?;
}
let r = BufReader::new(f);
if let FileRange::Range {len,..} = range {
Ok(Box::new(r.take(len as u64)))
} else {
Ok(Box::new(r))
}
}
///
/// Execute a command, pipe the contents of a file to stdin, return the output as a `String`
///
pub fn exec_cmdline_pipe_input<S,P>(cmd_path: &str, args: S, input: P, range: FileRange) -> Result<String>
where S: AsRef<str>, P: AsRef<Path>
{
let mut r = ranged_reader(input.as_ref(), range)?;
ensure_command_exists(cmd_path)?;
let args: Vec<&str> = args.as_ref().split_whitespace().collect::<Vec<_>>();
let mut child = Command::new(cmd_path)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(context!("unable to execute {}", cmd_path))?;
let stdin = child.stdin.as_mut().unwrap();
io::copy(&mut r, stdin)
.map_err(context!("error copying input to stdin"))?;
let output = child.wait_with_output()
.map_err(context!("error waiting for command {} to exit", cmd_path))?;
Ok(String::from_utf8(output.stdout).unwrap().trim().to_owned())
}
pub fn xz_compress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-T0 {}", path.display())
.map_err(context!("failed to compress {:?}", path))
}
pub fn xz_decompress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-d {}", path.display())
.map_err(context!("failed to decompress {:?}", path))
}
pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> {
let source = source.as_ref();
let target = target.as_ref();
if let Some(options) = options {
cmd!("/usr/bin/mount", "{} {} {}", options, source, target.display())
} else {
cmd!("/usr/bin/mount", "{} {}", source, target.display())
}.map_err(context!("failed to mount {} to {:?}", source, target))
}
pub fn umount<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/umount", "{}", path.display())
.map_err(context!("failed to unmount {:?}", path))
}
pub fn chown_user<P: AsRef<Path>>(path: P) -> Result<()> {
chown(path.as_ref(), 1000, 1000)
}
pub fn chown(path: &Path, uid: u32, gid: u32) -> Result<()> {
let cstr = CString::new(path.as_os_str().as_bytes())
.expect("path contains null byte");
unsafe {
if libc::chown(cstr.as_ptr(), uid, gid) == -1 {
let err = io::Error::last_os_error();
bail!("failed to chown({},{}) {:?}: {}", uid, gid, path, err);
}
}
Ok(())
}
pub fn chmod(path: &Path, mode: u32) -> Result<()> {
let meta = path.metadata()
.map_err(context!("Failed to read metadata from path {:?}", path))?;
meta.permissions().set_mode(mode);
Ok(())
}
/// Rename or move file at `from` to file path `to`
///
/// A wrapper around `fs::rename()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::rename(from, to)
.map_err(context!("error renaming {:?} to {:?}", from, to))
}
/// Create a symlink at path `dst` which points to `src`
///
/// A wrapper around `fs::symlink()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
unixfs::symlink(src, dst)
.map_err(context!("failed to create symlink {:?} to {:?}", dst, src))
}
/// Read directory `dir` and call closure `f` on each `DirEntry`
pub fn read_directory<F>(dir: impl AsRef<Path>, mut f: F) -> Result<()>
where
F: FnMut(&DirEntry) -> Result<()>
{
let dir = dir.as_ref();
let entries = fs::read_dir(dir)
.map_err(context!("failed to read directory {:?}", dir))?;
for dent in entries {
let dent = dent.map_err(context!("error reading entry from directory {:?}", dir))?;
f(&dent)?;
}
Ok(())
}
/// Remove file at `path` if it exists.
///
/// A wrapper around `fs::remove_file()` which on failure returns an error indicating the path of
/// the file which failed to be removed.
///
pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if path.exists() {
fs::remove_file(path)
.map_err(context!("failed to remove file {:?}", path))?;
}
Ok(())
}
/// Create directory `path` if it does not already exist.
///
/// A wrapper around `fs::create_dir_all()` which on failure returns an error indicating the path
/// of the directory which failed to be created.
///
pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if!path.exists() {
fs::create_dir_all(path)
.map_err(context!("failed to create directory {:?}", path))?;
}
Ok(())
}
/// Write `contents` to file `path`
///
/// A wrapper around `fs::write()` which on failure returns an error indicating the path
/// of the file which failed to be written.
///
pub fn write_file(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
let path = path.as_ref();
fs::write(path, contents)
.map_err(context!("failed to write to file {:?}", path))
}
/// Read content of file `path` into a `String`
///
/// A wrapper around `fs::read_to_string()` which on failure returns an error indicating the path
/// of the file which failed to be read.
///
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
let path = path.as_ref();
fs::read_to_string(path)
.map_err(context!("failed to read file {:?}", path))
}
/// Copy file at path `from` to a new file at path `to`
///
/// A wrapper around `fs::copy()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::copy(from, to)
.map_err(context!("failed to copy file {:?} to {:?}", from, to))?;
Ok(())
}
fn copy_path(from: &Path, to: &Path, chown_to: Option<(u32,u32)>) -> Result<()> |
}
pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> {
_copy_tree(from_base, to_base, None)
}
pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> {
_copy_tree(from_base, to_base, Some(chown_to))
}
fn _copy_tree(from_base: &Path, to_base: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
for entry in WalkDir::new(from_base) {
let entry = entry.map_err(|e| format_err!("Error walking directory tree: {}", e))?;
let path = entry.path();
let suffix = path.strip_prefix(from_base)
.map_err(|_| format_err!("Failed to strip prefix from {:?}", path))?;
let to = to_base.join(suffix);
if &to!= to_base {
copy_path(path, &to, chown_to)
.map_err(context!("failed to copy {:?} to {:?}", path, to))?;
}
}
Ok(())
}
pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> {
for entry in WalkDir::new(base) {
let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?;
if entry.path()!= base || include_base {
chown(entry.path(), chown_to.0, chown_to.1)
.map_err(context!("failed to chown {:?}", entry.path()))?;
}
}
Ok(())
}
pub fn is_euid_root() -> bool {
unsafe {
libc::geteuid() == 0
}
}
| {
if to.exists() {
bail!("destination path {} already exists which is not expected", to.display());
}
let meta = from.metadata()
.map_err(context!("failed to read metadata from source file {:?}", from))?;
if from.is_dir() {
util::create_dir(to)?;
} else {
util::copy_file(&from, &to)?;
}
if let Some((uid,gid)) = chown_to {
chown(to, uid, gid)?;
} else {
chown(to, meta.uid(), meta.gid())?;
}
Ok(()) | identifier_body |
util.rs | use std::path::{Path,PathBuf};
use std::process::{Command,Stdio};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::fs as unixfs;
use std::env;
use std::fs::{self, File, DirEntry};
use std::ffi::CString;
use std::io::{self, Seek, Read, BufReader, SeekFrom};
use walkdir::WalkDir;
use libc;
use crate::{Result, util};
pub fn is_valid_name(name: &str, maxsize: usize) -> bool {
name.len() <= maxsize &&
// Also false on empty string
is_first_char_alphabetic(name) &&
name.chars().all(is_alphanum_or_dash)
}
| is_ascii(c) && (c.is_alphanumeric() || c == '-')
}
fn is_ascii(c: char) -> bool {
c as u32 <= 0x7F
}
pub fn is_first_char_alphabetic(s: &str) -> bool {
if let Some(c) = s.chars().next() {
return is_ascii(c) && c.is_alphabetic()
}
false
}
fn search_path(filename: &str) -> Result<PathBuf> {
let path_var = env::var("PATH").unwrap_or("".into());
for mut path in env::split_paths(&path_var) {
path.push(filename);
if path.exists() {
return Ok(path);
}
}
bail!("could not find {} in $PATH", filename)
}
pub fn ensure_command_exists(cmd: &str) -> Result<()> {
let path = Path::new(cmd);
if!path.is_absolute() {
search_path(cmd)?;
return Ok(())
} else if path.exists() {
return Ok(())
}
bail!("cannot execute '{}': command does not exist", cmd)
}
pub fn sha256<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
let output = cmd_with_output!("/usr/bin/sha256sum", "{}", path.display())
.map_err(context!("failed to calculate sha256 on {:?}", path))?;
let v: Vec<&str> = output.split_whitespace().collect();
Ok(v[0].trim().to_owned())
}
#[derive(Copy,Clone)]
pub enum FileRange {
All,
Offset(usize),
Range{offset: usize, len: usize},
}
fn ranged_reader<P: AsRef<Path>>(path: P, range: FileRange) -> Result<Box<dyn Read>> {
let path = path.as_ref();
let mut f = File::open(path)
.map_err(context!("error opening input file {:?}", path))?;
let offset = match range {
FileRange::All => 0,
FileRange::Offset(n) => n,
FileRange::Range {offset,.. } => offset,
};
if offset > 0 {
f.seek(SeekFrom::Start(offset as u64))
.map_err(context!("error seeking to offset {} in input file {:?}", offset, path))?;
}
let r = BufReader::new(f);
if let FileRange::Range {len,..} = range {
Ok(Box::new(r.take(len as u64)))
} else {
Ok(Box::new(r))
}
}
///
/// Execute a command, pipe the contents of a file to stdin, return the output as a `String`
///
pub fn exec_cmdline_pipe_input<S,P>(cmd_path: &str, args: S, input: P, range: FileRange) -> Result<String>
where S: AsRef<str>, P: AsRef<Path>
{
let mut r = ranged_reader(input.as_ref(), range)?;
ensure_command_exists(cmd_path)?;
let args: Vec<&str> = args.as_ref().split_whitespace().collect::<Vec<_>>();
let mut child = Command::new(cmd_path)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(context!("unable to execute {}", cmd_path))?;
let stdin = child.stdin.as_mut().unwrap();
io::copy(&mut r, stdin)
.map_err(context!("error copying input to stdin"))?;
let output = child.wait_with_output()
.map_err(context!("error waiting for command {} to exit", cmd_path))?;
Ok(String::from_utf8(output.stdout).unwrap().trim().to_owned())
}
pub fn xz_compress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-T0 {}", path.display())
.map_err(context!("failed to compress {:?}", path))
}
pub fn xz_decompress<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/xz", "-d {}", path.display())
.map_err(context!("failed to decompress {:?}", path))
}
pub fn mount<P: AsRef<Path>>(source: impl AsRef<str>, target: P, options: Option<&str>) -> Result<()> {
let source = source.as_ref();
let target = target.as_ref();
if let Some(options) = options {
cmd!("/usr/bin/mount", "{} {} {}", options, source, target.display())
} else {
cmd!("/usr/bin/mount", "{} {}", source, target.display())
}.map_err(context!("failed to mount {} to {:?}", source, target))
}
pub fn umount<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
cmd!("/usr/bin/umount", "{}", path.display())
.map_err(context!("failed to unmount {:?}", path))
}
pub fn chown_user<P: AsRef<Path>>(path: P) -> Result<()> {
chown(path.as_ref(), 1000, 1000)
}
pub fn chown(path: &Path, uid: u32, gid: u32) -> Result<()> {
let cstr = CString::new(path.as_os_str().as_bytes())
.expect("path contains null byte");
unsafe {
if libc::chown(cstr.as_ptr(), uid, gid) == -1 {
let err = io::Error::last_os_error();
bail!("failed to chown({},{}) {:?}: {}", uid, gid, path, err);
}
}
Ok(())
}
pub fn chmod(path: &Path, mode: u32) -> Result<()> {
let meta = path.metadata()
.map_err(context!("Failed to read metadata from path {:?}", path))?;
meta.permissions().set_mode(mode);
Ok(())
}
/// Rename or move file at `from` to file path `to`
///
/// A wrapper around `fs::rename()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn rename(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::rename(from, to)
.map_err(context!("error renaming {:?} to {:?}", from, to))
}
/// Create a symlink at path `dst` which points to `src`
///
/// A wrapper around `fs::symlink()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
unixfs::symlink(src, dst)
.map_err(context!("failed to create symlink {:?} to {:?}", dst, src))
}
/// Read directory `dir` and call closure `f` on each `DirEntry`
pub fn read_directory<F>(dir: impl AsRef<Path>, mut f: F) -> Result<()>
where
F: FnMut(&DirEntry) -> Result<()>
{
let dir = dir.as_ref();
let entries = fs::read_dir(dir)
.map_err(context!("failed to read directory {:?}", dir))?;
for dent in entries {
let dent = dent.map_err(context!("error reading entry from directory {:?}", dir))?;
f(&dent)?;
}
Ok(())
}
/// Remove file at `path` if it exists.
///
/// A wrapper around `fs::remove_file()` which on failure returns an error indicating the path of
/// the file which failed to be removed.
///
pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if path.exists() {
fs::remove_file(path)
.map_err(context!("failed to remove file {:?}", path))?;
}
Ok(())
}
/// Create directory `path` if it does not already exist.
///
/// A wrapper around `fs::create_dir_all()` which on failure returns an error indicating the path
/// of the directory which failed to be created.
///
pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
if!path.exists() {
fs::create_dir_all(path)
.map_err(context!("failed to create directory {:?}", path))?;
}
Ok(())
}
/// Write `contents` to file `path`
///
/// A wrapper around `fs::write()` which on failure returns an error indicating the path
/// of the file which failed to be written.
///
pub fn write_file(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
let path = path.as_ref();
fs::write(path, contents)
.map_err(context!("failed to write to file {:?}", path))
}
/// Read content of file `path` into a `String`
///
/// A wrapper around `fs::read_to_string()` which on failure returns an error indicating the path
/// of the file which failed to be read.
///
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
let path = path.as_ref();
fs::read_to_string(path)
.map_err(context!("failed to read file {:?}", path))
}
/// Copy file at path `from` to a new file at path `to`
///
/// A wrapper around `fs::copy()` which on failure returns an error indicating the source and
/// destination paths.
///
pub fn copy_file(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
fs::copy(from, to)
.map_err(context!("failed to copy file {:?} to {:?}", from, to))?;
Ok(())
}
fn copy_path(from: &Path, to: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
if to.exists() {
bail!("destination path {} already exists which is not expected", to.display());
}
let meta = from.metadata()
.map_err(context!("failed to read metadata from source file {:?}", from))?;
if from.is_dir() {
util::create_dir(to)?;
} else {
util::copy_file(&from, &to)?;
}
if let Some((uid,gid)) = chown_to {
chown(to, uid, gid)?;
} else {
chown(to, meta.uid(), meta.gid())?;
}
Ok(())
}
pub fn copy_tree(from_base: &Path, to_base: &Path) -> Result<()> {
_copy_tree(from_base, to_base, None)
}
pub fn copy_tree_with_chown(from_base: &Path, to_base: &Path, chown_to: (u32,u32)) -> Result<()> {
_copy_tree(from_base, to_base, Some(chown_to))
}
fn _copy_tree(from_base: &Path, to_base: &Path, chown_to: Option<(u32,u32)>) -> Result<()> {
for entry in WalkDir::new(from_base) {
let entry = entry.map_err(|e| format_err!("Error walking directory tree: {}", e))?;
let path = entry.path();
let suffix = path.strip_prefix(from_base)
.map_err(|_| format_err!("Failed to strip prefix from {:?}", path))?;
let to = to_base.join(suffix);
if &to!= to_base {
copy_path(path, &to, chown_to)
.map_err(context!("failed to copy {:?} to {:?}", path, to))?;
}
}
Ok(())
}
pub fn chown_tree(base: &Path, chown_to: (u32,u32), include_base: bool) -> Result<()> {
for entry in WalkDir::new(base) {
let entry = entry.map_err(|e| format_err!("Error reading directory entry: {}", e))?;
if entry.path()!= base || include_base {
chown(entry.path(), chown_to.0, chown_to.1)
.map_err(context!("failed to chown {:?}", entry.path()))?;
}
}
Ok(())
}
pub fn is_euid_root() -> bool {
unsafe {
libc::geteuid() == 0
}
} | fn is_alphanum_or_dash(c: char) -> bool { | random_line_split |
lib.rs | //! A proportional-integral-derivative (PID) controller library.
//!
//! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller!
//!
//! # Example
//!
//! ```rust
//! use pid::Pid;
//!
//! // Create a new proportional-only PID controller with a setpoint of 15
//! let mut pid = Pid::new(15.0, 100.0);
//! pid.p(10.0, 100.0);
//!
//! // Input a measurement with an error of 5.0 from our setpoint
//! let output = pid.next_control_output(10.0);
//!
//! // Show that the error is correct by multiplying by our kp
//! assert_eq!(output.output, 50.0); // <--
//! assert_eq!(output.p, 50.0);
//!
//! // It won't change on repeat; the controller is proportional-only
//! let output = pid.next_control_output(10.0);
//! assert_eq!(output.output, 50.0); // <--
//! assert_eq!(output.p, 50.0);
//!
//! // Add a new integral term to the controller and input again
//! pid.i(1.0, 100.0);
//! let output = pid.next_control_output(10.0);
//!
//! // Now that the integral makes the controller stateful, it will change
//! assert_eq!(output.output, 55.0); // <--
//! assert_eq!(output.p, 50.0);
//! assert_eq!(output.i, 5.0);
//!
//! // Add our final derivative term and match our setpoint target
//! pid.d(2.0, 100.0);
//! let output = pid.next_control_output(15.0);
//!
//! // The output will now say to go down due to the derivative
//! assert_eq!(output.output, -5.0); // <--
//! assert_eq!(output.p, 0.0);
//! assert_eq!(output.i, 5.0);
//! assert_eq!(output.d, -10.0);
//! ```
#![no_std]
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// A trait for any numeric type usable in the PID controller
///
/// This trait is automatically implemented for all types that satisfy `PartialOrd + num_traits::Signed + Copy`. This includes all of the signed float types and builtin integer except for [isize]:
/// - [i8]
/// - [i16]
/// - [i32]
/// - [i64]
/// - [i128]
/// - [f32]
/// - [f64]
///
/// As well as any user type that matches the requirements
pub trait Number: PartialOrd + num_traits::Signed + Copy {}
// Implement `Number` for all types that
// satisfy `PartialOrd + num_traits::Signed + Copy`.
impl<T: PartialOrd + num_traits::Signed + Copy> Number for T {}
/// Adjustable proportional-integral-derivative (PID) controller.
///
/// # Examples
///
/// This controller provides a builder pattern interface which allows you to pick-and-choose which PID inputs you'd like to use during operation. Here's what a basic proportional-only controller could look like:
///
/// ```rust
/// use pid::Pid;
///
/// // Create limited controller
/// let mut p_controller = Pid::new(15.0, 100.0);
/// p_controller.p(10.0, 100.0);
///
/// // Get first output
/// let p_output = p_controller.next_control_output(400.0);
/// ```
///
/// This controller would give you set a proportional controller to `10.0` with a target of `15.0` and an output limit of `100.0` per [output](Self::next_control_output) iteration. The same controller with a full PID system built in looks like:
///
/// ```rust
/// use pid::Pid;
///
/// // Create full PID controller
/// let mut full_controller = Pid::new(15.0, 100.0);
/// full_controller.p(10.0, 100.0).i(4.5, 100.0).d(0.25, 100.0);
///
/// // Get first output
/// let full_output = full_controller.next_control_output(400.0);
/// ```
///
/// This [`next_control_output`](Self::next_control_output) method is what's used to input new values into the controller to tell it what the current state of the system is. In the examples above it's only being used once, but realistically this will be a hot method. Please see [ControlOutput] for examples of how to handle these outputs; it's quite straight forward and mirrors the values of this structure in some ways.
///
/// The last item of note is that these [`p`](Self::p()), [`i`](Self::i()), and [`d`](Self::d()) methods can be used *during* operation which lets you add and/or modify these controller values if need be.
///
/// # Type Warning
///
/// [Number] is abstract and can be used with anything from a [i32] to an [i128] (as well as user-defined types). Because of this, very small types might overflow during calculation in [`next_control_output`](Self::next_control_output). You probably don't want to use [i8] or user-defined types around that size so keep that in mind when designing your controller.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Pid<T: Number> {
/// Ideal setpoint to strive for.
pub setpoint: T,
/// Defines the overall output filter limit.
pub output_limit: T,
/// Proportional gain.
pub kp: T,
/// Integral gain.
pub ki: T,
/// Derivative gain.
pub kd: T,
/// Limiter for the proportional term: `-p_limit <= P <= p_limit`.
pub p_limit: T,
/// Limiter for the integral term: `-i_limit <= I <= i_limit`.
pub i_limit: T,
/// Limiter for the derivative term: `-d_limit <= D <= d_limit`.
pub d_limit: T,
/// Last calculated integral value if [Pid::ki] is used.
integral_term: T,
/// Previously found measurement whilst using the [Pid::next_control_output] method.
prev_measurement: Option<T>,
}
/// Output of [controller iterations](Pid::next_control_output) with weights
///
/// # Example
///
/// This structure is simple to use and features three weights: [p](Self::p), [i](Self::i), and [d](Self::d). These can be used to figure out how much each term from [Pid] contributed to the final [output](Self::output) value which should be taken as the final controller output for this iteration:
///
/// ```rust
/// use pid::{Pid, ControlOutput};
///
/// // Setup controller
/// let mut pid = Pid::new(15.0, 100.0);
/// pid.p(10.0, 100.0).i(1.0, 100.0).d(2.0, 100.0);
///
/// // Input an example value and get a report for an output iteration
/// let output = pid.next_control_output(26.2456);
/// println!("P: {}\nI: {}\nD: {}\nFinal Output: {}", output.p, output.i, output.d, output.output);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct ControlOutput<T: Number> {
/// Contribution of the P term to the output.
pub p: T,
/// Contribution of the I term to the output.
///
/// This integral term is equal to `sum[error(t) * ki(t)] (for all t)`
pub i: T,
/// Contribution of the D term to the output.
pub d: T,
/// Output of the PID controller.
pub output: T,
}
impl<T> Pid<T>
where
T: Number,
{
/// Creates a new controller with the target setpoint and the output limit
///
/// To set your P, I, and D terms into this controller, please use the following builder methods:
/// - [Self::p()]: Proportional term setting
/// - [Self::i()]: Integral term setting
/// - [Self::d()]: Derivative term setting
pub fn new(setpoint: impl Into<T>, output_limit: impl Into<T>) -> Self {
Self {
setpoint: setpoint.into(),
output_limit: output_limit.into(),
kp: T::zero(),
ki: T::zero(),
kd: T::zero(),
p_limit: T::zero(),
i_limit: T::zero(),
d_limit: T::zero(),
integral_term: T::zero(),
prev_measurement: None,
}
}
/// Sets the [Self::p] term for this controller.
pub fn p(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.kp = gain.into();
self.p_limit = limit.into();
self
}
/// Sets the [Self::i] term for this controller.
pub fn i(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.ki = gain.into();
self.i_limit = limit.into();
self
}
/// Sets the [Self::d] term for this controller.
pub fn d(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.kd = gain.into();
self.d_limit = limit.into();
self
}
/// Sets the [Pid::setpoint] to target for this controller.
pub fn setpoint(&mut self, setpoint: impl Into<T>) -> &mut Self {
self.setpoint = setpoint.into();
self
}
/// Given a new measurement, calculates the next [control output](ControlOutput).
///
/// # Panics
///
/// - If a setpoint has not been set via `update_setpoint()`.
pub fn next_control_output(&mut self, measurement: T) -> ControlOutput<T> {
// Calculate the error between the ideal setpoint and the current
// measurement to compare against
let error = self.setpoint - measurement;
// Calculate the proportional term and limit to it's individual limit
let p_unbounded = error * self.kp;
let p = apply_limit(self.p_limit, p_unbounded);
// Mitigate output jumps when ki(t)!= ki(t-1).
// While it's standard to use an error_integral that's a running sum of
// just the error (no ki), because we support ki changing dynamically,
// we store the entire term so that we don't need to remember previous
// ki values.
self.integral_term = self.integral_term + error * self.ki;
// Mitigate integral windup: Don't want to keep building up error
// beyond what i_limit will allow.
self.integral_term = apply_limit(self.i_limit, self.integral_term);
// Mitigate derivative kick: Use the derivative of the measurement
// rather than the derivative of the error.
let d_unbounded = -match self.prev_measurement.as_ref() {
Some(prev_measurement) => measurement - *prev_measurement,
None => T::zero(),
} * self.kd;
self.prev_measurement = Some(measurement);
let d = apply_limit(self.d_limit, d_unbounded);
// Calculate the final output by adding together the PID terms, then
// apply the final defined output limit
let output = p + self.integral_term + d;
let output = apply_limit(self.output_limit, output);
// Return the individual term's contributions and the final output
ControlOutput {
p,
i: self.integral_term,
d,
output: output,
}
}
/// Resets the integral term back to zero, this may drastically change the
/// control output.
pub fn reset_integral_term(&mut self) {
self.integral_term = T::zero();
}
}
/// Saturating the input `value` according the absolute `limit` (`-abs(limit) <= output <= abs(limit)`).
fn apply_limit<T: Number>(limit: T, value: T) -> T {
num_traits::clamp(value, -limit.abs(), limit.abs())
}
#[cfg(test)]
mod tests {
use super::Pid;
use crate::ControlOutput;
/// Proportional-only controller operation and limits
#[test]
fn proportional() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(2.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
assert_eq!(pid.setpoint, 10.0);
// Test simple proportional
assert_eq!(pid.next_control_output(0.0).output, 20.0);
// Test proportional limit
pid.p_limit = 10.0;
assert_eq!(pid.next_control_output(0.0).output, 10.0);
}
/// Derivative-only controller operation and limits
#[test]
fn derivative() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(0.0, 100.0).i(0.0, 100.0).d(2.0, 100.0);
// Test that there's no derivative since it's the first measurement
assert_eq!(pid.next_control_output(0.0).output, 0.0);
// Test that there's now a derivative
assert_eq!(pid.next_control_output(5.0).output, -10.0);
// Test derivative limit
pid.d_limit = 5.0;
assert_eq!(pid.next_control_output(10.0).output, -5.0);
}
/// Integral-only controller operation and limits
#[test]
fn integral() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(0.0, 100.0).i(2.0, 100.0).d(0.0, 100.0);
// Test basic integration
assert_eq!(pid.next_control_output(0.0).output, 20.0);
assert_eq!(pid.next_control_output(0.0).output, 40.0);
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test limit
pid.i_limit = 50.0;
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid.next_control_output(15.0).output, 40.0);
// Test that error integral accumulates negative values
let mut pid2 = Pid::new(-10.0, 100.0);
pid2.p(0.0, 100.0).i(2.0, 100.0).d(0.0, 100.0);
assert_eq!(pid2.next_control_output(0.0).output, -20.0);
assert_eq!(pid2.next_control_output(0.0).output, -40.0);
pid2.i_limit = 50.0;
assert_eq!(pid2.next_control_output(-5.0).output, -50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid2.next_control_output(-15.0).output, -40.0);
}
/// Checks that a full PID controller's limits work properly through multiple output iterations
#[test]
fn output_limit() {
let mut pid = Pid::new(10.0, 1.0);
pid.p(1.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.output, 1.0);
let out = pid.next_control_output(20.0);
assert_eq!(out.p, -10.0); // 1.0 * (10.0 - 20.0)
assert_eq!(out.output, -1.0);
}
/// Combined PID operation
#[test]
fn pid() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(1.0, 100.0).i(0.1, 100.0).d(1.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.i, 1.0); // 0.1 * 10.0
assert_eq!(out.d, 0.0); // -(1.0 * 0.0)
assert_eq!(out.output, 11.0);
let out = pid.next_control_output(5.0);
assert_eq!(out.p, 5.0); // 1.0 * 5.0
assert_eq!(out.i, 1.5); // 0.1 * (10.0 + 5.0)
assert_eq!(out.d, -5.0); // -(1.0 * 5.0)
assert_eq!(out.output, 1.5);
let out = pid.next_control_output(11.0);
assert_eq!(out.p, -1.0); // 1.0 * -1.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1)
assert_eq!(out.d, -6.0); // -(1.0 * 6.0)
assert_eq!(out.output, -5.6);
let out = pid.next_control_output(10.0);
assert_eq!(out.p, 0.0); // 1.0 * 0.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1.0 + 0.0)
assert_eq!(out.d, 1.0); // -(1.0 * -1.0)
assert_eq!(out.output, 2.4);
}
// NOTE: use for new test in future: /// Full PID operation with mixed float checking to make sure they're equal
/// PID operation with zero'd values, checking to see if different floats equal each other
#[test]
fn floats_zeros() {
let mut pid_f32 = Pid::new(10.0f32, 100.0);
pid_f32.p(0.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
let mut pid_f64 = Pid::new(10.0, 100.0f64);
pid_f64.p(0.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
for _ in 0..5 {
assert_eq!(
pid_f32.next_control_output(0.0).output,
pid_f64.next_control_output(0.0).output as f32
);
}
}
// NOTE: use for new test in future: /// Full PID operation with mixed signed integer checking to make sure they're equal
/// PID operation with zero'd values, checking to see if different floats equal each other
#[test] | let mut pid_i32 = Pid::new(10i32, 100);
pid_i32.p(0, 100).i(0, 100).d(0, 100);
for _ in 0..5 {
assert_eq!(
pid_i32.next_control_output(0).output,
pid_i8.next_control_output(0i8).output as i32
);
}
}
/// See if the controller can properly target to the setpoint after 2 output iterations
#[test]
fn setpoint() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(1.0, 100.0).i(0.1, 100.0).d(1.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.i, 1.0); // 0.1 * 10.0
assert_eq!(out.d, 0.0); // -(1.0 * 0.0)
assert_eq!(out.output, 11.0);
pid.setpoint(0.0);
assert_eq!(
pid.next_control_output(0.0),
ControlOutput {
p: 0.0,
i: 1.0,
d: -0.0,
output: 1.0
}
);
}
/// Make sure negative limits don't break the controller
#[test]
fn negative_limits() {
let mut pid = Pid::new(10.0f32, -10.0);
pid.p(1.0, -50.0).i(1.0, -50.0).d(1.0, -50.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0);
assert_eq!(out.i, 10.0);
assert_eq!(out.d, 0.0);
assert_eq!(out.output, 10.0);
}
} | fn signed_integers_zeros() {
let mut pid_i8 = Pid::new(10i8, 100);
pid_i8.p(0, 100).i(0, 100).d(0, 100);
| random_line_split |
lib.rs | //! A proportional-integral-derivative (PID) controller library.
//!
//! See [Pid] for the adjustable controller itself, as well as [ControlOutput] for the outputs and weights which you can use after setting up your controller. Follow the complete example below to setup your first controller!
//!
//! # Example
//!
//! ```rust
//! use pid::Pid;
//!
//! // Create a new proportional-only PID controller with a setpoint of 15
//! let mut pid = Pid::new(15.0, 100.0);
//! pid.p(10.0, 100.0);
//!
//! // Input a measurement with an error of 5.0 from our setpoint
//! let output = pid.next_control_output(10.0);
//!
//! // Show that the error is correct by multiplying by our kp
//! assert_eq!(output.output, 50.0); // <--
//! assert_eq!(output.p, 50.0);
//!
//! // It won't change on repeat; the controller is proportional-only
//! let output = pid.next_control_output(10.0);
//! assert_eq!(output.output, 50.0); // <--
//! assert_eq!(output.p, 50.0);
//!
//! // Add a new integral term to the controller and input again
//! pid.i(1.0, 100.0);
//! let output = pid.next_control_output(10.0);
//!
//! // Now that the integral makes the controller stateful, it will change
//! assert_eq!(output.output, 55.0); // <--
//! assert_eq!(output.p, 50.0);
//! assert_eq!(output.i, 5.0);
//!
//! // Add our final derivative term and match our setpoint target
//! pid.d(2.0, 100.0);
//! let output = pid.next_control_output(15.0);
//!
//! // The output will now say to go down due to the derivative
//! assert_eq!(output.output, -5.0); // <--
//! assert_eq!(output.p, 0.0);
//! assert_eq!(output.i, 5.0);
//! assert_eq!(output.d, -10.0);
//! ```
#![no_std]
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// A trait for any numeric type usable in the PID controller
///
/// This trait is automatically implemented for all types that satisfy `PartialOrd + num_traits::Signed + Copy`. This includes all of the signed float types and builtin integer except for [isize]:
/// - [i8]
/// - [i16]
/// - [i32]
/// - [i64]
/// - [i128]
/// - [f32]
/// - [f64]
///
/// As well as any user type that matches the requirements
pub trait Number: PartialOrd + num_traits::Signed + Copy {}
// Implement `Number` for all types that
// satisfy `PartialOrd + num_traits::Signed + Copy`.
impl<T: PartialOrd + num_traits::Signed + Copy> Number for T {}
/// Adjustable proportional-integral-derivative (PID) controller.
///
/// # Examples
///
/// This controller provides a builder pattern interface which allows you to pick-and-choose which PID inputs you'd like to use during operation. Here's what a basic proportional-only controller could look like:
///
/// ```rust
/// use pid::Pid;
///
/// // Create limited controller
/// let mut p_controller = Pid::new(15.0, 100.0);
/// p_controller.p(10.0, 100.0);
///
/// // Get first output
/// let p_output = p_controller.next_control_output(400.0);
/// ```
///
/// This controller would give you set a proportional controller to `10.0` with a target of `15.0` and an output limit of `100.0` per [output](Self::next_control_output) iteration. The same controller with a full PID system built in looks like:
///
/// ```rust
/// use pid::Pid;
///
/// // Create full PID controller
/// let mut full_controller = Pid::new(15.0, 100.0);
/// full_controller.p(10.0, 100.0).i(4.5, 100.0).d(0.25, 100.0);
///
/// // Get first output
/// let full_output = full_controller.next_control_output(400.0);
/// ```
///
/// This [`next_control_output`](Self::next_control_output) method is what's used to input new values into the controller to tell it what the current state of the system is. In the examples above it's only being used once, but realistically this will be a hot method. Please see [ControlOutput] for examples of how to handle these outputs; it's quite straight forward and mirrors the values of this structure in some ways.
///
/// The last item of note is that these [`p`](Self::p()), [`i`](Self::i()), and [`d`](Self::d()) methods can be used *during* operation which lets you add and/or modify these controller values if need be.
///
/// # Type Warning
///
/// [Number] is abstract and can be used with anything from a [i32] to an [i128] (as well as user-defined types). Because of this, very small types might overflow during calculation in [`next_control_output`](Self::next_control_output). You probably don't want to use [i8] or user-defined types around that size so keep that in mind when designing your controller.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Pid<T: Number> {
/// Ideal setpoint to strive for.
pub setpoint: T,
/// Defines the overall output filter limit.
pub output_limit: T,
/// Proportional gain.
pub kp: T,
/// Integral gain.
pub ki: T,
/// Derivative gain.
pub kd: T,
/// Limiter for the proportional term: `-p_limit <= P <= p_limit`.
pub p_limit: T,
/// Limiter for the integral term: `-i_limit <= I <= i_limit`.
pub i_limit: T,
/// Limiter for the derivative term: `-d_limit <= D <= d_limit`.
pub d_limit: T,
/// Last calculated integral value if [Pid::ki] is used.
integral_term: T,
/// Previously found measurement whilst using the [Pid::next_control_output] method.
prev_measurement: Option<T>,
}
/// Output of [controller iterations](Pid::next_control_output) with weights
///
/// # Example
///
/// This structure is simple to use and features three weights: [p](Self::p), [i](Self::i), and [d](Self::d). These can be used to figure out how much each term from [Pid] contributed to the final [output](Self::output) value which should be taken as the final controller output for this iteration:
///
/// ```rust
/// use pid::{Pid, ControlOutput};
///
/// // Setup controller
/// let mut pid = Pid::new(15.0, 100.0);
/// pid.p(10.0, 100.0).i(1.0, 100.0).d(2.0, 100.0);
///
/// // Input an example value and get a report for an output iteration
/// let output = pid.next_control_output(26.2456);
/// println!("P: {}\nI: {}\nD: {}\nFinal Output: {}", output.p, output.i, output.d, output.output);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct ControlOutput<T: Number> {
/// Contribution of the P term to the output.
pub p: T,
/// Contribution of the I term to the output.
///
/// This integral term is equal to `sum[error(t) * ki(t)] (for all t)`
pub i: T,
/// Contribution of the D term to the output.
pub d: T,
/// Output of the PID controller.
pub output: T,
}
impl<T> Pid<T>
where
T: Number,
{
/// Creates a new controller with the target setpoint and the output limit
///
/// To set your P, I, and D terms into this controller, please use the following builder methods:
/// - [Self::p()]: Proportional term setting
/// - [Self::i()]: Integral term setting
/// - [Self::d()]: Derivative term setting
pub fn new(setpoint: impl Into<T>, output_limit: impl Into<T>) -> Self {
Self {
setpoint: setpoint.into(),
output_limit: output_limit.into(),
kp: T::zero(),
ki: T::zero(),
kd: T::zero(),
p_limit: T::zero(),
i_limit: T::zero(),
d_limit: T::zero(),
integral_term: T::zero(),
prev_measurement: None,
}
}
/// Sets the [Self::p] term for this controller.
pub fn p(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.kp = gain.into();
self.p_limit = limit.into();
self
}
/// Sets the [Self::i] term for this controller.
pub fn i(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.ki = gain.into();
self.i_limit = limit.into();
self
}
/// Sets the [Self::d] term for this controller.
pub fn d(&mut self, gain: impl Into<T>, limit: impl Into<T>) -> &mut Self {
self.kd = gain.into();
self.d_limit = limit.into();
self
}
/// Sets the [Pid::setpoint] to target for this controller.
pub fn | (&mut self, setpoint: impl Into<T>) -> &mut Self {
self.setpoint = setpoint.into();
self
}
/// Given a new measurement, calculates the next [control output](ControlOutput).
///
/// # Panics
///
/// - If a setpoint has not been set via `update_setpoint()`.
pub fn next_control_output(&mut self, measurement: T) -> ControlOutput<T> {
// Calculate the error between the ideal setpoint and the current
// measurement to compare against
let error = self.setpoint - measurement;
// Calculate the proportional term and limit to it's individual limit
let p_unbounded = error * self.kp;
let p = apply_limit(self.p_limit, p_unbounded);
// Mitigate output jumps when ki(t)!= ki(t-1).
// While it's standard to use an error_integral that's a running sum of
// just the error (no ki), because we support ki changing dynamically,
// we store the entire term so that we don't need to remember previous
// ki values.
self.integral_term = self.integral_term + error * self.ki;
// Mitigate integral windup: Don't want to keep building up error
// beyond what i_limit will allow.
self.integral_term = apply_limit(self.i_limit, self.integral_term);
// Mitigate derivative kick: Use the derivative of the measurement
// rather than the derivative of the error.
let d_unbounded = -match self.prev_measurement.as_ref() {
Some(prev_measurement) => measurement - *prev_measurement,
None => T::zero(),
} * self.kd;
self.prev_measurement = Some(measurement);
let d = apply_limit(self.d_limit, d_unbounded);
// Calculate the final output by adding together the PID terms, then
// apply the final defined output limit
let output = p + self.integral_term + d;
let output = apply_limit(self.output_limit, output);
// Return the individual term's contributions and the final output
ControlOutput {
p,
i: self.integral_term,
d,
output: output,
}
}
/// Resets the integral term back to zero, this may drastically change the
/// control output.
pub fn reset_integral_term(&mut self) {
self.integral_term = T::zero();
}
}
/// Saturating the input `value` according the absolute `limit` (`-abs(limit) <= output <= abs(limit)`).
fn apply_limit<T: Number>(limit: T, value: T) -> T {
num_traits::clamp(value, -limit.abs(), limit.abs())
}
#[cfg(test)]
mod tests {
use super::Pid;
use crate::ControlOutput;
/// Proportional-only controller operation and limits
#[test]
fn proportional() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(2.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
assert_eq!(pid.setpoint, 10.0);
// Test simple proportional
assert_eq!(pid.next_control_output(0.0).output, 20.0);
// Test proportional limit
pid.p_limit = 10.0;
assert_eq!(pid.next_control_output(0.0).output, 10.0);
}
/// Derivative-only controller operation and limits
#[test]
fn derivative() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(0.0, 100.0).i(0.0, 100.0).d(2.0, 100.0);
// Test that there's no derivative since it's the first measurement
assert_eq!(pid.next_control_output(0.0).output, 0.0);
// Test that there's now a derivative
assert_eq!(pid.next_control_output(5.0).output, -10.0);
// Test derivative limit
pid.d_limit = 5.0;
assert_eq!(pid.next_control_output(10.0).output, -5.0);
}
/// Integral-only controller operation and limits
#[test]
fn integral() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(0.0, 100.0).i(2.0, 100.0).d(0.0, 100.0);
// Test basic integration
assert_eq!(pid.next_control_output(0.0).output, 20.0);
assert_eq!(pid.next_control_output(0.0).output, 40.0);
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test limit
pid.i_limit = 50.0;
assert_eq!(pid.next_control_output(5.0).output, 50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid.next_control_output(15.0).output, 40.0);
// Test that error integral accumulates negative values
let mut pid2 = Pid::new(-10.0, 100.0);
pid2.p(0.0, 100.0).i(2.0, 100.0).d(0.0, 100.0);
assert_eq!(pid2.next_control_output(0.0).output, -20.0);
assert_eq!(pid2.next_control_output(0.0).output, -40.0);
pid2.i_limit = 50.0;
assert_eq!(pid2.next_control_output(-5.0).output, -50.0);
// Test that limit doesn't impede reversal of error integral
assert_eq!(pid2.next_control_output(-15.0).output, -40.0);
}
/// Checks that a full PID controller's limits work properly through multiple output iterations
#[test]
fn output_limit() {
let mut pid = Pid::new(10.0, 1.0);
pid.p(1.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.output, 1.0);
let out = pid.next_control_output(20.0);
assert_eq!(out.p, -10.0); // 1.0 * (10.0 - 20.0)
assert_eq!(out.output, -1.0);
}
/// Combined PID operation
#[test]
fn pid() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(1.0, 100.0).i(0.1, 100.0).d(1.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.i, 1.0); // 0.1 * 10.0
assert_eq!(out.d, 0.0); // -(1.0 * 0.0)
assert_eq!(out.output, 11.0);
let out = pid.next_control_output(5.0);
assert_eq!(out.p, 5.0); // 1.0 * 5.0
assert_eq!(out.i, 1.5); // 0.1 * (10.0 + 5.0)
assert_eq!(out.d, -5.0); // -(1.0 * 5.0)
assert_eq!(out.output, 1.5);
let out = pid.next_control_output(11.0);
assert_eq!(out.p, -1.0); // 1.0 * -1.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1)
assert_eq!(out.d, -6.0); // -(1.0 * 6.0)
assert_eq!(out.output, -5.6);
let out = pid.next_control_output(10.0);
assert_eq!(out.p, 0.0); // 1.0 * 0.0
assert_eq!(out.i, 1.4); // 0.1 * (10.0 + 5.0 - 1.0 + 0.0)
assert_eq!(out.d, 1.0); // -(1.0 * -1.0)
assert_eq!(out.output, 2.4);
}
// NOTE: use for new test in future: /// Full PID operation with mixed float checking to make sure they're equal
/// PID operation with zero'd values, checking to see if different floats equal each other
#[test]
fn floats_zeros() {
let mut pid_f32 = Pid::new(10.0f32, 100.0);
pid_f32.p(0.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
let mut pid_f64 = Pid::new(10.0, 100.0f64);
pid_f64.p(0.0, 100.0).i(0.0, 100.0).d(0.0, 100.0);
for _ in 0..5 {
assert_eq!(
pid_f32.next_control_output(0.0).output,
pid_f64.next_control_output(0.0).output as f32
);
}
}
// NOTE: use for new test in future: /// Full PID operation with mixed signed integer checking to make sure they're equal
/// PID operation with zero'd values, checking to see if different floats equal each other
#[test]
fn signed_integers_zeros() {
let mut pid_i8 = Pid::new(10i8, 100);
pid_i8.p(0, 100).i(0, 100).d(0, 100);
let mut pid_i32 = Pid::new(10i32, 100);
pid_i32.p(0, 100).i(0, 100).d(0, 100);
for _ in 0..5 {
assert_eq!(
pid_i32.next_control_output(0).output,
pid_i8.next_control_output(0i8).output as i32
);
}
}
/// See if the controller can properly target to the setpoint after 2 output iterations
#[test]
fn setpoint() {
let mut pid = Pid::new(10.0, 100.0);
pid.p(1.0, 100.0).i(0.1, 100.0).d(1.0, 100.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0); // 1.0 * 10.0
assert_eq!(out.i, 1.0); // 0.1 * 10.0
assert_eq!(out.d, 0.0); // -(1.0 * 0.0)
assert_eq!(out.output, 11.0);
pid.setpoint(0.0);
assert_eq!(
pid.next_control_output(0.0),
ControlOutput {
p: 0.0,
i: 1.0,
d: -0.0,
output: 1.0
}
);
}
/// Make sure negative limits don't break the controller
#[test]
fn negative_limits() {
let mut pid = Pid::new(10.0f32, -10.0);
pid.p(1.0, -50.0).i(1.0, -50.0).d(1.0, -50.0);
let out = pid.next_control_output(0.0);
assert_eq!(out.p, 10.0);
assert_eq!(out.i, 10.0);
assert_eq!(out.d, 0.0);
assert_eq!(out.output, 10.0);
}
}
| setpoint | identifier_name |
mod.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains the actions that will drive a raft state machine.
//!
//! # Raft Ready
//!
//! Every messages or ticks may have side affect. Handling all those side
//! affect immediately is not efficient. Instead, tikv uses `Ready` to batch up
//! all the side affects and handle them at once for throughput.
//!
//! As raft store is the critical path in the whole system, we avoid most
//! blocking IO. So a typical processing is divided into two steps:
//!
//! - Handle raft ready to process the side affect and send IO tasks to
//! background threads
//! - Receive IO tasks completion and update the raft state machine
//!
//! There two steps can be processed concurrently.
mod async_writer;
use engine_traits::{KvEngine, RaftEngine};
use error_code::ErrorCodeExt;
use kvproto::raft_serverpb::RaftMessage;
use protobuf::Message as _;
use raft::{eraftpb, Ready};
use raftstore::store::{FetchedLogs, Transport, WriteTask};
use slog::{debug, error, trace, warn};
pub use self::async_writer::AsyncWriter;
use crate::{
batch::StoreContext,
fsm::{PeerFsm, PeerFsmDelegate},
raft::{Peer, Storage},
router::PeerTick,
};
impl<'a, EK: KvEngine, ER: RaftEngine, T: Transport> PeerFsmDelegate<'a, EK, ER, T> {
/// Raft relies on periodic ticks to keep the state machine sync with other
/// peers.
pub fn on_raft_tick(&mut self) {
if self.fsm.peer_mut().tick() {
self.fsm.peer_mut().set_has_ready();
}
self.schedule_tick(PeerTick::Raft);
}
}
impl<EK: KvEngine, ER: RaftEngine> Peer<EK, ER> {
#[inline]
fn tick(&mut self) -> bool |
/// Callback for fetching logs asynchronously.
pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) {
let FetchedLogs { context, logs } = fetched_logs;
let low = logs.low;
if!self.is_leader() {
self.entry_storage_mut().clean_async_fetch_res(low);
return;
}
if self.term()!= logs.term {
self.entry_storage_mut().clean_async_fetch_res(low);
} else {
self.entry_storage_mut()
.update_async_fetch_res(low, Some(logs));
}
self.raft_group_mut().on_entries_fetched(context);
// clean the async fetch result immediately if not used to free memory
self.entry_storage_mut().update_async_fetch_res(low, None);
self.set_has_ready();
}
/// Partially filled a raft message that will be sent to other peer.
fn prepare_raft_message(&mut self) -> RaftMessage {
let mut raft_msg = RaftMessage::new();
raft_msg.set_region_id(self.region().id);
raft_msg.set_from_peer(self.peer().clone());
// set current epoch
let epoch = self.storage().region().get_region_epoch();
let msg_epoch = raft_msg.mut_region_epoch();
msg_epoch.set_version(epoch.get_version());
msg_epoch.set_conf_ver(epoch.get_conf_ver());
raft_msg
}
/// Transform a message from raft lib to a message that can be sent to other
/// peers.
///
/// If the recipient can't be found, `None` is returned.
#[inline]
fn build_raft_message<T>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: eraftpb::Message,
) -> Option<RaftMessage> {
let to_peer = match self.peer_from_cache(msg.to) {
Some(p) => p,
None => {
warn!(self.logger, "failed to look up recipient peer"; "to_peer" => msg.to);
return None;
}
};
let mut raft_msg = self.prepare_raft_message();
raft_msg.set_to_peer(to_peer);
if msg.from!= self.peer().id {
debug!(
self.logger,
"redirecting message";
"msg_type" =>?msg.get_msg_type(),
"from" => msg.get_from(),
"to" => msg.get_to(),
);
}
raft_msg.set_message(msg);
Some(raft_msg)
}
/// Send a message.
///
/// The message is pushed into the send buffer, it may not be sent out until
/// transport is flushed explicitly.
fn send_raft_message<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: RaftMessage,
) {
let msg_type = msg.get_message().get_msg_type();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
trace!(
self.logger,
"send raft msg";
"msg_type" =>?msg_type,
"msg_size" => msg.get_message().compute_size(),
"to" => to_peer_id,
);
match ctx.trans.send(msg) {
Ok(()) => ctx.raft_metrics.send_message.add(msg_type, true),
Err(e) => {
// We use metrics to observe failure on production.
debug!(
self.logger,
"failed to send msg to other peer";
"target_peer_id" => to_peer_id,
"target_store_id" => to_store_id,
"err" =>?e,
"error_code" => %e.error_code(),
);
// unreachable store
self.raft_group_mut().report_unreachable(to_peer_id);
ctx.raft_metrics.send_message.add(msg_type, false);
}
}
}
fn handle_raft_committed_entries<T>(
&self,
_ctx: &mut crate::batch::StoreContext<EK, ER, T>,
_take_committed_entries: Vec<raft::prelude::Entry>,
) {
unimplemented!()
}
/// Processing the ready of raft. A detail description of how it's handled
/// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state.
///
/// It's should be called at the end of every round of processing. Any
/// writes will be handled asynchronously, and be notified once writes
/// are persisted.
#[inline]
pub fn handle_raft_ready<T: Transport>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
let has_ready = self.reset_has_ready();
if!has_ready {
return;
}
ctx.has_ready = true;
if!self.raft_group().has_ready() {
return;
}
debug!(self.logger, "handle raft ready");
let mut ready = self.raft_group_mut().ready();
// Update it after unstable entries pagination is introduced.
debug_assert!(ready.entries().last().map_or_else(
|| true,
|entry| entry.index == self.raft_group().raft.raft_log.last_index()
));
if!ready.messages().is_empty() {
debug_assert!(self.is_leader());
for msg in ready.take_messages() {
if let Some(msg) = self.build_raft_message(ctx, msg) {
self.send_raft_message(ctx, msg);
}
}
}
if!ready.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, ready.take_committed_entries());
}
let ready_number = ready.number();
let mut write_task = WriteTask::new(self.region_id(), self.peer_id(), ready_number);
self.storage_mut()
.handle_raft_ready(&mut ready, &mut write_task);
if!ready.persisted_messages().is_empty() {
write_task.messages = ready
.take_persisted_messages()
.into_iter()
.flat_map(|m| self.build_raft_message(ctx, m))
.collect();
}
// Ready number should increase monotonically.
assert!(self.async_writer.known_largest_number() < ready.number());
if let Some(task) = self.async_writer.write(ctx, write_task) {
// So the task doesn't need to be process asynchronously, directly advance.
let mut light_rd = self.raft_group_mut().advance_append(ready);
if!task.messages.is_empty() {
for m in task.messages {
self.send_raft_message(ctx, m);
}
}
if!light_rd.messages().is_empty() || light_rd.commit_index().is_some() {
panic!(
"{:?} unexpected messages [{}] commit index [{:?}]",
self.logger.list(),
light_rd.messages().len(),
light_rd.commit_index()
);
}
if!light_rd.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, light_rd.take_committed_entries());
}
} else {
// The task will be written asynchronously. Once it's persisted, it will be
// notified by `on_persisted`.
self.raft_group_mut().advance_append_async(ready);
}
ctx.raft_metrics.ready.has_ready_region.inc();
}
/// Called when an asynchronously write finishes.
pub fn on_persisted<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
peer_id: u64,
ready_number: u64,
) {
if peer_id!= self.peer_id() {
error!(self.logger, "peer id not matched"; "persisted_peer_id" => peer_id, "persisted_number" => ready_number);
return;
}
let persisted_message = self
.async_writer
.on_persisted(ctx, ready_number, &self.logger);
for msgs in persisted_message {
for msg in msgs {
self.send_raft_message(ctx, msg);
}
}
let persisted_number = self.async_writer.persisted_number();
self.raft_group_mut().on_persist_ready(persisted_number);
let persisted_index = self.raft_group().raft.raft_log.persisted;
self.storage_mut()
.entry_storage_mut()
.update_cache_persisted(persisted_index);
// We may need to check if there is persisted committed logs.
self.set_has_ready();
}
}
impl<ER: RaftEngine> Storage<ER> {
/// Apply the ready to the storage. If there is any states need to be
/// persisted, it will be written to `write_task`.
fn handle_raft_ready<EK: KvEngine>(
&mut self,
ready: &mut Ready,
write_task: &mut WriteTask<EK, ER>,
) {
let prev_raft_state = self.entry_storage().raft_state().clone();
// TODO: handle snapshot
let entry_storage = self.entry_storage_mut();
if!ready.entries().is_empty() {
entry_storage.append(ready.take_entries(), write_task);
}
if let Some(hs) = ready.hs() {
entry_storage.raft_state_mut().set_hard_state(hs.clone());
}
if prev_raft_state!= *entry_storage.raft_state() {
write_task.raft_state = Some(entry_storage.raft_state().clone());
}
}
}
| {
self.raft_group_mut().tick()
} | identifier_body |
mod.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains the actions that will drive a raft state machine.
//!
//! # Raft Ready
//!
//! Every messages or ticks may have side affect. Handling all those side
//! affect immediately is not efficient. Instead, tikv uses `Ready` to batch up
//! all the side affects and handle them at once for throughput.
//!
//! As raft store is the critical path in the whole system, we avoid most
//! blocking IO. So a typical processing is divided into two steps:
//!
//! - Handle raft ready to process the side affect and send IO tasks to
//! background threads
//! - Receive IO tasks completion and update the raft state machine
//!
//! There two steps can be processed concurrently.
mod async_writer;
use engine_traits::{KvEngine, RaftEngine};
use error_code::ErrorCodeExt;
use kvproto::raft_serverpb::RaftMessage;
use protobuf::Message as _;
use raft::{eraftpb, Ready};
use raftstore::store::{FetchedLogs, Transport, WriteTask};
use slog::{debug, error, trace, warn};
pub use self::async_writer::AsyncWriter;
use crate::{
batch::StoreContext,
fsm::{PeerFsm, PeerFsmDelegate},
raft::{Peer, Storage},
router::PeerTick,
};
impl<'a, EK: KvEngine, ER: RaftEngine, T: Transport> PeerFsmDelegate<'a, EK, ER, T> {
/// Raft relies on periodic ticks to keep the state machine sync with other
/// peers.
pub fn on_raft_tick(&mut self) {
if self.fsm.peer_mut().tick() {
self.fsm.peer_mut().set_has_ready();
}
self.schedule_tick(PeerTick::Raft);
}
}
impl<EK: KvEngine, ER: RaftEngine> Peer<EK, ER> {
#[inline]
fn tick(&mut self) -> bool {
self.raft_group_mut().tick()
}
/// Callback for fetching logs asynchronously.
pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) {
let FetchedLogs { context, logs } = fetched_logs;
let low = logs.low;
if!self.is_leader() {
self.entry_storage_mut().clean_async_fetch_res(low);
return;
}
if self.term()!= logs.term {
self.entry_storage_mut().clean_async_fetch_res(low);
} else {
self.entry_storage_mut()
.update_async_fetch_res(low, Some(logs));
}
self.raft_group_mut().on_entries_fetched(context);
// clean the async fetch result immediately if not used to free memory
self.entry_storage_mut().update_async_fetch_res(low, None);
self.set_has_ready();
}
/// Partially filled a raft message that will be sent to other peer.
fn prepare_raft_message(&mut self) -> RaftMessage {
let mut raft_msg = RaftMessage::new();
raft_msg.set_region_id(self.region().id);
raft_msg.set_from_peer(self.peer().clone());
// set current epoch
let epoch = self.storage().region().get_region_epoch();
let msg_epoch = raft_msg.mut_region_epoch();
msg_epoch.set_version(epoch.get_version());
msg_epoch.set_conf_ver(epoch.get_conf_ver());
raft_msg
}
/// Transform a message from raft lib to a message that can be sent to other
/// peers.
///
/// If the recipient can't be found, `None` is returned.
#[inline]
fn build_raft_message<T>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: eraftpb::Message,
) -> Option<RaftMessage> {
let to_peer = match self.peer_from_cache(msg.to) {
Some(p) => p,
None => {
warn!(self.logger, "failed to look up recipient peer"; "to_peer" => msg.to);
return None;
}
};
let mut raft_msg = self.prepare_raft_message();
raft_msg.set_to_peer(to_peer);
if msg.from!= self.peer().id {
debug!(
self.logger,
"redirecting message";
"msg_type" =>?msg.get_msg_type(),
"from" => msg.get_from(),
"to" => msg.get_to(),
);
}
raft_msg.set_message(msg);
Some(raft_msg)
}
/// Send a message.
///
/// The message is pushed into the send buffer, it may not be sent out until
/// transport is flushed explicitly.
fn send_raft_message<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: RaftMessage,
) {
let msg_type = msg.get_message().get_msg_type();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
trace!(
self.logger,
"send raft msg";
"msg_type" =>?msg_type,
"msg_size" => msg.get_message().compute_size(),
"to" => to_peer_id,
);
match ctx.trans.send(msg) {
Ok(()) => ctx.raft_metrics.send_message.add(msg_type, true),
Err(e) => {
// We use metrics to observe failure on production.
debug!(
self.logger,
"failed to send msg to other peer";
"target_peer_id" => to_peer_id,
"target_store_id" => to_store_id,
"err" =>?e,
"error_code" => %e.error_code(),
);
// unreachable store
self.raft_group_mut().report_unreachable(to_peer_id);
ctx.raft_metrics.send_message.add(msg_type, false);
}
}
}
fn handle_raft_committed_entries<T>(
&self,
_ctx: &mut crate::batch::StoreContext<EK, ER, T>, | _take_committed_entries: Vec<raft::prelude::Entry>,
) {
unimplemented!()
}
/// Processing the ready of raft. A detail description of how it's handled
/// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state.
///
/// It's should be called at the end of every round of processing. Any
/// writes will be handled asynchronously, and be notified once writes
/// are persisted.
#[inline]
pub fn handle_raft_ready<T: Transport>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
let has_ready = self.reset_has_ready();
if!has_ready {
return;
}
ctx.has_ready = true;
if!self.raft_group().has_ready() {
return;
}
debug!(self.logger, "handle raft ready");
let mut ready = self.raft_group_mut().ready();
// Update it after unstable entries pagination is introduced.
debug_assert!(ready.entries().last().map_or_else(
|| true,
|entry| entry.index == self.raft_group().raft.raft_log.last_index()
));
if!ready.messages().is_empty() {
debug_assert!(self.is_leader());
for msg in ready.take_messages() {
if let Some(msg) = self.build_raft_message(ctx, msg) {
self.send_raft_message(ctx, msg);
}
}
}
if!ready.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, ready.take_committed_entries());
}
let ready_number = ready.number();
let mut write_task = WriteTask::new(self.region_id(), self.peer_id(), ready_number);
self.storage_mut()
.handle_raft_ready(&mut ready, &mut write_task);
if!ready.persisted_messages().is_empty() {
write_task.messages = ready
.take_persisted_messages()
.into_iter()
.flat_map(|m| self.build_raft_message(ctx, m))
.collect();
}
// Ready number should increase monotonically.
assert!(self.async_writer.known_largest_number() < ready.number());
if let Some(task) = self.async_writer.write(ctx, write_task) {
// So the task doesn't need to be process asynchronously, directly advance.
let mut light_rd = self.raft_group_mut().advance_append(ready);
if!task.messages.is_empty() {
for m in task.messages {
self.send_raft_message(ctx, m);
}
}
if!light_rd.messages().is_empty() || light_rd.commit_index().is_some() {
panic!(
"{:?} unexpected messages [{}] commit index [{:?}]",
self.logger.list(),
light_rd.messages().len(),
light_rd.commit_index()
);
}
if!light_rd.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, light_rd.take_committed_entries());
}
} else {
// The task will be written asynchronously. Once it's persisted, it will be
// notified by `on_persisted`.
self.raft_group_mut().advance_append_async(ready);
}
ctx.raft_metrics.ready.has_ready_region.inc();
}
/// Called when an asynchronously write finishes.
pub fn on_persisted<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
peer_id: u64,
ready_number: u64,
) {
if peer_id!= self.peer_id() {
error!(self.logger, "peer id not matched"; "persisted_peer_id" => peer_id, "persisted_number" => ready_number);
return;
}
let persisted_message = self
.async_writer
.on_persisted(ctx, ready_number, &self.logger);
for msgs in persisted_message {
for msg in msgs {
self.send_raft_message(ctx, msg);
}
}
let persisted_number = self.async_writer.persisted_number();
self.raft_group_mut().on_persist_ready(persisted_number);
let persisted_index = self.raft_group().raft.raft_log.persisted;
self.storage_mut()
.entry_storage_mut()
.update_cache_persisted(persisted_index);
// We may need to check if there is persisted committed logs.
self.set_has_ready();
}
}
impl<ER: RaftEngine> Storage<ER> {
/// Apply the ready to the storage. If there is any states need to be
/// persisted, it will be written to `write_task`.
fn handle_raft_ready<EK: KvEngine>(
&mut self,
ready: &mut Ready,
write_task: &mut WriteTask<EK, ER>,
) {
let prev_raft_state = self.entry_storage().raft_state().clone();
// TODO: handle snapshot
let entry_storage = self.entry_storage_mut();
if!ready.entries().is_empty() {
entry_storage.append(ready.take_entries(), write_task);
}
if let Some(hs) = ready.hs() {
entry_storage.raft_state_mut().set_hard_state(hs.clone());
}
if prev_raft_state!= *entry_storage.raft_state() {
write_task.raft_state = Some(entry_storage.raft_state().clone());
}
}
} | random_line_split |
|
mod.rs | // Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains the actions that will drive a raft state machine.
//!
//! # Raft Ready
//!
//! Every messages or ticks may have side affect. Handling all those side
//! affect immediately is not efficient. Instead, tikv uses `Ready` to batch up
//! all the side affects and handle them at once for throughput.
//!
//! As raft store is the critical path in the whole system, we avoid most
//! blocking IO. So a typical processing is divided into two steps:
//!
//! - Handle raft ready to process the side affect and send IO tasks to
//! background threads
//! - Receive IO tasks completion and update the raft state machine
//!
//! There two steps can be processed concurrently.
mod async_writer;
use engine_traits::{KvEngine, RaftEngine};
use error_code::ErrorCodeExt;
use kvproto::raft_serverpb::RaftMessage;
use protobuf::Message as _;
use raft::{eraftpb, Ready};
use raftstore::store::{FetchedLogs, Transport, WriteTask};
use slog::{debug, error, trace, warn};
pub use self::async_writer::AsyncWriter;
use crate::{
batch::StoreContext,
fsm::{PeerFsm, PeerFsmDelegate},
raft::{Peer, Storage},
router::PeerTick,
};
impl<'a, EK: KvEngine, ER: RaftEngine, T: Transport> PeerFsmDelegate<'a, EK, ER, T> {
/// Raft relies on periodic ticks to keep the state machine sync with other
/// peers.
pub fn on_raft_tick(&mut self) {
if self.fsm.peer_mut().tick() {
self.fsm.peer_mut().set_has_ready();
}
self.schedule_tick(PeerTick::Raft);
}
}
impl<EK: KvEngine, ER: RaftEngine> Peer<EK, ER> {
#[inline]
fn | (&mut self) -> bool {
self.raft_group_mut().tick()
}
/// Callback for fetching logs asynchronously.
pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) {
let FetchedLogs { context, logs } = fetched_logs;
let low = logs.low;
if!self.is_leader() {
self.entry_storage_mut().clean_async_fetch_res(low);
return;
}
if self.term()!= logs.term {
self.entry_storage_mut().clean_async_fetch_res(low);
} else {
self.entry_storage_mut()
.update_async_fetch_res(low, Some(logs));
}
self.raft_group_mut().on_entries_fetched(context);
// clean the async fetch result immediately if not used to free memory
self.entry_storage_mut().update_async_fetch_res(low, None);
self.set_has_ready();
}
/// Partially filled a raft message that will be sent to other peer.
fn prepare_raft_message(&mut self) -> RaftMessage {
let mut raft_msg = RaftMessage::new();
raft_msg.set_region_id(self.region().id);
raft_msg.set_from_peer(self.peer().clone());
// set current epoch
let epoch = self.storage().region().get_region_epoch();
let msg_epoch = raft_msg.mut_region_epoch();
msg_epoch.set_version(epoch.get_version());
msg_epoch.set_conf_ver(epoch.get_conf_ver());
raft_msg
}
/// Transform a message from raft lib to a message that can be sent to other
/// peers.
///
/// If the recipient can't be found, `None` is returned.
#[inline]
fn build_raft_message<T>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: eraftpb::Message,
) -> Option<RaftMessage> {
let to_peer = match self.peer_from_cache(msg.to) {
Some(p) => p,
None => {
warn!(self.logger, "failed to look up recipient peer"; "to_peer" => msg.to);
return None;
}
};
let mut raft_msg = self.prepare_raft_message();
raft_msg.set_to_peer(to_peer);
if msg.from!= self.peer().id {
debug!(
self.logger,
"redirecting message";
"msg_type" =>?msg.get_msg_type(),
"from" => msg.get_from(),
"to" => msg.get_to(),
);
}
raft_msg.set_message(msg);
Some(raft_msg)
}
/// Send a message.
///
/// The message is pushed into the send buffer, it may not be sent out until
/// transport is flushed explicitly.
fn send_raft_message<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
msg: RaftMessage,
) {
let msg_type = msg.get_message().get_msg_type();
let to_peer_id = msg.get_to_peer().get_id();
let to_store_id = msg.get_to_peer().get_store_id();
trace!(
self.logger,
"send raft msg";
"msg_type" =>?msg_type,
"msg_size" => msg.get_message().compute_size(),
"to" => to_peer_id,
);
match ctx.trans.send(msg) {
Ok(()) => ctx.raft_metrics.send_message.add(msg_type, true),
Err(e) => {
// We use metrics to observe failure on production.
debug!(
self.logger,
"failed to send msg to other peer";
"target_peer_id" => to_peer_id,
"target_store_id" => to_store_id,
"err" =>?e,
"error_code" => %e.error_code(),
);
// unreachable store
self.raft_group_mut().report_unreachable(to_peer_id);
ctx.raft_metrics.send_message.add(msg_type, false);
}
}
}
fn handle_raft_committed_entries<T>(
&self,
_ctx: &mut crate::batch::StoreContext<EK, ER, T>,
_take_committed_entries: Vec<raft::prelude::Entry>,
) {
unimplemented!()
}
/// Processing the ready of raft. A detail description of how it's handled
/// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state.
///
/// It's should be called at the end of every round of processing. Any
/// writes will be handled asynchronously, and be notified once writes
/// are persisted.
#[inline]
pub fn handle_raft_ready<T: Transport>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
let has_ready = self.reset_has_ready();
if!has_ready {
return;
}
ctx.has_ready = true;
if!self.raft_group().has_ready() {
return;
}
debug!(self.logger, "handle raft ready");
let mut ready = self.raft_group_mut().ready();
// Update it after unstable entries pagination is introduced.
debug_assert!(ready.entries().last().map_or_else(
|| true,
|entry| entry.index == self.raft_group().raft.raft_log.last_index()
));
if!ready.messages().is_empty() {
debug_assert!(self.is_leader());
for msg in ready.take_messages() {
if let Some(msg) = self.build_raft_message(ctx, msg) {
self.send_raft_message(ctx, msg);
}
}
}
if!ready.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, ready.take_committed_entries());
}
let ready_number = ready.number();
let mut write_task = WriteTask::new(self.region_id(), self.peer_id(), ready_number);
self.storage_mut()
.handle_raft_ready(&mut ready, &mut write_task);
if!ready.persisted_messages().is_empty() {
write_task.messages = ready
.take_persisted_messages()
.into_iter()
.flat_map(|m| self.build_raft_message(ctx, m))
.collect();
}
// Ready number should increase monotonically.
assert!(self.async_writer.known_largest_number() < ready.number());
if let Some(task) = self.async_writer.write(ctx, write_task) {
// So the task doesn't need to be process asynchronously, directly advance.
let mut light_rd = self.raft_group_mut().advance_append(ready);
if!task.messages.is_empty() {
for m in task.messages {
self.send_raft_message(ctx, m);
}
}
if!light_rd.messages().is_empty() || light_rd.commit_index().is_some() {
panic!(
"{:?} unexpected messages [{}] commit index [{:?}]",
self.logger.list(),
light_rd.messages().len(),
light_rd.commit_index()
);
}
if!light_rd.committed_entries().is_empty() {
self.handle_raft_committed_entries(ctx, light_rd.take_committed_entries());
}
} else {
// The task will be written asynchronously. Once it's persisted, it will be
// notified by `on_persisted`.
self.raft_group_mut().advance_append_async(ready);
}
ctx.raft_metrics.ready.has_ready_region.inc();
}
/// Called when an asynchronously write finishes.
pub fn on_persisted<T: Transport>(
&mut self,
ctx: &mut StoreContext<EK, ER, T>,
peer_id: u64,
ready_number: u64,
) {
if peer_id!= self.peer_id() {
error!(self.logger, "peer id not matched"; "persisted_peer_id" => peer_id, "persisted_number" => ready_number);
return;
}
let persisted_message = self
.async_writer
.on_persisted(ctx, ready_number, &self.logger);
for msgs in persisted_message {
for msg in msgs {
self.send_raft_message(ctx, msg);
}
}
let persisted_number = self.async_writer.persisted_number();
self.raft_group_mut().on_persist_ready(persisted_number);
let persisted_index = self.raft_group().raft.raft_log.persisted;
self.storage_mut()
.entry_storage_mut()
.update_cache_persisted(persisted_index);
// We may need to check if there is persisted committed logs.
self.set_has_ready();
}
}
impl<ER: RaftEngine> Storage<ER> {
/// Apply the ready to the storage. If there is any states need to be
/// persisted, it will be written to `write_task`.
fn handle_raft_ready<EK: KvEngine>(
&mut self,
ready: &mut Ready,
write_task: &mut WriteTask<EK, ER>,
) {
let prev_raft_state = self.entry_storage().raft_state().clone();
// TODO: handle snapshot
let entry_storage = self.entry_storage_mut();
if!ready.entries().is_empty() {
entry_storage.append(ready.take_entries(), write_task);
}
if let Some(hs) = ready.hs() {
entry_storage.raft_state_mut().set_hard_state(hs.clone());
}
if prev_raft_state!= *entry_storage.raft_state() {
write_task.raft_state = Some(entry_storage.raft_state().clone());
}
}
}
| tick | identifier_name |
driver.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![feature(rustc_private)]
#![feature(str_strip)]
// FIXME: switch to something more ergonomic here, once available.
// (Currently there is no way to opt into sysroot crates without `extern crate`.)
#[allow(unused_extern_crates)]
extern crate rustc;
#[allow(unused_extern_crates)]
extern crate rustc_driver;
#[allow(unused_extern_crates)]
extern crate rustc_errors;
#[allow(unused_extern_crates)]
extern crate rustc_interface;
use rustc::ty::TyCtxt;
use rustc_interface::interface;
use rustc_tools_util::VersionInfo;
use lazy_static::lazy_static;
use std::borrow::Cow;
use std::env;
use std::ops::Deref;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{exit, Command};
mod lintlist;
/// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
/// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
fn arg_value<'a, T: Deref<Target = str>>(
args: &'a [T],
find_arg: &str,
pred: impl Fn(&str) -> bool,
) -> Option<&'a str> {
let mut args = args.iter().map(Deref::deref);
while let Some(arg) = args.next() {
let mut arg = arg.splitn(2, '=');
if arg.next()!= Some(find_arg) {
continue;
}
match arg.next().or_else(|| args.next()) {
Some(v) if pred(v) => return Some(v),
_ => {},
}
}
None
}
#[test]
fn test_arg_value() {
let args = &["--bar=bar", "--foobar", "123", "--foo"];
assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
assert_eq!(arg_value(args, "--bar", |_| false), None);
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
assert_eq!(arg_value(args, "--foo", |_| true), None);
}
struct DefaultCallbacks;
impl rustc_driver::Callbacks for DefaultCallbacks {}
struct ClippyCallbacks;
impl rustc_driver::Callbacks for ClippyCallbacks {
fn config(&mut self, config: &mut interface::Config) {
let previous = config.register_lints.take();
config.register_lints = Some(Box::new(move |sess, mut lint_store| {
// technically we're ~guaranteed that this is none but might as well call anything that
// is there already. Certainly it can't hurt.
if let Some(previous) = &previous {
(previous)(sess, lint_store);
}
let conf = clippy_lints::read_conf(&[], &sess);
clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
clippy_lints::register_renamed(&mut lint_store);
}));
// FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
// run on the unoptimized MIR. On the other hand this results in some false negatives. If
// MIR passes can be enabled / disabled separately, we should figure out, what passes to
// use for Clippy.
config.opts.debugging_opts.mir_opt_level = 0;
}
}
#[allow(clippy::find_map, clippy::filter_map)]
fn describe_lints() {
use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
use std::collections::HashSet;
println!(
"
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny <foo> and all attempts to override)
"
);
let lint_level = |lint: &Lint| {
LINT_LEVELS
.iter()
.find(|level_mapping| level_mapping.0 == lint.group)
.map(|(_, level)| match level {
Level::Allow => "allow",
Level::Warn => "warn",
Level::Deny => "deny",
})
.unwrap()
};
let mut lints: Vec<_> = ALL_LINTS.iter().collect();
// The sort doesn't case-fold but it's doubtful we care.
lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
let max_lint_name_len = lints
.iter()
.map(|lint| lint.name.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0);
let padded = |x: &str| {
let mut s = " ".repeat(max_lint_name_len - x.chars().count());
s.push_str(x);
s
};
let scoped = |x: &str| format!("clippy::{}", x);
let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
println!("Lint checks provided by clippy:\n");
println!(" {} {:7.7} meaning", padded("name"), "default");
println!(" {} {:7.7} -------", padded("----"), "-------");
let print_lints = |lints: &[&Lint]| {
for lint in lints {
let name = lint.name.replace("_", "-");
println!(
" {} {:7.7} {}",
padded(&scoped(&name)),
lint_level(lint),
lint.desc
);
}
println!("\n");
};
print_lints(&lints);
let max_group_name_len = std::cmp::max(
"clippy::all".len(),
lint_groups
.iter()
.map(|group| group.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0),
);
let padded_group = |x: &str| {
let mut s = " ".repeat(max_group_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint groups provided by clippy:\n");
println!(" {} sub-lints", padded_group("name"));
println!(" {} ---------", padded_group("----"));
println!(" {} the set of all clippy lints", padded_group("clippy::all"));
let print_lint_groups = || {
for group in lint_groups {
let name = group.to_lowercase().replace("_", "-");
let desc = lints
.iter()
.filter(|&lint| lint.group == group)
.map(|lint| lint.name)
.map(|name| name.replace("_", "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded_group(&scoped(&name)), desc);
}
println!("\n");
};
print_lint_groups();
}
fn display_help() {
println!(
"\
Checks a package to catch common mistakes and improve your Rust code.
Usage:
cargo clippy [options] [--] [<opts>...]
Common options:
-h, --help Print this message
-V, --version Print version info and exit
Other options are the same as `cargo check`.
To allow or deny a lint from the command line you can use `cargo clippy --`
with:
-W --warn OPT Set lint warnings
-A --allow OPT Set lint allowed
-D --deny OPT Set lint denied
-F --forbid OPT Set lint forbidden
You can use tool lints to allow or deny lints from your code, eg.:
#[allow(clippy::needless_lifetimes)]
"
);
}
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
lazy_static! {
static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static> = {
let hook = panic::take_hook();
panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
hook
};
}
fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
// Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
(*ICE_HOOK)(info);
// Separate the output with an empty line
eprintln!();
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
false,
false,
None,
false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!info.payload().is::<rustc_errors::ExplicitBug>() {
let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&d);
}
let version_info = rustc_tools_util::get_version_info!();
let xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
format!("we would appreciate a bug report: {}", bug_report_url).into(),
format!("Clippy version: {}", version_info).into(),
];
for note in &xs {
handler.note_without_error(¬e);
}
// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x!= "0");
if backtrace {
TyCtxt::try_print_query_stack(&handler);
}
}
fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
home.and_then(|home| {
toolchain.map(|toolchain| {
let mut path = PathBuf::from(home);
path.push("toolchains");
path.push(toolchain);
path
})
})
}
pub fn main() {
rustc_driver::init_rustc_env_logger();
lazy_static::initialize(&ICE_HOOK);
exit(
rustc_driver::catch_fatal_errors(move || {
let mut orig_args: Vec<String> = env::args().collect();
if orig_args.iter().any(|a| a == "--version" || a == "-V") {
let version_info = rustc_tools_util::get_version_info!();
println!("{}", version_info);
exit(0);
}
// Get the sysroot, looking from most specific to this invocation to the least:
// - command line
// - runtime environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
// - sysroot from rustc in the path
// - compile-time environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
let have_sys_root_arg = sys_root_arg.is_some();
let sys_root = sys_root_arg
.map(PathBuf::from)
.or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
.or_else(|| {
let home = std::env::var("RUSTUP_HOME") | .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
.ok();
toolchain_path(home, toolchain)
})
.or_else(|| {
Command::new("rustc")
.arg("--print")
.arg("sysroot")
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|s| PathBuf::from(s.trim()))
})
.or_else(|| option_env!("SYSROOT").map(PathBuf::from))
.or_else(|| {
let home = option_env!("RUSTUP_HOME")
.or(option_env!("MULTIRUST_HOME"))
.map(ToString::to_string);
let toolchain = option_env!("RUSTUP_TOOLCHAIN")
.or(option_env!("MULTIRUST_TOOLCHAIN"))
.map(ToString::to_string);
toolchain_path(home, toolchain)
})
.map(|pb| pb.to_string_lossy().to_string())
.expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
// Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
// We're invoking the compiler programmatically, so we ignore this/
let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
if wrapper_mode {
// we still want to be able to invoke it normally though
orig_args.remove(1);
}
if!wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
display_help();
exit(0);
}
let should_describe_lints = || {
let args: Vec<_> = env::args().collect();
args.windows(2).any(|args| {
args[1] == "help"
&& match args[0].as_str() {
"-W" | "-A" | "-D" | "-F" => true,
_ => false,
}
})
};
if!wrapper_mode && should_describe_lints() {
describe_lints();
exit(0);
}
// this conditional check for the --sysroot flag is there so users can call
// `clippy_driver` directly
// without having to pass --sysroot or anything
let mut args: Vec<String> = orig_args.clone();
if!have_sys_root_arg {
args.extend(vec!["--sysroot".into(), sys_root]);
};
// this check ensures that dependencies are built but not linted and the final
// crate is linted but not built
let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
|| arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
if clippy_enabled {
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
if s.is_empty() {
None
} else {
Some(s.to_string())
}
}));
}
}
let mut clippy = ClippyCallbacks;
let mut default = DefaultCallbacks;
let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
if clippy_enabled { &mut clippy } else { &mut default };
rustc_driver::run_compiler(&args, callbacks, None, None)
})
.and_then(|result| result)
.is_err() as i32,
)
} | .or_else(|_| std::env::var("MULTIRUST_HOME"))
.ok();
let toolchain = std::env::var("RUSTUP_TOOLCHAIN") | random_line_split |
driver.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![feature(rustc_private)]
#![feature(str_strip)]
// FIXME: switch to something more ergonomic here, once available.
// (Currently there is no way to opt into sysroot crates without `extern crate`.)
#[allow(unused_extern_crates)]
extern crate rustc;
#[allow(unused_extern_crates)]
extern crate rustc_driver;
#[allow(unused_extern_crates)]
extern crate rustc_errors;
#[allow(unused_extern_crates)]
extern crate rustc_interface;
use rustc::ty::TyCtxt;
use rustc_interface::interface;
use rustc_tools_util::VersionInfo;
use lazy_static::lazy_static;
use std::borrow::Cow;
use std::env;
use std::ops::Deref;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{exit, Command};
mod lintlist;
/// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
/// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
fn arg_value<'a, T: Deref<Target = str>>(
args: &'a [T],
find_arg: &str,
pred: impl Fn(&str) -> bool,
) -> Option<&'a str> {
let mut args = args.iter().map(Deref::deref);
while let Some(arg) = args.next() {
let mut arg = arg.splitn(2, '=');
if arg.next()!= Some(find_arg) {
continue;
}
match arg.next().or_else(|| args.next()) {
Some(v) if pred(v) => return Some(v),
_ => {},
}
}
None
}
#[test]
fn test_arg_value() {
let args = &["--bar=bar", "--foobar", "123", "--foo"];
assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
assert_eq!(arg_value(args, "--bar", |_| false), None);
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
assert_eq!(arg_value(args, "--foo", |_| true), None);
}
struct DefaultCallbacks;
impl rustc_driver::Callbacks for DefaultCallbacks {}
struct ClippyCallbacks;
impl rustc_driver::Callbacks for ClippyCallbacks {
fn config(&mut self, config: &mut interface::Config) {
let previous = config.register_lints.take();
config.register_lints = Some(Box::new(move |sess, mut lint_store| {
// technically we're ~guaranteed that this is none but might as well call anything that
// is there already. Certainly it can't hurt.
if let Some(previous) = &previous {
(previous)(sess, lint_store);
}
let conf = clippy_lints::read_conf(&[], &sess);
clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
clippy_lints::register_renamed(&mut lint_store);
}));
// FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
// run on the unoptimized MIR. On the other hand this results in some false negatives. If
// MIR passes can be enabled / disabled separately, we should figure out, what passes to
// use for Clippy.
config.opts.debugging_opts.mir_opt_level = 0;
}
}
#[allow(clippy::find_map, clippy::filter_map)]
fn describe_lints() {
use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
use std::collections::HashSet;
println!(
"
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny <foo> and all attempts to override)
"
);
let lint_level = |lint: &Lint| {
LINT_LEVELS
.iter()
.find(|level_mapping| level_mapping.0 == lint.group)
.map(|(_, level)| match level {
Level::Allow => "allow",
Level::Warn => "warn",
Level::Deny => "deny",
})
.unwrap()
};
let mut lints: Vec<_> = ALL_LINTS.iter().collect();
// The sort doesn't case-fold but it's doubtful we care.
lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
let max_lint_name_len = lints
.iter()
.map(|lint| lint.name.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0);
let padded = |x: &str| {
let mut s = " ".repeat(max_lint_name_len - x.chars().count());
s.push_str(x);
s
};
let scoped = |x: &str| format!("clippy::{}", x);
let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
println!("Lint checks provided by clippy:\n");
println!(" {} {:7.7} meaning", padded("name"), "default");
println!(" {} {:7.7} -------", padded("----"), "-------");
let print_lints = |lints: &[&Lint]| {
for lint in lints {
let name = lint.name.replace("_", "-");
println!(
" {} {:7.7} {}",
padded(&scoped(&name)),
lint_level(lint),
lint.desc
);
}
println!("\n");
};
print_lints(&lints);
let max_group_name_len = std::cmp::max(
"clippy::all".len(),
lint_groups
.iter()
.map(|group| group.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0),
);
let padded_group = |x: &str| {
let mut s = " ".repeat(max_group_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint groups provided by clippy:\n");
println!(" {} sub-lints", padded_group("name"));
println!(" {} ---------", padded_group("----"));
println!(" {} the set of all clippy lints", padded_group("clippy::all"));
let print_lint_groups = || {
for group in lint_groups {
let name = group.to_lowercase().replace("_", "-");
let desc = lints
.iter()
.filter(|&lint| lint.group == group)
.map(|lint| lint.name)
.map(|name| name.replace("_", "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded_group(&scoped(&name)), desc);
}
println!("\n");
};
print_lint_groups();
}
fn display_help() {
println!(
"\
Checks a package to catch common mistakes and improve your Rust code.
Usage:
cargo clippy [options] [--] [<opts>...]
Common options:
-h, --help Print this message
-V, --version Print version info and exit
Other options are the same as `cargo check`.
To allow or deny a lint from the command line you can use `cargo clippy --`
with:
-W --warn OPT Set lint warnings
-A --allow OPT Set lint allowed
-D --deny OPT Set lint denied
-F --forbid OPT Set lint forbidden
You can use tool lints to allow or deny lints from your code, eg.:
#[allow(clippy::needless_lifetimes)]
"
);
}
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
lazy_static! {
static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static> = {
let hook = panic::take_hook();
panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
hook
};
}
fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
// Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
(*ICE_HOOK)(info);
// Separate the output with an empty line
eprintln!();
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
false,
false,
None,
false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!info.payload().is::<rustc_errors::ExplicitBug>() {
let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&d);
}
let version_info = rustc_tools_util::get_version_info!();
let xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
format!("we would appreciate a bug report: {}", bug_report_url).into(),
format!("Clippy version: {}", version_info).into(),
];
for note in &xs {
handler.note_without_error(¬e);
}
// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x!= "0");
if backtrace {
TyCtxt::try_print_query_stack(&handler);
}
}
fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
home.and_then(|home| {
toolchain.map(|toolchain| {
let mut path = PathBuf::from(home);
path.push("toolchains");
path.push(toolchain);
path
})
})
}
pub fn main() {
rustc_driver::init_rustc_env_logger();
lazy_static::initialize(&ICE_HOOK);
exit(
rustc_driver::catch_fatal_errors(move || {
let mut orig_args: Vec<String> = env::args().collect();
if orig_args.iter().any(|a| a == "--version" || a == "-V") {
let version_info = rustc_tools_util::get_version_info!();
println!("{}", version_info);
exit(0);
}
// Get the sysroot, looking from most specific to this invocation to the least:
// - command line
// - runtime environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
// - sysroot from rustc in the path
// - compile-time environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
let have_sys_root_arg = sys_root_arg.is_some();
let sys_root = sys_root_arg
.map(PathBuf::from)
.or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
.or_else(|| {
let home = std::env::var("RUSTUP_HOME")
.or_else(|_| std::env::var("MULTIRUST_HOME"))
.ok();
let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
.or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
.ok();
toolchain_path(home, toolchain)
})
.or_else(|| {
Command::new("rustc")
.arg("--print")
.arg("sysroot")
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|s| PathBuf::from(s.trim()))
})
.or_else(|| option_env!("SYSROOT").map(PathBuf::from))
.or_else(|| {
let home = option_env!("RUSTUP_HOME")
.or(option_env!("MULTIRUST_HOME"))
.map(ToString::to_string);
let toolchain = option_env!("RUSTUP_TOOLCHAIN")
.or(option_env!("MULTIRUST_TOOLCHAIN"))
.map(ToString::to_string);
toolchain_path(home, toolchain)
})
.map(|pb| pb.to_string_lossy().to_string())
.expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
// Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
// We're invoking the compiler programmatically, so we ignore this/
let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
if wrapper_mode {
// we still want to be able to invoke it normally though
orig_args.remove(1);
}
if!wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
display_help();
exit(0);
}
let should_describe_lints = || {
let args: Vec<_> = env::args().collect();
args.windows(2).any(|args| {
args[1] == "help"
&& match args[0].as_str() {
"-W" | "-A" | "-D" | "-F" => true,
_ => false,
}
})
};
if!wrapper_mode && should_describe_lints() {
describe_lints();
exit(0);
}
// this conditional check for the --sysroot flag is there so users can call
// `clippy_driver` directly
// without having to pass --sysroot or anything
let mut args: Vec<String> = orig_args.clone();
if!have_sys_root_arg {
args.extend(vec!["--sysroot".into(), sys_root]);
};
// this check ensures that dependencies are built but not linted and the final
// crate is linted but not built
let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
|| arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
if clippy_enabled {
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
if s.is_empty() {
None
} else |
}));
}
}
let mut clippy = ClippyCallbacks;
let mut default = DefaultCallbacks;
let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
if clippy_enabled { &mut clippy } else { &mut default };
rustc_driver::run_compiler(&args, callbacks, None, None)
})
.and_then(|result| result)
.is_err() as i32,
)
}
| {
Some(s.to_string())
} | conditional_block |
driver.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![feature(rustc_private)]
#![feature(str_strip)]
// FIXME: switch to something more ergonomic here, once available.
// (Currently there is no way to opt into sysroot crates without `extern crate`.)
#[allow(unused_extern_crates)]
extern crate rustc;
#[allow(unused_extern_crates)]
extern crate rustc_driver;
#[allow(unused_extern_crates)]
extern crate rustc_errors;
#[allow(unused_extern_crates)]
extern crate rustc_interface;
use rustc::ty::TyCtxt;
use rustc_interface::interface;
use rustc_tools_util::VersionInfo;
use lazy_static::lazy_static;
use std::borrow::Cow;
use std::env;
use std::ops::Deref;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{exit, Command};
mod lintlist;
/// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
/// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
fn arg_value<'a, T: Deref<Target = str>>(
args: &'a [T],
find_arg: &str,
pred: impl Fn(&str) -> bool,
) -> Option<&'a str> {
let mut args = args.iter().map(Deref::deref);
while let Some(arg) = args.next() {
let mut arg = arg.splitn(2, '=');
if arg.next()!= Some(find_arg) {
continue;
}
match arg.next().or_else(|| args.next()) {
Some(v) if pred(v) => return Some(v),
_ => {},
}
}
None
}
#[test]
fn | () {
let args = &["--bar=bar", "--foobar", "123", "--foo"];
assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
assert_eq!(arg_value(args, "--bar", |_| false), None);
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
assert_eq!(arg_value(args, "--foo", |_| true), None);
}
struct DefaultCallbacks;
impl rustc_driver::Callbacks for DefaultCallbacks {}
struct ClippyCallbacks;
impl rustc_driver::Callbacks for ClippyCallbacks {
fn config(&mut self, config: &mut interface::Config) {
let previous = config.register_lints.take();
config.register_lints = Some(Box::new(move |sess, mut lint_store| {
// technically we're ~guaranteed that this is none but might as well call anything that
// is there already. Certainly it can't hurt.
if let Some(previous) = &previous {
(previous)(sess, lint_store);
}
let conf = clippy_lints::read_conf(&[], &sess);
clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
clippy_lints::register_renamed(&mut lint_store);
}));
// FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
// run on the unoptimized MIR. On the other hand this results in some false negatives. If
// MIR passes can be enabled / disabled separately, we should figure out, what passes to
// use for Clippy.
config.opts.debugging_opts.mir_opt_level = 0;
}
}
#[allow(clippy::find_map, clippy::filter_map)]
fn describe_lints() {
use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
use std::collections::HashSet;
println!(
"
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny <foo> and all attempts to override)
"
);
let lint_level = |lint: &Lint| {
LINT_LEVELS
.iter()
.find(|level_mapping| level_mapping.0 == lint.group)
.map(|(_, level)| match level {
Level::Allow => "allow",
Level::Warn => "warn",
Level::Deny => "deny",
})
.unwrap()
};
let mut lints: Vec<_> = ALL_LINTS.iter().collect();
// The sort doesn't case-fold but it's doubtful we care.
lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
let max_lint_name_len = lints
.iter()
.map(|lint| lint.name.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0);
let padded = |x: &str| {
let mut s = " ".repeat(max_lint_name_len - x.chars().count());
s.push_str(x);
s
};
let scoped = |x: &str| format!("clippy::{}", x);
let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
println!("Lint checks provided by clippy:\n");
println!(" {} {:7.7} meaning", padded("name"), "default");
println!(" {} {:7.7} -------", padded("----"), "-------");
let print_lints = |lints: &[&Lint]| {
for lint in lints {
let name = lint.name.replace("_", "-");
println!(
" {} {:7.7} {}",
padded(&scoped(&name)),
lint_level(lint),
lint.desc
);
}
println!("\n");
};
print_lints(&lints);
let max_group_name_len = std::cmp::max(
"clippy::all".len(),
lint_groups
.iter()
.map(|group| group.len())
.map(|len| len + "clippy::".len())
.max()
.unwrap_or(0),
);
let padded_group = |x: &str| {
let mut s = " ".repeat(max_group_name_len - x.chars().count());
s.push_str(x);
s
};
println!("Lint groups provided by clippy:\n");
println!(" {} sub-lints", padded_group("name"));
println!(" {} ---------", padded_group("----"));
println!(" {} the set of all clippy lints", padded_group("clippy::all"));
let print_lint_groups = || {
for group in lint_groups {
let name = group.to_lowercase().replace("_", "-");
let desc = lints
.iter()
.filter(|&lint| lint.group == group)
.map(|lint| lint.name)
.map(|name| name.replace("_", "-"))
.collect::<Vec<String>>()
.join(", ");
println!(" {} {}", padded_group(&scoped(&name)), desc);
}
println!("\n");
};
print_lint_groups();
}
fn display_help() {
println!(
"\
Checks a package to catch common mistakes and improve your Rust code.
Usage:
cargo clippy [options] [--] [<opts>...]
Common options:
-h, --help Print this message
-V, --version Print version info and exit
Other options are the same as `cargo check`.
To allow or deny a lint from the command line you can use `cargo clippy --`
with:
-W --warn OPT Set lint warnings
-A --allow OPT Set lint allowed
-D --deny OPT Set lint denied
-F --forbid OPT Set lint forbidden
You can use tool lints to allow or deny lints from your code, eg.:
#[allow(clippy::needless_lifetimes)]
"
);
}
const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
lazy_static! {
static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send +'static> = {
let hook = panic::take_hook();
panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
hook
};
}
fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
// Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
(*ICE_HOOK)(info);
// Separate the output with an empty line
eprintln!();
let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
rustc_errors::ColorConfig::Auto,
None,
false,
false,
None,
false,
));
let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
// a.span_bug or.bug call has already printed what
// it wants to print.
if!info.payload().is::<rustc_errors::ExplicitBug>() {
let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
handler.emit_diagnostic(&d);
}
let version_info = rustc_tools_util::get_version_info!();
let xs: Vec<Cow<'static, str>> = vec![
"the compiler unexpectedly panicked. this is a bug.".into(),
format!("we would appreciate a bug report: {}", bug_report_url).into(),
format!("Clippy version: {}", version_info).into(),
];
for note in &xs {
handler.note_without_error(¬e);
}
// If backtraces are enabled, also print the query stack
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x!= "0");
if backtrace {
TyCtxt::try_print_query_stack(&handler);
}
}
fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
home.and_then(|home| {
toolchain.map(|toolchain| {
let mut path = PathBuf::from(home);
path.push("toolchains");
path.push(toolchain);
path
})
})
}
pub fn main() {
rustc_driver::init_rustc_env_logger();
lazy_static::initialize(&ICE_HOOK);
exit(
rustc_driver::catch_fatal_errors(move || {
let mut orig_args: Vec<String> = env::args().collect();
if orig_args.iter().any(|a| a == "--version" || a == "-V") {
let version_info = rustc_tools_util::get_version_info!();
println!("{}", version_info);
exit(0);
}
// Get the sysroot, looking from most specific to this invocation to the least:
// - command line
// - runtime environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
// - sysroot from rustc in the path
// - compile-time environment
// - SYSROOT
// - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
let have_sys_root_arg = sys_root_arg.is_some();
let sys_root = sys_root_arg
.map(PathBuf::from)
.or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
.or_else(|| {
let home = std::env::var("RUSTUP_HOME")
.or_else(|_| std::env::var("MULTIRUST_HOME"))
.ok();
let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
.or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
.ok();
toolchain_path(home, toolchain)
})
.or_else(|| {
Command::new("rustc")
.arg("--print")
.arg("sysroot")
.output()
.ok()
.and_then(|out| String::from_utf8(out.stdout).ok())
.map(|s| PathBuf::from(s.trim()))
})
.or_else(|| option_env!("SYSROOT").map(PathBuf::from))
.or_else(|| {
let home = option_env!("RUSTUP_HOME")
.or(option_env!("MULTIRUST_HOME"))
.map(ToString::to_string);
let toolchain = option_env!("RUSTUP_TOOLCHAIN")
.or(option_env!("MULTIRUST_TOOLCHAIN"))
.map(ToString::to_string);
toolchain_path(home, toolchain)
})
.map(|pb| pb.to_string_lossy().to_string())
.expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
// Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
// We're invoking the compiler programmatically, so we ignore this/
let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
if wrapper_mode {
// we still want to be able to invoke it normally though
orig_args.remove(1);
}
if!wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
display_help();
exit(0);
}
let should_describe_lints = || {
let args: Vec<_> = env::args().collect();
args.windows(2).any(|args| {
args[1] == "help"
&& match args[0].as_str() {
"-W" | "-A" | "-D" | "-F" => true,
_ => false,
}
})
};
if!wrapper_mode && should_describe_lints() {
describe_lints();
exit(0);
}
// this conditional check for the --sysroot flag is there so users can call
// `clippy_driver` directly
// without having to pass --sysroot or anything
let mut args: Vec<String> = orig_args.clone();
if!have_sys_root_arg {
args.extend(vec!["--sysroot".into(), sys_root]);
};
// this check ensures that dependencies are built but not linted and the final
// crate is linted but not built
let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
|| arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
if clippy_enabled {
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
if s.is_empty() {
None
} else {
Some(s.to_string())
}
}));
}
}
let mut clippy = ClippyCallbacks;
let mut default = DefaultCallbacks;
let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
if clippy_enabled { &mut clippy } else { &mut default };
rustc_driver::run_compiler(&args, callbacks, None, None)
})
.and_then(|result| result)
.is_err() as i32,
)
}
| test_arg_value | identifier_name |
matrix_invert.rs | use std::error::Error;
use std::ffi::CString;
use std::time::Instant;
use crate::utils::matrix_utils::print_matrix;
use rustacuda::prelude::*;
use std::fmt;
pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> {
// Initialize the CUDA API
rustacuda::init(CudaFlags::empty())?;
// Get the first device
let device = Device::get_device(0)?;
let nx = 4;
let nxy = nx * nx;
let mut matrix_a = vec![0f32; nxy];
let mut blupp = 1f32;
for elem in matrix_a.iter_mut() {
*elem = blupp;
blupp = blupp + 1.0;
}
// ATTENTION: set one element to different value, otherwise it is a singular matrix
let idx = 2;
matrix_a[idx] = matrix_a[idx] + 12.0; // just do it!!!
let idx = 4;
matrix_a[idx] = matrix_a[idx] - 3.0; // just do it!!!
// make a unit matrix
let mut matrix_i = vec![0f32; nxy];
for r in 0..nx {
matrix_i[r * nx + r] = 1.0;
}
println!("orignal matrix_a: ");
print_matrix(&matrix_a, nx, nx);
println!("orignal matrix_i: ");
print_matrix(&matrix_i, nx, nx);
// Create a context associated to this device
let _context =
Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device)?;
let mut d_matrix_a = DeviceBuffer::from_slice(&matrix_a)?;
let mut d_matrix_i = DeviceBuffer::from_slice(&matrix_i)?;
// println!("include_str!(env!(KERNEL_PTX_PATH)) = {}", include_str!(env!("KERNEL_PTX_PATH")));
// Load the module containing the function we want to call
let module_data = CString::new(include_str!(env!("KERNEL_PTX_PATH")))?;
let module = Module::load_from_string(&module_data)?;
// Create a stream to submit work to
let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?;
let blocksize = 1;
let threads_per_block = (blocksize, blocksize, 1);
let b = (blocksize, blocksize, 1);
let block = (b.0 as u32, b.1 as u32, b.2 as u32);
let g = (
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
1 as i32,
);
let grid = (g.0 as u32, g.1 as u32, 1 as u32);
println!("block = {:?}, grid = {:?}", block, grid);
let start = Instant::now();
for i in 0..nx {
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.nodiag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.diag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.gaussjordan<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.set_zero<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
}
stream.synchronize()?;
let duration_cuda = start.elapsed();
d_matrix_a.copy_to(&mut matrix_a)?;
d_matrix_i.copy_to(&mut matrix_i)?;
println!("duration gpu invert_matrix_2D2D: {:?}", duration_cuda);
println!("gpu result inverted matrix: \n\n");
print_matrix(&matrix_i, nx, nx);
println!("former input matrix ");
print_matrix(&matrix_a, nx, nx);
//
// let start_cpu = Instant::now();
// let res_cpu = invert_matrix_cpu(&matrix_a, nx, ny);
// let duration_cpu = start_cpu.elapsed();
//
// println!("duration cpu: {:?}", duration_cpu);
//
// for x in 0..res_cpu.len() {
// // assert_eq!(res_cpu[x], out_host[x]);
// }
// The kernel launch is asynchronous, so we wait for the kernel to finish executing
Ok(())
}
impl fmt::Display for Matrix {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\nrows: {}, cols: {}\n", self.rows, self.cols)?;
for row in 0..self.rows {
for col in 0..self.cols {
write!(f, " {} ", self.get(row, col))?;
}
write!(f, "\n ")?;
}
write!(f, "\n ")
}
}
pub fn test_matrix_invert_cpu() {
let mut m = Matrix::zero(3, 3);
m.set(0, 0, 1.0);
m.set(0, 1, 2.0);
m.set(0, 2, 3.0);
m.set(1, 0, 0.0);
m.set(1, 1, 1.0);
m.set(1, 2, 4.0);
m.set(2, 0, 5.0);
m.set(2, 1, 6.0);
m.set(2, 2, 0.0);
let mut expected = Matrix::zero(3, 3);
expected.set(0, 0, -24.0);
expected.set(0, 1, 18.0);
expected.set(0, 2, 5.0);
expected.set(1, 0, 20.0);
expected.set(1, 1, -15.0);
expected.set(1, 2, -4.0);
expected.set(2, 0, -5.0);
expected.set(2, 1, 4.0); | // calculate the inverse and compare with expected result
let inv = matrix_invert_cpu(&m).unwrap();
assert_eq!(expected, inv);
println!("orignal: {}", m);
println!("inverted: {}", inv);
}
#[derive(Debug, PartialEq, Clone)]
pub struct Matrix {
data: Vec<f32>,
rows: usize,
cols: usize,
}
impl Matrix {
pub fn one(rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![1.0; cols * rows],
}
}
pub fn zero(rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![0.0; cols * rows],
}
}
pub fn identiy(rows: usize) -> Matrix {
let mut m = Matrix::zero(rows, rows);
for i in 0..rows {
m.set(i, i, 1.0);
}
m
}
pub fn get_rows(&self) -> usize {
self.rows
}
pub fn get_cols(&self) -> usize {
self.cols
}
pub fn set(&mut self, row: usize, col: usize, value: f32) -> &mut Matrix {
self.data[row * self.cols + col] = value;
self
}
pub fn get(&self, row: usize, col: usize) -> f32 {
self.data[row * self.cols + col]
}
}
pub fn matrix_invert_cpu(mat_a: &Matrix) -> Result<Matrix, MathError> {
if mat_a.rows!= mat_a.cols {
return Err(MathError::MatrixNotInvertableNotSquare);
}
let rows = mat_a.rows;
let mut cols = mat_a.cols;
// helper matrix for inverting
let mut dummy = Matrix::zero(rows, 2 * cols);
// copy matrix a to dummy (left half of dummy)
for row in 0..rows {
for col in 0..cols {
dummy.set(row, col, mat_a.get(row, col));
}
}
// set identiy matrix elements
for row in 0..rows {
dummy.set(row, cols + row, 1.0);
}
// apply all transformations to the identiy matrix as well
cols = 2 * mat_a.cols;
let mut tmp: f32 = 0.0;
for row in 0..rows {
// transform to an upper triangle matrix
// element in main diagonal is used to divide the current row
let mut elem = dummy.get(row, row);
if elem!= 0.0 {
// divide each element in current row by elem -> so A(row,row) = 1
for col in 0..cols {
tmp = dummy.get(row, col);
dummy.set(row, col, tmp / elem);
}
// subtract the line row from all the rows below this row
for row2 in row + 1..rows {
elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
} else {
return Err(MathError::MatrixNotInvertable(row, row, elem as f64));
}
}
// all elements below the main diagonal are 0
// iterate from the last row to the first row and
// set the elements right from the diagonal to 0
// transform to an upper triangle matri
// element in main diagonal is used to divide the current row
for row in (1..rows).rev() {
// transform to an lower triangle matrix
// subtract the line row from all the rows above this row
for row2 in (0..row).rev() {
let elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
}
let mut res = Matrix::zero(rows, rows);
for row in 0..rows {
for col in 0..mat_a.cols {
// res.data[row][col] = dummy.data[row][col + mat_a.cols];
tmp = dummy.get(row, col + mat_a.get_cols());
res.set(row, col, tmp);
}
}
Ok(res)
}
#[derive(Debug)]
pub enum MathError {
MatrixDimensionDontMatch,
MatrixNotInvertableNotSquare,
MatrixMulNotSquare,
MatrixNotInvertable(usize, usize, f64),
} | expected.set(2, 2, 1.0);
| random_line_split |
matrix_invert.rs | use std::error::Error;
use std::ffi::CString;
use std::time::Instant;
use crate::utils::matrix_utils::print_matrix;
use rustacuda::prelude::*;
use std::fmt;
pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> {
// Initialize the CUDA API
rustacuda::init(CudaFlags::empty())?;
// Get the first device
let device = Device::get_device(0)?;
let nx = 4;
let nxy = nx * nx;
let mut matrix_a = vec![0f32; nxy];
let mut blupp = 1f32;
for elem in matrix_a.iter_mut() {
*elem = blupp;
blupp = blupp + 1.0;
}
// ATTENTION: set one element to different value, otherwise it is a singular matrix
let idx = 2;
matrix_a[idx] = matrix_a[idx] + 12.0; // just do it!!!
let idx = 4;
matrix_a[idx] = matrix_a[idx] - 3.0; // just do it!!!
// make a unit matrix
let mut matrix_i = vec![0f32; nxy];
for r in 0..nx {
matrix_i[r * nx + r] = 1.0;
}
println!("orignal matrix_a: ");
print_matrix(&matrix_a, nx, nx);
println!("orignal matrix_i: ");
print_matrix(&matrix_i, nx, nx);
// Create a context associated to this device
let _context =
Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device)?;
let mut d_matrix_a = DeviceBuffer::from_slice(&matrix_a)?;
let mut d_matrix_i = DeviceBuffer::from_slice(&matrix_i)?;
// println!("include_str!(env!(KERNEL_PTX_PATH)) = {}", include_str!(env!("KERNEL_PTX_PATH")));
// Load the module containing the function we want to call
let module_data = CString::new(include_str!(env!("KERNEL_PTX_PATH")))?;
let module = Module::load_from_string(&module_data)?;
// Create a stream to submit work to
let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?;
let blocksize = 1;
let threads_per_block = (blocksize, blocksize, 1);
let b = (blocksize, blocksize, 1);
let block = (b.0 as u32, b.1 as u32, b.2 as u32);
let g = (
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
1 as i32,
);
let grid = (g.0 as u32, g.1 as u32, 1 as u32);
println!("block = {:?}, grid = {:?}", block, grid);
let start = Instant::now();
for i in 0..nx {
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.nodiag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.diag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.gaussjordan<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.set_zero<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
}
stream.synchronize()?;
let duration_cuda = start.elapsed();
d_matrix_a.copy_to(&mut matrix_a)?;
d_matrix_i.copy_to(&mut matrix_i)?;
println!("duration gpu invert_matrix_2D2D: {:?}", duration_cuda);
println!("gpu result inverted matrix: \n\n");
print_matrix(&matrix_i, nx, nx);
println!("former input matrix ");
print_matrix(&matrix_a, nx, nx);
//
// let start_cpu = Instant::now();
// let res_cpu = invert_matrix_cpu(&matrix_a, nx, ny);
// let duration_cpu = start_cpu.elapsed();
//
// println!("duration cpu: {:?}", duration_cpu);
//
// for x in 0..res_cpu.len() {
// // assert_eq!(res_cpu[x], out_host[x]);
// }
// The kernel launch is asynchronous, so we wait for the kernel to finish executing
Ok(())
}
impl fmt::Display for Matrix {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\nrows: {}, cols: {}\n", self.rows, self.cols)?;
for row in 0..self.rows {
for col in 0..self.cols {
write!(f, " {} ", self.get(row, col))?;
}
write!(f, "\n ")?;
}
write!(f, "\n ")
}
}
pub fn test_matrix_invert_cpu() {
let mut m = Matrix::zero(3, 3);
m.set(0, 0, 1.0);
m.set(0, 1, 2.0);
m.set(0, 2, 3.0);
m.set(1, 0, 0.0);
m.set(1, 1, 1.0);
m.set(1, 2, 4.0);
m.set(2, 0, 5.0);
m.set(2, 1, 6.0);
m.set(2, 2, 0.0);
let mut expected = Matrix::zero(3, 3);
expected.set(0, 0, -24.0);
expected.set(0, 1, 18.0);
expected.set(0, 2, 5.0);
expected.set(1, 0, 20.0);
expected.set(1, 1, -15.0);
expected.set(1, 2, -4.0);
expected.set(2, 0, -5.0);
expected.set(2, 1, 4.0);
expected.set(2, 2, 1.0);
// calculate the inverse and compare with expected result
let inv = matrix_invert_cpu(&m).unwrap();
assert_eq!(expected, inv);
println!("orignal: {}", m);
println!("inverted: {}", inv);
}
#[derive(Debug, PartialEq, Clone)]
pub struct Matrix {
data: Vec<f32>,
rows: usize,
cols: usize,
}
impl Matrix {
pub fn one(rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![1.0; cols * rows],
}
}
pub fn | (rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![0.0; cols * rows],
}
}
pub fn identiy(rows: usize) -> Matrix {
let mut m = Matrix::zero(rows, rows);
for i in 0..rows {
m.set(i, i, 1.0);
}
m
}
pub fn get_rows(&self) -> usize {
self.rows
}
pub fn get_cols(&self) -> usize {
self.cols
}
pub fn set(&mut self, row: usize, col: usize, value: f32) -> &mut Matrix {
self.data[row * self.cols + col] = value;
self
}
pub fn get(&self, row: usize, col: usize) -> f32 {
self.data[row * self.cols + col]
}
}
pub fn matrix_invert_cpu(mat_a: &Matrix) -> Result<Matrix, MathError> {
if mat_a.rows!= mat_a.cols {
return Err(MathError::MatrixNotInvertableNotSquare);
}
let rows = mat_a.rows;
let mut cols = mat_a.cols;
// helper matrix for inverting
let mut dummy = Matrix::zero(rows, 2 * cols);
// copy matrix a to dummy (left half of dummy)
for row in 0..rows {
for col in 0..cols {
dummy.set(row, col, mat_a.get(row, col));
}
}
// set identiy matrix elements
for row in 0..rows {
dummy.set(row, cols + row, 1.0);
}
// apply all transformations to the identiy matrix as well
cols = 2 * mat_a.cols;
let mut tmp: f32 = 0.0;
for row in 0..rows {
// transform to an upper triangle matrix
// element in main diagonal is used to divide the current row
let mut elem = dummy.get(row, row);
if elem!= 0.0 {
// divide each element in current row by elem -> so A(row,row) = 1
for col in 0..cols {
tmp = dummy.get(row, col);
dummy.set(row, col, tmp / elem);
}
// subtract the line row from all the rows below this row
for row2 in row + 1..rows {
elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
} else {
return Err(MathError::MatrixNotInvertable(row, row, elem as f64));
}
}
// all elements below the main diagonal are 0
// iterate from the last row to the first row and
// set the elements right from the diagonal to 0
// transform to an upper triangle matri
// element in main diagonal is used to divide the current row
for row in (1..rows).rev() {
// transform to an lower triangle matrix
// subtract the line row from all the rows above this row
for row2 in (0..row).rev() {
let elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
}
let mut res = Matrix::zero(rows, rows);
for row in 0..rows {
for col in 0..mat_a.cols {
// res.data[row][col] = dummy.data[row][col + mat_a.cols];
tmp = dummy.get(row, col + mat_a.get_cols());
res.set(row, col, tmp);
}
}
Ok(res)
}
#[derive(Debug)]
pub enum MathError {
MatrixDimensionDontMatch,
MatrixNotInvertableNotSquare,
MatrixMulNotSquare,
MatrixNotInvertable(usize, usize, f64),
}
| zero | identifier_name |
matrix_invert.rs | use std::error::Error;
use std::ffi::CString;
use std::time::Instant;
use crate::utils::matrix_utils::print_matrix;
use rustacuda::prelude::*;
use std::fmt;
pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> {
// Initialize the CUDA API
rustacuda::init(CudaFlags::empty())?;
// Get the first device
let device = Device::get_device(0)?;
let nx = 4;
let nxy = nx * nx;
let mut matrix_a = vec![0f32; nxy];
let mut blupp = 1f32;
for elem in matrix_a.iter_mut() {
*elem = blupp;
blupp = blupp + 1.0;
}
// ATTENTION: set one element to different value, otherwise it is a singular matrix
let idx = 2;
matrix_a[idx] = matrix_a[idx] + 12.0; // just do it!!!
let idx = 4;
matrix_a[idx] = matrix_a[idx] - 3.0; // just do it!!!
// make a unit matrix
let mut matrix_i = vec![0f32; nxy];
for r in 0..nx {
matrix_i[r * nx + r] = 1.0;
}
println!("orignal matrix_a: ");
print_matrix(&matrix_a, nx, nx);
println!("orignal matrix_i: ");
print_matrix(&matrix_i, nx, nx);
// Create a context associated to this device
let _context =
Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device)?;
let mut d_matrix_a = DeviceBuffer::from_slice(&matrix_a)?;
let mut d_matrix_i = DeviceBuffer::from_slice(&matrix_i)?;
// println!("include_str!(env!(KERNEL_PTX_PATH)) = {}", include_str!(env!("KERNEL_PTX_PATH")));
// Load the module containing the function we want to call
let module_data = CString::new(include_str!(env!("KERNEL_PTX_PATH")))?;
let module = Module::load_from_string(&module_data)?;
// Create a stream to submit work to
let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?;
let blocksize = 1;
let threads_per_block = (blocksize, blocksize, 1);
let b = (blocksize, blocksize, 1);
let block = (b.0 as u32, b.1 as u32, b.2 as u32);
let g = (
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
(nx as i32 + blocksize as i32 - 1) / blocksize as i32,
1 as i32,
);
let grid = (g.0 as u32, g.1 as u32, 1 as u32);
println!("block = {:?}, grid = {:?}", block, grid);
let start = Instant::now();
for i in 0..nx {
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.nodiag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.diag_normalize<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.gaussjordan<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
unsafe {
// Launch the `add` function with one block containing four threads on the stream.
let res = launch!(module.set_zero<<<grid, block, 0, stream>>>(
d_matrix_a.as_device_ptr(),
d_matrix_i.as_device_ptr(),
nx,
i,
block.0,
block.1
));
match res {
Ok(_o) => (),
Err(e) => println!("an error occured: {}", e),
}
}
}
stream.synchronize()?;
let duration_cuda = start.elapsed();
d_matrix_a.copy_to(&mut matrix_a)?;
d_matrix_i.copy_to(&mut matrix_i)?;
println!("duration gpu invert_matrix_2D2D: {:?}", duration_cuda);
println!("gpu result inverted matrix: \n\n");
print_matrix(&matrix_i, nx, nx);
println!("former input matrix ");
print_matrix(&matrix_a, nx, nx);
//
// let start_cpu = Instant::now();
// let res_cpu = invert_matrix_cpu(&matrix_a, nx, ny);
// let duration_cpu = start_cpu.elapsed();
//
// println!("duration cpu: {:?}", duration_cpu);
//
// for x in 0..res_cpu.len() {
// // assert_eq!(res_cpu[x], out_host[x]);
// }
// The kernel launch is asynchronous, so we wait for the kernel to finish executing
Ok(())
}
impl fmt::Display for Matrix {
// This trait requires `fmt` with this exact signature.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\nrows: {}, cols: {}\n", self.rows, self.cols)?;
for row in 0..self.rows {
for col in 0..self.cols {
write!(f, " {} ", self.get(row, col))?;
}
write!(f, "\n ")?;
}
write!(f, "\n ")
}
}
pub fn test_matrix_invert_cpu() {
let mut m = Matrix::zero(3, 3);
m.set(0, 0, 1.0);
m.set(0, 1, 2.0);
m.set(0, 2, 3.0);
m.set(1, 0, 0.0);
m.set(1, 1, 1.0);
m.set(1, 2, 4.0);
m.set(2, 0, 5.0);
m.set(2, 1, 6.0);
m.set(2, 2, 0.0);
let mut expected = Matrix::zero(3, 3);
expected.set(0, 0, -24.0);
expected.set(0, 1, 18.0);
expected.set(0, 2, 5.0);
expected.set(1, 0, 20.0);
expected.set(1, 1, -15.0);
expected.set(1, 2, -4.0);
expected.set(2, 0, -5.0);
expected.set(2, 1, 4.0);
expected.set(2, 2, 1.0);
// calculate the inverse and compare with expected result
let inv = matrix_invert_cpu(&m).unwrap();
assert_eq!(expected, inv);
println!("orignal: {}", m);
println!("inverted: {}", inv);
}
#[derive(Debug, PartialEq, Clone)]
pub struct Matrix {
data: Vec<f32>,
rows: usize,
cols: usize,
}
impl Matrix {
pub fn one(rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![1.0; cols * rows],
}
}
pub fn zero(rows: usize, cols: usize) -> Matrix {
Matrix {
rows: rows,
cols: cols,
data: vec![0.0; cols * rows],
}
}
pub fn identiy(rows: usize) -> Matrix {
let mut m = Matrix::zero(rows, rows);
for i in 0..rows {
m.set(i, i, 1.0);
}
m
}
pub fn get_rows(&self) -> usize {
self.rows
}
pub fn get_cols(&self) -> usize {
self.cols
}
pub fn set(&mut self, row: usize, col: usize, value: f32) -> &mut Matrix {
self.data[row * self.cols + col] = value;
self
}
pub fn get(&self, row: usize, col: usize) -> f32 {
self.data[row * self.cols + col]
}
}
pub fn matrix_invert_cpu(mat_a: &Matrix) -> Result<Matrix, MathError> | // apply all transformations to the identiy matrix as well
cols = 2 * mat_a.cols;
let mut tmp: f32 = 0.0;
for row in 0..rows {
// transform to an upper triangle matrix
// element in main diagonal is used to divide the current row
let mut elem = dummy.get(row, row);
if elem!= 0.0 {
// divide each element in current row by elem -> so A(row,row) = 1
for col in 0..cols {
tmp = dummy.get(row, col);
dummy.set(row, col, tmp / elem);
}
// subtract the line row from all the rows below this row
for row2 in row + 1..rows {
elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
} else {
return Err(MathError::MatrixNotInvertable(row, row, elem as f64));
}
}
// all elements below the main diagonal are 0
// iterate from the last row to the first row and
// set the elements right from the diagonal to 0
// transform to an upper triangle matri
// element in main diagonal is used to divide the current row
for row in (1..rows).rev() {
// transform to an lower triangle matrix
// subtract the line row from all the rows above this row
for row2 in (0..row).rev() {
let elem = dummy.get(row2, row);
for col in 0..cols {
// dummy.data[row2][col] = dummy.data[row2][col] - elem * dummy.data[row][col];
tmp = dummy.get(row2, col) - elem * dummy.get(row, col);
dummy.set(row2, col, tmp);
}
}
}
let mut res = Matrix::zero(rows, rows);
for row in 0..rows {
for col in 0..mat_a.cols {
// res.data[row][col] = dummy.data[row][col + mat_a.cols];
tmp = dummy.get(row, col + mat_a.get_cols());
res.set(row, col, tmp);
}
}
Ok(res)
}
#[derive(Debug)]
pub enum MathError {
MatrixDimensionDontMatch,
MatrixNotInvertableNotSquare,
MatrixMulNotSquare,
MatrixNotInvertable(usize, usize, f64),
}
| {
if mat_a.rows != mat_a.cols {
return Err(MathError::MatrixNotInvertableNotSquare);
}
let rows = mat_a.rows;
let mut cols = mat_a.cols;
// helper matrix for inverting
let mut dummy = Matrix::zero(rows, 2 * cols);
// copy matrix a to dummy (left half of dummy)
for row in 0..rows {
for col in 0..cols {
dummy.set(row, col, mat_a.get(row, col));
}
}
// set identiy matrix elements
for row in 0..rows {
dummy.set(row, cols + row, 1.0);
} | identifier_body |
upb.rs | // Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google LLC. 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
// OWNER 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.
//! UPB FFI wrapper code for use by Rust Protobuf.
use crate::__internal::{Private, RawArena, RawMessage};
use std::alloc;
use std::alloc::Layout;
use std::cell::UnsafeCell;
use std::fmt;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::ptr::{self, NonNull};
use std::slice;
/// See `upb/port/def.inc`.
const UPB_MALLOC_ALIGN: usize = 8;
/// A wrapper over a `upb_Arena`.
///
/// This is not a safe wrapper per se, because the allocation functions still
/// have sharp edges (see their safety docs for more info).
///
/// This is an owning type and will automatically free the arena when
/// dropped.
///
/// Note that this type is neither `Sync` nor `Send`.
#[derive(Debug)]
pub struct Arena {
// Safety invariant: this must always be a valid arena
raw: RawArena,
_not_sync: PhantomData<UnsafeCell<()>>,
}
extern "C" {
// `Option<NonNull<T: Sized>>` is ABI-compatible with `*mut T`
fn upb_Arena_New() -> Option<RawArena>;
fn upb_Arena_Free(arena: RawArena);
fn upb_Arena_Malloc(arena: RawArena, size: usize) -> *mut u8;
fn upb_Arena_Realloc(arena: RawArena, ptr: *mut u8, old: usize, new: usize) -> *mut u8;
}
impl Arena {
/// Allocates a fresh arena.
#[inline]
pub fn new() -> Self {
#[inline(never)]
#[cold]
fn arena_new_failed() ->! {
panic!("Could not create a new UPB arena");
}
// SAFETY:
// - `upb_Arena_New` is assumed to be implemented correctly and always sound to
// call; if it returned a non-null pointer, it is a valid arena.
unsafe {
let Some(raw) = upb_Arena_New() else { arena_new_failed() };
Self { raw, _not_sync: PhantomData }
}
}
/// Returns the raw, UPB-managed pointer to the arena.
#[inline]
pub fn raw(&self) -> RawArena {
self.raw
}
/// Allocates some memory on the arena.
///
/// # Safety
///
/// - `layout`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn alloc(&self, layout: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(layout.align() <= UPB_MALLOC_ALIGN);
// SAFETY: `self.raw` is a valid UPB arena
let ptr = unsafe { upb_Arena_Malloc(self.raw, layout.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
// SAFETY:
// - `upb_Arena_Malloc` promises that if the return pointer is non-null, it is
// dereferencable for `size` bytes and has an alignment of `UPB_MALLOC_ALIGN`
// until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), layout.size()) }
}
/// Resizes some memory on the arena.
///
/// # Safety
///
/// - `ptr` must be the data pointer returned by a previous call to `alloc`
/// or `resize` on `self`.
/// - After calling this function, `ptr` is no longer dereferencable - it is
/// zapped.
/// - `old` must be the layout `ptr` was allocated with via `alloc` or
/// `realloc`.
/// - `new`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn resize(&self, ptr: *mut u8, old: Layout, new: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(new.align() <= UPB_MALLOC_ALIGN);
// SAFETY:
// - `self.raw` is a valid UPB arena
// - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised
// by the caller.
let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()) };
if ptr.is_null() |
// SAFETY:
// - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is
// dereferencable for the new `size` in bytes until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), new.size()) }
}
}
impl Drop for Arena {
#[inline]
fn drop(&mut self) {
unsafe {
upb_Arena_Free(self.raw);
}
}
}
/// Serialized Protobuf wire format data.
///
/// It's typically produced by `<Message>::serialize()`.
pub struct SerializedData {
data: NonNull<u8>,
len: usize,
// The arena that owns `data`.
_arena: Arena,
}
impl SerializedData {
/// Construct `SerializedData` from raw pointers and its owning arena.
///
/// # Safety
/// - `arena` must be have allocated `data`
/// - `data` must be readable for `len` bytes and not mutate while this
/// struct exists
pub unsafe fn from_raw_parts(arena: Arena, data: NonNull<u8>, len: usize) -> Self {
SerializedData { _arena: arena, data, len }
}
/// Gets a raw slice pointer.
pub fn as_ptr(&self) -> *const [u8] {
ptr::slice_from_raw_parts(self.data.as_ptr(), self.len)
}
}
impl Deref for SerializedData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
// SAFETY: `data` is valid for `len` bytes as promised by
// the caller of `SerializedData::from_raw_parts`.
unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
}
}
impl fmt::Debug for SerializedData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.deref(), f)
}
}
// TODO(b/293919363): Investigate replacing this with direct access to UPB bits.
pub type BytesPresentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type BytesAbsentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type InnerBytesMut<'msg> = crate::vtable::RawVTableMutator<'msg, [u8]>;
/// The raw contents of every generated message.
#[derive(Debug)]
pub struct MessageInner {
pub msg: RawMessage,
pub arena: Arena,
}
/// Mutators that point to their original message use this to do so.
///
/// Since UPB expects runtimes to manage their own arenas, this needs to have
/// access to an `Arena`.
///
/// This has two possible designs:
/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
/// place any restriction on the layout of generated messages and their
/// mutators. This makes a vtable-based mutator three pointers, which can no
/// longer be returned in registers on most platforms.
/// - Store one pointer here, `&'msg MessageInner`, where `MessageInner` stores
/// a `RawMessage` and an `Arena`. This would require all generated messages
/// to store `MessageInner`, and since their mutators need to be able to
/// generate `BytesMut`, would also require `BytesMut` to store a `&'msg
/// MessageInner` since they can't store an owned `Arena`.
///
/// Note: even though this type is `Copy`, it should only be copied by
/// protobuf internals that can maintain mutation invariants:
///
/// - No concurrent mutation for any two fields in a message: this means
/// mutators cannot be `Send` but are `Sync`.
/// - If there are multiple accessible `Mut` to a single message at a time, they
/// must be different fields, and not be in the same oneof. As such, a `Mut`
/// cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
/// converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
#[derive(Clone, Copy, Debug)]
pub struct MutatorMessageRef<'msg> {
msg: RawMessage,
arena: &'msg Arena,
}
impl<'msg> MutatorMessageRef<'msg> {
#[doc(hidden)]
#[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
pub fn new(_private: Private, msg: &'msg mut MessageInner) -> Self {
MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
}
pub fn msg(&self) -> RawMessage {
self.msg
}
}
pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>(
msg_ref: MutatorMessageRef<'a>,
val: &'a [u8],
) -> &'a [u8] {
// SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`.
let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) };
debug_assert_eq!(new_alloc.len(), val.len());
let start: *mut u8 = new_alloc.as_mut_ptr().cast();
// SAFETY:
// - `new_alloc` is writeable for `val.len()` bytes.
// - After the copy, `new_alloc` is initialized for `val.len()` bytes.
unsafe {
val.as_ptr().copy_to_nonoverlapping(start, val.len());
&*(new_alloc as *mut _ as *mut [u8])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arena_new_and_free() {
let arena = Arena::new();
drop(arena);
}
#[test]
fn test_serialized_data_roundtrip() {
let arena = Arena::new();
let original_data = b"Hello world";
let len = original_data.len();
let serialized_data = unsafe {
SerializedData::from_raw_parts(
arena,
NonNull::new(original_data as *const _ as *mut _).unwrap(),
len,
)
};
assert_eq!(&*serialized_data, b"Hello world");
}
}
| {
alloc::handle_alloc_error(new);
} | conditional_block |
upb.rs | // Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google LLC. 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
// OWNER 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.
//! UPB FFI wrapper code for use by Rust Protobuf.
use crate::__internal::{Private, RawArena, RawMessage};
use std::alloc;
use std::alloc::Layout;
use std::cell::UnsafeCell;
use std::fmt;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::ptr::{self, NonNull};
use std::slice;
/// See `upb/port/def.inc`.
const UPB_MALLOC_ALIGN: usize = 8;
/// A wrapper over a `upb_Arena`.
///
/// This is not a safe wrapper per se, because the allocation functions still
/// have sharp edges (see their safety docs for more info).
///
/// This is an owning type and will automatically free the arena when
/// dropped.
///
/// Note that this type is neither `Sync` nor `Send`.
#[derive(Debug)]
pub struct Arena {
// Safety invariant: this must always be a valid arena
raw: RawArena,
_not_sync: PhantomData<UnsafeCell<()>>,
}
extern "C" {
// `Option<NonNull<T: Sized>>` is ABI-compatible with `*mut T`
fn upb_Arena_New() -> Option<RawArena>;
fn upb_Arena_Free(arena: RawArena);
fn upb_Arena_Malloc(arena: RawArena, size: usize) -> *mut u8;
fn upb_Arena_Realloc(arena: RawArena, ptr: *mut u8, old: usize, new: usize) -> *mut u8;
}
impl Arena {
/// Allocates a fresh arena.
#[inline]
pub fn new() -> Self {
#[inline(never)]
#[cold]
fn arena_new_failed() ->! {
panic!("Could not create a new UPB arena");
}
// SAFETY:
// - `upb_Arena_New` is assumed to be implemented correctly and always sound to
// call; if it returned a non-null pointer, it is a valid arena.
unsafe {
let Some(raw) = upb_Arena_New() else { arena_new_failed() };
Self { raw, _not_sync: PhantomData }
}
}
/// Returns the raw, UPB-managed pointer to the arena.
#[inline]
pub fn raw(&self) -> RawArena {
self.raw
}
/// Allocates some memory on the arena.
///
/// # Safety
///
/// - `layout`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn alloc(&self, layout: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(layout.align() <= UPB_MALLOC_ALIGN);
// SAFETY: `self.raw` is a valid UPB arena
let ptr = unsafe { upb_Arena_Malloc(self.raw, layout.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
// SAFETY:
// - `upb_Arena_Malloc` promises that if the return pointer is non-null, it is
// dereferencable for `size` bytes and has an alignment of `UPB_MALLOC_ALIGN`
// until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), layout.size()) }
}
/// Resizes some memory on the arena.
///
/// # Safety
///
/// - `ptr` must be the data pointer returned by a previous call to `alloc`
/// or `resize` on `self`.
/// - After calling this function, `ptr` is no longer dereferencable - it is
/// zapped.
/// - `old` must be the layout `ptr` was allocated with via `alloc` or
/// `realloc`.
/// - `new`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn resize(&self, ptr: *mut u8, old: Layout, new: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(new.align() <= UPB_MALLOC_ALIGN);
// SAFETY:
// - `self.raw` is a valid UPB arena
// - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised
// by the caller.
let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(new);
}
// SAFETY:
// - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is
// dereferencable for the new `size` in bytes until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), new.size()) }
}
}
impl Drop for Arena {
#[inline]
fn drop(&mut self) {
unsafe {
upb_Arena_Free(self.raw);
}
}
}
/// Serialized Protobuf wire format data.
///
/// It's typically produced by `<Message>::serialize()`.
pub struct SerializedData {
data: NonNull<u8>,
len: usize,
// The arena that owns `data`.
_arena: Arena,
}
impl SerializedData {
/// Construct `SerializedData` from raw pointers and its owning arena.
///
/// # Safety
/// - `arena` must be have allocated `data`
/// - `data` must be readable for `len` bytes and not mutate while this
/// struct exists
pub unsafe fn from_raw_parts(arena: Arena, data: NonNull<u8>, len: usize) -> Self {
SerializedData { _arena: arena, data, len }
}
/// Gets a raw slice pointer.
pub fn as_ptr(&self) -> *const [u8] {
ptr::slice_from_raw_parts(self.data.as_ptr(), self.len)
}
}
impl Deref for SerializedData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
// SAFETY: `data` is valid for `len` bytes as promised by
// the caller of `SerializedData::from_raw_parts`.
unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
}
}
impl fmt::Debug for SerializedData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.deref(), f)
}
}
// TODO(b/293919363): Investigate replacing this with direct access to UPB bits.
pub type BytesPresentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type BytesAbsentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type InnerBytesMut<'msg> = crate::vtable::RawVTableMutator<'msg, [u8]>;
/// The raw contents of every generated message.
#[derive(Debug)]
pub struct MessageInner {
pub msg: RawMessage,
pub arena: Arena,
}
/// Mutators that point to their original message use this to do so.
///
/// Since UPB expects runtimes to manage their own arenas, this needs to have
/// access to an `Arena`.
///
/// This has two possible designs:
/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
/// place any restriction on the layout of generated messages and their
/// mutators. This makes a vtable-based mutator three pointers, which can no
/// longer be returned in registers on most platforms.
/// - Store one pointer here, `&'msg MessageInner`, where `MessageInner` stores
/// a `RawMessage` and an `Arena`. This would require all generated messages
/// to store `MessageInner`, and since their mutators need to be able to
/// generate `BytesMut`, would also require `BytesMut` to store a `&'msg
/// MessageInner` since they can't store an owned `Arena`.
///
/// Note: even though this type is `Copy`, it should only be copied by
/// protobuf internals that can maintain mutation invariants:
///
/// - No concurrent mutation for any two fields in a message: this means
/// mutators cannot be `Send` but are `Sync`.
/// - If there are multiple accessible `Mut` to a single message at a time, they
/// must be different fields, and not be in the same oneof. As such, a `Mut`
/// cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
/// converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
#[derive(Clone, Copy, Debug)]
pub struct MutatorMessageRef<'msg> {
msg: RawMessage,
arena: &'msg Arena,
}
impl<'msg> MutatorMessageRef<'msg> {
#[doc(hidden)]
#[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
pub fn new(_private: Private, msg: &'msg mut MessageInner) -> Self {
MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
}
pub fn msg(&self) -> RawMessage { | pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>(
msg_ref: MutatorMessageRef<'a>,
val: &'a [u8],
) -> &'a [u8] {
// SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`.
let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) };
debug_assert_eq!(new_alloc.len(), val.len());
let start: *mut u8 = new_alloc.as_mut_ptr().cast();
// SAFETY:
// - `new_alloc` is writeable for `val.len()` bytes.
// - After the copy, `new_alloc` is initialized for `val.len()` bytes.
unsafe {
val.as_ptr().copy_to_nonoverlapping(start, val.len());
&*(new_alloc as *mut _ as *mut [u8])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arena_new_and_free() {
let arena = Arena::new();
drop(arena);
}
#[test]
fn test_serialized_data_roundtrip() {
let arena = Arena::new();
let original_data = b"Hello world";
let len = original_data.len();
let serialized_data = unsafe {
SerializedData::from_raw_parts(
arena,
NonNull::new(original_data as *const _ as *mut _).unwrap(),
len,
)
};
assert_eq!(&*serialized_data, b"Hello world");
}
} | self.msg
}
}
| random_line_split |
upb.rs | // Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google LLC. 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
// OWNER 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.
//! UPB FFI wrapper code for use by Rust Protobuf.
use crate::__internal::{Private, RawArena, RawMessage};
use std::alloc;
use std::alloc::Layout;
use std::cell::UnsafeCell;
use std::fmt;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::ptr::{self, NonNull};
use std::slice;
/// See `upb/port/def.inc`.
const UPB_MALLOC_ALIGN: usize = 8;
/// A wrapper over a `upb_Arena`.
///
/// This is not a safe wrapper per se, because the allocation functions still
/// have sharp edges (see their safety docs for more info).
///
/// This is an owning type and will automatically free the arena when
/// dropped.
///
/// Note that this type is neither `Sync` nor `Send`.
#[derive(Debug)]
pub struct Arena {
// Safety invariant: this must always be a valid arena
raw: RawArena,
_not_sync: PhantomData<UnsafeCell<()>>,
}
extern "C" {
// `Option<NonNull<T: Sized>>` is ABI-compatible with `*mut T`
fn upb_Arena_New() -> Option<RawArena>;
fn upb_Arena_Free(arena: RawArena);
fn upb_Arena_Malloc(arena: RawArena, size: usize) -> *mut u8;
fn upb_Arena_Realloc(arena: RawArena, ptr: *mut u8, old: usize, new: usize) -> *mut u8;
}
impl Arena {
/// Allocates a fresh arena.
#[inline]
pub fn new() -> Self {
#[inline(never)]
#[cold]
fn arena_new_failed() ->! {
panic!("Could not create a new UPB arena");
}
// SAFETY:
// - `upb_Arena_New` is assumed to be implemented correctly and always sound to
// call; if it returned a non-null pointer, it is a valid arena.
unsafe {
let Some(raw) = upb_Arena_New() else { arena_new_failed() };
Self { raw, _not_sync: PhantomData }
}
}
/// Returns the raw, UPB-managed pointer to the arena.
#[inline]
pub fn raw(&self) -> RawArena {
self.raw
}
/// Allocates some memory on the arena.
///
/// # Safety
///
/// - `layout`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn alloc(&self, layout: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(layout.align() <= UPB_MALLOC_ALIGN);
// SAFETY: `self.raw` is a valid UPB arena
let ptr = unsafe { upb_Arena_Malloc(self.raw, layout.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
// SAFETY:
// - `upb_Arena_Malloc` promises that if the return pointer is non-null, it is
// dereferencable for `size` bytes and has an alignment of `UPB_MALLOC_ALIGN`
// until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), layout.size()) }
}
/// Resizes some memory on the arena.
///
/// # Safety
///
/// - `ptr` must be the data pointer returned by a previous call to `alloc`
/// or `resize` on `self`.
/// - After calling this function, `ptr` is no longer dereferencable - it is
/// zapped.
/// - `old` must be the layout `ptr` was allocated with via `alloc` or
/// `realloc`.
/// - `new`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn resize(&self, ptr: *mut u8, old: Layout, new: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(new.align() <= UPB_MALLOC_ALIGN);
// SAFETY:
// - `self.raw` is a valid UPB arena
// - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised
// by the caller.
let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(new);
}
// SAFETY:
// - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is
// dereferencable for the new `size` in bytes until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), new.size()) }
}
}
impl Drop for Arena {
#[inline]
fn drop(&mut self) {
unsafe {
upb_Arena_Free(self.raw);
}
}
}
/// Serialized Protobuf wire format data.
///
/// It's typically produced by `<Message>::serialize()`.
pub struct SerializedData {
data: NonNull<u8>,
len: usize,
// The arena that owns `data`.
_arena: Arena,
}
impl SerializedData {
/// Construct `SerializedData` from raw pointers and its owning arena.
///
/// # Safety
/// - `arena` must be have allocated `data`
/// - `data` must be readable for `len` bytes and not mutate while this
/// struct exists
pub unsafe fn from_raw_parts(arena: Arena, data: NonNull<u8>, len: usize) -> Self {
SerializedData { _arena: arena, data, len }
}
/// Gets a raw slice pointer.
pub fn as_ptr(&self) -> *const [u8] {
ptr::slice_from_raw_parts(self.data.as_ptr(), self.len)
}
}
impl Deref for SerializedData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
// SAFETY: `data` is valid for `len` bytes as promised by
// the caller of `SerializedData::from_raw_parts`.
unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
}
}
impl fmt::Debug for SerializedData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.deref(), f)
}
}
// TODO(b/293919363): Investigate replacing this with direct access to UPB bits.
pub type BytesPresentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type BytesAbsentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type InnerBytesMut<'msg> = crate::vtable::RawVTableMutator<'msg, [u8]>;
/// The raw contents of every generated message.
#[derive(Debug)]
pub struct MessageInner {
pub msg: RawMessage,
pub arena: Arena,
}
/// Mutators that point to their original message use this to do so.
///
/// Since UPB expects runtimes to manage their own arenas, this needs to have
/// access to an `Arena`.
///
/// This has two possible designs:
/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
/// place any restriction on the layout of generated messages and their
/// mutators. This makes a vtable-based mutator three pointers, which can no
/// longer be returned in registers on most platforms.
/// - Store one pointer here, `&'msg MessageInner`, where `MessageInner` stores
/// a `RawMessage` and an `Arena`. This would require all generated messages
/// to store `MessageInner`, and since their mutators need to be able to
/// generate `BytesMut`, would also require `BytesMut` to store a `&'msg
/// MessageInner` since they can't store an owned `Arena`.
///
/// Note: even though this type is `Copy`, it should only be copied by
/// protobuf internals that can maintain mutation invariants:
///
/// - No concurrent mutation for any two fields in a message: this means
/// mutators cannot be `Send` but are `Sync`.
/// - If there are multiple accessible `Mut` to a single message at a time, they
/// must be different fields, and not be in the same oneof. As such, a `Mut`
/// cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
/// converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
#[derive(Clone, Copy, Debug)]
pub struct MutatorMessageRef<'msg> {
msg: RawMessage,
arena: &'msg Arena,
}
impl<'msg> MutatorMessageRef<'msg> {
#[doc(hidden)]
#[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
pub fn | (_private: Private, msg: &'msg mut MessageInner) -> Self {
MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
}
pub fn msg(&self) -> RawMessage {
self.msg
}
}
pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>(
msg_ref: MutatorMessageRef<'a>,
val: &'a [u8],
) -> &'a [u8] {
// SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`.
let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) };
debug_assert_eq!(new_alloc.len(), val.len());
let start: *mut u8 = new_alloc.as_mut_ptr().cast();
// SAFETY:
// - `new_alloc` is writeable for `val.len()` bytes.
// - After the copy, `new_alloc` is initialized for `val.len()` bytes.
unsafe {
val.as_ptr().copy_to_nonoverlapping(start, val.len());
&*(new_alloc as *mut _ as *mut [u8])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arena_new_and_free() {
let arena = Arena::new();
drop(arena);
}
#[test]
fn test_serialized_data_roundtrip() {
let arena = Arena::new();
let original_data = b"Hello world";
let len = original_data.len();
let serialized_data = unsafe {
SerializedData::from_raw_parts(
arena,
NonNull::new(original_data as *const _ as *mut _).unwrap(),
len,
)
};
assert_eq!(&*serialized_data, b"Hello world");
}
}
| new | identifier_name |
upb.rs | // Protocol Buffers - Google's data interchange format
// Copyright 2023 Google LLC. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google LLC. 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
// OWNER 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.
//! UPB FFI wrapper code for use by Rust Protobuf.
use crate::__internal::{Private, RawArena, RawMessage};
use std::alloc;
use std::alloc::Layout;
use std::cell::UnsafeCell;
use std::fmt;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::ptr::{self, NonNull};
use std::slice;
/// See `upb/port/def.inc`.
const UPB_MALLOC_ALIGN: usize = 8;
/// A wrapper over a `upb_Arena`.
///
/// This is not a safe wrapper per se, because the allocation functions still
/// have sharp edges (see their safety docs for more info).
///
/// This is an owning type and will automatically free the arena when
/// dropped.
///
/// Note that this type is neither `Sync` nor `Send`.
#[derive(Debug)]
pub struct Arena {
// Safety invariant: this must always be a valid arena
raw: RawArena,
_not_sync: PhantomData<UnsafeCell<()>>,
}
extern "C" {
// `Option<NonNull<T: Sized>>` is ABI-compatible with `*mut T`
fn upb_Arena_New() -> Option<RawArena>;
fn upb_Arena_Free(arena: RawArena);
fn upb_Arena_Malloc(arena: RawArena, size: usize) -> *mut u8;
fn upb_Arena_Realloc(arena: RawArena, ptr: *mut u8, old: usize, new: usize) -> *mut u8;
}
impl Arena {
/// Allocates a fresh arena.
#[inline]
pub fn new() -> Self {
#[inline(never)]
#[cold]
fn arena_new_failed() ->! {
panic!("Could not create a new UPB arena");
}
// SAFETY:
// - `upb_Arena_New` is assumed to be implemented correctly and always sound to
// call; if it returned a non-null pointer, it is a valid arena.
unsafe {
let Some(raw) = upb_Arena_New() else { arena_new_failed() };
Self { raw, _not_sync: PhantomData }
}
}
/// Returns the raw, UPB-managed pointer to the arena.
#[inline]
pub fn raw(&self) -> RawArena {
self.raw
}
/// Allocates some memory on the arena.
///
/// # Safety
///
/// - `layout`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn alloc(&self, layout: Layout) -> &mut [MaybeUninit<u8>] {
debug_assert!(layout.align() <= UPB_MALLOC_ALIGN);
// SAFETY: `self.raw` is a valid UPB arena
let ptr = unsafe { upb_Arena_Malloc(self.raw, layout.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(layout);
}
// SAFETY:
// - `upb_Arena_Malloc` promises that if the return pointer is non-null, it is
// dereferencable for `size` bytes and has an alignment of `UPB_MALLOC_ALIGN`
// until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), layout.size()) }
}
/// Resizes some memory on the arena.
///
/// # Safety
///
/// - `ptr` must be the data pointer returned by a previous call to `alloc`
/// or `resize` on `self`.
/// - After calling this function, `ptr` is no longer dereferencable - it is
/// zapped.
/// - `old` must be the layout `ptr` was allocated with via `alloc` or
/// `realloc`.
/// - `new`'s alignment must be less than `UPB_MALLOC_ALIGN`.
#[inline]
pub unsafe fn resize(&self, ptr: *mut u8, old: Layout, new: Layout) -> &mut [MaybeUninit<u8>] |
}
impl Drop for Arena {
#[inline]
fn drop(&mut self) {
unsafe {
upb_Arena_Free(self.raw);
}
}
}
/// Serialized Protobuf wire format data.
///
/// It's typically produced by `<Message>::serialize()`.
pub struct SerializedData {
data: NonNull<u8>,
len: usize,
// The arena that owns `data`.
_arena: Arena,
}
impl SerializedData {
/// Construct `SerializedData` from raw pointers and its owning arena.
///
/// # Safety
/// - `arena` must be have allocated `data`
/// - `data` must be readable for `len` bytes and not mutate while this
/// struct exists
pub unsafe fn from_raw_parts(arena: Arena, data: NonNull<u8>, len: usize) -> Self {
SerializedData { _arena: arena, data, len }
}
/// Gets a raw slice pointer.
pub fn as_ptr(&self) -> *const [u8] {
ptr::slice_from_raw_parts(self.data.as_ptr(), self.len)
}
}
impl Deref for SerializedData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
// SAFETY: `data` is valid for `len` bytes as promised by
// the caller of `SerializedData::from_raw_parts`.
unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
}
}
impl fmt::Debug for SerializedData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.deref(), f)
}
}
// TODO(b/293919363): Investigate replacing this with direct access to UPB bits.
pub type BytesPresentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type BytesAbsentMutData<'msg> = crate::vtable::RawVTableOptionalMutatorData<'msg, [u8]>;
pub type InnerBytesMut<'msg> = crate::vtable::RawVTableMutator<'msg, [u8]>;
/// The raw contents of every generated message.
#[derive(Debug)]
pub struct MessageInner {
pub msg: RawMessage,
pub arena: Arena,
}
/// Mutators that point to their original message use this to do so.
///
/// Since UPB expects runtimes to manage their own arenas, this needs to have
/// access to an `Arena`.
///
/// This has two possible designs:
/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
/// place any restriction on the layout of generated messages and their
/// mutators. This makes a vtable-based mutator three pointers, which can no
/// longer be returned in registers on most platforms.
/// - Store one pointer here, `&'msg MessageInner`, where `MessageInner` stores
/// a `RawMessage` and an `Arena`. This would require all generated messages
/// to store `MessageInner`, and since their mutators need to be able to
/// generate `BytesMut`, would also require `BytesMut` to store a `&'msg
/// MessageInner` since they can't store an owned `Arena`.
///
/// Note: even though this type is `Copy`, it should only be copied by
/// protobuf internals that can maintain mutation invariants:
///
/// - No concurrent mutation for any two fields in a message: this means
/// mutators cannot be `Send` but are `Sync`.
/// - If there are multiple accessible `Mut` to a single message at a time, they
/// must be different fields, and not be in the same oneof. As such, a `Mut`
/// cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
/// converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
#[derive(Clone, Copy, Debug)]
pub struct MutatorMessageRef<'msg> {
msg: RawMessage,
arena: &'msg Arena,
}
impl<'msg> MutatorMessageRef<'msg> {
#[doc(hidden)]
#[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
pub fn new(_private: Private, msg: &'msg mut MessageInner) -> Self {
MutatorMessageRef { msg: msg.msg, arena: &msg.arena }
}
pub fn msg(&self) -> RawMessage {
self.msg
}
}
pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>(
msg_ref: MutatorMessageRef<'a>,
val: &'a [u8],
) -> &'a [u8] {
// SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`.
let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) };
debug_assert_eq!(new_alloc.len(), val.len());
let start: *mut u8 = new_alloc.as_mut_ptr().cast();
// SAFETY:
// - `new_alloc` is writeable for `val.len()` bytes.
// - After the copy, `new_alloc` is initialized for `val.len()` bytes.
unsafe {
val.as_ptr().copy_to_nonoverlapping(start, val.len());
&*(new_alloc as *mut _ as *mut [u8])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_arena_new_and_free() {
let arena = Arena::new();
drop(arena);
}
#[test]
fn test_serialized_data_roundtrip() {
let arena = Arena::new();
let original_data = b"Hello world";
let len = original_data.len();
let serialized_data = unsafe {
SerializedData::from_raw_parts(
arena,
NonNull::new(original_data as *const _ as *mut _).unwrap(),
len,
)
};
assert_eq!(&*serialized_data, b"Hello world");
}
}
| {
debug_assert!(new.align() <= UPB_MALLOC_ALIGN);
// SAFETY:
// - `self.raw` is a valid UPB arena
// - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised
// by the caller.
let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()) };
if ptr.is_null() {
alloc::handle_alloc_error(new);
}
// SAFETY:
// - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is
// dereferencable for the new `size` in bytes until the arena is destroyed.
// - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a
// `UPB_MALLOC_ALIGN` boundary.
unsafe { slice::from_raw_parts_mut(ptr.cast(), new.size()) }
} | identifier_body |
more.rs | use crate::librb::uoff_t;
use libc;
use libc::fclose;
use libc::fstat;
use libc::isatty;
use libc::off64_t;
use libc::off_t;
use libc::printf;
use libc::putchar_unlocked;
use libc::stat;
use libc::termios;
use libc::FILE;
extern "C" {
#[no_mangle]
fn _exit(_: libc::c_int) ->!;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
static mut stdin: *mut FILE;
#[no_mangle]
fn getc_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn ftello(__stream: *mut FILE) -> off64_t;
#[no_mangle]
fn fileno_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn tcsetattr(
__fd: libc::c_int,
__optional_actions: libc::c_int,
__termios_p: *const termios,
) -> libc::c_int;
#[no_mangle]
fn bb_signals(sigs: libc::c_int, f: Option<unsafe extern "C" fn(_: libc::c_int) -> ()>);
#[no_mangle]
fn bb_putchar_stderr(ch: libc::c_char) -> libc::c_int;
#[no_mangle]
fn die_if_ferror_stdout();
#[no_mangle]
fn fflush_all() -> libc::c_int;
#[no_mangle]
fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn fopen_for_read(path: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _:...) -> u32;
#[no_mangle]
fn bb_cat(argv: *mut *mut libc::c_char) -> libc::c_int;
#[no_mangle] | ) -> libc::c_int;
#[no_mangle]
fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int;
#[no_mangle]
static mut bb_common_bufsiz1: [libc::c_char; 0];
}
pub type C2RustUnnamed = libc::c_uint;
pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct globals {
pub tty_fileno: libc::c_int,
pub terminal_width: libc::c_uint,
pub terminal_height: libc::c_uint,
pub initial_settings: termios,
}
#[inline(always)]
unsafe extern "C" fn bb_ascii_tolower(mut a: libc::c_uchar) -> libc::c_uchar {
let mut b: libc::c_uchar = (a as libc::c_int - 'A' as i32) as libc::c_uchar;
if b as libc::c_int <= 'Z' as i32 - 'A' as i32 {
a = (a as libc::c_int + ('a' as i32 - 'A' as i32)) as libc::c_uchar
}
return a;
}
unsafe extern "C" fn get_wh() {
/* never returns w, h <= 1 */
get_terminal_width_height(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height,
);
let ref mut fresh0 = (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height;
*fresh0 = (*fresh0).wrapping_sub(1i32 as libc::c_uint);
}
unsafe extern "C" fn tcsetattr_tty_TCSANOW(mut settings: *mut termios) {
tcsetattr(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
0i32,
settings,
);
}
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) {
/* bb_putchar_stderr doesn't use stdio buffering,
* therefore it is safe in signal handler */
bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
_exit(1i32);
}
#[no_mangle]
pub unsafe extern "C" fn more_main(
mut _argc: libc::c_int,
mut argv: *mut *mut libc::c_char,
) -> libc::c_int {
let mut current_block: u64;
let mut c: libc::c_int = 0;
c = c;
let mut input: libc::c_int = 0i32;
let mut spaces: libc::c_int = 0i32;
let mut please_display_more_prompt: libc::c_int = 0;
let mut tty: *mut FILE = 0 as *mut FILE;
/* Parse options */
/* Accepted but ignored: */
/* -d Display help instead of ringing bell */
/* -f Count logical lines (IOW: long lines are not folded) */
/* -l Do not pause after any line containing a ^L (form feed) */
/* -s Squeeze blank lines into one */
/* -u Suppress underlining */
getopt32(argv, b"dflsu\x00" as *const u8 as *const libc::c_char);
argv = argv.offset(optind as isize);
/* Another popular pager, most, detects when stdout
* is not a tty and turns into cat. This makes sense. */
if isatty(1i32) == 0 {
return bb_cat(argv);
}
tty = fopen_for_read(b"/dev/tty\x00" as *const u8 as *const libc::c_char);
if tty.is_null() {
return bb_cat(argv);
}
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno = fileno_unlocked(tty);
/* Turn on unbuffered input; turn off echoing */
set_termios_to_raw(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings,
0i32,
);
bb_signals(
BB_FATAL_SIGS as libc::c_int,
Some(gotsig as unsafe extern "C" fn(_: libc::c_int) -> ()),
);
's_75: loop {
let mut st: stat = std::mem::zeroed();
let mut file: *mut FILE = 0 as *mut FILE;
let mut len: libc::c_int = 0;
let mut lines: libc::c_int = 0;
file = stdin;
if!(*argv).is_null() {
file = fopen_or_warn(*argv, b"r\x00" as *const u8 as *const libc::c_char);
if file.is_null() {
current_block = 12349973810996921269;
} else {
current_block = 15089075282327824602;
}
} else {
current_block = 15089075282327824602;
}
match current_block {
15089075282327824602 => {
st.st_size = 0i32 as off_t;
fstat(fileno_unlocked(file), &mut st);
get_wh();
please_display_more_prompt = 0i32;
len = 0i32;
lines = 0i32;
loop {
let mut wrap: libc::c_int = 0;
if spaces!= 0 {
spaces -= 1
} else {
c = getc_unlocked(file);
if c == -1i32 {
break;
}
}
loop
/* if tty was destroyed (closed xterm, etc) */
/* Then outputting this will also put a character on
* the beginning of that new line. Thus we first want to
* display the prompt (if any), so we skip the putchar()
* and go back to the top of the loop, without reading
* a new character. */
{
if input!= 'r' as i32 && please_display_more_prompt!= 0 {
len = printf(b"--More-- \x00" as *const u8 as *const libc::c_char);
if st.st_size!= 0 {
let mut d: uoff_t = (st.st_size as uoff_t).wrapping_div(100i32 as libc::c_ulong);
if d == 0i32 as libc::c_ulong {
d = 1i32 as uoff_t
}
len += printf(
b"(%u%% of %lu bytes)\x00" as *const u8 as *const libc::c_char,
(ftello(file) as uoff_t).wrapping_div(d) as libc::c_int,
st.st_size,
)
}
loop
/*
* We've just displayed the "--More--" prompt, so now we need
* to get input from the user.
*/
{
fflush_all();
input = getc_unlocked(tty);
input = bb_ascii_tolower(input as libc::c_uchar) as libc::c_int;
/* Erase the last message */
printf(
b"\r%*s\r\x00" as *const u8 as *const libc::c_char,
len,
b"\x00" as *const u8 as *const libc::c_char,
);
if input == 'q' as i32 {
break's_75;
}
/* Due to various multibyte escape
* sequences, it's not ok to accept
* any input as a command to scroll
* the screen. We only allow known
* commands, else we show help msg. */
if input =='' as i32 || input == '\n' as i32 || input == 'r' as i32 {
break;
}
len = printf(
b"(Enter:next line Space:next page Q:quit R:show the rest)\x00" as *const u8
as *const libc::c_char,
)
}
len = 0i32;
lines = 0i32;
please_display_more_prompt = 0i32;
/* The user may have resized the terminal.
* Re-read the dimensions. */
get_wh();
}
/* Crudely convert tabs into spaces, which are
* a bajillion times easier to deal with. */
if c == '\t' as i32 {
spaces = (!len as libc::c_uint).wrapping_rem(8i32 as libc::c_uint) as libc::c_int;
c ='' as i32
}
/*
* There are two input streams to worry about here:
*
* c : the character we are reading from the file being "mored"
* input: a character received from the keyboard
*
* If we hit a newline in the _file_ stream, we want to test and
* see if any characters have been hit in the _input_ stream. This
* allows the user to quit while in the middle of a file.
*/
len += 1;
wrap = (len as libc::c_uint
> (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width)
as libc::c_int;
if c == '\n' as i32 || wrap!= 0 {
/* Then outputting this character
* will move us to a new line. */
lines += 1;
if lines as libc::c_uint
>= (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height
|| input == '\n' as i32
{
please_display_more_prompt = 1i32
}
len = 0i32
}
if!(c!= '\n' as i32 && wrap!= 0) {
break;
}
}
/* My small mind cannot fathom backspaces and UTF-8 */
putchar_unlocked(c);
die_if_ferror_stdout();
}
fclose(file);
fflush_all();
}
_ => {}
}
if!(!(*argv).is_null() && {
argv = argv.offset(1);
!(*argv).is_null()
}) {
break;
}
}
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
return 0i32;
} | fn get_terminal_width_height(
fd: libc::c_int,
width: *mut libc::c_uint,
height: *mut libc::c_uint, | random_line_split |
more.rs | use crate::librb::uoff_t;
use libc;
use libc::fclose;
use libc::fstat;
use libc::isatty;
use libc::off64_t;
use libc::off_t;
use libc::printf;
use libc::putchar_unlocked;
use libc::stat;
use libc::termios;
use libc::FILE;
extern "C" {
#[no_mangle]
fn _exit(_: libc::c_int) ->!;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
static mut stdin: *mut FILE;
#[no_mangle]
fn getc_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn ftello(__stream: *mut FILE) -> off64_t;
#[no_mangle]
fn fileno_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn tcsetattr(
__fd: libc::c_int,
__optional_actions: libc::c_int,
__termios_p: *const termios,
) -> libc::c_int;
#[no_mangle]
fn bb_signals(sigs: libc::c_int, f: Option<unsafe extern "C" fn(_: libc::c_int) -> ()>);
#[no_mangle]
fn bb_putchar_stderr(ch: libc::c_char) -> libc::c_int;
#[no_mangle]
fn die_if_ferror_stdout();
#[no_mangle]
fn fflush_all() -> libc::c_int;
#[no_mangle]
fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn fopen_for_read(path: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _:...) -> u32;
#[no_mangle]
fn bb_cat(argv: *mut *mut libc::c_char) -> libc::c_int;
#[no_mangle]
fn get_terminal_width_height(
fd: libc::c_int,
width: *mut libc::c_uint,
height: *mut libc::c_uint,
) -> libc::c_int;
#[no_mangle]
fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int;
#[no_mangle]
static mut bb_common_bufsiz1: [libc::c_char; 0];
}
pub type C2RustUnnamed = libc::c_uint;
pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct globals {
pub tty_fileno: libc::c_int,
pub terminal_width: libc::c_uint,
pub terminal_height: libc::c_uint,
pub initial_settings: termios,
}
#[inline(always)]
unsafe extern "C" fn bb_ascii_tolower(mut a: libc::c_uchar) -> libc::c_uchar {
let mut b: libc::c_uchar = (a as libc::c_int - 'A' as i32) as libc::c_uchar;
if b as libc::c_int <= 'Z' as i32 - 'A' as i32 {
a = (a as libc::c_int + ('a' as i32 - 'A' as i32)) as libc::c_uchar
}
return a;
}
unsafe extern "C" fn get_wh() {
/* never returns w, h <= 1 */
get_terminal_width_height(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height,
);
let ref mut fresh0 = (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height;
*fresh0 = (*fresh0).wrapping_sub(1i32 as libc::c_uint);
}
unsafe extern "C" fn tcsetattr_tty_TCSANOW(mut settings: *mut termios) |
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) {
/* bb_putchar_stderr doesn't use stdio buffering,
* therefore it is safe in signal handler */
bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
_exit(1i32);
}
#[no_mangle]
pub unsafe extern "C" fn more_main(
mut _argc: libc::c_int,
mut argv: *mut *mut libc::c_char,
) -> libc::c_int {
let mut current_block: u64;
let mut c: libc::c_int = 0;
c = c;
let mut input: libc::c_int = 0i32;
let mut spaces: libc::c_int = 0i32;
let mut please_display_more_prompt: libc::c_int = 0;
let mut tty: *mut FILE = 0 as *mut FILE;
/* Parse options */
/* Accepted but ignored: */
/* -d Display help instead of ringing bell */
/* -f Count logical lines (IOW: long lines are not folded) */
/* -l Do not pause after any line containing a ^L (form feed) */
/* -s Squeeze blank lines into one */
/* -u Suppress underlining */
getopt32(argv, b"dflsu\x00" as *const u8 as *const libc::c_char);
argv = argv.offset(optind as isize);
/* Another popular pager, most, detects when stdout
* is not a tty and turns into cat. This makes sense. */
if isatty(1i32) == 0 {
return bb_cat(argv);
}
tty = fopen_for_read(b"/dev/tty\x00" as *const u8 as *const libc::c_char);
if tty.is_null() {
return bb_cat(argv);
}
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno = fileno_unlocked(tty);
/* Turn on unbuffered input; turn off echoing */
set_termios_to_raw(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings,
0i32,
);
bb_signals(
BB_FATAL_SIGS as libc::c_int,
Some(gotsig as unsafe extern "C" fn(_: libc::c_int) -> ()),
);
's_75: loop {
let mut st: stat = std::mem::zeroed();
let mut file: *mut FILE = 0 as *mut FILE;
let mut len: libc::c_int = 0;
let mut lines: libc::c_int = 0;
file = stdin;
if!(*argv).is_null() {
file = fopen_or_warn(*argv, b"r\x00" as *const u8 as *const libc::c_char);
if file.is_null() {
current_block = 12349973810996921269;
} else {
current_block = 15089075282327824602;
}
} else {
current_block = 15089075282327824602;
}
match current_block {
15089075282327824602 => {
st.st_size = 0i32 as off_t;
fstat(fileno_unlocked(file), &mut st);
get_wh();
please_display_more_prompt = 0i32;
len = 0i32;
lines = 0i32;
loop {
let mut wrap: libc::c_int = 0;
if spaces!= 0 {
spaces -= 1
} else {
c = getc_unlocked(file);
if c == -1i32 {
break;
}
}
loop
/* if tty was destroyed (closed xterm, etc) */
/* Then outputting this will also put a character on
* the beginning of that new line. Thus we first want to
* display the prompt (if any), so we skip the putchar()
* and go back to the top of the loop, without reading
* a new character. */
{
if input!= 'r' as i32 && please_display_more_prompt!= 0 {
len = printf(b"--More-- \x00" as *const u8 as *const libc::c_char);
if st.st_size!= 0 {
let mut d: uoff_t = (st.st_size as uoff_t).wrapping_div(100i32 as libc::c_ulong);
if d == 0i32 as libc::c_ulong {
d = 1i32 as uoff_t
}
len += printf(
b"(%u%% of %lu bytes)\x00" as *const u8 as *const libc::c_char,
(ftello(file) as uoff_t).wrapping_div(d) as libc::c_int,
st.st_size,
)
}
loop
/*
* We've just displayed the "--More--" prompt, so now we need
* to get input from the user.
*/
{
fflush_all();
input = getc_unlocked(tty);
input = bb_ascii_tolower(input as libc::c_uchar) as libc::c_int;
/* Erase the last message */
printf(
b"\r%*s\r\x00" as *const u8 as *const libc::c_char,
len,
b"\x00" as *const u8 as *const libc::c_char,
);
if input == 'q' as i32 {
break's_75;
}
/* Due to various multibyte escape
* sequences, it's not ok to accept
* any input as a command to scroll
* the screen. We only allow known
* commands, else we show help msg. */
if input =='' as i32 || input == '\n' as i32 || input == 'r' as i32 {
break;
}
len = printf(
b"(Enter:next line Space:next page Q:quit R:show the rest)\x00" as *const u8
as *const libc::c_char,
)
}
len = 0i32;
lines = 0i32;
please_display_more_prompt = 0i32;
/* The user may have resized the terminal.
* Re-read the dimensions. */
get_wh();
}
/* Crudely convert tabs into spaces, which are
* a bajillion times easier to deal with. */
if c == '\t' as i32 {
spaces = (!len as libc::c_uint).wrapping_rem(8i32 as libc::c_uint) as libc::c_int;
c ='' as i32
}
/*
* There are two input streams to worry about here:
*
* c : the character we are reading from the file being "mored"
* input: a character received from the keyboard
*
* If we hit a newline in the _file_ stream, we want to test and
* see if any characters have been hit in the _input_ stream. This
* allows the user to quit while in the middle of a file.
*/
len += 1;
wrap = (len as libc::c_uint
> (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width)
as libc::c_int;
if c == '\n' as i32 || wrap!= 0 {
/* Then outputting this character
* will move us to a new line. */
lines += 1;
if lines as libc::c_uint
>= (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height
|| input == '\n' as i32
{
please_display_more_prompt = 1i32
}
len = 0i32
}
if!(c!= '\n' as i32 && wrap!= 0) {
break;
}
}
/* My small mind cannot fathom backspaces and UTF-8 */
putchar_unlocked(c);
die_if_ferror_stdout();
}
fclose(file);
fflush_all();
}
_ => {}
}
if!(!(*argv).is_null() && {
argv = argv.offset(1);
!(*argv).is_null()
}) {
break;
}
}
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
return 0i32;
}
| {
tcsetattr(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
0i32,
settings,
);
} | identifier_body |
more.rs | use crate::librb::uoff_t;
use libc;
use libc::fclose;
use libc::fstat;
use libc::isatty;
use libc::off64_t;
use libc::off_t;
use libc::printf;
use libc::putchar_unlocked;
use libc::stat;
use libc::termios;
use libc::FILE;
extern "C" {
#[no_mangle]
fn _exit(_: libc::c_int) ->!;
#[no_mangle]
static mut optind: libc::c_int;
#[no_mangle]
static mut stdin: *mut FILE;
#[no_mangle]
fn getc_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn ftello(__stream: *mut FILE) -> off64_t;
#[no_mangle]
fn fileno_unlocked(__stream: *mut FILE) -> libc::c_int;
#[no_mangle]
fn tcsetattr(
__fd: libc::c_int,
__optional_actions: libc::c_int,
__termios_p: *const termios,
) -> libc::c_int;
#[no_mangle]
fn bb_signals(sigs: libc::c_int, f: Option<unsafe extern "C" fn(_: libc::c_int) -> ()>);
#[no_mangle]
fn bb_putchar_stderr(ch: libc::c_char) -> libc::c_int;
#[no_mangle]
fn die_if_ferror_stdout();
#[no_mangle]
fn fflush_all() -> libc::c_int;
#[no_mangle]
fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn fopen_for_read(path: *const libc::c_char) -> *mut FILE;
#[no_mangle]
fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _:...) -> u32;
#[no_mangle]
fn bb_cat(argv: *mut *mut libc::c_char) -> libc::c_int;
#[no_mangle]
fn get_terminal_width_height(
fd: libc::c_int,
width: *mut libc::c_uint,
height: *mut libc::c_uint,
) -> libc::c_int;
#[no_mangle]
fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int;
#[no_mangle]
static mut bb_common_bufsiz1: [libc::c_char; 0];
}
pub type C2RustUnnamed = libc::c_uint;
pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct globals {
pub tty_fileno: libc::c_int,
pub terminal_width: libc::c_uint,
pub terminal_height: libc::c_uint,
pub initial_settings: termios,
}
#[inline(always)]
unsafe extern "C" fn bb_ascii_tolower(mut a: libc::c_uchar) -> libc::c_uchar {
let mut b: libc::c_uchar = (a as libc::c_int - 'A' as i32) as libc::c_uchar;
if b as libc::c_int <= 'Z' as i32 - 'A' as i32 {
a = (a as libc::c_int + ('a' as i32 - 'A' as i32)) as libc::c_uchar
}
return a;
}
unsafe extern "C" fn get_wh() {
/* never returns w, h <= 1 */
get_terminal_width_height(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height,
);
let ref mut fresh0 = (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height;
*fresh0 = (*fresh0).wrapping_sub(1i32 as libc::c_uint);
}
unsafe extern "C" fn | (mut settings: *mut termios) {
tcsetattr(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
0i32,
settings,
);
}
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) {
/* bb_putchar_stderr doesn't use stdio buffering,
* therefore it is safe in signal handler */
bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
_exit(1i32);
}
#[no_mangle]
pub unsafe extern "C" fn more_main(
mut _argc: libc::c_int,
mut argv: *mut *mut libc::c_char,
) -> libc::c_int {
let mut current_block: u64;
let mut c: libc::c_int = 0;
c = c;
let mut input: libc::c_int = 0i32;
let mut spaces: libc::c_int = 0i32;
let mut please_display_more_prompt: libc::c_int = 0;
let mut tty: *mut FILE = 0 as *mut FILE;
/* Parse options */
/* Accepted but ignored: */
/* -d Display help instead of ringing bell */
/* -f Count logical lines (IOW: long lines are not folded) */
/* -l Do not pause after any line containing a ^L (form feed) */
/* -s Squeeze blank lines into one */
/* -u Suppress underlining */
getopt32(argv, b"dflsu\x00" as *const u8 as *const libc::c_char);
argv = argv.offset(optind as isize);
/* Another popular pager, most, detects when stdout
* is not a tty and turns into cat. This makes sense. */
if isatty(1i32) == 0 {
return bb_cat(argv);
}
tty = fopen_for_read(b"/dev/tty\x00" as *const u8 as *const libc::c_char);
if tty.is_null() {
return bb_cat(argv);
}
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno = fileno_unlocked(tty);
/* Turn on unbuffered input; turn off echoing */
set_termios_to_raw(
(*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno,
&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings,
0i32,
);
bb_signals(
BB_FATAL_SIGS as libc::c_int,
Some(gotsig as unsafe extern "C" fn(_: libc::c_int) -> ()),
);
's_75: loop {
let mut st: stat = std::mem::zeroed();
let mut file: *mut FILE = 0 as *mut FILE;
let mut len: libc::c_int = 0;
let mut lines: libc::c_int = 0;
file = stdin;
if!(*argv).is_null() {
file = fopen_or_warn(*argv, b"r\x00" as *const u8 as *const libc::c_char);
if file.is_null() {
current_block = 12349973810996921269;
} else {
current_block = 15089075282327824602;
}
} else {
current_block = 15089075282327824602;
}
match current_block {
15089075282327824602 => {
st.st_size = 0i32 as off_t;
fstat(fileno_unlocked(file), &mut st);
get_wh();
please_display_more_prompt = 0i32;
len = 0i32;
lines = 0i32;
loop {
let mut wrap: libc::c_int = 0;
if spaces!= 0 {
spaces -= 1
} else {
c = getc_unlocked(file);
if c == -1i32 {
break;
}
}
loop
/* if tty was destroyed (closed xterm, etc) */
/* Then outputting this will also put a character on
* the beginning of that new line. Thus we first want to
* display the prompt (if any), so we skip the putchar()
* and go back to the top of the loop, without reading
* a new character. */
{
if input!= 'r' as i32 && please_display_more_prompt!= 0 {
len = printf(b"--More-- \x00" as *const u8 as *const libc::c_char);
if st.st_size!= 0 {
let mut d: uoff_t = (st.st_size as uoff_t).wrapping_div(100i32 as libc::c_ulong);
if d == 0i32 as libc::c_ulong {
d = 1i32 as uoff_t
}
len += printf(
b"(%u%% of %lu bytes)\x00" as *const u8 as *const libc::c_char,
(ftello(file) as uoff_t).wrapping_div(d) as libc::c_int,
st.st_size,
)
}
loop
/*
* We've just displayed the "--More--" prompt, so now we need
* to get input from the user.
*/
{
fflush_all();
input = getc_unlocked(tty);
input = bb_ascii_tolower(input as libc::c_uchar) as libc::c_int;
/* Erase the last message */
printf(
b"\r%*s\r\x00" as *const u8 as *const libc::c_char,
len,
b"\x00" as *const u8 as *const libc::c_char,
);
if input == 'q' as i32 {
break's_75;
}
/* Due to various multibyte escape
* sequences, it's not ok to accept
* any input as a command to scroll
* the screen. We only allow known
* commands, else we show help msg. */
if input =='' as i32 || input == '\n' as i32 || input == 'r' as i32 {
break;
}
len = printf(
b"(Enter:next line Space:next page Q:quit R:show the rest)\x00" as *const u8
as *const libc::c_char,
)
}
len = 0i32;
lines = 0i32;
please_display_more_prompt = 0i32;
/* The user may have resized the terminal.
* Re-read the dimensions. */
get_wh();
}
/* Crudely convert tabs into spaces, which are
* a bajillion times easier to deal with. */
if c == '\t' as i32 {
spaces = (!len as libc::c_uint).wrapping_rem(8i32 as libc::c_uint) as libc::c_int;
c ='' as i32
}
/*
* There are two input streams to worry about here:
*
* c : the character we are reading from the file being "mored"
* input: a character received from the keyboard
*
* If we hit a newline in the _file_ stream, we want to test and
* see if any characters have been hit in the _input_ stream. This
* allows the user to quit while in the middle of a file.
*/
len += 1;
wrap = (len as libc::c_uint
> (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_width)
as libc::c_int;
if c == '\n' as i32 || wrap!= 0 {
/* Then outputting this character
* will move us to a new line. */
lines += 1;
if lines as libc::c_uint
>= (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).terminal_height
|| input == '\n' as i32
{
please_display_more_prompt = 1i32
}
len = 0i32
}
if!(c!= '\n' as i32 && wrap!= 0) {
break;
}
}
/* My small mind cannot fathom backspaces and UTF-8 */
putchar_unlocked(c);
die_if_ferror_stdout();
}
fclose(file);
fflush_all();
}
_ => {}
}
if!(!(*argv).is_null() && {
argv = argv.offset(1);
!(*argv).is_null()
}) {
break;
}
}
tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings);
return 0i32;
}
| tcsetattr_tty_TCSANOW | identifier_name |
point_cloud.rs | 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.
*/
//! The actual point cloud
use indexmap::IndexMap;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::fmt;
use glob::{glob_with, MatchOptions};
use std::io::Read;
use yaml_rust::{Yaml, YamlLoader};
use std::marker::PhantomData;
use std::cmp::min;
use rayon::prelude::*;
use super::*;
use super::errors::*;
use super::labels::*;
use super::labels::values::*;
use crate::datasources::*;
use crate::datasources::DataSource;
use super::distances::*;
use crate::utils::*;
/// This abstracts away data access and the distance calculation. It handles both the labels and
/// points.
///
pub struct PointCloud<M: Metric> {
addresses: IndexMap<PointIndex, (usize,usize)>,
names_to_indexes: IndexMap<PointName, PointIndex>,
indexes_to_names: IndexMap<PointIndex, PointName>,
data_sources: Vec<Box<dyn DataSource>>,
label_sources: Vec<MetadataList>,
loaded_centers: Mutex<IndexMap<PointIndex, Arc<Vec<f32>>>>,
data_dim: usize,
labels_scheme: LabelScheme,
chunk:usize,
metric: PhantomData<M>,
}
impl<M: Metric> fmt::Debug for PointCloud<M> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"PointCloud {{ number of points: {}, number of memmaps: {}}}",
self.addresses.len(), self.data_sources.len()
)
}
}
impl<M: Metric> PointCloud<M> {
/// Builds the point cloud from a collection of memmaps. If you want it to load all the data
/// into ram, pass a true for the ram.
pub fn from_memmap_files(
data_dim: usize,
labels_scheme: LabelScheme,
data_path: &[PathBuf],
labels_path: &[PathBuf],
ram: bool,
) -> PointCloudResult<PointCloud<M>> {
if data_path.len()!= labels_path.len() {
panic!(
"Mismatch of label and data paths Data: {:?}, Labels: {:?}",
data_path, labels_path
);
}
let mut addresses = IndexMap::new();
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
let mut current_count: u64 = 0;
let mut data_sources = Vec::new();
let mut label_sources = Vec::new();
for (i,(dp,lp)) in data_path.iter().zip(labels_path).enumerate() {
let new_data: Box<dyn DataSource>;
if ram {
new_data = Box::new((DataMemmap::new(data_dim, &dp)?).convert_to_ram());
} else {
new_data = Box::new(DataMemmap::new(data_dim, &dp)?);
}
let new_labels = labels_scheme.open(&lp)?;
if new_data.len()!= new_labels.len() {
panic!("The data count {:?} differs from the label count {:?} for the {}th data and label files", new_data.len(), new_labels.len(), i);
}
for j in 0..new_data.len() {
let x = (i, j);
let name = new_labels
.get_name(j)
.unwrap_or_else(|| format!("{}", current_count));
if names_to_indexes.contains_key(&name) {
println!(
"Duplicate {:?} on line {} of file {:?}",
&name, j, labels_path[i]
);
} else {
names_to_indexes.insert(name.clone(), current_count);
indexes_to_names.insert(current_count, name.clone());
addresses.insert(current_count, x);
}
current_count += 1;
}
data_sources.push(new_data);
label_sources.push(new_labels);
}
// This could possibly be improved to be architecture specific. It depends on the CPU cache size
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: data_sources,
label_sources: label_sources,
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
labels_scheme,
loaded_centers: Mutex::new(IndexMap::new()),
chunk,
metric: PhantomData,
})
}
/// Builds the point cloud from data in ram.
/// This is for complex metadata
pub fn from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: MetadataList,
) -> PointCloudResult<PointCloud<M>> {
let mut addresses = IndexMap::new();
let data_source = Box::new(DataRam::new(data_dim, data)?);
let labels_scheme = labels.scheme()?;
let label_source = labels;
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
for j in 0..(data_source.len()) {
let name = label_source.get_name(j).unwrap_or_else(|| format!("{}", j));
if names_to_indexes.contains_key(&name) {
println!("Duplicate {:?} on line {} of file", &name, j);
} else {
names_to_indexes.insert(name.clone(), j as PointIndex);
indexes_to_names.insert(j as PointIndex, name.clone());
addresses.insert(j as u64, (0,j));
}
}
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: vec![data_source],
label_sources: vec![label_source],
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
loaded_centers: Mutex::new(IndexMap::new()),
labels_scheme,
chunk,
metric: PhantomData,
})
}
/// Given a yaml file on disk, it builds a point cloud. Minimal example below.
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// labels_dim: 10
/// in_ram: True
/// ```
/// This assumes that your labels are either a CSV or a memmap file.
/// If one specifies a schema then this is the minimal example
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// schema:
/// natural: u32
/// integer: i32
/// real: f32
/// string: String
/// boolean: bool
/// ```
pub fn from_yaml(params: &Yaml) -> PointCloudResult<PointCloud<M>> {
let data_paths = &get_file_list(
params["data_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let labels_paths = &get_file_list(
params["labels_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let data_dim = params["data_dim"]
.as_i64()
.expect("Unable to read the 'data_dim'") as usize;
let mut deser = LabelScheme::new();
if params["schema"].is_badvalue() {
let labels_dim = params["labels_dim"]
.as_i64()
.expect("Unable to read the 'labels_dim' or the'schema'")
as usize;
deser.add_vector("y".to_string(), labels_dim, "f32");
} else {
build_label_schema_yaml(&mut deser, ¶ms["schema"]);
}
let ram_bool = match params["in_ram"].as_bool() {
Some(b) => b,
None => true,
};
PointCloud::<M>::from_memmap_files(data_dim, deser, data_paths, labels_paths, ram_bool)
}
/// Runs `from_yaml` on the file at a given path
pub fn from_file<P: AsRef<Path>>(path: P) -> PointCloudResult<PointCloud<M>> {
let mut config_file =
File::open(&path).expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let mut config = String::new();
config_file
.read_to_string(&mut config)
.expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let params_files = YamlLoader::load_from_str(&config).unwrap();
PointCloud::<M>::from_yaml(¶ms_files[0])
}
/// Builds the point cloud from data in ram. This is for quick things with simple metadata
pub fn simple_from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: Box<[f32]>,
labels_dim: usize,
) -> PointCloudResult<PointCloud<M>> {
assert!(data.len() / data_dim == labels.len() / labels_dim);
let list = MetadataList::simple_vec(labels, labels_dim);
PointCloud::<M>::from_ram(data, data_dim, list)
}
/// Total number of points in the point cloud
pub fn len(&self) -> usize {
self.data_sources.iter().fold(0, |acc, mm| acc + mm.len())
}
/// Dimension of the data in the point cloud
pub fn dim(&self) -> usize {
self.data_dim
}
/// The names of the data are currently a shallow wrapper around a usize.
pub fn reference_indexes(&self) -> Vec<PointIndex> {
self.addresses.keys().cloned().collect()
}
/// Returns a arc that points to a AVX2 packed point. This also acts like a cache for these center
/// points to ensure that we don't load multiple copies into memory. Used for heavily
/// referenced points, like centers.
pub fn get_center(&self, pn: PointIndex) -> PointCloudResult<Arc<Vec<f32>>> {
let mut loaded_centers = self.loaded_centers.lock().unwrap();
Ok(Arc::clone(
loaded_centers
.entry(pn)
.or_insert(Arc::new(Vec::from(self.get_point(pn)?))),
))
}
#[inline]
fn get_address(&self,pn: PointIndex) -> PointCloudResult<(usize,usize)> {
match self.addresses.get(&pn) {
Some((i, j)) => Ok((*i,*j)),
None => panic!("Index not found"),
}
}
/// Returns a slice corresponding to the point in question. Used for rarely referenced points,
/// like outliers or leaves.
pub fn get_point(&self, pn: PointIndex) -> PointCloudResult<&[f32]> {
let (i,j) = self.get_address(pn)?;
self.data_sources[i].get(j)
}
/// Gets the name from an index
pub fn get_name(&self, pi: &PointIndex) -> Option<&PointName> {
self.indexes_to_names.get(pi)
}
/// Gets the index from the name
pub fn get_index(&self, pn: &PointName) -> Option<&PointIndex> {
self.names_to_indexes.get(pn)
}
/// Gets all names in the point cloud
pub fn get_names(&self) -> Vec<PointName> {
self.names_to_indexes.keys().cloned().collect()
}
/// Gets a schema to use
pub fn schema_json(&self) -> String {
self.labels_scheme.schema_json()
}
/// Returns the label of a point.
///
/// This will be changed to return a label structure that can contain many different pieces of info.
pub fn get_metadata(&self, pn: PointIndex) -> PointCloudResult<Metadata> {
let (i,j) = self.get_address(pn)?;
self.label_sources[i].get(j)
}
/// Returns a complex summary of a collection of metadatas associated to a point
pub fn get_metasummary(&self, pns: &[PointIndex]) -> PointCloudResult<MetaSummary> {
let mut disk_splits: Vec<Vec<usize>> = vec![Vec::new(); self.label_sources.len()];
for pn in pns.iter() {
let (i,j) = self.get_address(*pn)?;
disk_splits[i].push(j);
}
let disk_summaries: Vec<MetaSummary> = disk_splits
.iter()
.enumerate()
.map(|(i, indexes)| self.label_sources[i].get_summary(indexes).unwrap())
.collect();
MetaSummary::combine(&disk_summaries)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_indices(
&self,
is: &[PointIndex],
js: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let mut dists: Vec<f32> = vec![0.0;is.len()*js.len()];
if is.len()*js.len() > self.chunk {
let dist_iter = dists.par_chunks_mut(js.len());
let indexes_iter = is.par_iter().map(|i| (i,js));
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,(i,chunk_indexes))| {
match self.get_point(*i) {
Ok(x) => {
for (d,j) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*j) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
},
Err(e) => {
*error.lock().unwrap() = Err(e);
}
};
});
(error.into_inner().unwrap())?;
} else {
for (k,i) in is.iter().enumerate() {
let x = self.get_point(*i)?;
for (l,j) in js.iter().enumerate() {
let y = self.get_point(*j)?;
dists[k*js.len() + l] = (M::dense)(x, y);
}
}
}
Ok(dists)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_index(
&self,
i: PointIndex,
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
self.distances_to_point(self.get_point(i)?,indexes)
}
/// Create and adjacency matrix
pub fn adj(&self,
mut indexes: &[PointIndex],
) -> PointCloudResult<AdjMatrix> {
let mut vals = HashMap::new();
while indexes.len() > 1 {
let i = indexes[0];
indexes = &indexes[1..];
let distances = self.distances_to_point_index(i, &indexes)?;
indexes.iter().zip(distances).for_each(|(j, d)| {
if i < *j {
vals.insert((i, *j), d);
} else {
vals.insert((*j, i), d);
}
});
}
Ok(AdjMatrix { vals })
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point(
&self,
x: &[f32],
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let len = indexes.len();
if len > self.chunk * 3 {
let mut dists: Vec<f32> = vec![0.0;len];
let dist_iter = dists.par_chunks_mut(self.chunk);
let indexes_iter = indexes.par_chunks(self.chunk);
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,chunk_indexes)| {
for (d,i) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*i) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
});
(error.into_inner().unwrap())?;
Ok(dists)
} else {
indexes
.iter()
.map(|i| {
let y = self.get_point(*i)?;
Ok((M::dense)(x, y))
})
.collect()
}
}
}
fn build_label_schema_yaml(label_scheme: &mut LabelScheme, schema_yaml: &Yaml) | }
fn get_file_list(files_reg: &str) -> Vec<PathBuf> {
let options = MatchOptions {
case_sensitive: false,
..Default::default()
};
let mut paths = Vec::new();
let glob_paths = match glob_with(files_reg, &options) {
Ok(expr) => expr,
Err(e) => panic!("Pattern reading error {:?}", e),
};
for entry in glob_paths {
let path = match entry {
| {
if let Some(schema_map) = schema_yaml.as_hash() {
for (k, v) in schema_map.iter() {
let key = k.as_str().unwrap().to_string();
match v.as_str().unwrap() {
"u32" => label_scheme.add_u32(key),
"f32" => label_scheme.add_f32(key),
"i32" => label_scheme.add_i32(key),
"bool" => label_scheme.add_bool(key),
"string" => label_scheme.add_string(key),
"name" => label_scheme.add_name_column(&key),
_ => panic!(
"Unknown type in schema yaml, also it should be (VALUE: TYPE): {:?}",
(k, v)
),
}
}
} else {
panic!("Need to correctly edit the yaml");
} | identifier_body |
point_cloud.rs | 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.
*/
//! The actual point cloud
use indexmap::IndexMap;
use std::collections::HashMap;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::fmt;
use glob::{glob_with, MatchOptions};
use std::io::Read;
use yaml_rust::{Yaml, YamlLoader};
use std::marker::PhantomData;
use std::cmp::min;
use rayon::prelude::*;
use super::*;
use super::errors::*;
use super::labels::*;
use super::labels::values::*;
use crate::datasources::*;
use crate::datasources::DataSource;
use super::distances::*;
use crate::utils::*;
/// This abstracts away data access and the distance calculation. It handles both the labels and
/// points.
///
pub struct PointCloud<M: Metric> {
addresses: IndexMap<PointIndex, (usize,usize)>,
names_to_indexes: IndexMap<PointName, PointIndex>,
indexes_to_names: IndexMap<PointIndex, PointName>,
data_sources: Vec<Box<dyn DataSource>>,
label_sources: Vec<MetadataList>,
loaded_centers: Mutex<IndexMap<PointIndex, Arc<Vec<f32>>>>,
data_dim: usize,
labels_scheme: LabelScheme,
chunk:usize,
metric: PhantomData<M>,
}
impl<M: Metric> fmt::Debug for PointCloud<M> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"PointCloud {{ number of points: {}, number of memmaps: {}}}",
self.addresses.len(), self.data_sources.len()
)
}
}
impl<M: Metric> PointCloud<M> {
/// Builds the point cloud from a collection of memmaps. If you want it to load all the data
/// into ram, pass a true for the ram.
pub fn from_memmap_files(
data_dim: usize,
labels_scheme: LabelScheme,
data_path: &[PathBuf],
labels_path: &[PathBuf],
ram: bool,
) -> PointCloudResult<PointCloud<M>> {
if data_path.len()!= labels_path.len() {
panic!(
"Mismatch of label and data paths Data: {:?}, Labels: {:?}",
data_path, labels_path
);
}
let mut addresses = IndexMap::new();
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
let mut current_count: u64 = 0;
let mut data_sources = Vec::new();
let mut label_sources = Vec::new();
for (i,(dp,lp)) in data_path.iter().zip(labels_path).enumerate() {
let new_data: Box<dyn DataSource>;
if ram {
new_data = Box::new((DataMemmap::new(data_dim, &dp)?).convert_to_ram());
} else {
new_data = Box::new(DataMemmap::new(data_dim, &dp)?);
}
let new_labels = labels_scheme.open(&lp)?;
if new_data.len()!= new_labels.len() {
panic!("The data count {:?} differs from the label count {:?} for the {}th data and label files", new_data.len(), new_labels.len(), i);
}
for j in 0..new_data.len() {
let x = (i, j);
let name = new_labels
.get_name(j)
.unwrap_or_else(|| format!("{}", current_count));
if names_to_indexes.contains_key(&name) {
println!(
"Duplicate {:?} on line {} of file {:?}",
&name, j, labels_path[i]
);
} else {
names_to_indexes.insert(name.clone(), current_count);
indexes_to_names.insert(current_count, name.clone());
addresses.insert(current_count, x);
}
current_count += 1;
}
data_sources.push(new_data);
label_sources.push(new_labels);
}
// This could possibly be improved to be architecture specific. It depends on the CPU cache size
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: data_sources,
label_sources: label_sources,
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
labels_scheme,
loaded_centers: Mutex::new(IndexMap::new()),
chunk,
metric: PhantomData,
})
}
/// Builds the point cloud from data in ram.
/// This is for complex metadata
pub fn from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: MetadataList,
) -> PointCloudResult<PointCloud<M>> {
let mut addresses = IndexMap::new();
let data_source = Box::new(DataRam::new(data_dim, data)?);
let labels_scheme = labels.scheme()?;
let label_source = labels;
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
for j in 0..(data_source.len()) {
let name = label_source.get_name(j).unwrap_or_else(|| format!("{}", j));
if names_to_indexes.contains_key(&name) {
println!("Duplicate {:?} on line {} of file", &name, j);
} else {
names_to_indexes.insert(name.clone(), j as PointIndex);
indexes_to_names.insert(j as PointIndex, name.clone());
addresses.insert(j as u64, (0,j));
}
}
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: vec![data_source],
label_sources: vec![label_source],
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
loaded_centers: Mutex::new(IndexMap::new()),
labels_scheme,
chunk,
metric: PhantomData,
})
}
/// Given a yaml file on disk, it builds a point cloud. Minimal example below.
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// labels_dim: 10
/// in_ram: True
/// ```
/// This assumes that your labels are either a CSV or a memmap file.
/// If one specifies a schema then this is the minimal example
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// schema:
/// natural: u32
/// integer: i32
/// real: f32
/// string: String
/// boolean: bool
/// ```
pub fn from_yaml(params: &Yaml) -> PointCloudResult<PointCloud<M>> {
let data_paths = &get_file_list(
params["data_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let labels_paths = &get_file_list(
params["labels_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let data_dim = params["data_dim"]
.as_i64()
.expect("Unable to read the 'data_dim'") as usize;
let mut deser = LabelScheme::new();
if params["schema"].is_badvalue() {
let labels_dim = params["labels_dim"]
.as_i64()
.expect("Unable to read the 'labels_dim' or the'schema'")
as usize;
deser.add_vector("y".to_string(), labels_dim, "f32");
} else {
build_label_schema_yaml(&mut deser, ¶ms["schema"]);
}
let ram_bool = match params["in_ram"].as_bool() {
Some(b) => b,
None => true,
};
PointCloud::<M>::from_memmap_files(data_dim, deser, data_paths, labels_paths, ram_bool)
}
/// Runs `from_yaml` on the file at a given path
pub fn from_file<P: AsRef<Path>>(path: P) -> PointCloudResult<PointCloud<M>> {
let mut config_file =
File::open(&path).expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let mut config = String::new();
config_file
.read_to_string(&mut config)
.expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let params_files = YamlLoader::load_from_str(&config).unwrap();
PointCloud::<M>::from_yaml(¶ms_files[0])
}
/// Builds the point cloud from data in ram. This is for quick things with simple metadata
pub fn simple_from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: Box<[f32]>,
labels_dim: usize,
) -> PointCloudResult<PointCloud<M>> {
assert!(data.len() / data_dim == labels.len() / labels_dim);
let list = MetadataList::simple_vec(labels, labels_dim);
PointCloud::<M>::from_ram(data, data_dim, list)
}
/// Total number of points in the point cloud
pub fn | (&self) -> usize {
self.data_sources.iter().fold(0, |acc, mm| acc + mm.len())
}
/// Dimension of the data in the point cloud
pub fn dim(&self) -> usize {
self.data_dim
}
/// The names of the data are currently a shallow wrapper around a usize.
pub fn reference_indexes(&self) -> Vec<PointIndex> {
self.addresses.keys().cloned().collect()
}
/// Returns a arc that points to a AVX2 packed point. This also acts like a cache for these center
/// points to ensure that we don't load multiple copies into memory. Used for heavily
/// referenced points, like centers.
pub fn get_center(&self, pn: PointIndex) -> PointCloudResult<Arc<Vec<f32>>> {
let mut loaded_centers = self.loaded_centers.lock().unwrap();
Ok(Arc::clone(
loaded_centers
.entry(pn)
.or_insert(Arc::new(Vec::from(self.get_point(pn)?))),
))
}
#[inline]
fn get_address(&self,pn: PointIndex) -> PointCloudResult<(usize,usize)> {
match self.addresses.get(&pn) {
Some((i, j)) => Ok((*i,*j)),
None => panic!("Index not found"),
}
}
/// Returns a slice corresponding to the point in question. Used for rarely referenced points,
/// like outliers or leaves.
pub fn get_point(&self, pn: PointIndex) -> PointCloudResult<&[f32]> {
let (i,j) = self.get_address(pn)?;
self.data_sources[i].get(j)
}
/// Gets the name from an index
pub fn get_name(&self, pi: &PointIndex) -> Option<&PointName> {
self.indexes_to_names.get(pi)
}
/// Gets the index from the name
pub fn get_index(&self, pn: &PointName) -> Option<&PointIndex> {
self.names_to_indexes.get(pn)
}
/// Gets all names in the point cloud
pub fn get_names(&self) -> Vec<PointName> {
self.names_to_indexes.keys().cloned().collect()
}
/// Gets a schema to use
pub fn schema_json(&self) -> String {
self.labels_scheme.schema_json()
}
/// Returns the label of a point.
///
/// This will be changed to return a label structure that can contain many different pieces of info.
pub fn get_metadata(&self, pn: PointIndex) -> PointCloudResult<Metadata> {
let (i,j) = self.get_address(pn)?;
self.label_sources[i].get(j)
}
/// Returns a complex summary of a collection of metadatas associated to a point
pub fn get_metasummary(&self, pns: &[PointIndex]) -> PointCloudResult<MetaSummary> {
let mut disk_splits: Vec<Vec<usize>> = vec![Vec::new(); self.label_sources.len()];
for pn in pns.iter() {
let (i,j) = self.get_address(*pn)?;
disk_splits[i].push(j);
}
let disk_summaries: Vec<MetaSummary> = disk_splits
.iter()
.enumerate()
.map(|(i, indexes)| self.label_sources[i].get_summary(indexes).unwrap())
.collect();
MetaSummary::combine(&disk_summaries)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_indices(
&self,
is: &[PointIndex],
js: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let mut dists: Vec<f32> = vec![0.0;is.len()*js.len()];
if is.len()*js.len() > self.chunk {
let dist_iter = dists.par_chunks_mut(js.len());
let indexes_iter = is.par_iter().map(|i| (i,js));
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,(i,chunk_indexes))| {
match self.get_point(*i) {
Ok(x) => {
for (d,j) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*j) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
},
Err(e) => {
*error.lock().unwrap() = Err(e);
}
};
});
(error.into_inner().unwrap())?;
} else {
for (k,i) in is.iter().enumerate() {
let x = self.get_point(*i)?;
for (l,j) in js.iter().enumerate() {
let y = self.get_point(*j)?;
dists[k*js.len() + l] = (M::dense)(x, y);
}
}
}
Ok(dists)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_index(
&self,
i: PointIndex,
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
self.distances_to_point(self.get_point(i)?,indexes)
}
/// Create and adjacency matrix
pub fn adj(&self,
mut indexes: &[PointIndex],
) -> PointCloudResult<AdjMatrix> {
let mut vals = HashMap::new();
while indexes.len() > 1 {
let i = indexes[0];
indexes = &indexes[1..];
let distances = self.distances_to_point_index(i, &indexes)?;
indexes.iter().zip(distances).for_each(|(j, d)| {
if i < *j {
vals.insert((i, *j), d);
} else {
vals.insert((*j, i), d);
}
});
}
Ok(AdjMatrix { vals })
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point(
&self,
x: &[f32],
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let len = indexes.len();
if len > self.chunk * 3 {
let mut dists: Vec<f32> = vec![0.0;len];
let dist_iter = dists.par_chunks_mut(self.chunk);
let indexes_iter = indexes.par_chunks(self.chunk);
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,chunk_indexes)| {
for (d,i) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*i) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
});
(error.into_inner().unwrap())?;
Ok(dists)
} else {
indexes
.iter()
.map(|i| {
let y = self.get_point(*i)?;
Ok((M::dense)(x, y))
})
.collect()
}
}
}
fn build_label_schema_yaml(label_scheme: &mut LabelScheme, schema_yaml: &Yaml) {
if let Some(schema_map) = schema_yaml.as_hash() {
for (k, v) in schema_map.iter() {
let key = k.as_str().unwrap().to_string();
match v.as_str().unwrap() {
"u32" => label_scheme.add_u32(key),
"f32" => label_scheme.add_f32(key),
"i32" => label_scheme.add_i32(key),
"bool" => label_scheme.add_bool(key),
"string" => label_scheme.add_string(key),
"name" => label_scheme.add_name_column(&key),
_ => panic!(
"Unknown type in schema yaml, also it should be (VALUE: TYPE): {:?}",
(k, v)
),
}
}
} else {
panic!("Need to correctly edit the yaml");
}
}
fn get_file_list(files_reg: &str) -> Vec<PathBuf> {
let options = MatchOptions {
case_sensitive: false,
..Default::default()
};
let mut paths = Vec::new();
let glob_paths = match glob_with(files_reg, &options) {
Ok(expr) => expr,
Err(e) => panic!("Pattern reading error {:?}", e),
};
for entry in glob_paths {
let path = match entry {
| len | identifier_name |
point_cloud.rs | path::PathBuf;
use std::sync::{Arc, Mutex};
use std::fmt;
use glob::{glob_with, MatchOptions};
use std::io::Read;
use yaml_rust::{Yaml, YamlLoader};
use std::marker::PhantomData;
use std::cmp::min;
use rayon::prelude::*;
use super::*;
use super::errors::*;
use super::labels::*;
use super::labels::values::*;
use crate::datasources::*;
use crate::datasources::DataSource;
use super::distances::*;
use crate::utils::*;
/// This abstracts away data access and the distance calculation. It handles both the labels and
/// points.
///
pub struct PointCloud<M: Metric> {
addresses: IndexMap<PointIndex, (usize,usize)>,
names_to_indexes: IndexMap<PointName, PointIndex>,
indexes_to_names: IndexMap<PointIndex, PointName>,
data_sources: Vec<Box<dyn DataSource>>,
label_sources: Vec<MetadataList>,
loaded_centers: Mutex<IndexMap<PointIndex, Arc<Vec<f32>>>>,
data_dim: usize,
labels_scheme: LabelScheme,
chunk:usize,
metric: PhantomData<M>,
}
impl<M: Metric> fmt::Debug for PointCloud<M> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"PointCloud {{ number of points: {}, number of memmaps: {}}}",
self.addresses.len(), self.data_sources.len()
)
}
}
impl<M: Metric> PointCloud<M> {
/// Builds the point cloud from a collection of memmaps. If you want it to load all the data
/// into ram, pass a true for the ram.
pub fn from_memmap_files(
data_dim: usize,
labels_scheme: LabelScheme,
data_path: &[PathBuf],
labels_path: &[PathBuf],
ram: bool,
) -> PointCloudResult<PointCloud<M>> {
if data_path.len()!= labels_path.len() {
panic!(
"Mismatch of label and data paths Data: {:?}, Labels: {:?}",
data_path, labels_path
);
}
let mut addresses = IndexMap::new();
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
let mut current_count: u64 = 0;
let mut data_sources = Vec::new();
let mut label_sources = Vec::new();
for (i,(dp,lp)) in data_path.iter().zip(labels_path).enumerate() {
let new_data: Box<dyn DataSource>;
if ram {
new_data = Box::new((DataMemmap::new(data_dim, &dp)?).convert_to_ram());
} else {
new_data = Box::new(DataMemmap::new(data_dim, &dp)?);
}
let new_labels = labels_scheme.open(&lp)?;
if new_data.len()!= new_labels.len() {
panic!("The data count {:?} differs from the label count {:?} for the {}th data and label files", new_data.len(), new_labels.len(), i);
}
for j in 0..new_data.len() {
let x = (i, j);
let name = new_labels
.get_name(j)
.unwrap_or_else(|| format!("{}", current_count));
if names_to_indexes.contains_key(&name) {
println!(
"Duplicate {:?} on line {} of file {:?}",
&name, j, labels_path[i]
);
} else {
names_to_indexes.insert(name.clone(), current_count);
indexes_to_names.insert(current_count, name.clone());
addresses.insert(current_count, x);
}
current_count += 1;
}
data_sources.push(new_data);
label_sources.push(new_labels);
}
// This could possibly be improved to be architecture specific. It depends on the CPU cache size
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: data_sources,
label_sources: label_sources,
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
labels_scheme,
loaded_centers: Mutex::new(IndexMap::new()),
chunk,
metric: PhantomData,
})
}
/// Builds the point cloud from data in ram.
/// This is for complex metadata
pub fn from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: MetadataList,
) -> PointCloudResult<PointCloud<M>> {
let mut addresses = IndexMap::new();
let data_source = Box::new(DataRam::new(data_dim, data)?);
let labels_scheme = labels.scheme()?;
let label_source = labels;
let mut names_to_indexes: IndexMap<PointName, PointIndex> = IndexMap::new();
let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new();
for j in 0..(data_source.len()) {
let name = label_source.get_name(j).unwrap_or_else(|| format!("{}", j));
if names_to_indexes.contains_key(&name) {
println!("Duplicate {:?} on line {} of file", &name, j);
} else {
names_to_indexes.insert(name.clone(), j as PointIndex);
indexes_to_names.insert(j as PointIndex, name.clone());
addresses.insert(j as u64, (0,j));
}
}
let chunk = min(15000/data_dim,20);
Ok(PointCloud {
data_sources: vec![data_source],
label_sources: vec![label_source],
names_to_indexes: names_to_indexes,
indexes_to_names: indexes_to_names,
addresses: addresses,
data_dim,
loaded_centers: Mutex::new(IndexMap::new()),
labels_scheme,
chunk,
metric: PhantomData,
})
}
/// Given a yaml file on disk, it builds a point cloud. Minimal example below.
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// labels_dim: 10
/// in_ram: True
/// ```
/// This assumes that your labels are either a CSV or a memmap file.
/// If one specifies a schema then this is the minimal example
/// ```yaml
/// ---
/// data_path: DATAMEMMAP
/// labels_path: LABELS_CSV_OR_MEMMAP
/// count: NUMBER_OF_DATA_POINTS
/// data_dim: 784
/// schema:
/// natural: u32
/// integer: i32
/// real: f32
/// string: String
/// boolean: bool
/// ```
pub fn from_yaml(params: &Yaml) -> PointCloudResult<PointCloud<M>> {
let data_paths = &get_file_list(
params["data_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let labels_paths = &get_file_list(
params["labels_path"]
.as_str()
.expect("Unable to read the 'labels_path'"),
);
let data_dim = params["data_dim"]
.as_i64()
.expect("Unable to read the 'data_dim'") as usize;
let mut deser = LabelScheme::new();
if params["schema"].is_badvalue() {
let labels_dim = params["labels_dim"]
.as_i64()
.expect("Unable to read the 'labels_dim' or the'schema'")
as usize;
deser.add_vector("y".to_string(), labels_dim, "f32");
} else {
build_label_schema_yaml(&mut deser, ¶ms["schema"]);
}
let ram_bool = match params["in_ram"].as_bool() {
Some(b) => b,
None => true,
};
PointCloud::<M>::from_memmap_files(data_dim, deser, data_paths, labels_paths, ram_bool)
}
/// Runs `from_yaml` on the file at a given path
pub fn from_file<P: AsRef<Path>>(path: P) -> PointCloudResult<PointCloud<M>> {
let mut config_file =
File::open(&path).expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let mut config = String::new();
config_file
.read_to_string(&mut config)
.expect(&format!("Unable to read config file {:?}", &path.as_ref()));
let params_files = YamlLoader::load_from_str(&config).unwrap();
PointCloud::<M>::from_yaml(¶ms_files[0])
}
/// Builds the point cloud from data in ram. This is for quick things with simple metadata
pub fn simple_from_ram(
data: Box<[f32]>,
data_dim: usize,
labels: Box<[f32]>,
labels_dim: usize,
) -> PointCloudResult<PointCloud<M>> {
assert!(data.len() / data_dim == labels.len() / labels_dim);
let list = MetadataList::simple_vec(labels, labels_dim);
PointCloud::<M>::from_ram(data, data_dim, list)
}
/// Total number of points in the point cloud
pub fn len(&self) -> usize {
self.data_sources.iter().fold(0, |acc, mm| acc + mm.len())
}
/// Dimension of the data in the point cloud
pub fn dim(&self) -> usize {
self.data_dim
}
/// The names of the data are currently a shallow wrapper around a usize.
pub fn reference_indexes(&self) -> Vec<PointIndex> {
self.addresses.keys().cloned().collect()
}
/// Returns a arc that points to a AVX2 packed point. This also acts like a cache for these center
/// points to ensure that we don't load multiple copies into memory. Used for heavily
/// referenced points, like centers.
pub fn get_center(&self, pn: PointIndex) -> PointCloudResult<Arc<Vec<f32>>> {
let mut loaded_centers = self.loaded_centers.lock().unwrap();
Ok(Arc::clone(
loaded_centers
.entry(pn)
.or_insert(Arc::new(Vec::from(self.get_point(pn)?))),
))
}
#[inline]
fn get_address(&self,pn: PointIndex) -> PointCloudResult<(usize,usize)> {
match self.addresses.get(&pn) {
Some((i, j)) => Ok((*i,*j)),
None => panic!("Index not found"),
}
}
/// Returns a slice corresponding to the point in question. Used for rarely referenced points,
/// like outliers or leaves.
pub fn get_point(&self, pn: PointIndex) -> PointCloudResult<&[f32]> {
let (i,j) = self.get_address(pn)?;
self.data_sources[i].get(j)
}
/// Gets the name from an index
pub fn get_name(&self, pi: &PointIndex) -> Option<&PointName> {
self.indexes_to_names.get(pi)
}
/// Gets the index from the name
pub fn get_index(&self, pn: &PointName) -> Option<&PointIndex> {
self.names_to_indexes.get(pn)
}
/// Gets all names in the point cloud
pub fn get_names(&self) -> Vec<PointName> {
self.names_to_indexes.keys().cloned().collect()
}
/// Gets a schema to use
pub fn schema_json(&self) -> String {
self.labels_scheme.schema_json()
}
/// Returns the label of a point.
///
/// This will be changed to return a label structure that can contain many different pieces of info.
pub fn get_metadata(&self, pn: PointIndex) -> PointCloudResult<Metadata> {
let (i,j) = self.get_address(pn)?;
self.label_sources[i].get(j)
}
/// Returns a complex summary of a collection of metadatas associated to a point
pub fn get_metasummary(&self, pns: &[PointIndex]) -> PointCloudResult<MetaSummary> {
let mut disk_splits: Vec<Vec<usize>> = vec![Vec::new(); self.label_sources.len()];
for pn in pns.iter() {
let (i,j) = self.get_address(*pn)?;
disk_splits[i].push(j);
}
let disk_summaries: Vec<MetaSummary> = disk_splits
.iter()
.enumerate()
.map(|(i, indexes)| self.label_sources[i].get_summary(indexes).unwrap())
.collect();
MetaSummary::combine(&disk_summaries)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_indices(
&self,
is: &[PointIndex],
js: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let mut dists: Vec<f32> = vec![0.0;is.len()*js.len()];
if is.len()*js.len() > self.chunk {
let dist_iter = dists.par_chunks_mut(js.len());
let indexes_iter = is.par_iter().map(|i| (i,js));
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,(i,chunk_indexes))| {
match self.get_point(*i) {
Ok(x) => {
for (d,j) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*j) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
},
Err(e) => {
*error.lock().unwrap() = Err(e);
}
};
});
(error.into_inner().unwrap())?;
} else {
for (k,i) in is.iter().enumerate() {
let x = self.get_point(*i)?;
for (l,j) in js.iter().enumerate() {
let y = self.get_point(*j)?;
dists[k*js.len() + l] = (M::dense)(x, y);
}
}
}
Ok(dists)
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point_index(
&self,
i: PointIndex,
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
self.distances_to_point(self.get_point(i)?,indexes)
}
/// Create and adjacency matrix
pub fn adj(&self,
mut indexes: &[PointIndex],
) -> PointCloudResult<AdjMatrix> {
let mut vals = HashMap::new();
while indexes.len() > 1 {
let i = indexes[0];
indexes = &indexes[1..];
let distances = self.distances_to_point_index(i, &indexes)?;
indexes.iter().zip(distances).for_each(|(j, d)| {
if i < *j {
vals.insert((i, *j), d);
} else {
vals.insert((*j, i), d);
}
});
}
Ok(AdjMatrix { vals })
}
/// The main distance function. This paralizes if there are more than 100 points.
pub fn distances_to_point(
&self,
x: &[f32],
indexes: &[PointIndex],
) -> PointCloudResult<Vec<f32>> {
let len = indexes.len();
if len > self.chunk * 3 {
let mut dists: Vec<f32> = vec![0.0;len];
let dist_iter = dists.par_chunks_mut(self.chunk);
let indexes_iter = indexes.par_chunks(self.chunk);
let error: Mutex<Result<(), PointCloudError>> = Mutex::new(Ok(()));
dist_iter.zip(indexes_iter).for_each(|(chunk_dists,chunk_indexes)| {
for (d,i) in chunk_dists.iter_mut().zip(chunk_indexes) {
match self.get_point(*i) {
Ok(y) => *d = (M::dense)(x, y),
Err(e) => {
*error.lock().unwrap() = Err(e);
}
}
}
});
(error.into_inner().unwrap())?;
Ok(dists)
} else {
indexes
.iter()
.map(|i| {
let y = self.get_point(*i)?;
Ok((M::dense)(x, y))
})
.collect()
}
}
}
fn build_label_schema_yaml(label_scheme: &mut LabelScheme, schema_yaml: &Yaml) {
if let Some(schema_map) = schema_yaml.as_hash() {
for (k, v) in schema_map.iter() {
let key = k.as_str().unwrap().to_string();
match v.as_str().unwrap() {
"u32" => label_scheme.add_u32(key),
"f32" => label_scheme.add_f32(key),
"i32" => label_scheme.add_i32(key),
"bool" => label_scheme.add_bool(key),
"string" => label_scheme.add_string(key),
"name" => label_scheme.add_name_column(&key),
_ => panic!(
"Unknown type in schema yaml, also it should be (VALUE: TYPE): {:?}",
(k, v)
),
}
}
} else {
panic!("Need to correctly edit the yaml");
}
}
fn get_file_list(files_reg: &str) -> Vec<PathBuf> {
let options = MatchOptions {
case_sensitive: false,
..Default::default()
};
let mut paths = Vec::new();
let glob_paths = match glob_with(files_reg, &options) {
Ok(expr) => expr,
Err(e) => panic!("Pattern reading error {:?}", e),
};
for entry in glob_paths {
let path = match entry {
Ok(expr) => expr,
Err(e) => panic!("Error reading path {:?}", e),
};
paths.push(path)
}
paths
}
/*
#[cfg(test)]
mod tests { | random_line_split |
||
day_15.rs | mod point;
mod astar;
use {
crate::{
astar::Pathfinder,
point::{
Point,
Neighbors,
},
},
std::{
fmt,
cmp::Ordering,
collections::{
HashSet,
HashMap,
},
time::Instant,
usize,
},
rayon::prelude::*,
};
pub struct ManhattanDistHeuristic;
impl astar::Heuristic for ManhattanDistHeuristic {
type Item = Point;
type Score = usize;
fn score(from: &Point, to: &Point) -> usize { from.manhattan_dist_to(*to) }
fn zero_score() -> usize { 0 }
fn infinity_score() -> usize { usize::MAX }
}
pub struct CavernWorld;
impl astar::World for CavernWorld {
type Point = Point;
type Score = usize;
type Neighbors = Neighbors;
type Heuristic = ManhattanDistHeuristic;
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() }
fn neighbor_dist() -> usize { 1 }
fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) }
}
type CavernPathfinder = Pathfinder<CavernWorld>;
#[derive(Copy, Clone, Eq, PartialEq)]
enum Team {
Elf,
Goblin,
}
impl fmt::Display for Team {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match self {
Team::Goblin => "Goblin",
Team::Elf => "Elf",
})
}
}
#[derive(Clone)]
struct Fighter {
team: Team,
pos: Point,
hp: isize,
}
const BASE_ATTACK_POWER: isize = 3;
impl Fighter {
fn new(team: Team, pos: Point) -> Self {
Self {
team,
pos,
hp: 200,
}
}
}
impl fmt::Debug for Fighter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Fighter ( {} @ {} )", self.team, self.pos)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Tile {
Empty,
Blocked,
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Tile::Empty => write!(f, "."),
Tile::Blocked => write!(f, "#"),
}
}
}
#[derive(Clone)]
struct Cavern {
tiles: Vec<Tile>,
width: usize,
height: usize,
fighters: Vec<Fighter>,
fighter_positions: HashMap<Point, usize>,
elf_attack_power: isize,
}
impl Cavern {
fn parse(s: &str) -> Self {
let mut width = 0;
let mut height = 0;
let mut fighters = Vec::new();
let mut tiles = Vec::new();
for (y, line) in s.lines().enumerate() {
height += 1;
width = line.len(); // assume all lines are the same length
for (x, char) in line.chars().enumerate() {
let point = Point::new(x as isize, y as isize);
match char {
'#' => tiles.push(Tile::Blocked),
'E' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Elf, point));
}
'G' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Goblin, point));
}
_ => tiles.push(Tile::Empty),
}
}
}
let mut cavern = Self {
tiles,
width,
height,
fighters,
fighter_positions: HashMap::new(),
elf_attack_power: BASE_ATTACK_POWER,
};
cavern.refresh_fighter_positions();
cavern
}
fn refresh_fighter_positions(&mut self) {
self.fighter_positions.clear();
for (i, f) in self.fighters.iter().enumerate() {
self.fighter_positions.insert(f.pos, i);
}
}
fn is_free_space(&self, point: Point) -> bool {
match self.tile_at(point) {
Tile::Empty => self.fighter_at(point).is_none(),
Tile::Blocked => false,
}
}
fn fighter_at(&self, point: Point) -> Option<usize> {
self.fighter_positions.get(&point)
.filter(|&&i| self.fighters[i].hp > 0)
.cloned()
}
fn tile_at(&self, point: Point) -> Tile {
let off = self.width as isize * point.y + point.x;
if off >= 0 && off < self.tiles.len() as isize {
self.tiles[off as usize]
} else {
Tile::Blocked
}
}
fn find_targets(&self, i: usize, targets: &mut Vec<usize>) {
targets.clear();
let fighter = &self.fighters[i];
targets.extend(self.fighters.iter().enumerate()
.filter(|(_, other)| other.hp > 0)
.filter_map(|(j, other)| if other.team!= fighter.team {
Some(j)
} else {
None
}));
}
fn move_fighter(&mut self, i: usize, targets: &[usize], pathfinder: &mut CavernPathfinder) {
let fighter = &self.fighters[i];
let dests: HashSet<_> = targets.iter()
.flat_map(|j| {
let target_pos = self.fighters[*j].pos;
target_pos.neighbors_reading_order()
})
.filter(|p| self.is_free_space(*p) || *p == fighter.pos)
.collect();
if!dests.contains(&fighter.pos) | let b_dest = *b.last().unwrap();
// sort first by shortest paths...
match a.len().cmp(&b.len()) {
// then by origin pos in reading order
Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest),
dest_order => dest_order,
}
});
if!paths.is_empty() {
// move this fighter to the first step of the chosen path
self.fighters[i].pos = paths[0][0];
self.refresh_fighter_positions();
}
}
}
fn resolve_attacks(&mut self, i: usize) {
let neighbors = self.fighters[i].pos.neighbors_reading_order();
let target_index = neighbors
.filter_map(|neighbor| {
self.fighters.iter().enumerate()
.filter_map(|(j, f)| {
if f.pos == neighbor
&& f.hp > 0
&& f.team!= self.fighters[i].team {
Some(j)
} else {
None
}
})
.next()
})
.min_by(|a, b| {
let a = &self.fighters[*a];
let b = &self.fighters[*b];
match a.hp.cmp(&b.hp) {
Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos),
hp_order => hp_order,
}
});
if let Some(j) = target_index {
let attack_power = match self.fighters[i].team {
Team::Elf => self.elf_attack_power,
Team::Goblin => BASE_ATTACK_POWER,
};
self.fighters[j].hp = isize::max(0, self.fighters[j].hp - attack_power);
}
}
fn tick(&mut self, pathfinder: &mut CavernPathfinder) -> Option<Team> {
let mut targets = Vec::new();
self.fighters.sort_by(|a, b| Point::cmp_reading_order(a.pos, b.pos));
self.refresh_fighter_positions();
for i in 0..self.fighters.len() {
if self.fighters[i].hp > 0 {
self.find_targets(i, &mut targets);
if targets.is_empty() {
let winner = self.fighters[i].team;
// all enemies are dead, battle is over
return Some(winner);
}
self.move_fighter(i, &targets, pathfinder);
self.resolve_attacks(i);
}
}
None
}
fn elves(&self) -> impl Iterator<Item=&Fighter> {
self.fighters.iter().filter(|f| f.hp > 0 && f.team == Team::Elf)
}
}
impl fmt::Display for Cavern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..self.height as isize {
for x in 0..self.width as isize {
let pos = Point::new(x, y);
match self.fighter_at(pos) {
Some(fighter_pos) => match self.fighters[fighter_pos].team {
Team::Elf => write!(f, "E")?,
Team::Goblin => write!(f, "G")?,
}
None => write!(f, "{}", self.tile_at(pos))?,
}
}
writeln!(f)?;
}
Ok(())
}
}
struct Outcome {
elf_power: isize,
elves_remaining: Vec<Fighter>,
winner: Team,
hp_sum: isize,
time: isize,
}
impl Outcome {
fn new(cavern: &Cavern, winner: Team, time: isize) -> Self {
let hp_sum = cavern.fighters.iter().map(|f| f.hp).sum::<isize>();
Self {
hp_sum,
elf_power: cavern.elf_attack_power,
elves_remaining: cavern.elves().cloned().collect(),
winner,
time,
}
}
fn value(&self) -> isize {
self.hp_sum * self.time
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}\t\tteam survived after {}\trounds * {}\t\tremaining HP = {},\telf power = {},\tsurviving elves = {}",
self.winner,
self.time,
self.hp_sum,
self.value(),
self.elf_power,
self.elves_remaining.len())
}
}
fn main() {
let input = include_str!("day_15.txt");
let initial_state = Cavern::parse(input);
let total_start_time = Instant::now();
let initial_elves = initial_state.elves().count();
let chunk_size: isize = 8;
let mut winning_outcomes = (0..).filter_map(|chunk| {
let chunk_outcomes: Vec<Outcome> = (0..chunk_size).into_par_iter()
.map(|i| {
let mut pathfinder = CavernPathfinder::new();
let attack_boost = (chunk_size * chunk + i) as isize;
let mut cavern = initial_state.clone();
cavern.elf_attack_power += attack_boost;
let mut time = 0;
loop {
if let Some(winner) = cavern.tick(&mut pathfinder) {
break Outcome::new(&cavern, winner, time);
} else {
time += 1;
}
}
})
.collect();
chunk_outcomes.into_iter()
.inspect(|outcome| println!("{}", outcome))
.find(|outcome| outcome.elves_remaining.len() == initial_elves)
});
let winning_outcome = winning_outcomes.next().unwrap();
println!("final outcome: {}", winning_outcome);
for elf in &winning_outcome.elves_remaining {
println!(" surviving elf with {} HP", elf.hp);
}
let total_elapsed = Instant::now() - total_start_time;
println!("elapsed time: {}.{}s", total_elapsed.as_secs(), total_elapsed.subsec_millis());
}
| {
let mut paths = Vec::new();
let origin_points = fighter.pos.neighbors_reading_order()
.filter(|p| self.is_free_space(*p));
let mut path = Vec::new();
for origin in origin_points {
for &dest in &dests {
let free_tile_pred = |p: &Point| self.is_free_space(*p);
if pathfinder.find_path(origin, dest, free_tile_pred, &mut path) {
paths.push(path.clone());
path.clear();
}
}
}
paths.sort_by(|a, b| {
let a_dest = *a.last().unwrap(); | conditional_block |
day_15.rs | mod point;
mod astar;
use {
crate::{
astar::Pathfinder,
point::{
Point,
Neighbors,
},
},
std::{
fmt,
cmp::Ordering,
collections::{
HashSet,
HashMap,
},
time::Instant,
usize,
},
rayon::prelude::*,
};
pub struct ManhattanDistHeuristic;
impl astar::Heuristic for ManhattanDistHeuristic {
type Item = Point;
type Score = usize;
fn score(from: &Point, to: &Point) -> usize { from.manhattan_dist_to(*to) }
fn zero_score() -> usize { 0 }
fn infinity_score() -> usize { usize::MAX }
}
pub struct CavernWorld;
impl astar::World for CavernWorld {
type Point = Point;
type Score = usize;
type Neighbors = Neighbors;
type Heuristic = ManhattanDistHeuristic;
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() }
fn neighbor_dist() -> usize { 1 }
fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) }
}
type CavernPathfinder = Pathfinder<CavernWorld>;
#[derive(Copy, Clone, Eq, PartialEq)]
enum Team {
Elf,
Goblin,
}
impl fmt::Display for Team {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match self {
Team::Goblin => "Goblin",
Team::Elf => "Elf",
})
}
}
#[derive(Clone)]
struct Fighter {
team: Team,
pos: Point,
hp: isize,
}
const BASE_ATTACK_POWER: isize = 3;
impl Fighter {
fn new(team: Team, pos: Point) -> Self {
Self {
team,
pos,
hp: 200,
}
}
}
impl fmt::Debug for Fighter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Fighter ( {} @ {} )", self.team, self.pos)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Tile {
Empty,
Blocked,
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Tile::Empty => write!(f, "."),
Tile::Blocked => write!(f, "#"),
}
}
}
#[derive(Clone)]
struct Cavern {
tiles: Vec<Tile>,
width: usize,
height: usize,
fighters: Vec<Fighter>,
fighter_positions: HashMap<Point, usize>,
elf_attack_power: isize,
}
impl Cavern {
fn parse(s: &str) -> Self {
let mut width = 0;
let mut height = 0;
let mut fighters = Vec::new();
let mut tiles = Vec::new();
for (y, line) in s.lines().enumerate() {
height += 1;
width = line.len(); // assume all lines are the same length
for (x, char) in line.chars().enumerate() {
let point = Point::new(x as isize, y as isize);
match char {
'#' => tiles.push(Tile::Blocked),
'E' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Elf, point));
}
'G' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Goblin, point));
}
_ => tiles.push(Tile::Empty),
}
}
}
let mut cavern = Self {
tiles,
width,
height,
fighters,
fighter_positions: HashMap::new(),
elf_attack_power: BASE_ATTACK_POWER,
};
cavern.refresh_fighter_positions();
cavern
}
fn refresh_fighter_positions(&mut self) {
self.fighter_positions.clear();
for (i, f) in self.fighters.iter().enumerate() {
self.fighter_positions.insert(f.pos, i);
}
}
fn is_free_space(&self, point: Point) -> bool {
match self.tile_at(point) {
Tile::Empty => self.fighter_at(point).is_none(),
Tile::Blocked => false,
}
}
fn fighter_at(&self, point: Point) -> Option<usize> {
self.fighter_positions.get(&point)
.filter(|&&i| self.fighters[i].hp > 0)
.cloned()
}
fn tile_at(&self, point: Point) -> Tile {
let off = self.width as isize * point.y + point.x;
if off >= 0 && off < self.tiles.len() as isize {
self.tiles[off as usize]
} else {
Tile::Blocked
}
}
fn find_targets(&self, i: usize, targets: &mut Vec<usize>) {
targets.clear();
let fighter = &self.fighters[i];
targets.extend(self.fighters.iter().enumerate()
.filter(|(_, other)| other.hp > 0)
.filter_map(|(j, other)| if other.team!= fighter.team {
Some(j)
} else {
None
}));
}
fn move_fighter(&mut self, i: usize, targets: &[usize], pathfinder: &mut CavernPathfinder) {
let fighter = &self.fighters[i];
let dests: HashSet<_> = targets.iter()
.flat_map(|j| {
let target_pos = self.fighters[*j].pos;
target_pos.neighbors_reading_order()
})
.filter(|p| self.is_free_space(*p) || *p == fighter.pos)
.collect();
if!dests.contains(&fighter.pos) {
let mut paths = Vec::new();
let origin_points = fighter.pos.neighbors_reading_order()
.filter(|p| self.is_free_space(*p));
let mut path = Vec::new();
for origin in origin_points {
for &dest in &dests {
let free_tile_pred = |p: &Point| self.is_free_space(*p);
if pathfinder.find_path(origin, dest, free_tile_pred, &mut path) {
paths.push(path.clone());
path.clear();
}
}
}
paths.sort_by(|a, b| {
let a_dest = *a.last().unwrap();
let b_dest = *b.last().unwrap();
// sort first by shortest paths...
match a.len().cmp(&b.len()) {
// then by origin pos in reading order
Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest),
dest_order => dest_order,
}
});
if!paths.is_empty() {
// move this fighter to the first step of the chosen path
self.fighters[i].pos = paths[0][0];
self.refresh_fighter_positions();
}
}
}
fn resolve_attacks(&mut self, i: usize) | match a.hp.cmp(&b.hp) {
Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos),
hp_order => hp_order,
}
});
if let Some(j) = target_index {
let attack_power = match self.fighters[i].team {
Team::Elf => self.elf_attack_power,
Team::Goblin => BASE_ATTACK_POWER,
};
self.fighters[j].hp = isize::max(0, self.fighters[j].hp - attack_power);
}
}
fn tick(&mut self, pathfinder: &mut CavernPathfinder) -> Option<Team> {
let mut targets = Vec::new();
self.fighters.sort_by(|a, b| Point::cmp_reading_order(a.pos, b.pos));
self.refresh_fighter_positions();
for i in 0..self.fighters.len() {
if self.fighters[i].hp > 0 {
self.find_targets(i, &mut targets);
if targets.is_empty() {
let winner = self.fighters[i].team;
// all enemies are dead, battle is over
return Some(winner);
}
self.move_fighter(i, &targets, pathfinder);
self.resolve_attacks(i);
}
}
None
}
fn elves(&self) -> impl Iterator<Item=&Fighter> {
self.fighters.iter().filter(|f| f.hp > 0 && f.team == Team::Elf)
}
}
impl fmt::Display for Cavern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..self.height as isize {
for x in 0..self.width as isize {
let pos = Point::new(x, y);
match self.fighter_at(pos) {
Some(fighter_pos) => match self.fighters[fighter_pos].team {
Team::Elf => write!(f, "E")?,
Team::Goblin => write!(f, "G")?,
}
None => write!(f, "{}", self.tile_at(pos))?,
}
}
writeln!(f)?;
}
Ok(())
}
}
struct Outcome {
elf_power: isize,
elves_remaining: Vec<Fighter>,
winner: Team,
hp_sum: isize,
time: isize,
}
impl Outcome {
fn new(cavern: &Cavern, winner: Team, time: isize) -> Self {
let hp_sum = cavern.fighters.iter().map(|f| f.hp).sum::<isize>();
Self {
hp_sum,
elf_power: cavern.elf_attack_power,
elves_remaining: cavern.elves().cloned().collect(),
winner,
time,
}
}
fn value(&self) -> isize {
self.hp_sum * self.time
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}\t\tteam survived after {}\trounds * {}\t\tremaining HP = {},\telf power = {},\tsurviving elves = {}",
self.winner,
self.time,
self.hp_sum,
self.value(),
self.elf_power,
self.elves_remaining.len())
}
}
fn main() {
let input = include_str!("day_15.txt");
let initial_state = Cavern::parse(input);
let total_start_time = Instant::now();
let initial_elves = initial_state.elves().count();
let chunk_size: isize = 8;
let mut winning_outcomes = (0..).filter_map(|chunk| {
let chunk_outcomes: Vec<Outcome> = (0..chunk_size).into_par_iter()
.map(|i| {
let mut pathfinder = CavernPathfinder::new();
let attack_boost = (chunk_size * chunk + i) as isize;
let mut cavern = initial_state.clone();
cavern.elf_attack_power += attack_boost;
let mut time = 0;
loop {
if let Some(winner) = cavern.tick(&mut pathfinder) {
break Outcome::new(&cavern, winner, time);
} else {
time += 1;
}
}
})
.collect();
chunk_outcomes.into_iter()
.inspect(|outcome| println!("{}", outcome))
.find(|outcome| outcome.elves_remaining.len() == initial_elves)
});
let winning_outcome = winning_outcomes.next().unwrap();
println!("final outcome: {}", winning_outcome);
for elf in &winning_outcome.elves_remaining {
println!(" surviving elf with {} HP", elf.hp);
}
let total_elapsed = Instant::now() - total_start_time;
println!("elapsed time: {}.{}s", total_elapsed.as_secs(), total_elapsed.subsec_millis());
}
| {
let neighbors = self.fighters[i].pos.neighbors_reading_order();
let target_index = neighbors
.filter_map(|neighbor| {
self.fighters.iter().enumerate()
.filter_map(|(j, f)| {
if f.pos == neighbor
&& f.hp > 0
&& f.team != self.fighters[i].team {
Some(j)
} else {
None
}
})
.next()
})
.min_by(|a, b| {
let a = &self.fighters[*a];
let b = &self.fighters[*b]; | identifier_body |
day_15.rs | mod point;
mod astar;
use {
crate::{
astar::Pathfinder,
point::{
Point,
Neighbors,
},
},
std::{
fmt,
cmp::Ordering,
collections::{
HashSet,
HashMap,
},
time::Instant,
usize,
},
rayon::prelude::*,
};
pub struct ManhattanDistHeuristic;
impl astar::Heuristic for ManhattanDistHeuristic {
type Item = Point;
type Score = usize;
fn score(from: &Point, to: &Point) -> usize { from.manhattan_dist_to(*to) }
fn zero_score() -> usize { 0 }
fn infinity_score() -> usize { usize::MAX }
}
pub struct CavernWorld;
impl astar::World for CavernWorld {
type Point = Point;
type Score = usize;
type Neighbors = Neighbors;
type Heuristic = ManhattanDistHeuristic;
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() }
fn neighbor_dist() -> usize { 1 }
fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) }
}
type CavernPathfinder = Pathfinder<CavernWorld>;
#[derive(Copy, Clone, Eq, PartialEq)]
enum Team {
Elf,
Goblin,
}
impl fmt::Display for Team {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match self {
Team::Goblin => "Goblin",
Team::Elf => "Elf",
})
}
}
#[derive(Clone)]
struct Fighter {
team: Team,
pos: Point,
hp: isize,
}
const BASE_ATTACK_POWER: isize = 3;
impl Fighter {
fn new(team: Team, pos: Point) -> Self {
Self {
team,
pos,
hp: 200,
}
}
}
impl fmt::Debug for Fighter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Fighter ( {} @ {} )", self.team, self.pos)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Tile {
Empty,
Blocked,
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Tile::Empty => write!(f, "."),
Tile::Blocked => write!(f, "#"),
}
}
}
#[derive(Clone)]
struct Cavern {
tiles: Vec<Tile>,
width: usize,
height: usize,
fighters: Vec<Fighter>,
fighter_positions: HashMap<Point, usize>,
elf_attack_power: isize,
}
impl Cavern {
fn parse(s: &str) -> Self {
let mut width = 0;
let mut height = 0;
let mut fighters = Vec::new();
let mut tiles = Vec::new();
for (y, line) in s.lines().enumerate() {
height += 1;
width = line.len(); // assume all lines are the same length
for (x, char) in line.chars().enumerate() {
let point = Point::new(x as isize, y as isize);
match char {
'#' => tiles.push(Tile::Blocked),
'E' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Elf, point));
}
'G' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Goblin, point));
}
_ => tiles.push(Tile::Empty),
}
}
}
let mut cavern = Self {
tiles,
width,
height,
fighters,
fighter_positions: HashMap::new(),
elf_attack_power: BASE_ATTACK_POWER,
};
cavern.refresh_fighter_positions();
cavern
}
fn refresh_fighter_positions(&mut self) {
self.fighter_positions.clear();
for (i, f) in self.fighters.iter().enumerate() {
self.fighter_positions.insert(f.pos, i);
}
}
fn is_free_space(&self, point: Point) -> bool {
match self.tile_at(point) {
Tile::Empty => self.fighter_at(point).is_none(),
Tile::Blocked => false,
}
}
fn fighter_at(&self, point: Point) -> Option<usize> {
self.fighter_positions.get(&point)
.filter(|&&i| self.fighters[i].hp > 0)
.cloned()
}
fn tile_at(&self, point: Point) -> Tile {
let off = self.width as isize * point.y + point.x;
if off >= 0 && off < self.tiles.len() as isize {
self.tiles[off as usize]
} else {
Tile::Blocked
}
}
fn | (&self, i: usize, targets: &mut Vec<usize>) {
targets.clear();
let fighter = &self.fighters[i];
targets.extend(self.fighters.iter().enumerate()
.filter(|(_, other)| other.hp > 0)
.filter_map(|(j, other)| if other.team!= fighter.team {
Some(j)
} else {
None
}));
}
fn move_fighter(&mut self, i: usize, targets: &[usize], pathfinder: &mut CavernPathfinder) {
let fighter = &self.fighters[i];
let dests: HashSet<_> = targets.iter()
.flat_map(|j| {
let target_pos = self.fighters[*j].pos;
target_pos.neighbors_reading_order()
})
.filter(|p| self.is_free_space(*p) || *p == fighter.pos)
.collect();
if!dests.contains(&fighter.pos) {
let mut paths = Vec::new();
let origin_points = fighter.pos.neighbors_reading_order()
.filter(|p| self.is_free_space(*p));
let mut path = Vec::new();
for origin in origin_points {
for &dest in &dests {
let free_tile_pred = |p: &Point| self.is_free_space(*p);
if pathfinder.find_path(origin, dest, free_tile_pred, &mut path) {
paths.push(path.clone());
path.clear();
}
}
}
paths.sort_by(|a, b| {
let a_dest = *a.last().unwrap();
let b_dest = *b.last().unwrap();
// sort first by shortest paths...
match a.len().cmp(&b.len()) {
// then by origin pos in reading order
Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest),
dest_order => dest_order,
}
});
if!paths.is_empty() {
// move this fighter to the first step of the chosen path
self.fighters[i].pos = paths[0][0];
self.refresh_fighter_positions();
}
}
}
fn resolve_attacks(&mut self, i: usize) {
let neighbors = self.fighters[i].pos.neighbors_reading_order();
let target_index = neighbors
.filter_map(|neighbor| {
self.fighters.iter().enumerate()
.filter_map(|(j, f)| {
if f.pos == neighbor
&& f.hp > 0
&& f.team!= self.fighters[i].team {
Some(j)
} else {
None
}
})
.next()
})
.min_by(|a, b| {
let a = &self.fighters[*a];
let b = &self.fighters[*b];
match a.hp.cmp(&b.hp) {
Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos),
hp_order => hp_order,
}
});
if let Some(j) = target_index {
let attack_power = match self.fighters[i].team {
Team::Elf => self.elf_attack_power,
Team::Goblin => BASE_ATTACK_POWER,
};
self.fighters[j].hp = isize::max(0, self.fighters[j].hp - attack_power);
}
}
fn tick(&mut self, pathfinder: &mut CavernPathfinder) -> Option<Team> {
let mut targets = Vec::new();
self.fighters.sort_by(|a, b| Point::cmp_reading_order(a.pos, b.pos));
self.refresh_fighter_positions();
for i in 0..self.fighters.len() {
if self.fighters[i].hp > 0 {
self.find_targets(i, &mut targets);
if targets.is_empty() {
let winner = self.fighters[i].team;
// all enemies are dead, battle is over
return Some(winner);
}
self.move_fighter(i, &targets, pathfinder);
self.resolve_attacks(i);
}
}
None
}
fn elves(&self) -> impl Iterator<Item=&Fighter> {
self.fighters.iter().filter(|f| f.hp > 0 && f.team == Team::Elf)
}
}
impl fmt::Display for Cavern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..self.height as isize {
for x in 0..self.width as isize {
let pos = Point::new(x, y);
match self.fighter_at(pos) {
Some(fighter_pos) => match self.fighters[fighter_pos].team {
Team::Elf => write!(f, "E")?,
Team::Goblin => write!(f, "G")?,
}
None => write!(f, "{}", self.tile_at(pos))?,
}
}
writeln!(f)?;
}
Ok(())
}
}
struct Outcome {
elf_power: isize,
elves_remaining: Vec<Fighter>,
winner: Team,
hp_sum: isize,
time: isize,
}
impl Outcome {
fn new(cavern: &Cavern, winner: Team, time: isize) -> Self {
let hp_sum = cavern.fighters.iter().map(|f| f.hp).sum::<isize>();
Self {
hp_sum,
elf_power: cavern.elf_attack_power,
elves_remaining: cavern.elves().cloned().collect(),
winner,
time,
}
}
fn value(&self) -> isize {
self.hp_sum * self.time
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}\t\tteam survived after {}\trounds * {}\t\tremaining HP = {},\telf power = {},\tsurviving elves = {}",
self.winner,
self.time,
self.hp_sum,
self.value(),
self.elf_power,
self.elves_remaining.len())
}
}
fn main() {
let input = include_str!("day_15.txt");
let initial_state = Cavern::parse(input);
let total_start_time = Instant::now();
let initial_elves = initial_state.elves().count();
let chunk_size: isize = 8;
let mut winning_outcomes = (0..).filter_map(|chunk| {
let chunk_outcomes: Vec<Outcome> = (0..chunk_size).into_par_iter()
.map(|i| {
let mut pathfinder = CavernPathfinder::new();
let attack_boost = (chunk_size * chunk + i) as isize;
let mut cavern = initial_state.clone();
cavern.elf_attack_power += attack_boost;
let mut time = 0;
loop {
if let Some(winner) = cavern.tick(&mut pathfinder) {
break Outcome::new(&cavern, winner, time);
} else {
time += 1;
}
}
})
.collect();
chunk_outcomes.into_iter()
.inspect(|outcome| println!("{}", outcome))
.find(|outcome| outcome.elves_remaining.len() == initial_elves)
});
let winning_outcome = winning_outcomes.next().unwrap();
println!("final outcome: {}", winning_outcome);
for elf in &winning_outcome.elves_remaining {
println!(" surviving elf with {} HP", elf.hp);
}
let total_elapsed = Instant::now() - total_start_time;
println!("elapsed time: {}.{}s", total_elapsed.as_secs(), total_elapsed.subsec_millis());
}
| find_targets | identifier_name |
day_15.rs | mod point;
mod astar;
use {
crate::{
astar::Pathfinder,
point::{
Point,
Neighbors,
},
},
std::{
fmt,
cmp::Ordering,
collections::{
HashSet,
HashMap,
},
time::Instant,
usize,
},
rayon::prelude::*,
};
pub struct ManhattanDistHeuristic;
impl astar::Heuristic for ManhattanDistHeuristic {
type Item = Point;
type Score = usize;
fn score(from: &Point, to: &Point) -> usize { from.manhattan_dist_to(*to) }
fn zero_score() -> usize { 0 }
fn infinity_score() -> usize { usize::MAX }
}
pub struct CavernWorld;
impl astar::World for CavernWorld {
type Point = Point;
type Score = usize;
type Neighbors = Neighbors;
type Heuristic = ManhattanDistHeuristic;
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() }
fn neighbor_dist() -> usize { 1 }
fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) }
}
type CavernPathfinder = Pathfinder<CavernWorld>;
#[derive(Copy, Clone, Eq, PartialEq)]
enum Team {
Elf,
Goblin,
}
impl fmt::Display for Team {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match self {
Team::Goblin => "Goblin",
Team::Elf => "Elf",
})
}
}
#[derive(Clone)]
struct Fighter {
team: Team,
pos: Point,
hp: isize,
}
const BASE_ATTACK_POWER: isize = 3;
impl Fighter {
fn new(team: Team, pos: Point) -> Self {
Self {
team,
pos,
hp: 200,
}
}
}
impl fmt::Debug for Fighter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Fighter ( {} @ {} )", self.team, self.pos)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Tile {
Empty,
Blocked,
}
impl fmt::Display for Tile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Tile::Empty => write!(f, "."),
Tile::Blocked => write!(f, "#"),
}
}
}
#[derive(Clone)]
struct Cavern {
tiles: Vec<Tile>,
width: usize,
height: usize,
fighters: Vec<Fighter>,
fighter_positions: HashMap<Point, usize>,
elf_attack_power: isize,
}
impl Cavern {
fn parse(s: &str) -> Self {
let mut width = 0;
let mut height = 0; | for (y, line) in s.lines().enumerate() {
height += 1;
width = line.len(); // assume all lines are the same length
for (x, char) in line.chars().enumerate() {
let point = Point::new(x as isize, y as isize);
match char {
'#' => tiles.push(Tile::Blocked),
'E' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Elf, point));
}
'G' => {
tiles.push(Tile::Empty);
fighters.push(Fighter::new(Team::Goblin, point));
}
_ => tiles.push(Tile::Empty),
}
}
}
let mut cavern = Self {
tiles,
width,
height,
fighters,
fighter_positions: HashMap::new(),
elf_attack_power: BASE_ATTACK_POWER,
};
cavern.refresh_fighter_positions();
cavern
}
fn refresh_fighter_positions(&mut self) {
self.fighter_positions.clear();
for (i, f) in self.fighters.iter().enumerate() {
self.fighter_positions.insert(f.pos, i);
}
}
fn is_free_space(&self, point: Point) -> bool {
match self.tile_at(point) {
Tile::Empty => self.fighter_at(point).is_none(),
Tile::Blocked => false,
}
}
fn fighter_at(&self, point: Point) -> Option<usize> {
self.fighter_positions.get(&point)
.filter(|&&i| self.fighters[i].hp > 0)
.cloned()
}
fn tile_at(&self, point: Point) -> Tile {
let off = self.width as isize * point.y + point.x;
if off >= 0 && off < self.tiles.len() as isize {
self.tiles[off as usize]
} else {
Tile::Blocked
}
}
fn find_targets(&self, i: usize, targets: &mut Vec<usize>) {
targets.clear();
let fighter = &self.fighters[i];
targets.extend(self.fighters.iter().enumerate()
.filter(|(_, other)| other.hp > 0)
.filter_map(|(j, other)| if other.team!= fighter.team {
Some(j)
} else {
None
}));
}
fn move_fighter(&mut self, i: usize, targets: &[usize], pathfinder: &mut CavernPathfinder) {
let fighter = &self.fighters[i];
let dests: HashSet<_> = targets.iter()
.flat_map(|j| {
let target_pos = self.fighters[*j].pos;
target_pos.neighbors_reading_order()
})
.filter(|p| self.is_free_space(*p) || *p == fighter.pos)
.collect();
if!dests.contains(&fighter.pos) {
let mut paths = Vec::new();
let origin_points = fighter.pos.neighbors_reading_order()
.filter(|p| self.is_free_space(*p));
let mut path = Vec::new();
for origin in origin_points {
for &dest in &dests {
let free_tile_pred = |p: &Point| self.is_free_space(*p);
if pathfinder.find_path(origin, dest, free_tile_pred, &mut path) {
paths.push(path.clone());
path.clear();
}
}
}
paths.sort_by(|a, b| {
let a_dest = *a.last().unwrap();
let b_dest = *b.last().unwrap();
// sort first by shortest paths...
match a.len().cmp(&b.len()) {
// then by origin pos in reading order
Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest),
dest_order => dest_order,
}
});
if!paths.is_empty() {
// move this fighter to the first step of the chosen path
self.fighters[i].pos = paths[0][0];
self.refresh_fighter_positions();
}
}
}
fn resolve_attacks(&mut self, i: usize) {
let neighbors = self.fighters[i].pos.neighbors_reading_order();
let target_index = neighbors
.filter_map(|neighbor| {
self.fighters.iter().enumerate()
.filter_map(|(j, f)| {
if f.pos == neighbor
&& f.hp > 0
&& f.team!= self.fighters[i].team {
Some(j)
} else {
None
}
})
.next()
})
.min_by(|a, b| {
let a = &self.fighters[*a];
let b = &self.fighters[*b];
match a.hp.cmp(&b.hp) {
Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos),
hp_order => hp_order,
}
});
if let Some(j) = target_index {
let attack_power = match self.fighters[i].team {
Team::Elf => self.elf_attack_power,
Team::Goblin => BASE_ATTACK_POWER,
};
self.fighters[j].hp = isize::max(0, self.fighters[j].hp - attack_power);
}
}
fn tick(&mut self, pathfinder: &mut CavernPathfinder) -> Option<Team> {
let mut targets = Vec::new();
self.fighters.sort_by(|a, b| Point::cmp_reading_order(a.pos, b.pos));
self.refresh_fighter_positions();
for i in 0..self.fighters.len() {
if self.fighters[i].hp > 0 {
self.find_targets(i, &mut targets);
if targets.is_empty() {
let winner = self.fighters[i].team;
// all enemies are dead, battle is over
return Some(winner);
}
self.move_fighter(i, &targets, pathfinder);
self.resolve_attacks(i);
}
}
None
}
fn elves(&self) -> impl Iterator<Item=&Fighter> {
self.fighters.iter().filter(|f| f.hp > 0 && f.team == Team::Elf)
}
}
impl fmt::Display for Cavern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..self.height as isize {
for x in 0..self.width as isize {
let pos = Point::new(x, y);
match self.fighter_at(pos) {
Some(fighter_pos) => match self.fighters[fighter_pos].team {
Team::Elf => write!(f, "E")?,
Team::Goblin => write!(f, "G")?,
}
None => write!(f, "{}", self.tile_at(pos))?,
}
}
writeln!(f)?;
}
Ok(())
}
}
struct Outcome {
elf_power: isize,
elves_remaining: Vec<Fighter>,
winner: Team,
hp_sum: isize,
time: isize,
}
impl Outcome {
fn new(cavern: &Cavern, winner: Team, time: isize) -> Self {
let hp_sum = cavern.fighters.iter().map(|f| f.hp).sum::<isize>();
Self {
hp_sum,
elf_power: cavern.elf_attack_power,
elves_remaining: cavern.elves().cloned().collect(),
winner,
time,
}
}
fn value(&self) -> isize {
self.hp_sum * self.time
}
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}\t\tteam survived after {}\trounds * {}\t\tremaining HP = {},\telf power = {},\tsurviving elves = {}",
self.winner,
self.time,
self.hp_sum,
self.value(),
self.elf_power,
self.elves_remaining.len())
}
}
fn main() {
let input = include_str!("day_15.txt");
let initial_state = Cavern::parse(input);
let total_start_time = Instant::now();
let initial_elves = initial_state.elves().count();
let chunk_size: isize = 8;
let mut winning_outcomes = (0..).filter_map(|chunk| {
let chunk_outcomes: Vec<Outcome> = (0..chunk_size).into_par_iter()
.map(|i| {
let mut pathfinder = CavernPathfinder::new();
let attack_boost = (chunk_size * chunk + i) as isize;
let mut cavern = initial_state.clone();
cavern.elf_attack_power += attack_boost;
let mut time = 0;
loop {
if let Some(winner) = cavern.tick(&mut pathfinder) {
break Outcome::new(&cavern, winner, time);
} else {
time += 1;
}
}
})
.collect();
chunk_outcomes.into_iter()
.inspect(|outcome| println!("{}", outcome))
.find(|outcome| outcome.elves_remaining.len() == initial_elves)
});
let winning_outcome = winning_outcomes.next().unwrap();
println!("final outcome: {}", winning_outcome);
for elf in &winning_outcome.elves_remaining {
println!(" surviving elf with {} HP", elf.hp);
}
let total_elapsed = Instant::now() - total_start_time;
println!("elapsed time: {}.{}s", total_elapsed.as_secs(), total_elapsed.subsec_millis());
} | let mut fighters = Vec::new();
let mut tiles = Vec::new();
| random_line_split |
install.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
extern crate clap;
extern crate libc;
mod mode;
#[macro_use]
extern crate uucore;
use clap::{App, Arg, ArgMatches};
use std::fs;
use std::path::{Path, PathBuf};
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
suffix: String,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction {
/// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_2: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATED: &str = "created";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = App::new(executable!())
.version(VERSION)
.about(ABOUT)
.usage(&usage[..])
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("(unimplemented) make a backup of each existing destination file")
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_2)
.short("b")
.help("(unimplemented) like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("(unimplemented) compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATED)
.short("D")
.help("(unimplemented) create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("(unimplemented) set group ownership, instead of process's current group")
.value_name("GROUP")
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("(unimplemented) set ownership (super-user only)")
.value_name("OWNER")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("(unimplemented) apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("(unimplemented) strip symbol tables")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("(unimplemented) program used to strip binaries")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("(unimplemented) override the usual backup suffix")
.value_name("SUFFIX")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("(unimplemented) move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true))
.get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_BACKUP) {
Err("--backup")
} else if matches.is_present(OPT_BACKUP_2) {
Err("-b")
} else if matches.is_present(OPT_COMPARE) {
Err("--compare, -C")
} else if matches.is_present(OPT_CREATED) {
Err("-D")
} else if matches.is_present(OPT_GROUP) {
Err("--group, -g")
} else if matches.is_present(OPT_OWNER) {
Err("--owner, -o")
} else if matches.is_present(OPT_PRESERVE_TIMESTAMPS) {
Err("--preserve-timestamps, -p")
} else if matches.is_present(OPT_STRIP) {
Err("--strip, -s")
} else if matches.is_present(OPT_STRIP_PROGRAM) {
Err("--strip-program")
} else if matches.is_present(OPT_SUFFIX) {
Err("--suffix, -S")
} else if matches.is_present(OPT_TARGET_DIRECTORY) {
Err("--target-directory, -t")
} else if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present("directory") {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) {
Some(x) => match mode::parse(&x[..], considering_dir) {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err);
return Err(1);
}
},
None => {
show_error!(
"option '--mode' requires an argument\n \
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
None
};
let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) {
Some(x) => x,
None => {
show_error!(
"option '--suffix' requires an argument\n\
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
"~"
};
Ok(Behavior {
main_function,
specified_mode,
suffix: backup_suffix.to_string(),
verbose: matches.is_present(OPT_VERBOSE),
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for directory in paths.iter() {
let path = Path::new(directory);
// if the path already exist, don't try to create it again
if!path.exists() {
if let Err(e) = fs::create_dir(directory) {
show_info!("{}: {}", path.display(), e.to_string());
all_successful = false;
}
}
if mode::chmod(&path, b.mode()).is_err() {
all_successful = false;
}
if b.verbose {
show_info!("created directory '{}'", path.display());
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(paths: Vec<String>, b: Behavior) -> i32 {
if paths.len() < 2 {
println!("{} requires at least 2 arguments.", executable!());
1
} else {
let sources = &paths[0..paths.len() - 1]
.iter()
.map(PathBuf::from)
.collect::<Vec<_>>();
let target = Path::new(paths.last().unwrap());
if (target.is_file() || is_new_file_path(target)) && sources.len() == 1 {
/* If the target already exist or directly creatable */
copy_file_to_file(&sources[0], &target.to_path_buf(), &b)
} else {
copy_files_into_dir(sources, &target.to_path_buf(), &b)
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> i32 {
if!target_dir.is_dir() {
show_error!("target ‘{}’ is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
let targetpath = match sourcepath.as_os_str().to_str() {
Some(name) => target_dir.join(name),
None => {
show_error!(
"cannot stat ‘{}’: No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
};
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behavior) -> i32 {
if copy(file, &target, b).is_err() {
1
} else {
| Copy one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
fn copy(from: &PathBuf, to: &PathBuf, b: &Behavior) -> Result<(), ()> {
let io_result = fs::copy(from, to);
if let Err(err) = io_result {
show_error!(
"install: cannot install ‘{}’ to ‘{}’: {}",
from.display(),
to.display(),
err
);
return Err(());
}
if mode::chmod(&to, b.mode()).is_err() {
return Err(());
}
if b.verbose {
show_info!("'{}' -> '{}'", from.display(), to.display());
}
Ok(())
}
| 0
}
}
/// | conditional_block |
install.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
extern crate clap;
extern crate libc;
mod mode;
#[macro_use]
extern crate uucore;
use clap::{App, Arg, ArgMatches};
use std::fs;
use std::path::{Path, PathBuf};
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
suffix: String,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction {
/// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_2: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATED: &str = "created";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = App::new(executable!())
.version(VERSION)
.about(ABOUT)
.usage(&usage[..])
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("(unimplemented) make a backup of each existing destination file")
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_2)
.short("b")
.help("(unimplemented) like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("(unimplemented) compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATED)
.short("D")
.help("(unimplemented) create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("(unimplemented) set group ownership, instead of process's current group")
.value_name("GROUP")
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("(unimplemented) set ownership (super-user only)")
.value_name("OWNER")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("(unimplemented) apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("(unimplemented) strip symbol tables")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("(unimplemented) program used to strip binaries")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("(unimplemented) override the usual backup suffix")
.value_name("SUFFIX")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("(unimplemented) move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true))
.get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_BACKUP) {
Err("--backup")
} else if matches.is_present(OPT_BACKUP_2) {
Err("-b")
} else if matches.is_present(OPT_COMPARE) {
Err("--compare, -C")
} else if matches.is_present(OPT_CREATED) {
Err("-D")
} else if matches.is_present(OPT_GROUP) {
Err("--group, -g")
} else if matches.is_present(OPT_OWNER) {
Err("--owner, -o")
} else if matches.is_present(OPT_PRESERVE_TIMESTAMPS) {
Err("--preserve-timestamps, -p")
} else if matches.is_present(OPT_STRIP) {
Err("--strip, -s")
} else if matches.is_present(OPT_STRIP_PROGRAM) {
Err("--strip-program")
} else if matches.is_present(OPT_SUFFIX) {
Err("--suffix, -S")
} else if matches.is_present(OPT_TARGET_DIRECTORY) {
Err("--target-directory, -t")
} else if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present("directory") {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) {
Some(x) => match mode::parse(&x[..], considering_dir) {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err);
return Err(1);
}
},
None => {
show_error!(
"option '--mode' requires an argument\n \
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
None
};
let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) {
Some(x) => x,
None => {
show_error!(
"option '--suffix' requires an argument\n\
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
"~"
};
Ok(Behavior {
main_function,
specified_mode,
suffix: backup_suffix.to_string(),
verbose: matches.is_present(OPT_VERBOSE),
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for directory in paths.iter() {
let path = Path::new(directory);
// if the path already exist, don't try to create it again
if!path.exists() {
if let Err(e) = fs::create_dir(directory) {
show_info!("{}: {}", path.display(), e.to_string());
all_successful = false;
}
}
if mode::chmod(&path, b.mode()).is_err() {
all_successful = false;
}
if b.verbose {
show_info!("created directory '{}'", path.display());
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(paths: Vec<String>, b: Behavior) -> i32 {
if paths.len() < 2 {
println!("{} requires at least 2 arguments.", executable!());
1
} else {
let sources = &paths[0..paths.len() - 1]
.iter()
.map(PathBuf::from)
.collect::<Vec<_>>();
let target = Path::new(paths.last().unwrap());
if (target.is_file() || is_new_file_path(target)) && sources.len() == 1 {
/* If the target already exist or directly creatable */
copy_file_to_file(&sources[0], &target.to_path_buf(), &b)
} else {
copy_files_into_dir(sources, &target.to_path_buf(), &b)
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> i32 {
if!target_dir.is_dir() {
show_error!("target ‘{}’ is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
let targetpath = match sourcepath.as_os_str().to_str() {
Some(name) => target_dir.join(name),
None => {
show_error!(
"cannot stat ‘{}’: No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
};
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behavior) -> i32 {
if | py one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
fn copy(from: &PathBuf, to: &PathBuf, b: &Behavior) -> Result<(), ()> {
let io_result = fs::copy(from, to);
if let Err(err) = io_result {
show_error!(
"install: cannot install ‘{}’ to ‘{}’: {}",
from.display(),
to.display(),
err
);
return Err(());
}
if mode::chmod(&to, b.mode()).is_err() {
return Err(());
}
if b.verbose {
show_info!("'{}' -> '{}'", from.display(), to.display());
}
Ok(())
}
| copy(file, &target, b).is_err() {
1
} else {
0
}
}
/// Co | identifier_body |
install.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
extern crate clap;
extern crate libc;
mod mode;
#[macro_use]
extern crate uucore;
use clap::{App, Arg, ArgMatches};
use std::fs;
use std::path::{Path, PathBuf};
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
suffix: String,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction {
/// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_2: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATED: &str = "created";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = App::new(executable!())
.version(VERSION)
.about(ABOUT)
.usage(&usage[..])
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("(unimplemented) make a backup of each existing destination file")
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_2)
.short("b")
.help("(unimplemented) like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("(unimplemented) compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATED)
.short("D")
.help("(unimplemented) create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("(unimplemented) set group ownership, instead of process's current group")
.value_name("GROUP")
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("(unimplemented) set ownership (super-user only)")
.value_name("OWNER")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("(unimplemented) apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("(unimplemented) strip symbol tables")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("(unimplemented) program used to strip binaries")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("(unimplemented) override the usual backup suffix")
.value_name("SUFFIX")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("(unimplemented) move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true))
.get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_BACKUP) {
Err("--backup")
} else if matches.is_present(OPT_BACKUP_2) {
Err("-b")
} else if matches.is_present(OPT_COMPARE) {
Err("--compare, -C")
} else if matches.is_present(OPT_CREATED) {
Err("-D")
} else if matches.is_present(OPT_GROUP) {
Err("--group, -g")
} else if matches.is_present(OPT_OWNER) {
Err("--owner, -o")
} else if matches.is_present(OPT_PRESERVE_TIMESTAMPS) {
Err("--preserve-timestamps, -p")
} else if matches.is_present(OPT_STRIP) {
Err("--strip, -s")
} else if matches.is_present(OPT_STRIP_PROGRAM) {
Err("--strip-program")
} else if matches.is_present(OPT_SUFFIX) {
Err("--suffix, -S")
} else if matches.is_present(OPT_TARGET_DIRECTORY) {
Err("--target-directory, -t")
} else if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn | (matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present("directory") {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) {
Some(x) => match mode::parse(&x[..], considering_dir) {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err);
return Err(1);
}
},
None => {
show_error!(
"option '--mode' requires an argument\n \
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
None
};
let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) {
Some(x) => x,
None => {
show_error!(
"option '--suffix' requires an argument\n\
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
"~"
};
Ok(Behavior {
main_function,
specified_mode,
suffix: backup_suffix.to_string(),
verbose: matches.is_present(OPT_VERBOSE),
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for directory in paths.iter() {
let path = Path::new(directory);
// if the path already exist, don't try to create it again
if!path.exists() {
if let Err(e) = fs::create_dir(directory) {
show_info!("{}: {}", path.display(), e.to_string());
all_successful = false;
}
}
if mode::chmod(&path, b.mode()).is_err() {
all_successful = false;
}
if b.verbose {
show_info!("created directory '{}'", path.display());
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(paths: Vec<String>, b: Behavior) -> i32 {
if paths.len() < 2 {
println!("{} requires at least 2 arguments.", executable!());
1
} else {
let sources = &paths[0..paths.len() - 1]
.iter()
.map(PathBuf::from)
.collect::<Vec<_>>();
let target = Path::new(paths.last().unwrap());
if (target.is_file() || is_new_file_path(target)) && sources.len() == 1 {
/* If the target already exist or directly creatable */
copy_file_to_file(&sources[0], &target.to_path_buf(), &b)
} else {
copy_files_into_dir(sources, &target.to_path_buf(), &b)
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> i32 {
if!target_dir.is_dir() {
show_error!("target ‘{}’ is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
let targetpath = match sourcepath.as_os_str().to_str() {
Some(name) => target_dir.join(name),
None => {
show_error!(
"cannot stat ‘{}’: No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
};
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behavior) -> i32 {
if copy(file, &target, b).is_err() {
1
} else {
0
}
}
/// Copy one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
fn copy(from: &PathBuf, to: &PathBuf, b: &Behavior) -> Result<(), ()> {
let io_result = fs::copy(from, to);
if let Err(err) = io_result {
show_error!(
"install: cannot install ‘{}’ to ‘{}’: {}",
from.display(),
to.display(),
err
);
return Err(());
}
if mode::chmod(&to, b.mode()).is_err() {
return Err(());
}
if b.verbose {
show_info!("'{}' -> '{}'", from.display(), to.display());
}
Ok(())
}
| behavior | identifier_name |
install.rs | // * This file is part of the uutils coreutils package.
// *
// * (c) Ben Eills <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
// spell-checker:ignore (ToDO) rwxr sourcepath targetpath
extern crate clap;
extern crate libc;
mod mode;
#[macro_use]
extern crate uucore;
use clap::{App, Arg, ArgMatches};
use std::fs;
use std::path::{Path, PathBuf};
use std::result::Result;
const DEFAULT_MODE: u32 = 0o755;
#[allow(dead_code)]
pub struct Behavior {
main_function: MainFunction,
specified_mode: Option<u32>,
suffix: String,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum MainFunction { | /// Create directories
Directory,
/// Install files to locations (primary functionality)
Standard,
}
impl Behavior {
/// Determine the mode for chmod after copy.
pub fn mode(&self) -> u32 {
match self.specified_mode {
Some(x) => x,
None => DEFAULT_MODE,
}
}
}
static ABOUT: &str = "Copy SOURCE to DEST or multiple SOURCE(s) to the existing
DIRECTORY, while setting permission modes and owner/group";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static OPT_COMPARE: &str = "compare";
static OPT_BACKUP: &str = "backup";
static OPT_BACKUP_2: &str = "backup2";
static OPT_DIRECTORY: &str = "directory";
static OPT_IGNORED: &str = "ignored";
static OPT_CREATED: &str = "created";
static OPT_GROUP: &str = "group";
static OPT_MODE: &str = "mode";
static OPT_OWNER: &str = "owner";
static OPT_PRESERVE_TIMESTAMPS: &str = "preserve-timestamps";
static OPT_STRIP: &str = "strip";
static OPT_STRIP_PROGRAM: &str = "strip-program";
static OPT_SUFFIX: &str = "suffix";
static OPT_TARGET_DIRECTORY: &str = "target-directory";
static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory";
static OPT_VERBOSE: &str = "verbose";
static OPT_PRESERVE_CONTEXT: &str = "preserve-context";
static OPT_CONTEXT: &str = "context";
static ARG_FILES: &str = "files";
fn get_usage() -> String {
format!("{0} [OPTION]... [FILE]...", executable!())
}
/// Main install utility function, called from main.rs.
///
/// Returns a program return code.
///
pub fn uumain(args: impl uucore::Args) -> i32 {
let usage = get_usage();
let matches = App::new(executable!())
.version(VERSION)
.about(ABOUT)
.usage(&usage[..])
.arg(
Arg::with_name(OPT_BACKUP)
.long(OPT_BACKUP)
.help("(unimplemented) make a backup of each existing destination file")
.value_name("CONTROL")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_BACKUP_2)
.short("b")
.help("(unimplemented) like --backup but does not accept an argument")
)
.arg(
Arg::with_name(OPT_IGNORED)
.short("c")
.help("ignored")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_COMPARE)
.short("C")
.long(OPT_COMPARE)
.help("(unimplemented) compare each pair of source and destination files, and in some cases, do not modify the destination at all")
)
.arg(
Arg::with_name(OPT_DIRECTORY)
.short("d")
.long(OPT_DIRECTORY)
.help("treat all arguments as directory names. create all components of the specified directories")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CREATED)
.short("D")
.help("(unimplemented) create all leading components of DEST except the last, then copy SOURCE to DEST")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_GROUP)
.short("g")
.long(OPT_GROUP)
.help("(unimplemented) set group ownership, instead of process's current group")
.value_name("GROUP")
)
.arg(
Arg::with_name(OPT_MODE)
.short("m")
.long(OPT_MODE)
.help("set permission mode (as in chmod), instead of rwxr-xr-x")
.value_name("MODE")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_OWNER)
.short("o")
.long(OPT_OWNER)
.help("(unimplemented) set ownership (super-user only)")
.value_name("OWNER")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_TIMESTAMPS)
.short("p")
.long(OPT_PRESERVE_TIMESTAMPS)
.help("(unimplemented) apply access/modification times of SOURCE files to corresponding destination files")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP)
.short("s")
.long(OPT_STRIP)
.help("(unimplemented) strip symbol tables")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_STRIP_PROGRAM)
.long(OPT_STRIP_PROGRAM)
.help("(unimplemented) program used to strip binaries")
.value_name("PROGRAM")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_SUFFIX)
.short("S")
.long(OPT_SUFFIX)
.help("(unimplemented) override the usual backup suffix")
.value_name("SUFFIX")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_TARGET_DIRECTORY)
.short("t")
.long(OPT_TARGET_DIRECTORY)
.help("(unimplemented) move all SOURCE arguments into DIRECTORY")
.value_name("DIRECTORY")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_NO_TARGET_DIRECTORY)
.short("T")
.long(OPT_NO_TARGET_DIRECTORY)
.help("(unimplemented) treat DEST as a normal file")
)
.arg(
Arg::with_name(OPT_VERBOSE)
.short("v")
.long(OPT_VERBOSE)
.help("explain what is being done")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_PRESERVE_CONTEXT)
.short("P")
.long(OPT_PRESERVE_CONTEXT)
.help("(unimplemented) preserve security context")
)
.arg(
// TODO implement flag
Arg::with_name(OPT_CONTEXT)
.short("Z")
.long(OPT_CONTEXT)
.help("(unimplemented) set security context of files and directories")
.value_name("CONTEXT")
)
.arg(Arg::with_name(ARG_FILES).multiple(true).takes_value(true))
.get_matches_from(args);
let paths: Vec<String> = matches
.values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect())
.unwrap_or_default();
if let Err(s) = check_unimplemented(&matches) {
show_error!("Unimplemented feature: {}", s);
return 2;
}
let behavior = match behavior(&matches) {
Ok(x) => x,
Err(ret) => {
return ret;
}
};
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
}
}
/// Check for unimplemented command line arguments.
///
/// Either return the degenerate Ok value, or an Err with string.
///
/// # Errors
///
/// Error datum is a string of the unimplemented argument.
///
///
fn check_unimplemented<'a>(matches: &ArgMatches) -> Result<(), &'a str> {
if matches.is_present(OPT_BACKUP) {
Err("--backup")
} else if matches.is_present(OPT_BACKUP_2) {
Err("-b")
} else if matches.is_present(OPT_COMPARE) {
Err("--compare, -C")
} else if matches.is_present(OPT_CREATED) {
Err("-D")
} else if matches.is_present(OPT_GROUP) {
Err("--group, -g")
} else if matches.is_present(OPT_OWNER) {
Err("--owner, -o")
} else if matches.is_present(OPT_PRESERVE_TIMESTAMPS) {
Err("--preserve-timestamps, -p")
} else if matches.is_present(OPT_STRIP) {
Err("--strip, -s")
} else if matches.is_present(OPT_STRIP_PROGRAM) {
Err("--strip-program")
} else if matches.is_present(OPT_SUFFIX) {
Err("--suffix, -S")
} else if matches.is_present(OPT_TARGET_DIRECTORY) {
Err("--target-directory, -t")
} else if matches.is_present(OPT_NO_TARGET_DIRECTORY) {
Err("--no-target-directory, -T")
} else if matches.is_present(OPT_PRESERVE_CONTEXT) {
Err("--preserve-context, -P")
} else if matches.is_present(OPT_CONTEXT) {
Err("--context, -Z")
} else {
Ok(())
}
}
/// Determine behavior, given command line arguments.
///
/// If successful, returns a filled-out Behavior struct.
///
/// # Errors
///
/// In event of failure, returns an integer intended as a program return code.
///
fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let main_function = if matches.is_present("directory") {
MainFunction::Directory
} else {
MainFunction::Standard
};
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) {
Some(x) => match mode::parse(&x[..], considering_dir) {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err);
return Err(1);
}
},
None => {
show_error!(
"option '--mode' requires an argument\n \
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
None
};
let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) {
Some(x) => x,
None => {
show_error!(
"option '--suffix' requires an argument\n\
Try '{} --help' for more information.",
executable!()
);
return Err(1);
}
}
} else {
"~"
};
Ok(Behavior {
main_function,
specified_mode,
suffix: backup_suffix.to_string(),
verbose: matches.is_present(OPT_VERBOSE),
})
}
/// Creates directories.
///
/// GNU man pages describe this functionality as creating 'all components of
/// the specified directories'.
///
/// Returns an integer intended as a program return code.
///
fn directory(paths: Vec<String>, b: Behavior) -> i32 {
if paths.is_empty() {
println!("{} with -d requires at least one argument.", executable!());
1
} else {
let mut all_successful = true;
for directory in paths.iter() {
let path = Path::new(directory);
// if the path already exist, don't try to create it again
if!path.exists() {
if let Err(e) = fs::create_dir(directory) {
show_info!("{}: {}", path.display(), e.to_string());
all_successful = false;
}
}
if mode::chmod(&path, b.mode()).is_err() {
all_successful = false;
}
if b.verbose {
show_info!("created directory '{}'", path.display());
}
}
if all_successful {
0
} else {
1
}
}
}
/// Test if the path is a new file path that can be
/// created immediately
fn is_new_file_path(path: &Path) -> bool {
!path.exists()
&& (path.parent().map(Path::is_dir).unwrap_or(true)
|| path.parent().unwrap().to_string_lossy().is_empty()) // In case of a simple file
}
/// Perform an install, given a list of paths and behavior.
///
/// Returns an integer intended as a program return code.
///
fn standard(paths: Vec<String>, b: Behavior) -> i32 {
if paths.len() < 2 {
println!("{} requires at least 2 arguments.", executable!());
1
} else {
let sources = &paths[0..paths.len() - 1]
.iter()
.map(PathBuf::from)
.collect::<Vec<_>>();
let target = Path::new(paths.last().unwrap());
if (target.is_file() || is_new_file_path(target)) && sources.len() == 1 {
/* If the target already exist or directly creatable */
copy_file_to_file(&sources[0], &target.to_path_buf(), &b)
} else {
copy_files_into_dir(sources, &target.to_path_buf(), &b)
}
}
}
/// Copy some files into a directory.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _files_ must all exist as non-directories.
/// _target_dir_ must be a directory.
///
fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> i32 {
if!target_dir.is_dir() {
show_error!("target ‘{}’ is not a directory", target_dir.display());
return 1;
}
let mut all_successful = true;
for sourcepath in files.iter() {
let targetpath = match sourcepath.as_os_str().to_str() {
Some(name) => target_dir.join(name),
None => {
show_error!(
"cannot stat ‘{}’: No such file or directory",
sourcepath.display()
);
all_successful = false;
continue;
}
};
if copy(sourcepath, &targetpath, b).is_err() {
all_successful = false;
}
}
if all_successful {
0
} else {
1
}
}
/// Copy a file to another file.
///
/// Prints verbose information and error messages.
/// Returns an integer intended as a program return code.
///
/// # Parameters
///
/// _file_ must exist as a non-directory.
/// _target_ must be a non-directory
///
fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behavior) -> i32 {
if copy(file, &target, b).is_err() {
1
} else {
0
}
}
/// Copy one file to a new location, changing metadata.
///
/// # Parameters
///
/// _from_ must exist as a non-directory.
/// _to_ must be a non-existent file, whose parent directory exists.
///
/// # Errors
///
/// If the copy system call fails, we print a verbose error and return an empty error value.
///
fn copy(from: &PathBuf, to: &PathBuf, b: &Behavior) -> Result<(), ()> {
let io_result = fs::copy(from, to);
if let Err(err) = io_result {
show_error!(
"install: cannot install ‘{}’ to ‘{}’: {}",
from.display(),
to.display(),
err
);
return Err(());
}
if mode::chmod(&to, b.mode()).is_err() {
return Err(());
}
if b.verbose {
show_info!("'{}' -> '{}'", from.display(), to.display());
}
Ok(())
} | random_line_split |
|
asset.rs | /*
* This file is part of the UnityPack rust package.
* (c) Istvan Fehervari <[email protected]>
*
* All rights reserved 2017
*/
use assetbundle::AssetBundle;
use assetbundle::Signature;
use assetbundle::FSDescriptor;
use typetree::{TypeMetadata, TypeNode};
use resources::default_type_metadata;
use binaryreader::*;
use object::ObjectInfo;
use std::collections::HashMap;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use std::io;
use lzma;
use uuid::Uuid;
use std::sync::Arc;
use error::{Error, Result};
pub struct Asset {
pub name: String,
pub bundle_offset: u64,
pub objects: HashMap<i64, ObjectInfo>,
pub is_loaded: bool,
pub endianness: Endianness,
pub tree: Option<TypeMetadata>,
pub types: HashMap<i64, Arc<TypeNode>>,
pub asset_refs: Vec<AssetOrRef>,
adds: Vec<(i64, i32)>,
pub typenames: HashMap<i64, String>,
// properties
metadata_size: u32,
file_size: u32,
pub format: u32,
pub data_offset: u32,
pub long_object_ids: bool,
}
impl Asset {
pub fn new(bundle: &mut AssetBundle) -> Result<Asset> {
let is_compressed = bundle.is_compressed();
let ref descriptor = bundle.descriptor;
let decompressed: Vec<u8>;
let mut asset = Asset {
bundle_offset: 0,
name: String::new(),
objects: HashMap::new(),
is_loaded: false,
endianness: Endianness::Big,
tree: None,
types: HashMap::new(),
// when requesting first element it should be the asset itself
asset_refs: vec![AssetOrRef::Asset],
adds: Vec::new(),
typenames: HashMap::new(),
metadata_size: 0,
file_size: 0,
format: 0,
data_offset: 0,
long_object_ids: false,
};
{
let buffer = match &mut bundle.signature {
&mut Signature::UnityFS(ref mut buf) => {
asset.bundle_offset = buf.tell();
return Ok(asset);
}
&mut Signature::UnityWeb(ref mut buf) | &mut Signature::UnityRaw(ref mut buf) => {
buf
}
_ => {
return Err(Error::InvalidSignatureError);
}
};
let offset = buffer.tell();
let header_size: u32;
if!is_compressed {
asset.name = buffer.read_string()?;
header_size = buffer.read_u32(&Endianness::Big)?;
buffer.read_u32(&Endianness::Big)?; // size
} else {
header_size = match descriptor {
&FSDescriptor::Raw(ref desc) => desc.asset_header_size,
_ => {
return Err(Error::AssetError("Invalid raw descriptor".to_string()));
}
};
}
let ofs = buffer.tell(); // save current offset so pointer can be later restored
if is_compressed {
let mut compressed_data = Vec::new();
try!(buffer.read_to_end(&mut compressed_data));
decompressed = match lzma::decompress(&mut compressed_data) {
Ok(data) => data,
Err(err) => {
return Err(Error::LZMADecompressionError(Box::new(err)));
}
};
asset.bundle_offset = 0;
try!(buffer.seek(SeekFrom::Start(ofs))); // restore pointer
} else {
asset.bundle_offset = offset + header_size as u64 - 4;
if asset.is_resource() {
asset.bundle_offset -= asset.name.len() as u64;
}
return Ok(asset);
}
}
// replace buffer in signature
bundle.signature = Signature::UnityRawCompressed(decompressed);
Ok(asset)
}
pub fn is_resource(&self) -> bool {
self.name.as_str().ends_with(".resource")
}
pub fn load_objects(&mut self, signature: &mut Signature) -> io::Result<()> {
if!self.is_loaded {
self.load(signature)?;
}
Ok(())
}
fn load(&mut self, signature: &mut Signature) -> Result<()> {
if self.is_resource() {
self.is_loaded = true;
return Ok(());
}
match signature {
&mut Signature::UnityFS(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRaw(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRawCompressed(ref mut buf) => {
self.load_from_buffer(&mut BufReader::new(Cursor::new(buf.as_slice())))?;
}
_ => {
return Err(Error::AssetError(format!(
"Signature not supported for loading objects: {:?}",
signature
)))
}
};
Ok(())
}
fn load_from_buffer<R: Read + Seek + Teller>(&mut self, buffer: &mut R) -> Result<()> {
let _ = buffer.seek(SeekFrom::Start(self.bundle_offset));
self.metadata_size = buffer.read_u32(&self.endianness)?;
self.file_size = buffer.read_u32(&self.endianness)?;
self.format = buffer.read_u32(&self.endianness)?;
self.data_offset = buffer.read_u32(&self.endianness)?;
if self.format >= 9 {
self.endianness = match buffer.read_u32(&self.endianness)? {
0 => Endianness::Little,
_ => Endianness::Big,
};
}
let tree = TypeMetadata::new(buffer, self.format, &self.endianness)?;
self.tree = Some(tree);
if (self.format >= 7) && (self.format <= 13) {
self.long_object_ids = buffer.read_u32(&self.endianness)?!= 0
}
let num_objects = buffer.read_u32(&self.endianness)?;
for _ in 0..num_objects {
if self.format >= 14 {
buffer.align();
}
let obj = ObjectInfo::new(self, buffer)?;
self.register_object(obj)?;
}
if self.format >= 11 {
let num_adds = buffer.read_u32(&self.endianness)?;
for _ in 0..num_adds {
if self.format >= 14 {
buffer.align();
}
let id = self.read_id(buffer)?;
let add = buffer.read_i32(&self.endianness)?;
self.adds.push((id, add));
}
}
let num_refs = buffer.read_u32(&self.endianness)?;
if self.format >= 6 {
for _ in 0..num_refs {
let asset_ref = AssetRef::new(buffer, &self.endianness)?;
self.asset_refs.push(AssetOrRef::AssetRef(asset_ref));
}
}
let unk_string = buffer.read_string()?;
if unk_string!= "" {
return Err(Error::AssetError(format!(
"Error while loading Asset, ending string is not empty but {:?}",
unk_string
)));
}
// we need to clone the keys to avoid borrow-checker problems
let mut keys: Vec<i64> = Vec::with_capacity(self.objects.keys().len());
{
let hashed_keys = self.objects.keys();
for k in hashed_keys {
keys.push(*k);
}
}
for k in keys {
let mut obj = self.objects.remove(&k).unwrap();
let type_name = obj.get_type(self, buffer);
obj.type_name = type_name;
self.typenames.insert(obj.type_id, obj.type_name.clone());
self.objects.insert(k, obj);
}
self.is_loaded = true;
Ok(())
}
fn register_object(&mut self, obj: ObjectInfo) -> Result<()> {
let ref tree = match &self.tree {
&Some(ref t) => t,
&None => return Ok(()),
};
match tree.type_trees.get(&obj.type_id) {
Some(o_type) => {
self.types.insert(obj.type_id, o_type.clone());
}
None => {
match self.types.get(&obj.type_id) {
Some(_) => {}
None => {
let ref trees = default_type_metadata()?.type_trees;
match trees.get(&(obj.class_id as i64)) {
Some(o) => {
self.types.insert(obj.type_id, o.clone());
}
None => {
// log warning
println!("Warning: {:?} is absent from structs.dat", obj.class_id);
// self.types.insert(obj.type_id, None)
}
};
}
};
}
};
match self.objects.get(&obj.path_id) {
Some(_) => {
return Err(Error::AssetError(format!(
"Duplicate asset object: {} (path_id={})",
obj,
obj.path_id
)))
}
None => {}
}
self.objects.insert(obj.path_id, obj);
Ok(())
}
pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> {
if self.format >= 14 {
return buffer.read_i64(&self.endianness);
}
let result = buffer.read_i32(&self.endianness)? as i64;
return Ok(result);
}
pub fn get_file_by_id(&self, id: &i32) -> Result<String> {
match &self.asset_refs[*id as usize] {
&AssetOrRef::Asset => Ok(self.name.clone()),
&AssetOrRef::AssetRef(ref a_ref) => Ok(a_ref.file_path.clone()),
}
}
}
#[allow(dead_code)]
pub struct | {
asset_path: String,
guid: Uuid,
asset_type: i32,
pub file_path: String,
// probably want to add a reference to the calling Asset itself
}
impl AssetRef {
pub fn new<R: Read + Seek + Teller>(
buffer: &mut R,
endianness: &Endianness,
) -> Result<AssetRef> {
let asset_path = buffer.read_string()?;
let mut uuid_buffer = [0; 16];
buffer.read_exact(&mut uuid_buffer)?;
let guid = match Uuid::from_bytes(&uuid_buffer) {
Ok(uuid) => uuid,
Err(err) => return Err(Error::UuidError(format!("{}", err))),
};
let asset_type = buffer.read_i32(endianness)?;
let file_path = buffer.read_string()?;
Ok(AssetRef {
asset_path: asset_path,
guid: guid,
asset_type: asset_type,
file_path: file_path,
})
}
}
pub enum AssetOrRef {
Asset,
AssetRef(AssetRef),
}
| AssetRef | identifier_name |
asset.rs | /*
* This file is part of the UnityPack rust package.
* (c) Istvan Fehervari <[email protected]>
*
* All rights reserved 2017
*/
use assetbundle::AssetBundle;
use assetbundle::Signature;
use assetbundle::FSDescriptor;
use typetree::{TypeMetadata, TypeNode};
use resources::default_type_metadata;
use binaryreader::*;
use object::ObjectInfo;
use std::collections::HashMap;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use std::io;
use lzma;
use uuid::Uuid;
use std::sync::Arc;
use error::{Error, Result};
pub struct Asset {
pub name: String,
pub bundle_offset: u64,
pub objects: HashMap<i64, ObjectInfo>,
pub is_loaded: bool,
pub endianness: Endianness,
pub tree: Option<TypeMetadata>,
pub types: HashMap<i64, Arc<TypeNode>>,
pub asset_refs: Vec<AssetOrRef>,
adds: Vec<(i64, i32)>,
pub typenames: HashMap<i64, String>,
// properties
metadata_size: u32,
file_size: u32,
pub format: u32,
pub data_offset: u32,
pub long_object_ids: bool,
}
impl Asset {
pub fn new(bundle: &mut AssetBundle) -> Result<Asset> {
let is_compressed = bundle.is_compressed();
let ref descriptor = bundle.descriptor;
let decompressed: Vec<u8>;
let mut asset = Asset {
bundle_offset: 0,
name: String::new(),
objects: HashMap::new(),
is_loaded: false,
endianness: Endianness::Big,
tree: None,
types: HashMap::new(),
// when requesting first element it should be the asset itself
asset_refs: vec![AssetOrRef::Asset],
adds: Vec::new(),
typenames: HashMap::new(),
metadata_size: 0,
file_size: 0,
format: 0,
data_offset: 0,
long_object_ids: false,
};
{
let buffer = match &mut bundle.signature {
&mut Signature::UnityFS(ref mut buf) => {
asset.bundle_offset = buf.tell();
return Ok(asset);
}
&mut Signature::UnityWeb(ref mut buf) | &mut Signature::UnityRaw(ref mut buf) => {
buf
}
_ => {
return Err(Error::InvalidSignatureError);
}
};
let offset = buffer.tell();
let header_size: u32;
if!is_compressed {
asset.name = buffer.read_string()?;
header_size = buffer.read_u32(&Endianness::Big)?;
buffer.read_u32(&Endianness::Big)?; // size
} else {
header_size = match descriptor {
&FSDescriptor::Raw(ref desc) => desc.asset_header_size,
_ => {
return Err(Error::AssetError("Invalid raw descriptor".to_string()));
}
};
}
let ofs = buffer.tell(); // save current offset so pointer can be later restored
if is_compressed {
let mut compressed_data = Vec::new();
try!(buffer.read_to_end(&mut compressed_data));
decompressed = match lzma::decompress(&mut compressed_data) {
Ok(data) => data,
Err(err) => {
return Err(Error::LZMADecompressionError(Box::new(err)));
}
};
asset.bundle_offset = 0;
try!(buffer.seek(SeekFrom::Start(ofs))); // restore pointer
} else {
asset.bundle_offset = offset + header_size as u64 - 4;
if asset.is_resource() {
asset.bundle_offset -= asset.name.len() as u64;
}
return Ok(asset);
}
}
// replace buffer in signature
bundle.signature = Signature::UnityRawCompressed(decompressed);
Ok(asset)
}
pub fn is_resource(&self) -> bool {
self.name.as_str().ends_with(".resource")
}
pub fn load_objects(&mut self, signature: &mut Signature) -> io::Result<()> {
if!self.is_loaded {
self.load(signature)?;
}
Ok(())
}
fn load(&mut self, signature: &mut Signature) -> Result<()> {
if self.is_resource() {
self.is_loaded = true;
return Ok(());
}
match signature {
&mut Signature::UnityFS(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRaw(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRawCompressed(ref mut buf) => {
self.load_from_buffer(&mut BufReader::new(Cursor::new(buf.as_slice())))?;
}
_ => {
return Err(Error::AssetError(format!(
"Signature not supported for loading objects: {:?}",
signature
)))
}
};
Ok(())
}
fn load_from_buffer<R: Read + Seek + Teller>(&mut self, buffer: &mut R) -> Result<()> {
let _ = buffer.seek(SeekFrom::Start(self.bundle_offset));
self.metadata_size = buffer.read_u32(&self.endianness)?;
self.file_size = buffer.read_u32(&self.endianness)?;
self.format = buffer.read_u32(&self.endianness)?;
self.data_offset = buffer.read_u32(&self.endianness)?;
if self.format >= 9 {
self.endianness = match buffer.read_u32(&self.endianness)? {
0 => Endianness::Little,
_ => Endianness::Big,
};
}
let tree = TypeMetadata::new(buffer, self.format, &self.endianness)?;
self.tree = Some(tree);
if (self.format >= 7) && (self.format <= 13) {
self.long_object_ids = buffer.read_u32(&self.endianness)?!= 0
}
let num_objects = buffer.read_u32(&self.endianness)?;
for _ in 0..num_objects {
if self.format >= 14 {
buffer.align();
}
let obj = ObjectInfo::new(self, buffer)?;
self.register_object(obj)?;
}
if self.format >= 11 {
let num_adds = buffer.read_u32(&self.endianness)?;
for _ in 0..num_adds {
if self.format >= 14 {
buffer.align();
}
let id = self.read_id(buffer)?;
let add = buffer.read_i32(&self.endianness)?;
self.adds.push((id, add));
}
}
let num_refs = buffer.read_u32(&self.endianness)?;
if self.format >= 6 {
for _ in 0..num_refs {
let asset_ref = AssetRef::new(buffer, &self.endianness)?;
self.asset_refs.push(AssetOrRef::AssetRef(asset_ref));
}
}
let unk_string = buffer.read_string()?;
if unk_string!= "" {
return Err(Error::AssetError(format!(
"Error while loading Asset, ending string is not empty but {:?}",
unk_string
)));
}
// we need to clone the keys to avoid borrow-checker problems
let mut keys: Vec<i64> = Vec::with_capacity(self.objects.keys().len());
{
let hashed_keys = self.objects.keys();
for k in hashed_keys {
keys.push(*k);
}
}
for k in keys {
let mut obj = self.objects.remove(&k).unwrap();
let type_name = obj.get_type(self, buffer);
obj.type_name = type_name;
self.typenames.insert(obj.type_id, obj.type_name.clone());
self.objects.insert(k, obj);
}
self.is_loaded = true;
Ok(())
}
fn register_object(&mut self, obj: ObjectInfo) -> Result<()> {
let ref tree = match &self.tree {
&Some(ref t) => t,
&None => return Ok(()),
};
match tree.type_trees.get(&obj.type_id) {
Some(o_type) => {
self.types.insert(obj.type_id, o_type.clone());
}
None => {
match self.types.get(&obj.type_id) {
Some(_) => {}
None => {
let ref trees = default_type_metadata()?.type_trees;
match trees.get(&(obj.class_id as i64)) {
Some(o) => {
self.types.insert(obj.type_id, o.clone());
}
None => {
// log warning
println!("Warning: {:?} is absent from structs.dat", obj.class_id);
// self.types.insert(obj.type_id, None)
}
};
}
};
}
};
match self.objects.get(&obj.path_id) {
Some(_) => {
return Err(Error::AssetError(format!(
"Duplicate asset object: {} (path_id={})",
obj,
obj.path_id
)))
}
None => |
}
self.objects.insert(obj.path_id, obj);
Ok(())
}
pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> {
if self.format >= 14 {
return buffer.read_i64(&self.endianness);
}
let result = buffer.read_i32(&self.endianness)? as i64;
return Ok(result);
}
pub fn get_file_by_id(&self, id: &i32) -> Result<String> {
match &self.asset_refs[*id as usize] {
&AssetOrRef::Asset => Ok(self.name.clone()),
&AssetOrRef::AssetRef(ref a_ref) => Ok(a_ref.file_path.clone()),
}
}
}
#[allow(dead_code)]
pub struct AssetRef {
asset_path: String,
guid: Uuid,
asset_type: i32,
pub file_path: String,
// probably want to add a reference to the calling Asset itself
}
impl AssetRef {
pub fn new<R: Read + Seek + Teller>(
buffer: &mut R,
endianness: &Endianness,
) -> Result<AssetRef> {
let asset_path = buffer.read_string()?;
let mut uuid_buffer = [0; 16];
buffer.read_exact(&mut uuid_buffer)?;
let guid = match Uuid::from_bytes(&uuid_buffer) {
Ok(uuid) => uuid,
Err(err) => return Err(Error::UuidError(format!("{}", err))),
};
let asset_type = buffer.read_i32(endianness)?;
let file_path = buffer.read_string()?;
Ok(AssetRef {
asset_path: asset_path,
guid: guid,
asset_type: asset_type,
file_path: file_path,
})
}
}
pub enum AssetOrRef {
Asset,
AssetRef(AssetRef),
}
| {} | conditional_block |
asset.rs | /*
* This file is part of the UnityPack rust package.
* (c) Istvan Fehervari <[email protected]>
*
* All rights reserved 2017
*/
use assetbundle::AssetBundle;
use assetbundle::Signature;
use assetbundle::FSDescriptor;
use typetree::{TypeMetadata, TypeNode};
use resources::default_type_metadata;
use binaryreader::*;
use object::ObjectInfo;
use std::collections::HashMap;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use std::io;
use lzma;
use uuid::Uuid;
use std::sync::Arc;
use error::{Error, Result};
pub struct Asset {
pub name: String,
pub bundle_offset: u64,
pub objects: HashMap<i64, ObjectInfo>,
pub is_loaded: bool,
pub endianness: Endianness,
pub tree: Option<TypeMetadata>,
pub types: HashMap<i64, Arc<TypeNode>>,
pub asset_refs: Vec<AssetOrRef>,
adds: Vec<(i64, i32)>,
pub typenames: HashMap<i64, String>,
// properties
metadata_size: u32,
file_size: u32,
pub format: u32,
pub data_offset: u32,
pub long_object_ids: bool,
}
impl Asset {
pub fn new(bundle: &mut AssetBundle) -> Result<Asset> {
let is_compressed = bundle.is_compressed();
let ref descriptor = bundle.descriptor;
let decompressed: Vec<u8>;
let mut asset = Asset {
bundle_offset: 0,
name: String::new(),
objects: HashMap::new(),
is_loaded: false,
endianness: Endianness::Big,
tree: None,
types: HashMap::new(),
// when requesting first element it should be the asset itself
asset_refs: vec![AssetOrRef::Asset],
adds: Vec::new(),
typenames: HashMap::new(),
metadata_size: 0,
file_size: 0,
format: 0,
data_offset: 0,
long_object_ids: false,
};
{
let buffer = match &mut bundle.signature {
&mut Signature::UnityFS(ref mut buf) => {
asset.bundle_offset = buf.tell();
return Ok(asset);
}
&mut Signature::UnityWeb(ref mut buf) | &mut Signature::UnityRaw(ref mut buf) => {
buf
}
_ => {
return Err(Error::InvalidSignatureError);
}
};
let offset = buffer.tell();
let header_size: u32;
if!is_compressed {
asset.name = buffer.read_string()?;
header_size = buffer.read_u32(&Endianness::Big)?;
buffer.read_u32(&Endianness::Big)?; // size
} else {
header_size = match descriptor {
&FSDescriptor::Raw(ref desc) => desc.asset_header_size,
_ => {
return Err(Error::AssetError("Invalid raw descriptor".to_string()));
}
};
}
let ofs = buffer.tell(); // save current offset so pointer can be later restored
if is_compressed {
let mut compressed_data = Vec::new();
try!(buffer.read_to_end(&mut compressed_data));
decompressed = match lzma::decompress(&mut compressed_data) {
Ok(data) => data,
Err(err) => {
return Err(Error::LZMADecompressionError(Box::new(err)));
}
};
asset.bundle_offset = 0;
try!(buffer.seek(SeekFrom::Start(ofs))); // restore pointer
} else {
asset.bundle_offset = offset + header_size as u64 - 4;
if asset.is_resource() {
asset.bundle_offset -= asset.name.len() as u64;
}
return Ok(asset);
}
}
// replace buffer in signature
bundle.signature = Signature::UnityRawCompressed(decompressed);
Ok(asset)
}
pub fn is_resource(&self) -> bool {
self.name.as_str().ends_with(".resource")
}
pub fn load_objects(&mut self, signature: &mut Signature) -> io::Result<()> {
if!self.is_loaded {
self.load(signature)?;
}
Ok(())
}
fn load(&mut self, signature: &mut Signature) -> Result<()> {
if self.is_resource() {
self.is_loaded = true;
return Ok(());
}
match signature {
&mut Signature::UnityFS(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRaw(ref mut buf) => {
self.load_from_buffer(buf)?;
}
&mut Signature::UnityRawCompressed(ref mut buf) => {
self.load_from_buffer(&mut BufReader::new(Cursor::new(buf.as_slice())))?;
}
_ => {
return Err(Error::AssetError(format!(
"Signature not supported for loading objects: {:?}",
signature
)))
}
};
Ok(())
}
fn load_from_buffer<R: Read + Seek + Teller>(&mut self, buffer: &mut R) -> Result<()> {
let _ = buffer.seek(SeekFrom::Start(self.bundle_offset));
self.metadata_size = buffer.read_u32(&self.endianness)?;
self.file_size = buffer.read_u32(&self.endianness)?;
self.format = buffer.read_u32(&self.endianness)?;
self.data_offset = buffer.read_u32(&self.endianness)?;
if self.format >= 9 {
self.endianness = match buffer.read_u32(&self.endianness)? {
0 => Endianness::Little,
_ => Endianness::Big,
};
}
let tree = TypeMetadata::new(buffer, self.format, &self.endianness)?;
self.tree = Some(tree);
if (self.format >= 7) && (self.format <= 13) {
self.long_object_ids = buffer.read_u32(&self.endianness)?!= 0
}
let num_objects = buffer.read_u32(&self.endianness)?;
for _ in 0..num_objects {
if self.format >= 14 {
buffer.align();
}
let obj = ObjectInfo::new(self, buffer)?;
self.register_object(obj)?;
}
if self.format >= 11 {
let num_adds = buffer.read_u32(&self.endianness)?;
for _ in 0..num_adds {
if self.format >= 14 {
buffer.align();
}
let id = self.read_id(buffer)?;
let add = buffer.read_i32(&self.endianness)?;
self.adds.push((id, add));
}
}
let num_refs = buffer.read_u32(&self.endianness)?;
if self.format >= 6 {
for _ in 0..num_refs {
let asset_ref = AssetRef::new(buffer, &self.endianness)?;
self.asset_refs.push(AssetOrRef::AssetRef(asset_ref));
}
}
let unk_string = buffer.read_string()?;
if unk_string!= "" {
return Err(Error::AssetError(format!(
"Error while loading Asset, ending string is not empty but {:?}",
unk_string
)));
}
// we need to clone the keys to avoid borrow-checker problems
let mut keys: Vec<i64> = Vec::with_capacity(self.objects.keys().len());
{
let hashed_keys = self.objects.keys();
for k in hashed_keys {
keys.push(*k);
}
}
for k in keys {
let mut obj = self.objects.remove(&k).unwrap();
let type_name = obj.get_type(self, buffer);
obj.type_name = type_name;
self.typenames.insert(obj.type_id, obj.type_name.clone());
self.objects.insert(k, obj);
}
self.is_loaded = true;
Ok(())
}
fn register_object(&mut self, obj: ObjectInfo) -> Result<()> {
let ref tree = match &self.tree {
&Some(ref t) => t,
&None => return Ok(()),
};
match tree.type_trees.get(&obj.type_id) {
Some(o_type) => {
self.types.insert(obj.type_id, o_type.clone());
}
None => {
match self.types.get(&obj.type_id) {
Some(_) => {}
None => {
let ref trees = default_type_metadata()?.type_trees;
match trees.get(&(obj.class_id as i64)) {
Some(o) => {
self.types.insert(obj.type_id, o.clone());
}
None => {
// log warning
println!("Warning: {:?} is absent from structs.dat", obj.class_id);
// self.types.insert(obj.type_id, None)
}
};
}
};
}
};
match self.objects.get(&obj.path_id) {
Some(_) => {
return Err(Error::AssetError(format!(
"Duplicate asset object: {} (path_id={})",
obj,
obj.path_id
)))
}
None => {}
}
self.objects.insert(obj.path_id, obj);
Ok(())
}
pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> {
if self.format >= 14 {
return buffer.read_i64(&self.endianness);
}
let result = buffer.read_i32(&self.endianness)? as i64;
return Ok(result);
}
pub fn get_file_by_id(&self, id: &i32) -> Result<String> {
match &self.asset_refs[*id as usize] {
&AssetOrRef::Asset => Ok(self.name.clone()),
&AssetOrRef::AssetRef(ref a_ref) => Ok(a_ref.file_path.clone()),
}
}
}
#[allow(dead_code)]
pub struct AssetRef {
asset_path: String,
guid: Uuid,
asset_type: i32,
pub file_path: String,
// probably want to add a reference to the calling Asset itself
}
impl AssetRef {
pub fn new<R: Read + Seek + Teller>(
buffer: &mut R,
endianness: &Endianness,
) -> Result<AssetRef> {
let asset_path = buffer.read_string()?;
let mut uuid_buffer = [0; 16];
buffer.read_exact(&mut uuid_buffer)?;
let guid = match Uuid::from_bytes(&uuid_buffer) {
Ok(uuid) => uuid,
Err(err) => return Err(Error::UuidError(format!("{}", err))),
};
let asset_type = buffer.read_i32(endianness)?;
let file_path = buffer.read_string()?;
Ok(AssetRef {
asset_path: asset_path,
guid: guid,
asset_type: asset_type,
file_path: file_path,
})
}
}
| } | pub enum AssetOrRef {
Asset,
AssetRef(AssetRef), | random_line_split |
mod.rs | // Copyright 2020-2023 - Nym Technologies SA <[email protected]>
// SPDX-License-Identifier: Apache-2.0
use crate::config::persistence::paths::MixNodePaths;
use crate::config::template::CONFIG_TEMPLATE;
use nym_bin_common::logging::LoggingSettings;
use nym_config::defaults::{
mainnet, DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT,
DEFAULT_VERLOC_LISTENING_PORT,
};
use nym_config::helpers::inaddr_any;
use nym_config::{
must_get_home, read_config_from_toml_file, save_formatted_config_to_file, NymConfigTemplate,
DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME, DEFAULT_DATA_DIR, NYM_DIR,
};
use serde::{Deserialize, Serialize};
use std::io;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use url::Url;
pub(crate) mod old_config_v1_1_21;
pub mod persistence;
mod template;
const DEFAULT_MIXNODES_DIR: &str = "mixnodes";
// 'RTT MEASUREMENT'
const DEFAULT_PACKETS_PER_NODE: usize = 100;
const DEFAULT_CONNECTION_TIMEOUT: Duration = Duration::from_millis(5000);
const DEFAULT_PACKET_TIMEOUT: Duration = Duration::from_millis(1500);
const DEFAULT_DELAY_BETWEEN_PACKETS: Duration = Duration::from_millis(50);
const DEFAULT_BATCH_SIZE: usize = 50;
const DEFAULT_TESTING_INTERVAL: Duration = Duration::from_secs(60 * 60 * 12);
const DEFAULT_RETRY_TIMEOUT: Duration = Duration::from_secs(60 * 30);
// 'DEBUG'
const DEFAULT_NODE_STATS_LOGGING_DELAY: Duration = Duration::from_millis(60_000);
const DEFAULT_NODE_STATS_UPDATING_DELAY: Duration = Duration::from_millis(30_000);
const DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF: Duration = Duration::from_millis(10_000);
const DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF: Duration = Duration::from_millis(300_000);
const DEFAULT_INITIAL_CONNECTION_TIMEOUT: Duration = Duration::from_millis(1_500);
const DEFAULT_MAXIMUM_CONNECTION_BUFFER_SIZE: usize = 2000;
/// Derive default path to mixnodes's config directory.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/config`
pub fn default_config_directory<P: AsRef<Path>>(id: P) -> PathBuf {
must_get_home()
.join(NYM_DIR)
.join(DEFAULT_MIXNODES_DIR)
.join(id)
.join(DEFAULT_CONFIG_DIR)
}
/// Derive default path to mixnodes's config file.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/config/config.toml`
pub fn default_config_filepath<P: AsRef<Path>>(id: P) -> PathBuf {
default_config_directory(id).join(DEFAULT_CONFIG_FILENAME)
}
/// Derive default path to mixnodes's data directory where files, such as keys, are stored.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/data`
pub fn default_data_directory<P: AsRef<Path>>(id: P) -> PathBuf {
must_get_home()
.join(NYM_DIR)
.join(DEFAULT_MIXNODES_DIR)
.join(id)
.join(DEFAULT_DATA_DIR)
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub mixnode: MixNode,
pub storage_paths: MixNodePaths,
#[serde(default)]
pub verloc: Verloc,
#[serde(default)]
pub logging: LoggingSettings,
#[serde(default)]
pub debug: Debug,
}
impl NymConfigTemplate for Config {
fn template() -> &'static str {
CONFIG_TEMPLATE
}
}
impl Config {
pub fn new<S: AsRef<str>>(id: S) -> Self {
Config {
mixnode: MixNode::new_default(id.as_ref()),
storage_paths: MixNodePaths::new_default(id.as_ref()),
verloc: Default::default(),
logging: Default::default(),
debug: Default::default(),
}
}
pub fn read_from_toml_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
read_config_from_toml_file(path)
}
pub fn read_from_default_path<P: AsRef<Path>>(id: P) -> io::Result<Self> {
Self::read_from_toml_file(default_config_filepath(id))
}
pub fn default_location(&self) -> PathBuf {
default_config_filepath(&self.mixnode.id)
}
pub fn save_to_default_location(&self) -> io::Result<()> {
let config_save_location: PathBuf = self.default_location();
save_formatted_config_to_file(self, config_save_location)
}
// builder methods
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.mixnode.nym_api_urls = nym_api_urls;
self
}
pub fn with_listening_address(mut self, listening_address: IpAddr) -> Self {
self.mixnode.listening_address = listening_address;
self
}
pub fn with_mix_port(mut self, port: u16) -> Self {
self.mixnode.mix_port = port;
self
}
pub fn with_verloc_port(mut self, port: u16) -> Self {
self.mixnode.verloc_port = port;
self
}
pub fn with_http_api_port(mut self, port: u16) -> Self {
self.mixnode.http_api_port = port;
self
}
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
self.mixnode.nym_api_urls.clone()
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct MixNode {
/// Version of the mixnode for which this configuration was created.
pub version: String,
/// ID specifies the human readable ID of this particular mixnode.
pub id: String,
/// Address to which this mixnode will bind to and will be listening for packets.
pub listening_address: IpAddr,
/// Port used for listening for all mixnet traffic.
/// (default: 1789)
pub mix_port: u16,
/// Port used for listening for verloc traffic.
/// (default: 1790)
pub verloc_port: u16,
/// Port used for listening for http requests.
/// (default: 8000)
pub http_api_port: u16,
/// Addresses to nym APIs from which the node gets the view of the network.
pub nym_api_urls: Vec<Url>,
}
impl MixNode {
pub fn new_default<S: Into<String>>(id: S) -> Self {
MixNode {
version: env!("CARGO_PKG_VERSION").to_string(),
id: id.into(),
listening_address: inaddr_any(),
mix_port: DEFAULT_MIX_LISTENING_PORT,
verloc_port: DEFAULT_VERLOC_LISTENING_PORT,
http_api_port: DEFAULT_HTTP_API_LISTENING_PORT,
nym_api_urls: vec![Url::from_str(mainnet::NYM_API).expect("Invalid default API URL")],
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Verloc {
/// Specifies number of echo packets sent to each node during a measurement run.
pub packets_per_node: usize,
/// Specifies maximum amount of time to wait for the connection to get established.
#[serde(with = "humantime_serde")]
pub connection_timeout: Duration,
/// Specifies maximum amount of time to wait for the reply packet to arrive before abandoning the test.
#[serde(with = "humantime_serde")]
pub packet_timeout: Duration,
/// Specifies delay between subsequent test packets being sent (after receiving a reply).
#[serde(with = "humantime_serde")]
pub delay_between_packets: Duration,
/// Specifies number of nodes being tested at once.
pub tested_nodes_batch_size: usize,
/// Specifies delay between subsequent test runs.
#[serde(with = "humantime_serde")]
pub testing_interval: Duration,
/// Specifies delay between attempting to run the measurement again if the previous run failed
/// due to being unable to get the list of nodes.
#[serde(with = "humantime_serde")]
pub retry_timeout: Duration,
}
impl Default for Verloc {
fn default() -> Self {
Verloc {
packets_per_node: DEFAULT_PACKETS_PER_NODE,
connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
packet_timeout: DEFAULT_PACKET_TIMEOUT,
delay_between_packets: DEFAULT_DELAY_BETWEEN_PACKETS,
tested_nodes_batch_size: DEFAULT_BATCH_SIZE,
testing_interval: DEFAULT_TESTING_INTERVAL,
retry_timeout: DEFAULT_RETRY_TIMEOUT,
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct Debug {
/// Delay between each subsequent node statistics being logged to the console
#[serde(with = "humantime_serde")]
pub node_stats_logging_delay: Duration,
/// Delay between each subsequent node statistics being updated
#[serde(with = "humantime_serde")]
pub node_stats_updating_delay: Duration,
/// Initial value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
#[serde(with = "humantime_serde")]
pub packet_forwarding_initial_backoff: Duration,
/// Maximum value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
#[serde(with = "humantime_serde")]
pub packet_forwarding_maximum_backoff: Duration,
/// Timeout for establishing initial connection when trying to forward a sphinx packet.
#[serde(with = "humantime_serde")]
pub initial_connection_timeout: Duration,
/// Maximum number of packets that can be stored waiting to get sent to a particular connection.
pub maximum_connection_buffer_size: usize,
/// Specifies whether the mixnode should be using the legacy framing for the sphinx packets.
// it's set to true by default. The reason for that decision is to preserve compatibility with the
// existing nodes whilst everyone else is upgrading and getting the code for handling the new field.
// It shall be disabled in the subsequent releases.
pub use_legacy_framed_packet_version: bool,
}
impl Default for Debug {
fn default() -> Self {
Debug {
node_stats_logging_delay: DEFAULT_NODE_STATS_LOGGING_DELAY,
node_stats_updating_delay: DEFAULT_NODE_STATS_UPDATING_DELAY,
packet_forwarding_initial_backoff: DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF,
packet_forwarding_maximum_backoff: DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF,
initial_connection_timeout: DEFAULT_INITIAL_CONNECTION_TIMEOUT,
maximum_connection_buffer_size: DEFAULT_MAXIMUM_CONNECTION_BUFFER_SIZE,
// TODO: remember to change it in one of future releases!!
use_legacy_framed_packet_version: true,
} | }
} | random_line_split |
|
mod.rs | // Copyright 2020-2023 - Nym Technologies SA <[email protected]>
// SPDX-License-Identifier: Apache-2.0
use crate::config::persistence::paths::MixNodePaths;
use crate::config::template::CONFIG_TEMPLATE;
use nym_bin_common::logging::LoggingSettings;
use nym_config::defaults::{
mainnet, DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT,
DEFAULT_VERLOC_LISTENING_PORT,
};
use nym_config::helpers::inaddr_any;
use nym_config::{
must_get_home, read_config_from_toml_file, save_formatted_config_to_file, NymConfigTemplate,
DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME, DEFAULT_DATA_DIR, NYM_DIR,
};
use serde::{Deserialize, Serialize};
use std::io;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use url::Url;
pub(crate) mod old_config_v1_1_21;
pub mod persistence;
mod template;
const DEFAULT_MIXNODES_DIR: &str = "mixnodes";
// 'RTT MEASUREMENT'
const DEFAULT_PACKETS_PER_NODE: usize = 100;
const DEFAULT_CONNECTION_TIMEOUT: Duration = Duration::from_millis(5000);
const DEFAULT_PACKET_TIMEOUT: Duration = Duration::from_millis(1500);
const DEFAULT_DELAY_BETWEEN_PACKETS: Duration = Duration::from_millis(50);
const DEFAULT_BATCH_SIZE: usize = 50;
const DEFAULT_TESTING_INTERVAL: Duration = Duration::from_secs(60 * 60 * 12);
const DEFAULT_RETRY_TIMEOUT: Duration = Duration::from_secs(60 * 30);
// 'DEBUG'
const DEFAULT_NODE_STATS_LOGGING_DELAY: Duration = Duration::from_millis(60_000);
const DEFAULT_NODE_STATS_UPDATING_DELAY: Duration = Duration::from_millis(30_000);
const DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF: Duration = Duration::from_millis(10_000);
const DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF: Duration = Duration::from_millis(300_000);
const DEFAULT_INITIAL_CONNECTION_TIMEOUT: Duration = Duration::from_millis(1_500);
const DEFAULT_MAXIMUM_CONNECTION_BUFFER_SIZE: usize = 2000;
/// Derive default path to mixnodes's config directory.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/config`
pub fn default_config_directory<P: AsRef<Path>>(id: P) -> PathBuf {
must_get_home()
.join(NYM_DIR)
.join(DEFAULT_MIXNODES_DIR)
.join(id)
.join(DEFAULT_CONFIG_DIR)
}
/// Derive default path to mixnodes's config file.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/config/config.toml`
pub fn default_config_filepath<P: AsRef<Path>>(id: P) -> PathBuf {
default_config_directory(id).join(DEFAULT_CONFIG_FILENAME)
}
/// Derive default path to mixnodes's data directory where files, such as keys, are stored.
/// It should get resolved to `$HOME/.nym/mixnodes/<id>/data`
pub fn default_data_directory<P: AsRef<Path>>(id: P) -> PathBuf {
must_get_home()
.join(NYM_DIR)
.join(DEFAULT_MIXNODES_DIR)
.join(id)
.join(DEFAULT_DATA_DIR)
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub mixnode: MixNode,
pub storage_paths: MixNodePaths,
#[serde(default)]
pub verloc: Verloc,
#[serde(default)]
pub logging: LoggingSettings,
#[serde(default)]
pub debug: Debug,
}
impl NymConfigTemplate for Config {
fn template() -> &'static str {
CONFIG_TEMPLATE
}
}
impl Config {
pub fn new<S: AsRef<str>>(id: S) -> Self {
Config {
mixnode: MixNode::new_default(id.as_ref()),
storage_paths: MixNodePaths::new_default(id.as_ref()),
verloc: Default::default(),
logging: Default::default(),
debug: Default::default(),
}
}
pub fn read_from_toml_file<P: AsRef<Path>>(path: P) -> io::Result<Self> {
read_config_from_toml_file(path)
}
pub fn read_from_default_path<P: AsRef<Path>>(id: P) -> io::Result<Self> {
Self::read_from_toml_file(default_config_filepath(id))
}
pub fn default_location(&self) -> PathBuf {
default_config_filepath(&self.mixnode.id)
}
pub fn save_to_default_location(&self) -> io::Result<()> {
let config_save_location: PathBuf = self.default_location();
save_formatted_config_to_file(self, config_save_location)
}
// builder methods
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.mixnode.nym_api_urls = nym_api_urls;
self
}
pub fn with_listening_address(mut self, listening_address: IpAddr) -> Self {
self.mixnode.listening_address = listening_address;
self
}
pub fn | (mut self, port: u16) -> Self {
self.mixnode.mix_port = port;
self
}
pub fn with_verloc_port(mut self, port: u16) -> Self {
self.mixnode.verloc_port = port;
self
}
pub fn with_http_api_port(mut self, port: u16) -> Self {
self.mixnode.http_api_port = port;
self
}
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
self.mixnode.nym_api_urls.clone()
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct MixNode {
/// Version of the mixnode for which this configuration was created.
pub version: String,
/// ID specifies the human readable ID of this particular mixnode.
pub id: String,
/// Address to which this mixnode will bind to and will be listening for packets.
pub listening_address: IpAddr,
/// Port used for listening for all mixnet traffic.
/// (default: 1789)
pub mix_port: u16,
/// Port used for listening for verloc traffic.
/// (default: 1790)
pub verloc_port: u16,
/// Port used for listening for http requests.
/// (default: 8000)
pub http_api_port: u16,
/// Addresses to nym APIs from which the node gets the view of the network.
pub nym_api_urls: Vec<Url>,
}
impl MixNode {
pub fn new_default<S: Into<String>>(id: S) -> Self {
MixNode {
version: env!("CARGO_PKG_VERSION").to_string(),
id: id.into(),
listening_address: inaddr_any(),
mix_port: DEFAULT_MIX_LISTENING_PORT,
verloc_port: DEFAULT_VERLOC_LISTENING_PORT,
http_api_port: DEFAULT_HTTP_API_LISTENING_PORT,
nym_api_urls: vec![Url::from_str(mainnet::NYM_API).expect("Invalid default API URL")],
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Verloc {
/// Specifies number of echo packets sent to each node during a measurement run.
pub packets_per_node: usize,
/// Specifies maximum amount of time to wait for the connection to get established.
#[serde(with = "humantime_serde")]
pub connection_timeout: Duration,
/// Specifies maximum amount of time to wait for the reply packet to arrive before abandoning the test.
#[serde(with = "humantime_serde")]
pub packet_timeout: Duration,
/// Specifies delay between subsequent test packets being sent (after receiving a reply).
#[serde(with = "humantime_serde")]
pub delay_between_packets: Duration,
/// Specifies number of nodes being tested at once.
pub tested_nodes_batch_size: usize,
/// Specifies delay between subsequent test runs.
#[serde(with = "humantime_serde")]
pub testing_interval: Duration,
/// Specifies delay between attempting to run the measurement again if the previous run failed
/// due to being unable to get the list of nodes.
#[serde(with = "humantime_serde")]
pub retry_timeout: Duration,
}
impl Default for Verloc {
fn default() -> Self {
Verloc {
packets_per_node: DEFAULT_PACKETS_PER_NODE,
connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
packet_timeout: DEFAULT_PACKET_TIMEOUT,
delay_between_packets: DEFAULT_DELAY_BETWEEN_PACKETS,
tested_nodes_batch_size: DEFAULT_BATCH_SIZE,
testing_interval: DEFAULT_TESTING_INTERVAL,
retry_timeout: DEFAULT_RETRY_TIMEOUT,
}
}
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct Debug {
/// Delay between each subsequent node statistics being logged to the console
#[serde(with = "humantime_serde")]
pub node_stats_logging_delay: Duration,
/// Delay between each subsequent node statistics being updated
#[serde(with = "humantime_serde")]
pub node_stats_updating_delay: Duration,
/// Initial value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
#[serde(with = "humantime_serde")]
pub packet_forwarding_initial_backoff: Duration,
/// Maximum value of an exponential backoff to reconnect to dropped TCP connection when
/// forwarding sphinx packets.
#[serde(with = "humantime_serde")]
pub packet_forwarding_maximum_backoff: Duration,
/// Timeout for establishing initial connection when trying to forward a sphinx packet.
#[serde(with = "humantime_serde")]
pub initial_connection_timeout: Duration,
/// Maximum number of packets that can be stored waiting to get sent to a particular connection.
pub maximum_connection_buffer_size: usize,
/// Specifies whether the mixnode should be using the legacy framing for the sphinx packets.
// it's set to true by default. The reason for that decision is to preserve compatibility with the
// existing nodes whilst everyone else is upgrading and getting the code for handling the new field.
// It shall be disabled in the subsequent releases.
pub use_legacy_framed_packet_version: bool,
}
impl Default for Debug {
fn default() -> Self {
Debug {
node_stats_logging_delay: DEFAULT_NODE_STATS_LOGGING_DELAY,
node_stats_updating_delay: DEFAULT_NODE_STATS_UPDATING_DELAY,
packet_forwarding_initial_backoff: DEFAULT_PACKET_FORWARDING_INITIAL_BACKOFF,
packet_forwarding_maximum_backoff: DEFAULT_PACKET_FORWARDING_MAXIMUM_BACKOFF,
initial_connection_timeout: DEFAULT_INITIAL_CONNECTION_TIMEOUT,
maximum_connection_buffer_size: DEFAULT_MAXIMUM_CONNECTION_BUFFER_SIZE,
// TODO: remember to change it in one of future releases!!
use_legacy_framed_packet_version: true,
}
}
}
| with_mix_port | identifier_name |
interpreter.rs | use super::{environment::Environment, primitives};
use calyx::{errors::FutilResult, ir};
use std::collections::HashMap;
/// Evaluates a group, given an environment.
pub fn eval_group(
group: ir::RRC<ir::Group>,
env: &Environment,
) -> FutilResult<Environment> {
eval_assigns(&(group.borrow()).assignments, &env)
}
// XXX(karen): I think it will need another copy of environment for each
// iteration of assignment statements
/// Evaluates a group's assignment statements in an environment.
fn eval_assigns(
assigns: &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be deleted later
// (unless we want to display the clock cycle)?
let mut counter = 0;
// Filter out the assignment statements that are not only from cells.
// XXX: for now, also excludes cells not in the env map
let ok_assigns = assigns
.iter()
.filter(|&a| {
!a.dst.borrow().is_hole()
// dummy way of making sure the map has the a.src cell
&& env.get_cell(&get_cell_from_port(&a.src)).is_some()
&& env.get_cell(&get_cell_from_port(&a.dst)).is_some()
})
.collect::<Vec<_>>();
// While done_assign.src is 0 (we use done_assign.src because done_assign.dst is not a cell's port; it should be a group's port)
while write_env.get_from_port(&done_assign.src.borrow()) == 0 && counter < 5
{
// println!("Clock cycle {}", counter);
/*println!(
"state of done_cell {:1} : {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
// "staging" updates
//let mut iter_updates = write_env.clone();
// for assign in assigns
for assign in &ok_assigns {
// check if the assign.guard!= 0
// should it be evaluating the guard in write_env environment?
if eval_guard(&assign.guard, &write_env)!= 0 {
// check if the cells are constants?
// cell of assign.src
let src_cell = get_cell_from_port(&assign.src);
// cell of assign.dst
let dst_cell = get_cell_from_port(&assign.dst);
/*println!(
"src cell {:1} port: {:2}, dest cell {:3} port: {:4}",
src_cell,
&assign.src.borrow().name,
dst_cell,
&assign.dst.borrow().name
);*/
// perform a read from `env` for assign.src
// XXX(karen): should read from the previous iteration's env?
let read_val = env.get_from_port(&assign.src.borrow());
// update internal state of the cell and
// queue any required updates.
//determine if dst_cell is a combinational cell or not
if is_combinational(&dst_cell, &assign.dst.borrow().name, env) {
// write to assign.dst to e2 immediately, if combinational
write_env.put(
&dst_cell,
&assign.dst.borrow().name,
read_val,
);
/*println!(
"reg0.write_en = {}",
write_env.get(
&ir::Id::from("reg0"),
&ir::Id::from("write_en")
)
);*/
// now, update the internal state of the cell;
// for now, this only includes adds;
// TODO (use primitive Cell parameters)
let inputs;
let outputs;
// TODO: hacky way to avoid updating the cell state.
// Also, how to get input and output vectors in general??
if &assign.dst.borrow().name!= "write_en" {
// get dst_cell's input vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
inputs = vec![
(cell.borrow())
.get("left")
.borrow()
.name
.clone(),
(cell.borrow())
.get("right")
.borrow()
.name
.clone(),
]
}
_ => panic!("could not find cell"),
}
// get dst_cell's output vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
outputs = vec![(cell.borrow())
.get("out")
.borrow()
.name
.clone()]
//clean this up later?
}
_ => panic!("could not find cell"),
}
// update the cell state in write_env
write_env = primitives::update_cell_state(
&dst_cell, &inputs, &outputs, &write_env,
)?;
}
} else {
// otherwise, add the write to the update queue; currently only handles registers
// get input cell
let inputs = vec![src_cell.clone()];
// get dst_cell's output port
let outputs = vec![assign.dst.borrow().name.clone()];
write_env =
init_cells(&dst_cell, inputs, outputs, write_env)?;
}
}
}
// write_env = iter_updates.do_tick()
write_env = write_env.do_tick();
counter += 1;
}
/*println!(
"\nFinal state of the done cell, i.e. {:1}: {:?} \n",
&done_cell, | Ok(write_env)
}
/// Evaluate guard implementation
#[allow(clippy::borrowed_box)]
// XXX: Allow for this warning. It would make sense to use a reference when we
// have the `box` match pattern available in Rust.
fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 {
(match &**guard {
ir::Guard::Or(g1, g2) => {
(eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1)
}
ir::Guard::And(g1, g2) => {
(eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1)
}
ir::Guard::Not(g) => eval_guard(g, &env)!= 0,
ir::Guard::Eq(g1, g2) => {
env.get_from_port(&g1.borrow()) == env.get_from_port(&g2.borrow())
}
ir::Guard::Neq(g1, g2) => {
env.get_from_port(&g1.borrow())!= env.get_from_port(&g2.borrow())
}
ir::Guard::Gt(g1, g2) => {
env.get_from_port(&g1.borrow()) > env.get_from_port(&g2.borrow())
}
ir::Guard::Lt(g1, g2) => {
env.get_from_port(&g1.borrow()) < env.get_from_port(&g2.borrow())
}
ir::Guard::Geq(g1, g2) => {
env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow())
}
ir::Guard::Leq(g1, g2) => {
env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow())
}
ir::Guard::Port(p) => env.get_from_port(&p.borrow())!= 0,
ir::Guard::True => true,
}) as u64
}
/// Get the cell id a port belongs to.
/// Very similar to ir::Port::get_parent_name, except it can also panic
fn get_cell_from_port(port: &ir::RRC<ir::Port>) -> ir::Id {
if port.borrow().is_hole() {
panic!("Unexpected hole. Cannot get cell: {}", port.borrow().name)
}
port.borrow().get_parent_name()
}
/// Returns the assignment statement with the done signal; assumes there aren't other groups to check?
fn get_done_signal(assigns: &[ir::Assignment]) -> &ir::Assignment {
assigns
.iter()
.find(|assign| {
let dst = assign.dst.borrow();
dst.is_hole() && dst.name == "done"
})
.expect("Group does not have a done signal")
}
/// Determines if writing a particular cell and cell port is combinational or not. Will need to change implementation later.
fn is_combinational(cell: &ir::Id, port: &ir::Id, env: &Environment) -> bool {
// if cell is none,
let cellg = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
let cb = cellg.borrow();
let celltype = cb.type_name().unwrap_or_else(|| panic!("Constant?"));
// TODO; get cell attributes
match (*celltype).id.as_str() {
"std_reg" => match port.id.as_str() {
// XXX(rachit): Why is this a "combinational" port?
"write_en" => true,
"out" => false,
"done" => false,
_ => false,
},
"std_const"
| "std_slice"
| "std_lsh"
| "std_rsh"
| "std_add"
| "std_sub"
| "std_mod"
| "std_mult"
| "std_div"
| "std_not"
| "std_and"
| "std_or"
| "std_xor"
| "std_gt"
| "std_lt"
| "std_eq"
| "std_neq"
| "std_ge"
| "std_le"
| "fixed_p_std_const"
| "fixed_p_std_add"
| "fixed_p_std_sub"
| "fixed_p_std_mult"
| "fixed_p_std_div"
| "fixed_p_std_gt"
| "fixed_p_std_add_dbit" => true,
_ => false,
}
}
/// Initializes values for the update queue, i.e. for non-combinational cells
#[allow(clippy::unnecessary_wraps)]
fn init_cells(
cell: &ir::Id,
inputs: Vec<ir::Id>,
outputs: Vec<ir::Id>,
mut env: Environment,
) -> FutilResult<Environment> {
let cell_r = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
// get the cell type
match cell_r.borrow().type_name() {
None => panic!("bad"),
Some(ct) => match ct.id.as_str() {
"std_sqrt" => { //:(
// has intermediate steps/computation
}
"std_reg" => {
let map: HashMap<String, u64> = HashMap::new();
// reg.in = dst port should go here
env.add_update(cell.clone(), inputs, outputs, map);
}
_ => panic!(
"attempted to initalize an update for a combinational cell"
),
},
}
Ok(env)
} | write_env.map.get(&done_cell)
);*/ | random_line_split |
interpreter.rs | use super::{environment::Environment, primitives};
use calyx::{errors::FutilResult, ir};
use std::collections::HashMap;
/// Evaluates a group, given an environment.
pub fn eval_group(
group: ir::RRC<ir::Group>,
env: &Environment,
) -> FutilResult<Environment> {
eval_assigns(&(group.borrow()).assignments, &env)
}
// XXX(karen): I think it will need another copy of environment for each
// iteration of assignment statements
/// Evaluates a group's assignment statements in an environment.
fn eval_assigns(
assigns: &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be deleted later
// (unless we want to display the clock cycle)?
let mut counter = 0;
// Filter out the assignment statements that are not only from cells.
// XXX: for now, also excludes cells not in the env map
let ok_assigns = assigns
.iter()
.filter(|&a| {
!a.dst.borrow().is_hole()
// dummy way of making sure the map has the a.src cell
&& env.get_cell(&get_cell_from_port(&a.src)).is_some()
&& env.get_cell(&get_cell_from_port(&a.dst)).is_some()
})
.collect::<Vec<_>>();
// While done_assign.src is 0 (we use done_assign.src because done_assign.dst is not a cell's port; it should be a group's port)
while write_env.get_from_port(&done_assign.src.borrow()) == 0 && counter < 5
{
// println!("Clock cycle {}", counter);
/*println!(
"state of done_cell {:1} : {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
// "staging" updates
//let mut iter_updates = write_env.clone();
// for assign in assigns
for assign in &ok_assigns {
// check if the assign.guard!= 0
// should it be evaluating the guard in write_env environment?
if eval_guard(&assign.guard, &write_env)!= 0 {
// check if the cells are constants?
// cell of assign.src
let src_cell = get_cell_from_port(&assign.src);
// cell of assign.dst
let dst_cell = get_cell_from_port(&assign.dst);
/*println!(
"src cell {:1} port: {:2}, dest cell {:3} port: {:4}",
src_cell,
&assign.src.borrow().name,
dst_cell,
&assign.dst.borrow().name
);*/
// perform a read from `env` for assign.src
// XXX(karen): should read from the previous iteration's env?
let read_val = env.get_from_port(&assign.src.borrow());
// update internal state of the cell and
// queue any required updates.
//determine if dst_cell is a combinational cell or not
if is_combinational(&dst_cell, &assign.dst.borrow().name, env) {
// write to assign.dst to e2 immediately, if combinational
write_env.put(
&dst_cell,
&assign.dst.borrow().name,
read_val,
);
/*println!(
"reg0.write_en = {}",
write_env.get(
&ir::Id::from("reg0"),
&ir::Id::from("write_en")
)
);*/
// now, update the internal state of the cell;
// for now, this only includes adds;
// TODO (use primitive Cell parameters)
let inputs;
let outputs;
// TODO: hacky way to avoid updating the cell state.
// Also, how to get input and output vectors in general??
if &assign.dst.borrow().name!= "write_en" {
// get dst_cell's input vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
inputs = vec![
(cell.borrow())
.get("left")
.borrow()
.name
.clone(),
(cell.borrow())
.get("right")
.borrow()
.name
.clone(),
]
}
_ => panic!("could not find cell"),
}
// get dst_cell's output vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
outputs = vec![(cell.borrow())
.get("out")
.borrow()
.name
.clone()]
//clean this up later?
}
_ => panic!("could not find cell"),
}
// update the cell state in write_env
write_env = primitives::update_cell_state(
&dst_cell, &inputs, &outputs, &write_env,
)?;
}
} else {
// otherwise, add the write to the update queue; currently only handles registers
// get input cell
let inputs = vec![src_cell.clone()];
// get dst_cell's output port
let outputs = vec![assign.dst.borrow().name.clone()];
write_env =
init_cells(&dst_cell, inputs, outputs, write_env)?;
}
}
}
// write_env = iter_updates.do_tick()
write_env = write_env.do_tick();
counter += 1;
}
/*println!(
"\nFinal state of the done cell, i.e. {:1}: {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
Ok(write_env)
}
/// Evaluate guard implementation
#[allow(clippy::borrowed_box)]
// XXX: Allow for this warning. It would make sense to use a reference when we
// have the `box` match pattern available in Rust.
fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 {
(match &**guard {
ir::Guard::Or(g1, g2) => {
(eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1)
}
ir::Guard::And(g1, g2) => {
(eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1)
}
ir::Guard::Not(g) => eval_guard(g, &env)!= 0,
ir::Guard::Eq(g1, g2) => {
env.get_from_port(&g1.borrow()) == env.get_from_port(&g2.borrow())
}
ir::Guard::Neq(g1, g2) => {
env.get_from_port(&g1.borrow())!= env.get_from_port(&g2.borrow())
}
ir::Guard::Gt(g1, g2) => {
env.get_from_port(&g1.borrow()) > env.get_from_port(&g2.borrow())
}
ir::Guard::Lt(g1, g2) => {
env.get_from_port(&g1.borrow()) < env.get_from_port(&g2.borrow())
}
ir::Guard::Geq(g1, g2) => {
env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow())
}
ir::Guard::Leq(g1, g2) => {
env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow())
}
ir::Guard::Port(p) => env.get_from_port(&p.borrow())!= 0,
ir::Guard::True => true,
}) as u64
}
/// Get the cell id a port belongs to.
/// Very similar to ir::Port::get_parent_name, except it can also panic
fn get_cell_from_port(port: &ir::RRC<ir::Port>) -> ir::Id {
if port.borrow().is_hole() {
panic!("Unexpected hole. Cannot get cell: {}", port.borrow().name)
}
port.borrow().get_parent_name()
}
/// Returns the assignment statement with the done signal; assumes there aren't other groups to check?
fn | (assigns: &[ir::Assignment]) -> &ir::Assignment {
assigns
.iter()
.find(|assign| {
let dst = assign.dst.borrow();
dst.is_hole() && dst.name == "done"
})
.expect("Group does not have a done signal")
}
/// Determines if writing a particular cell and cell port is combinational or not. Will need to change implementation later.
fn is_combinational(cell: &ir::Id, port: &ir::Id, env: &Environment) -> bool {
// if cell is none,
let cellg = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
let cb = cellg.borrow();
let celltype = cb.type_name().unwrap_or_else(|| panic!("Constant?"));
// TODO; get cell attributes
match (*celltype).id.as_str() {
"std_reg" => match port.id.as_str() {
// XXX(rachit): Why is this a "combinational" port?
"write_en" => true,
"out" => false,
"done" => false,
_ => false,
},
"std_const"
| "std_slice"
| "std_lsh"
| "std_rsh"
| "std_add"
| "std_sub"
| "std_mod"
| "std_mult"
| "std_div"
| "std_not"
| "std_and"
| "std_or"
| "std_xor"
| "std_gt"
| "std_lt"
| "std_eq"
| "std_neq"
| "std_ge"
| "std_le"
| "fixed_p_std_const"
| "fixed_p_std_add"
| "fixed_p_std_sub"
| "fixed_p_std_mult"
| "fixed_p_std_div"
| "fixed_p_std_gt"
| "fixed_p_std_add_dbit" => true,
_ => false,
}
}
/// Initializes values for the update queue, i.e. for non-combinational cells
#[allow(clippy::unnecessary_wraps)]
fn init_cells(
cell: &ir::Id,
inputs: Vec<ir::Id>,
outputs: Vec<ir::Id>,
mut env: Environment,
) -> FutilResult<Environment> {
let cell_r = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
// get the cell type
match cell_r.borrow().type_name() {
None => panic!("bad"),
Some(ct) => match ct.id.as_str() {
"std_sqrt" => { //:(
// has intermediate steps/computation
}
"std_reg" => {
let map: HashMap<String, u64> = HashMap::new();
// reg.in = dst port should go here
env.add_update(cell.clone(), inputs, outputs, map);
}
_ => panic!(
"attempted to initalize an update for a combinational cell"
),
},
}
Ok(env)
}
| get_done_signal | identifier_name |
interpreter.rs | use super::{environment::Environment, primitives};
use calyx::{errors::FutilResult, ir};
use std::collections::HashMap;
/// Evaluates a group, given an environment.
pub fn eval_group(
group: ir::RRC<ir::Group>,
env: &Environment,
) -> FutilResult<Environment> {
eval_assigns(&(group.borrow()).assignments, &env)
}
// XXX(karen): I think it will need another copy of environment for each
// iteration of assignment statements
/// Evaluates a group's assignment statements in an environment.
fn eval_assigns(
assigns: &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be deleted later
// (unless we want to display the clock cycle)?
let mut counter = 0;
// Filter out the assignment statements that are not only from cells.
// XXX: for now, also excludes cells not in the env map
let ok_assigns = assigns
.iter()
.filter(|&a| {
!a.dst.borrow().is_hole()
// dummy way of making sure the map has the a.src cell
&& env.get_cell(&get_cell_from_port(&a.src)).is_some()
&& env.get_cell(&get_cell_from_port(&a.dst)).is_some()
})
.collect::<Vec<_>>();
// While done_assign.src is 0 (we use done_assign.src because done_assign.dst is not a cell's port; it should be a group's port)
while write_env.get_from_port(&done_assign.src.borrow()) == 0 && counter < 5
{
// println!("Clock cycle {}", counter);
/*println!(
"state of done_cell {:1} : {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
// "staging" updates
//let mut iter_updates = write_env.clone();
// for assign in assigns
for assign in &ok_assigns {
// check if the assign.guard!= 0
// should it be evaluating the guard in write_env environment?
if eval_guard(&assign.guard, &write_env)!= 0 | // queue any required updates.
//determine if dst_cell is a combinational cell or not
if is_combinational(&dst_cell, &assign.dst.borrow().name, env) {
// write to assign.dst to e2 immediately, if combinational
write_env.put(
&dst_cell,
&assign.dst.borrow().name,
read_val,
);
/*println!(
"reg0.write_en = {}",
write_env.get(
&ir::Id::from("reg0"),
&ir::Id::from("write_en")
)
);*/
// now, update the internal state of the cell;
// for now, this only includes adds;
// TODO (use primitive Cell parameters)
let inputs;
let outputs;
// TODO: hacky way to avoid updating the cell state.
// Also, how to get input and output vectors in general??
if &assign.dst.borrow().name!= "write_en" {
// get dst_cell's input vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
inputs = vec![
(cell.borrow())
.get("left")
.borrow()
.name
.clone(),
(cell.borrow())
.get("right")
.borrow()
.name
.clone(),
]
}
_ => panic!("could not find cell"),
}
// get dst_cell's output vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
outputs = vec![(cell.borrow())
.get("out")
.borrow()
.name
.clone()]
//clean this up later?
}
_ => panic!("could not find cell"),
}
// update the cell state in write_env
write_env = primitives::update_cell_state(
&dst_cell, &inputs, &outputs, &write_env,
)?;
}
} else {
// otherwise, add the write to the update queue; currently only handles registers
// get input cell
let inputs = vec![src_cell.clone()];
// get dst_cell's output port
let outputs = vec![assign.dst.borrow().name.clone()];
write_env =
init_cells(&dst_cell, inputs, outputs, write_env)?;
}
}
}
// write_env = iter_updates.do_tick()
write_env = write_env.do_tick();
counter += 1;
}
/*println!(
"\nFinal state of the done cell, i.e. {:1}: {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
Ok(write_env)
}
/// Evaluate guard implementation
#[allow(clippy::borrowed_box)]
// XXX: Allow for this warning. It would make sense to use a reference when we
// have the `box` match pattern available in Rust.
fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 {
(match &**guard {
ir::Guard::Or(g1, g2) => {
(eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1)
}
ir::Guard::And(g1, g2) => {
(eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1)
}
ir::Guard::Not(g) => eval_guard(g, &env)!= 0,
ir::Guard::Eq(g1, g2) => {
env.get_from_port(&g1.borrow()) == env.get_from_port(&g2.borrow())
}
ir::Guard::Neq(g1, g2) => {
env.get_from_port(&g1.borrow())!= env.get_from_port(&g2.borrow())
}
ir::Guard::Gt(g1, g2) => {
env.get_from_port(&g1.borrow()) > env.get_from_port(&g2.borrow())
}
ir::Guard::Lt(g1, g2) => {
env.get_from_port(&g1.borrow()) < env.get_from_port(&g2.borrow())
}
ir::Guard::Geq(g1, g2) => {
env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow())
}
ir::Guard::Leq(g1, g2) => {
env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow())
}
ir::Guard::Port(p) => env.get_from_port(&p.borrow())!= 0,
ir::Guard::True => true,
}) as u64
}
/// Get the cell id a port belongs to.
/// Very similar to ir::Port::get_parent_name, except it can also panic
fn get_cell_from_port(port: &ir::RRC<ir::Port>) -> ir::Id {
if port.borrow().is_hole() {
panic!("Unexpected hole. Cannot get cell: {}", port.borrow().name)
}
port.borrow().get_parent_name()
}
/// Returns the assignment statement with the done signal; assumes there aren't other groups to check?
fn get_done_signal(assigns: &[ir::Assignment]) -> &ir::Assignment {
assigns
.iter()
.find(|assign| {
let dst = assign.dst.borrow();
dst.is_hole() && dst.name == "done"
})
.expect("Group does not have a done signal")
}
/// Determines if writing a particular cell and cell port is combinational or not. Will need to change implementation later.
fn is_combinational(cell: &ir::Id, port: &ir::Id, env: &Environment) -> bool {
// if cell is none,
let cellg = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
let cb = cellg.borrow();
let celltype = cb.type_name().unwrap_or_else(|| panic!("Constant?"));
// TODO; get cell attributes
match (*celltype).id.as_str() {
"std_reg" => match port.id.as_str() {
// XXX(rachit): Why is this a "combinational" port?
"write_en" => true,
"out" => false,
"done" => false,
_ => false,
},
"std_const"
| "std_slice"
| "std_lsh"
| "std_rsh"
| "std_add"
| "std_sub"
| "std_mod"
| "std_mult"
| "std_div"
| "std_not"
| "std_and"
| "std_or"
| "std_xor"
| "std_gt"
| "std_lt"
| "std_eq"
| "std_neq"
| "std_ge"
| "std_le"
| "fixed_p_std_const"
| "fixed_p_std_add"
| "fixed_p_std_sub"
| "fixed_p_std_mult"
| "fixed_p_std_div"
| "fixed_p_std_gt"
| "fixed_p_std_add_dbit" => true,
_ => false,
}
}
/// Initializes values for the update queue, i.e. for non-combinational cells
#[allow(clippy::unnecessary_wraps)]
fn init_cells(
cell: &ir::Id,
inputs: Vec<ir::Id>,
outputs: Vec<ir::Id>,
mut env: Environment,
) -> FutilResult<Environment> {
let cell_r = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
// get the cell type
match cell_r.borrow().type_name() {
None => panic!("bad"),
Some(ct) => match ct.id.as_str() {
"std_sqrt" => { //:(
// has intermediate steps/computation
}
"std_reg" => {
let map: HashMap<String, u64> = HashMap::new();
// reg.in = dst port should go here
env.add_update(cell.clone(), inputs, outputs, map);
}
_ => panic!(
"attempted to initalize an update for a combinational cell"
),
},
}
Ok(env)
}
| {
// check if the cells are constants?
// cell of assign.src
let src_cell = get_cell_from_port(&assign.src);
// cell of assign.dst
let dst_cell = get_cell_from_port(&assign.dst);
/*println!(
"src cell {:1} port: {:2}, dest cell {:3} port: {:4}",
src_cell,
&assign.src.borrow().name,
dst_cell,
&assign.dst.borrow().name
);*/
// perform a read from `env` for assign.src
// XXX(karen): should read from the previous iteration's env?
let read_val = env.get_from_port(&assign.src.borrow());
// update internal state of the cell and | conditional_block |
interpreter.rs | use super::{environment::Environment, primitives};
use calyx::{errors::FutilResult, ir};
use std::collections::HashMap;
/// Evaluates a group, given an environment.
pub fn eval_group(
group: ir::RRC<ir::Group>,
env: &Environment,
) -> FutilResult<Environment> {
eval_assigns(&(group.borrow()).assignments, &env)
}
// XXX(karen): I think it will need another copy of environment for each
// iteration of assignment statements
/// Evaluates a group's assignment statements in an environment.
fn eval_assigns(
assigns: &[ir::Assignment],
env: &Environment,
) -> FutilResult<Environment> {
// Find the done signal in the sequence of assignments
let done_assign = get_done_signal(assigns);
// e2 = Clone the current environment
let mut write_env = env.clone();
// XXX: Prevent infinite loops. should probably be deleted later
// (unless we want to display the clock cycle)?
let mut counter = 0;
// Filter out the assignment statements that are not only from cells.
// XXX: for now, also excludes cells not in the env map
let ok_assigns = assigns
.iter()
.filter(|&a| {
!a.dst.borrow().is_hole()
// dummy way of making sure the map has the a.src cell
&& env.get_cell(&get_cell_from_port(&a.src)).is_some()
&& env.get_cell(&get_cell_from_port(&a.dst)).is_some()
})
.collect::<Vec<_>>();
// While done_assign.src is 0 (we use done_assign.src because done_assign.dst is not a cell's port; it should be a group's port)
while write_env.get_from_port(&done_assign.src.borrow()) == 0 && counter < 5
{
// println!("Clock cycle {}", counter);
/*println!(
"state of done_cell {:1} : {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
// "staging" updates
//let mut iter_updates = write_env.clone();
// for assign in assigns
for assign in &ok_assigns {
// check if the assign.guard!= 0
// should it be evaluating the guard in write_env environment?
if eval_guard(&assign.guard, &write_env)!= 0 {
// check if the cells are constants?
// cell of assign.src
let src_cell = get_cell_from_port(&assign.src);
// cell of assign.dst
let dst_cell = get_cell_from_port(&assign.dst);
/*println!(
"src cell {:1} port: {:2}, dest cell {:3} port: {:4}",
src_cell,
&assign.src.borrow().name,
dst_cell,
&assign.dst.borrow().name
);*/
// perform a read from `env` for assign.src
// XXX(karen): should read from the previous iteration's env?
let read_val = env.get_from_port(&assign.src.borrow());
// update internal state of the cell and
// queue any required updates.
//determine if dst_cell is a combinational cell or not
if is_combinational(&dst_cell, &assign.dst.borrow().name, env) {
// write to assign.dst to e2 immediately, if combinational
write_env.put(
&dst_cell,
&assign.dst.borrow().name,
read_val,
);
/*println!(
"reg0.write_en = {}",
write_env.get(
&ir::Id::from("reg0"),
&ir::Id::from("write_en")
)
);*/
// now, update the internal state of the cell;
// for now, this only includes adds;
// TODO (use primitive Cell parameters)
let inputs;
let outputs;
// TODO: hacky way to avoid updating the cell state.
// Also, how to get input and output vectors in general??
if &assign.dst.borrow().name!= "write_en" {
// get dst_cell's input vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
inputs = vec![
(cell.borrow())
.get("left")
.borrow()
.name
.clone(),
(cell.borrow())
.get("right")
.borrow()
.name
.clone(),
]
}
_ => panic!("could not find cell"),
}
// get dst_cell's output vector
match &write_env.get_cell(&dst_cell) {
Some(cell) => {
outputs = vec![(cell.borrow())
.get("out")
.borrow()
.name
.clone()]
//clean this up later?
}
_ => panic!("could not find cell"),
}
// update the cell state in write_env
write_env = primitives::update_cell_state(
&dst_cell, &inputs, &outputs, &write_env,
)?;
}
} else {
// otherwise, add the write to the update queue; currently only handles registers
// get input cell
let inputs = vec![src_cell.clone()];
// get dst_cell's output port
let outputs = vec![assign.dst.borrow().name.clone()];
write_env =
init_cells(&dst_cell, inputs, outputs, write_env)?;
}
}
}
// write_env = iter_updates.do_tick()
write_env = write_env.do_tick();
counter += 1;
}
/*println!(
"\nFinal state of the done cell, i.e. {:1}: {:?} \n",
&done_cell,
write_env.map.get(&done_cell)
);*/
Ok(write_env)
}
/// Evaluate guard implementation
#[allow(clippy::borrowed_box)]
// XXX: Allow for this warning. It would make sense to use a reference when we
// have the `box` match pattern available in Rust.
fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 | }
ir::Guard::Geq(g1, g2) => {
env.get_from_port(&g1.borrow()) >= env.get_from_port(&g2.borrow())
}
ir::Guard::Leq(g1, g2) => {
env.get_from_port(&g1.borrow()) <= env.get_from_port(&g2.borrow())
}
ir::Guard::Port(p) => env.get_from_port(&p.borrow())!= 0,
ir::Guard::True => true,
}) as u64
}
/// Get the cell id a port belongs to.
/// Very similar to ir::Port::get_parent_name, except it can also panic
fn get_cell_from_port(port: &ir::RRC<ir::Port>) -> ir::Id {
if port.borrow().is_hole() {
panic!("Unexpected hole. Cannot get cell: {}", port.borrow().name)
}
port.borrow().get_parent_name()
}
/// Returns the assignment statement with the done signal; assumes there aren't other groups to check?
fn get_done_signal(assigns: &[ir::Assignment]) -> &ir::Assignment {
assigns
.iter()
.find(|assign| {
let dst = assign.dst.borrow();
dst.is_hole() && dst.name == "done"
})
.expect("Group does not have a done signal")
}
/// Determines if writing a particular cell and cell port is combinational or not. Will need to change implementation later.
fn is_combinational(cell: &ir::Id, port: &ir::Id, env: &Environment) -> bool {
// if cell is none,
let cellg = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
let cb = cellg.borrow();
let celltype = cb.type_name().unwrap_or_else(|| panic!("Constant?"));
// TODO; get cell attributes
match (*celltype).id.as_str() {
"std_reg" => match port.id.as_str() {
// XXX(rachit): Why is this a "combinational" port?
"write_en" => true,
"out" => false,
"done" => false,
_ => false,
},
"std_const"
| "std_slice"
| "std_lsh"
| "std_rsh"
| "std_add"
| "std_sub"
| "std_mod"
| "std_mult"
| "std_div"
| "std_not"
| "std_and"
| "std_or"
| "std_xor"
| "std_gt"
| "std_lt"
| "std_eq"
| "std_neq"
| "std_ge"
| "std_le"
| "fixed_p_std_const"
| "fixed_p_std_add"
| "fixed_p_std_sub"
| "fixed_p_std_mult"
| "fixed_p_std_div"
| "fixed_p_std_gt"
| "fixed_p_std_add_dbit" => true,
_ => false,
}
}
/// Initializes values for the update queue, i.e. for non-combinational cells
#[allow(clippy::unnecessary_wraps)]
fn init_cells(
cell: &ir::Id,
inputs: Vec<ir::Id>,
outputs: Vec<ir::Id>,
mut env: Environment,
) -> FutilResult<Environment> {
let cell_r = env
.get_cell(cell)
.unwrap_or_else(|| panic!("Cannot find cell with name"));
// get the cell type
match cell_r.borrow().type_name() {
None => panic!("bad"),
Some(ct) => match ct.id.as_str() {
"std_sqrt" => { //:(
// has intermediate steps/computation
}
"std_reg" => {
let map: HashMap<String, u64> = HashMap::new();
// reg.in = dst port should go here
env.add_update(cell.clone(), inputs, outputs, map);
}
_ => panic!(
"attempted to initalize an update for a combinational cell"
),
},
}
Ok(env)
}
| {
(match &**guard {
ir::Guard::Or(g1, g2) => {
(eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1)
}
ir::Guard::And(g1, g2) => {
(eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1)
}
ir::Guard::Not(g) => eval_guard(g, &env) != 0,
ir::Guard::Eq(g1, g2) => {
env.get_from_port(&g1.borrow()) == env.get_from_port(&g2.borrow())
}
ir::Guard::Neq(g1, g2) => {
env.get_from_port(&g1.borrow()) != env.get_from_port(&g2.borrow())
}
ir::Guard::Gt(g1, g2) => {
env.get_from_port(&g1.borrow()) > env.get_from_port(&g2.borrow())
}
ir::Guard::Lt(g1, g2) => {
env.get_from_port(&g1.borrow()) < env.get_from_port(&g2.borrow()) | identifier_body |
lib.rs | #![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::default_trait_access,
clippy::use_self,
clippy::wildcard_imports
)]
use arr_macro::arr;
use derivative::Derivative;
use enr::*;
use ethereum_types::*;
use futures::{Sink, SinkExt};
use heapless::{
consts::{U16, U4096},
FnvIndexMap,
};
use log::*;
use std::{
collections::{HashSet, VecDeque},
future::Future,
net::SocketAddr,
ops::BitXor,
ptr::NonNull,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
net::UdpSocket,
prelude::*,
stream::{StreamExt, *},
};
use tokio_util::{codec::*, udp::*};
pub mod proto;
pub mod topic;
pub type RawNodeId = [u8; 32];
#[must_use]
pub fn distance(a: H256, b: H256) -> U256 {
U256::from_big_endian(&a.bitxor(b).0)
}
#[must_use]
pub fn logdistance(a: H256, b: H256) -> Option<usize> {
for i in (0..H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d!= 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log distance is -inf
}
#[derive(Clone, Copy, Debug)]
pub enum PeerState {
New,
Ready,
}
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub struct NodeEntry<K: EnrKey> {
pub record: Enr<K>,
pub peer_state: PeerState,
pub liveness: Option<Instant>,
}
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
struct Bucket<K: EnrKey> {
nodes: Box<FnvIndexMap<RawNodeId, NodeEntry<K>, U16>>,
recently_seen: Option<Enr<K>>,
}
pub struct NodeTable<K: EnrKey> {
host_id: H256,
buckets: Box<[Bucket<K>; 256]>,
all_nodes: Box<heapless::FnvIndexSet<RawNodeId, U4096>>,
}
impl<K: EnrKey> NodeTable<K> {
#[must_use]
pub fn new(host_id: H256) -> Self {
Self {
host_id,
buckets: Box::new(arr![Default::default(); 256]),
all_nodes: Default::default(),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.all_nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn bucket_idx(&self, node_id: H256) -> Option<usize> {
logdistance(self.host_id, node_id)
}
fn bucket(&mut self, node_id: H256) -> Option<&mut Bucket<K>> {
Some(&mut self.buckets[self.bucket_idx(node_id)?])
}
pub fn node_mut(&mut self, node_id: H256) -> Option<&mut NodeEntry<K>> {
let bucket = self.bucket(node_id)?;
bucket.nodes.get_mut(&node_id.0)
}
pub fn add_node(&mut self, record: Enr<K>, peer_state: PeerState) {
let node_id = H256(record.node_id().raw());
// If we don't have such node already...
if!self.all_nodes.contains(&node_id.0) {
// Check that we're not adding self
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If there's space, add it...
if bucket.nodes.len() < bucket.nodes.capacity() {
let node_id = node_id.0;
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state,
liveness: None,
},
);
} else {
//...or if at capacity, update replacement cache instead
bucket.recently_seen = Some(record);
}
}
}
}
pub fn evict_node(&mut self, node_id: H256) {
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If this node actually exists, remove it.
if bucket.nodes.remove(&node_id.0).is_some() {
self.all_nodes.remove(&node_id.0);
// And if there is a replacement, move it into the table
if let Some(record) = bucket.recently_seen.take() {
let node_id = record.node_id().raw();
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state: PeerState::New,
liveness: None,
},
);
}
}
}
}
pub fn update_liveness(&mut self, node_id: H256, timestamp: Instant) {
if let Some(node) = self.node_mut(node_id) {
node.liveness = Some(timestamp);
}
}
pub fn random_node(&mut self) -> Option<&mut NodeEntry<K>> {
let node_id = *self
.all_nodes
.iter()
.nth(rand::random::<usize>() % self.all_nodes.len())?;
Some(
self.node_mut(H256(node_id))
.expect("this node always exists at this point; qed"),
)
}
pub fn bucket_nodes(&mut self, logdistance: u8) -> BucketNodes<'_, K> {
BucketNodes(NodeEntries {
node_table: self,
current_bucket: logdistance as usize,
max_bucket: logdistance as usize,
current_bucket_remaining: None,
})
}
pub fn closest(&mut self) -> Closest<'_, K> {
Closest(NodeEntries {
node_table: self,
current_bucket: 0,
max_bucket: 255,
current_bucket_remaining: None,
})
}
}
pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for Closest<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
struct NodeEntries<'a, K: EnrKey> {
node_table: &'a mut NodeTable<K>,
current_bucket: usize,
max_bucket: usize,
current_bucket_remaining: Option<Vec<NonNull<NodeEntry<K>>>>,
}
impl<'a, K: EnrKey> Iterator for NodeEntries<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let NodeEntries {
node_table,
current_bucket,
max_bucket,
current_bucket_remaining,
} = self;
trace!("Current bucket is {}", *current_bucket);
let host_id = node_table.host_id;
if let Some(ptr) = current_bucket_remaining
.get_or_insert_with(|| {
let mut nodes = node_table.buckets[*current_bucket]
.nodes
.values_mut()
.collect::<Vec<_>>();
trace!("Nodes before sorting: {:?}", nodes);
nodes.sort_by(|a, b| {
distance(host_id, H256(b.record.node_id().raw()))
.cmp(&distance(host_id, H256(a.record.node_id().raw())))
});
trace!("Nodes after sorting: {:?}", nodes);
nodes.into_iter().map(From::from).collect()
})
.pop()
|
if *current_bucket == *max_bucket {
return None;
}
*current_bucket += 1;
*current_bucket_remaining = None;
}
}
}
pub enum DiscoveryRequest {
Ping,
}
pub enum DiscoveryResponse {
Pong,
}
pub enum DiscoveryPacket {
WhoAreYou,
FindNode,
Ping,
Pong,
}
pub enum TableUpdate {
Added { node_id: H256, addr: SocketAddr },
Removed { node_id: H256 },
}
#[allow(dead_code)]
pub struct Discovery<K: EnrKey> {
node_table: Arc<Mutex<NodeTable<K>>>,
concurrency: usize,
}
impl<K: EnrKey + Send +'static> Discovery<K> {
pub async fn new<
F: Fn(TableUpdate) -> Fut + Send + Sync +'static,
Fut: Future<Output = ()> + Send,
>(
addr: String,
host_id: H256,
on_table_update: F,
) -> Self {
let socket = UdpSocket::bind(addr).await.unwrap();
let on_table_update = Arc::new(on_table_update);
// Create a node table
let node_table = Arc::new(Mutex::new(NodeTable::new(host_id)));
let (tx, mut rx) = futures::StreamExt::split(UdpFramed::new(socket, BytesCodec::new()));
// Ougoing router
let (outgoing_sender, mut rx) = tokio::sync::mpsc::channel::<(H256, DiscoveryPacket)>(1);
// tokio::spawn(async move {
// while let Some((node_id, request)) = rx.next().await {
// if let Some(node) = node_table.lock().unwrap().node_mut(node_id) {
// if let Some(ip) = node.record.ip() {}
// }
// let _ = io_tx.send((node_id, request)).await;
// }
// });
// Liveness check service
let unanswered_pings = Arc::new(Mutex::new(HashSet::<H256>::new()));
tokio::spawn({
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
async move {
const PING_TIMEOUT: u64 = 10;
const SCAN_IN: u64 = 30_000;
loop {
let d = {
let node_id = node_table
.lock()
.unwrap()
.random_node()
.map(|entry| H256(entry.record.node_id().raw()))
.filter(|node|!unanswered_pings.lock().unwrap().contains(node));
if let Some(node_id) = node_id {
let mut outgoing_sender = outgoing_sender.clone();
let on_table_update = on_table_update.clone();
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
tokio::spawn(async move {
let _ =
outgoing_sender.send((node_id, DiscoveryPacket::Ping)).await;
tokio::time::delay_for(std::time::Duration::from_secs(
PING_TIMEOUT,
))
.await;
if unanswered_pings.lock().unwrap().remove(&node_id) {
node_table.lock().unwrap().evict_node(node_id);
(on_table_update)(TableUpdate::Removed { node_id }).await;
}
});
}
tokio::time::delay_for(Duration::from_millis(
SCAN_IN / node_table.lock().unwrap().len() as u64,
))
};
d.await;
}
}
});
// Incoming router
// tokio::spawn(async move {
// while let Some((node_id, response)) = io_rx.next().await {
// match response {
// DiscoveryResponse::Pong => {
// unanswered_pings.lock().unwrap().remove(&node_id);
// }
// }
// }
// });
Self {
node_table,
concurrency: 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::SecretKey;
#[test]
fn test_iterator() {
let _ = env_logger::try_init();
let host_id = H256::random();
let mut table = NodeTable::<SecretKey>::new(host_id);
for _ in 0..9000 {
table.add_node(
EnrBuilder::new("v4")
.build(&SecretKey::random(&mut rand::thread_rng()))
.unwrap(),
PeerState::Ready,
)
}
let mut max_distance = U256::zero();
for entry in table.closest() {
let dst = distance(host_id, H256(entry.record.node_id().raw()));
trace!("Computed distance is {}", dst);
assert!(dst >= max_distance);
max_distance = dst;
}
}
}
| {
// Safety: we have exclusive access to underlying node table
return Some(unsafe { &mut *ptr.as_ptr() });
} | conditional_block |
lib.rs | #![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::default_trait_access,
clippy::use_self,
clippy::wildcard_imports
)]
use arr_macro::arr;
use derivative::Derivative;
use enr::*;
use ethereum_types::*;
use futures::{Sink, SinkExt};
use heapless::{
consts::{U16, U4096},
FnvIndexMap,
};
use log::*;
use std::{
collections::{HashSet, VecDeque},
future::Future,
net::SocketAddr,
ops::BitXor,
ptr::NonNull,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
net::UdpSocket,
prelude::*,
stream::{StreamExt, *},
};
use tokio_util::{codec::*, udp::*};
pub mod proto;
pub mod topic;
pub type RawNodeId = [u8; 32];
#[must_use]
pub fn distance(a: H256, b: H256) -> U256 {
U256::from_big_endian(&a.bitxor(b).0)
}
#[must_use]
pub fn logdistance(a: H256, b: H256) -> Option<usize> {
for i in (0..H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d!= 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log distance is -inf
}
#[derive(Clone, Copy, Debug)]
pub enum PeerState {
New,
Ready,
}
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub struct NodeEntry<K: EnrKey> {
pub record: Enr<K>,
pub peer_state: PeerState,
pub liveness: Option<Instant>,
}
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
struct Bucket<K: EnrKey> {
nodes: Box<FnvIndexMap<RawNodeId, NodeEntry<K>, U16>>,
recently_seen: Option<Enr<K>>,
}
pub struct NodeTable<K: EnrKey> {
host_id: H256,
buckets: Box<[Bucket<K>; 256]>,
all_nodes: Box<heapless::FnvIndexSet<RawNodeId, U4096>>,
}
impl<K: EnrKey> NodeTable<K> {
#[must_use]
pub fn new(host_id: H256) -> Self {
Self {
host_id,
buckets: Box::new(arr![Default::default(); 256]),
all_nodes: Default::default(),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.all_nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn bucket_idx(&self, node_id: H256) -> Option<usize> {
logdistance(self.host_id, node_id)
}
fn bucket(&mut self, node_id: H256) -> Option<&mut Bucket<K>> {
Some(&mut self.buckets[self.bucket_idx(node_id)?])
}
pub fn node_mut(&mut self, node_id: H256) -> Option<&mut NodeEntry<K>> {
let bucket = self.bucket(node_id)?;
bucket.nodes.get_mut(&node_id.0)
}
pub fn add_node(&mut self, record: Enr<K>, peer_state: PeerState) {
let node_id = H256(record.node_id().raw());
// If we don't have such node already...
if!self.all_nodes.contains(&node_id.0) {
// Check that we're not adding self
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If there's space, add it...
if bucket.nodes.len() < bucket.nodes.capacity() {
let node_id = node_id.0;
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state,
liveness: None,
},
);
} else {
//...or if at capacity, update replacement cache instead
bucket.recently_seen = Some(record);
}
}
}
}
pub fn evict_node(&mut self, node_id: H256) {
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If this node actually exists, remove it.
if bucket.nodes.remove(&node_id.0).is_some() {
self.all_nodes.remove(&node_id.0);
// And if there is a replacement, move it into the table
if let Some(record) = bucket.recently_seen.take() {
let node_id = record.node_id().raw();
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state: PeerState::New,
liveness: None,
},
);
}
}
}
}
pub fn update_liveness(&mut self, node_id: H256, timestamp: Instant) {
if let Some(node) = self.node_mut(node_id) {
node.liveness = Some(timestamp);
}
}
pub fn random_node(&mut self) -> Option<&mut NodeEntry<K>> {
let node_id = *self
.all_nodes
.iter()
.nth(rand::random::<usize>() % self.all_nodes.len())?;
Some(
self.node_mut(H256(node_id))
.expect("this node always exists at this point; qed"),
)
}
pub fn bucket_nodes(&mut self, logdistance: u8) -> BucketNodes<'_, K> {
BucketNodes(NodeEntries {
node_table: self,
current_bucket: logdistance as usize,
max_bucket: logdistance as usize,
current_bucket_remaining: None,
})
}
pub fn closest(&mut self) -> Closest<'_, K> |
}
pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for Closest<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
struct NodeEntries<'a, K: EnrKey> {
node_table: &'a mut NodeTable<K>,
current_bucket: usize,
max_bucket: usize,
current_bucket_remaining: Option<Vec<NonNull<NodeEntry<K>>>>,
}
impl<'a, K: EnrKey> Iterator for NodeEntries<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let NodeEntries {
node_table,
current_bucket,
max_bucket,
current_bucket_remaining,
} = self;
trace!("Current bucket is {}", *current_bucket);
let host_id = node_table.host_id;
if let Some(ptr) = current_bucket_remaining
.get_or_insert_with(|| {
let mut nodes = node_table.buckets[*current_bucket]
.nodes
.values_mut()
.collect::<Vec<_>>();
trace!("Nodes before sorting: {:?}", nodes);
nodes.sort_by(|a, b| {
distance(host_id, H256(b.record.node_id().raw()))
.cmp(&distance(host_id, H256(a.record.node_id().raw())))
});
trace!("Nodes after sorting: {:?}", nodes);
nodes.into_iter().map(From::from).collect()
})
.pop()
{
// Safety: we have exclusive access to underlying node table
return Some(unsafe { &mut *ptr.as_ptr() });
}
if *current_bucket == *max_bucket {
return None;
}
*current_bucket += 1;
*current_bucket_remaining = None;
}
}
}
pub enum DiscoveryRequest {
Ping,
}
pub enum DiscoveryResponse {
Pong,
}
pub enum DiscoveryPacket {
WhoAreYou,
FindNode,
Ping,
Pong,
}
pub enum TableUpdate {
Added { node_id: H256, addr: SocketAddr },
Removed { node_id: H256 },
}
#[allow(dead_code)]
pub struct Discovery<K: EnrKey> {
node_table: Arc<Mutex<NodeTable<K>>>,
concurrency: usize,
}
impl<K: EnrKey + Send +'static> Discovery<K> {
pub async fn new<
F: Fn(TableUpdate) -> Fut + Send + Sync +'static,
Fut: Future<Output = ()> + Send,
>(
addr: String,
host_id: H256,
on_table_update: F,
) -> Self {
let socket = UdpSocket::bind(addr).await.unwrap();
let on_table_update = Arc::new(on_table_update);
// Create a node table
let node_table = Arc::new(Mutex::new(NodeTable::new(host_id)));
let (tx, mut rx) = futures::StreamExt::split(UdpFramed::new(socket, BytesCodec::new()));
// Ougoing router
let (outgoing_sender, mut rx) = tokio::sync::mpsc::channel::<(H256, DiscoveryPacket)>(1);
// tokio::spawn(async move {
// while let Some((node_id, request)) = rx.next().await {
// if let Some(node) = node_table.lock().unwrap().node_mut(node_id) {
// if let Some(ip) = node.record.ip() {}
// }
// let _ = io_tx.send((node_id, request)).await;
// }
// });
// Liveness check service
let unanswered_pings = Arc::new(Mutex::new(HashSet::<H256>::new()));
tokio::spawn({
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
async move {
const PING_TIMEOUT: u64 = 10;
const SCAN_IN: u64 = 30_000;
loop {
let d = {
let node_id = node_table
.lock()
.unwrap()
.random_node()
.map(|entry| H256(entry.record.node_id().raw()))
.filter(|node|!unanswered_pings.lock().unwrap().contains(node));
if let Some(node_id) = node_id {
let mut outgoing_sender = outgoing_sender.clone();
let on_table_update = on_table_update.clone();
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
tokio::spawn(async move {
let _ =
outgoing_sender.send((node_id, DiscoveryPacket::Ping)).await;
tokio::time::delay_for(std::time::Duration::from_secs(
PING_TIMEOUT,
))
.await;
if unanswered_pings.lock().unwrap().remove(&node_id) {
node_table.lock().unwrap().evict_node(node_id);
(on_table_update)(TableUpdate::Removed { node_id }).await;
}
});
}
tokio::time::delay_for(Duration::from_millis(
SCAN_IN / node_table.lock().unwrap().len() as u64,
))
};
d.await;
}
}
});
// Incoming router
// tokio::spawn(async move {
// while let Some((node_id, response)) = io_rx.next().await {
// match response {
// DiscoveryResponse::Pong => {
// unanswered_pings.lock().unwrap().remove(&node_id);
// }
// }
// }
// });
Self {
node_table,
concurrency: 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::SecretKey;
#[test]
fn test_iterator() {
let _ = env_logger::try_init();
let host_id = H256::random();
let mut table = NodeTable::<SecretKey>::new(host_id);
for _ in 0..9000 {
table.add_node(
EnrBuilder::new("v4")
.build(&SecretKey::random(&mut rand::thread_rng()))
.unwrap(),
PeerState::Ready,
)
}
let mut max_distance = U256::zero();
for entry in table.closest() {
let dst = distance(host_id, H256(entry.record.node_id().raw()));
trace!("Computed distance is {}", dst);
assert!(dst >= max_distance);
max_distance = dst;
}
}
}
| {
Closest(NodeEntries {
node_table: self,
current_bucket: 0,
max_bucket: 255,
current_bucket_remaining: None,
})
} | identifier_body |
lib.rs | #![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::default_trait_access,
clippy::use_self,
clippy::wildcard_imports
)]
use arr_macro::arr;
use derivative::Derivative;
use enr::*;
use ethereum_types::*;
use futures::{Sink, SinkExt};
use heapless::{
consts::{U16, U4096},
FnvIndexMap,
};
use log::*;
use std::{
collections::{HashSet, VecDeque},
future::Future,
net::SocketAddr,
ops::BitXor,
ptr::NonNull,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
net::UdpSocket,
prelude::*,
stream::{StreamExt, *},
};
use tokio_util::{codec::*, udp::*};
pub mod proto;
pub mod topic;
pub type RawNodeId = [u8; 32];
#[must_use]
pub fn distance(a: H256, b: H256) -> U256 {
U256::from_big_endian(&a.bitxor(b).0)
}
#[must_use]
pub fn logdistance(a: H256, b: H256) -> Option<usize> {
for i in (0..H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d!= 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log distance is -inf
}
#[derive(Clone, Copy, Debug)]
pub enum PeerState {
New,
Ready,
}
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub struct NodeEntry<K: EnrKey> {
pub record: Enr<K>,
pub peer_state: PeerState,
pub liveness: Option<Instant>,
}
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
struct Bucket<K: EnrKey> {
nodes: Box<FnvIndexMap<RawNodeId, NodeEntry<K>, U16>>,
recently_seen: Option<Enr<K>>,
}
pub struct NodeTable<K: EnrKey> {
host_id: H256,
buckets: Box<[Bucket<K>; 256]>,
all_nodes: Box<heapless::FnvIndexSet<RawNodeId, U4096>>,
}
impl<K: EnrKey> NodeTable<K> {
#[must_use]
pub fn new(host_id: H256) -> Self {
Self {
host_id,
buckets: Box::new(arr![Default::default(); 256]),
all_nodes: Default::default(),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.all_nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn bucket_idx(&self, node_id: H256) -> Option<usize> {
logdistance(self.host_id, node_id)
}
fn bucket(&mut self, node_id: H256) -> Option<&mut Bucket<K>> {
Some(&mut self.buckets[self.bucket_idx(node_id)?])
}
pub fn node_mut(&mut self, node_id: H256) -> Option<&mut NodeEntry<K>> {
let bucket = self.bucket(node_id)?;
bucket.nodes.get_mut(&node_id.0)
}
pub fn add_node(&mut self, record: Enr<K>, peer_state: PeerState) {
let node_id = H256(record.node_id().raw());
// If we don't have such node already...
if!self.all_nodes.contains(&node_id.0) {
// Check that we're not adding self
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If there's space, add it...
if bucket.nodes.len() < bucket.nodes.capacity() {
let node_id = node_id.0;
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state,
liveness: None,
},
);
} else {
//...or if at capacity, update replacement cache instead
bucket.recently_seen = Some(record);
}
}
}
}
pub fn evict_node(&mut self, node_id: H256) {
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If this node actually exists, remove it.
if bucket.nodes.remove(&node_id.0).is_some() {
self.all_nodes.remove(&node_id.0);
// And if there is a replacement, move it into the table
if let Some(record) = bucket.recently_seen.take() {
let node_id = record.node_id().raw();
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state: PeerState::New,
liveness: None,
},
);
}
}
}
}
pub fn update_liveness(&mut self, node_id: H256, timestamp: Instant) {
if let Some(node) = self.node_mut(node_id) {
node.liveness = Some(timestamp);
}
}
pub fn random_node(&mut self) -> Option<&mut NodeEntry<K>> {
let node_id = *self
.all_nodes
.iter()
.nth(rand::random::<usize>() % self.all_nodes.len())?;
Some(
self.node_mut(H256(node_id))
.expect("this node always exists at this point; qed"),
)
}
pub fn bucket_nodes(&mut self, logdistance: u8) -> BucketNodes<'_, K> {
BucketNodes(NodeEntries {
node_table: self,
current_bucket: logdistance as usize,
max_bucket: logdistance as usize,
current_bucket_remaining: None,
})
}
pub fn closest(&mut self) -> Closest<'_, K> {
Closest(NodeEntries {
node_table: self,
current_bucket: 0,
max_bucket: 255,
current_bucket_remaining: None,
})
}
}
pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for Closest<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
struct NodeEntries<'a, K: EnrKey> {
node_table: &'a mut NodeTable<K>,
current_bucket: usize,
max_bucket: usize,
current_bucket_remaining: Option<Vec<NonNull<NodeEntry<K>>>>,
}
impl<'a, K: EnrKey> Iterator for NodeEntries<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let NodeEntries {
node_table,
current_bucket,
max_bucket,
current_bucket_remaining,
} = self;
trace!("Current bucket is {}", *current_bucket);
let host_id = node_table.host_id;
if let Some(ptr) = current_bucket_remaining
.get_or_insert_with(|| {
let mut nodes = node_table.buckets[*current_bucket]
.nodes
.values_mut()
.collect::<Vec<_>>();
trace!("Nodes before sorting: {:?}", nodes);
nodes.sort_by(|a, b| {
distance(host_id, H256(b.record.node_id().raw()))
.cmp(&distance(host_id, H256(a.record.node_id().raw())))
});
trace!("Nodes after sorting: {:?}", nodes);
nodes.into_iter().map(From::from).collect()
})
.pop()
{
// Safety: we have exclusive access to underlying node table
return Some(unsafe { &mut *ptr.as_ptr() });
}
if *current_bucket == *max_bucket {
return None;
}
*current_bucket += 1;
*current_bucket_remaining = None;
}
}
}
pub enum DiscoveryRequest {
Ping,
}
pub enum DiscoveryResponse {
Pong,
}
pub enum DiscoveryPacket {
WhoAreYou,
FindNode,
Ping,
Pong,
}
pub enum TableUpdate {
Added { node_id: H256, addr: SocketAddr },
Removed { node_id: H256 },
}
#[allow(dead_code)]
pub struct Discovery<K: EnrKey> {
node_table: Arc<Mutex<NodeTable<K>>>,
concurrency: usize,
}
impl<K: EnrKey + Send +'static> Discovery<K> {
pub async fn new<
F: Fn(TableUpdate) -> Fut + Send + Sync +'static,
Fut: Future<Output = ()> + Send,
>(
addr: String,
host_id: H256,
on_table_update: F,
) -> Self {
let socket = UdpSocket::bind(addr).await.unwrap();
let on_table_update = Arc::new(on_table_update);
// Create a node table
let node_table = Arc::new(Mutex::new(NodeTable::new(host_id)));
let (tx, mut rx) = futures::StreamExt::split(UdpFramed::new(socket, BytesCodec::new()));
// Ougoing router
let (outgoing_sender, mut rx) = tokio::sync::mpsc::channel::<(H256, DiscoveryPacket)>(1);
// tokio::spawn(async move {
// while let Some((node_id, request)) = rx.next().await {
// if let Some(node) = node_table.lock().unwrap().node_mut(node_id) {
// if let Some(ip) = node.record.ip() {}
// }
// let _ = io_tx.send((node_id, request)).await;
// }
// });
// Liveness check service
let unanswered_pings = Arc::new(Mutex::new(HashSet::<H256>::new()));
tokio::spawn({
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
async move {
const PING_TIMEOUT: u64 = 10;
const SCAN_IN: u64 = 30_000;
loop {
let d = {
let node_id = node_table
.lock()
.unwrap()
.random_node()
.map(|entry| H256(entry.record.node_id().raw()))
.filter(|node|!unanswered_pings.lock().unwrap().contains(node));
if let Some(node_id) = node_id {
let mut outgoing_sender = outgoing_sender.clone();
let on_table_update = on_table_update.clone();
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
tokio::spawn(async move {
let _ =
outgoing_sender.send((node_id, DiscoveryPacket::Ping)).await;
tokio::time::delay_for(std::time::Duration::from_secs(
PING_TIMEOUT,
))
.await;
if unanswered_pings.lock().unwrap().remove(&node_id) {
node_table.lock().unwrap().evict_node(node_id);
(on_table_update)(TableUpdate::Removed { node_id }).await;
}
});
}
tokio::time::delay_for(Duration::from_millis(
SCAN_IN / node_table.lock().unwrap().len() as u64,
))
};
d.await;
}
}
});
// Incoming router
// tokio::spawn(async move {
// while let Some((node_id, response)) = io_rx.next().await {
// match response {
// DiscoveryResponse::Pong => {
// unanswered_pings.lock().unwrap().remove(&node_id);
// }
// }
// }
// });
Self {
node_table,
concurrency: 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::SecretKey;
#[test]
fn | () {
let _ = env_logger::try_init();
let host_id = H256::random();
let mut table = NodeTable::<SecretKey>::new(host_id);
for _ in 0..9000 {
table.add_node(
EnrBuilder::new("v4")
.build(&SecretKey::random(&mut rand::thread_rng()))
.unwrap(),
PeerState::Ready,
)
}
let mut max_distance = U256::zero();
for entry in table.closest() {
let dst = distance(host_id, H256(entry.record.node_id().raw()));
trace!("Computed distance is {}", dst);
assert!(dst >= max_distance);
max_distance = dst;
}
}
}
| test_iterator | identifier_name |
lib.rs | #![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::default_trait_access,
clippy::use_self,
clippy::wildcard_imports
)]
use arr_macro::arr;
use derivative::Derivative;
use enr::*;
use ethereum_types::*;
use futures::{Sink, SinkExt};
use heapless::{
consts::{U16, U4096},
FnvIndexMap,
};
use log::*;
use std::{
collections::{HashSet, VecDeque},
future::Future,
net::SocketAddr, | ptr::NonNull,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
net::UdpSocket,
prelude::*,
stream::{StreamExt, *},
};
use tokio_util::{codec::*, udp::*};
pub mod proto;
pub mod topic;
pub type RawNodeId = [u8; 32];
#[must_use]
pub fn distance(a: H256, b: H256) -> U256 {
U256::from_big_endian(&a.bitxor(b).0)
}
#[must_use]
pub fn logdistance(a: H256, b: H256) -> Option<usize> {
for i in (0..H256::len_bytes()).rev() {
let byte_index = H256::len_bytes() - i - 1;
let d: u8 = a[byte_index] ^ b[byte_index];
if d!= 0 {
let high_bit_index = 7 - d.leading_zeros() as usize;
return Some(i * 8 + high_bit_index);
}
}
None // a and b are equal, so log distance is -inf
}
#[derive(Clone, Copy, Debug)]
pub enum PeerState {
New,
Ready,
}
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub struct NodeEntry<K: EnrKey> {
pub record: Enr<K>,
pub peer_state: PeerState,
pub liveness: Option<Instant>,
}
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
struct Bucket<K: EnrKey> {
nodes: Box<FnvIndexMap<RawNodeId, NodeEntry<K>, U16>>,
recently_seen: Option<Enr<K>>,
}
pub struct NodeTable<K: EnrKey> {
host_id: H256,
buckets: Box<[Bucket<K>; 256]>,
all_nodes: Box<heapless::FnvIndexSet<RawNodeId, U4096>>,
}
impl<K: EnrKey> NodeTable<K> {
#[must_use]
pub fn new(host_id: H256) -> Self {
Self {
host_id,
buckets: Box::new(arr![Default::default(); 256]),
all_nodes: Default::default(),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.all_nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn bucket_idx(&self, node_id: H256) -> Option<usize> {
logdistance(self.host_id, node_id)
}
fn bucket(&mut self, node_id: H256) -> Option<&mut Bucket<K>> {
Some(&mut self.buckets[self.bucket_idx(node_id)?])
}
pub fn node_mut(&mut self, node_id: H256) -> Option<&mut NodeEntry<K>> {
let bucket = self.bucket(node_id)?;
bucket.nodes.get_mut(&node_id.0)
}
pub fn add_node(&mut self, record: Enr<K>, peer_state: PeerState) {
let node_id = H256(record.node_id().raw());
// If we don't have such node already...
if!self.all_nodes.contains(&node_id.0) {
// Check that we're not adding self
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If there's space, add it...
if bucket.nodes.len() < bucket.nodes.capacity() {
let node_id = node_id.0;
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state,
liveness: None,
},
);
} else {
//...or if at capacity, update replacement cache instead
bucket.recently_seen = Some(record);
}
}
}
}
pub fn evict_node(&mut self, node_id: H256) {
if let Some(bucket_idx) = self.bucket_idx(node_id) {
let bucket = &mut self.buckets[bucket_idx];
// If this node actually exists, remove it.
if bucket.nodes.remove(&node_id.0).is_some() {
self.all_nodes.remove(&node_id.0);
// And if there is a replacement, move it into the table
if let Some(record) = bucket.recently_seen.take() {
let node_id = record.node_id().raw();
let _ = self.all_nodes.insert(node_id);
let _ = bucket.nodes.insert(
node_id,
NodeEntry {
record,
peer_state: PeerState::New,
liveness: None,
},
);
}
}
}
}
pub fn update_liveness(&mut self, node_id: H256, timestamp: Instant) {
if let Some(node) = self.node_mut(node_id) {
node.liveness = Some(timestamp);
}
}
pub fn random_node(&mut self) -> Option<&mut NodeEntry<K>> {
let node_id = *self
.all_nodes
.iter()
.nth(rand::random::<usize>() % self.all_nodes.len())?;
Some(
self.node_mut(H256(node_id))
.expect("this node always exists at this point; qed"),
)
}
pub fn bucket_nodes(&mut self, logdistance: u8) -> BucketNodes<'_, K> {
BucketNodes(NodeEntries {
node_table: self,
current_bucket: logdistance as usize,
max_bucket: logdistance as usize,
current_bucket_remaining: None,
})
}
pub fn closest(&mut self) -> Closest<'_, K> {
Closest(NodeEntries {
node_table: self,
current_bucket: 0,
max_bucket: 255,
current_bucket_remaining: None,
})
}
}
pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>);
impl<'a, K: EnrKey> Iterator for Closest<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
struct NodeEntries<'a, K: EnrKey> {
node_table: &'a mut NodeTable<K>,
current_bucket: usize,
max_bucket: usize,
current_bucket_remaining: Option<Vec<NonNull<NodeEntry<K>>>>,
}
impl<'a, K: EnrKey> Iterator for NodeEntries<'a, K> {
type Item = &'a mut NodeEntry<K>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let NodeEntries {
node_table,
current_bucket,
max_bucket,
current_bucket_remaining,
} = self;
trace!("Current bucket is {}", *current_bucket);
let host_id = node_table.host_id;
if let Some(ptr) = current_bucket_remaining
.get_or_insert_with(|| {
let mut nodes = node_table.buckets[*current_bucket]
.nodes
.values_mut()
.collect::<Vec<_>>();
trace!("Nodes before sorting: {:?}", nodes);
nodes.sort_by(|a, b| {
distance(host_id, H256(b.record.node_id().raw()))
.cmp(&distance(host_id, H256(a.record.node_id().raw())))
});
trace!("Nodes after sorting: {:?}", nodes);
nodes.into_iter().map(From::from).collect()
})
.pop()
{
// Safety: we have exclusive access to underlying node table
return Some(unsafe { &mut *ptr.as_ptr() });
}
if *current_bucket == *max_bucket {
return None;
}
*current_bucket += 1;
*current_bucket_remaining = None;
}
}
}
pub enum DiscoveryRequest {
Ping,
}
pub enum DiscoveryResponse {
Pong,
}
pub enum DiscoveryPacket {
WhoAreYou,
FindNode,
Ping,
Pong,
}
pub enum TableUpdate {
Added { node_id: H256, addr: SocketAddr },
Removed { node_id: H256 },
}
#[allow(dead_code)]
pub struct Discovery<K: EnrKey> {
node_table: Arc<Mutex<NodeTable<K>>>,
concurrency: usize,
}
impl<K: EnrKey + Send +'static> Discovery<K> {
pub async fn new<
F: Fn(TableUpdate) -> Fut + Send + Sync +'static,
Fut: Future<Output = ()> + Send,
>(
addr: String,
host_id: H256,
on_table_update: F,
) -> Self {
let socket = UdpSocket::bind(addr).await.unwrap();
let on_table_update = Arc::new(on_table_update);
// Create a node table
let node_table = Arc::new(Mutex::new(NodeTable::new(host_id)));
let (tx, mut rx) = futures::StreamExt::split(UdpFramed::new(socket, BytesCodec::new()));
// Ougoing router
let (outgoing_sender, mut rx) = tokio::sync::mpsc::channel::<(H256, DiscoveryPacket)>(1);
// tokio::spawn(async move {
// while let Some((node_id, request)) = rx.next().await {
// if let Some(node) = node_table.lock().unwrap().node_mut(node_id) {
// if let Some(ip) = node.record.ip() {}
// }
// let _ = io_tx.send((node_id, request)).await;
// }
// });
// Liveness check service
let unanswered_pings = Arc::new(Mutex::new(HashSet::<H256>::new()));
tokio::spawn({
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
async move {
const PING_TIMEOUT: u64 = 10;
const SCAN_IN: u64 = 30_000;
loop {
let d = {
let node_id = node_table
.lock()
.unwrap()
.random_node()
.map(|entry| H256(entry.record.node_id().raw()))
.filter(|node|!unanswered_pings.lock().unwrap().contains(node));
if let Some(node_id) = node_id {
let mut outgoing_sender = outgoing_sender.clone();
let on_table_update = on_table_update.clone();
let node_table = node_table.clone();
let unanswered_pings = unanswered_pings.clone();
tokio::spawn(async move {
let _ =
outgoing_sender.send((node_id, DiscoveryPacket::Ping)).await;
tokio::time::delay_for(std::time::Duration::from_secs(
PING_TIMEOUT,
))
.await;
if unanswered_pings.lock().unwrap().remove(&node_id) {
node_table.lock().unwrap().evict_node(node_id);
(on_table_update)(TableUpdate::Removed { node_id }).await;
}
});
}
tokio::time::delay_for(Duration::from_millis(
SCAN_IN / node_table.lock().unwrap().len() as u64,
))
};
d.await;
}
}
});
// Incoming router
// tokio::spawn(async move {
// while let Some((node_id, response)) = io_rx.next().await {
// match response {
// DiscoveryResponse::Pong => {
// unanswered_pings.lock().unwrap().remove(&node_id);
// }
// }
// }
// });
Self {
node_table,
concurrency: 3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use secp256k1::SecretKey;
#[test]
fn test_iterator() {
let _ = env_logger::try_init();
let host_id = H256::random();
let mut table = NodeTable::<SecretKey>::new(host_id);
for _ in 0..9000 {
table.add_node(
EnrBuilder::new("v4")
.build(&SecretKey::random(&mut rand::thread_rng()))
.unwrap(),
PeerState::Ready,
)
}
let mut max_distance = U256::zero();
for entry in table.closest() {
let dst = distance(host_id, H256(entry.record.node_id().raw()));
trace!("Computed distance is {}", dst);
assert!(dst >= max_distance);
max_distance = dst;
}
}
} | ops::BitXor, | random_line_split |
bytesearch.rs | use crate::insn::MAX_CHAR_SET_LENGTH;
use core::fmt;
extern crate memchr;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Facilities for searching bytes.
pub trait ByteSearcher {
/// Search for ourselves in a slice of bytes.
/// The length of the slice is unspecified and may be 0.
/// \return the next index of ourselves in the slice, or None.
fn find_in(&self, rhs: &[u8]) -> Option<usize>;
}
/// Helper trait that describes matching against literal bytes.
pub trait ByteSeq: ByteSearcher + core::fmt::Debug + Copy + Clone {
/// Number of bytes.
const LENGTH: usize;
/// Test if a slice is equal.
/// The slice must have exactly LENGTH bytes.
fn equals_known_len(&self, rhs: &[u8]) -> bool;
}
extern "C" {
fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
}
impl<const N: usize> ByteSeq for [u8; N] {
const LENGTH: usize = N;
#[inline(always)]
fn equals_known_len(&self, rhs: &[u8]) -> bool {
debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length");
if cfg!(feature = "prohibit-unsafe") {
// Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare.
self == rhs
} else {
// Warning: this is delicate. We intend for the compiler to emit optimized bytewise comparisons of unaligned LENGTH bytes,
// where LENGTH is a compile-time constant. Rust's default == on slices will perform a pointer comparison which will always be false,
// and kill any vectorization.
// memcmp() will be optimized to the builtin.
unsafe { memcmp(self.as_ptr(), rhs.as_ptr(), Self::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_len(win) {
// Black magic?
return Some((win.as_ptr() as usize) - (rhs.as_ptr() as usize));
}
}
None
}
}
/// A ByteSet is any set of bytes.
pub trait ByteSet {
/// \return whether the ByteSet contains the byte.
fn contains(&self, b: u8) -> bool;
}
/// A ByteArraySet wraps a small array and uses linear equality.
#[derive(Copy, Clone, Debug)]
#[repr(align(4))]
pub struct ByteArraySet<ArraySet: SmallArraySet>(pub ArraySet);
/// Cover over contains() to avoid bumping into native contains call.
impl<ArraySet: SmallArraySet> ByteArraySet<ArraySet> {
#[inline(always)]
pub fn contains(self, b: u8) -> bool {
self.0.contains(b)
}
}
impl<ArraySet: SmallArraySet> ByteSearcher for ByteArraySet<ArraySet> {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
self.0.find_in(rhs)
}
}
/// A SmallArraySet is a set implemented as a small byte array.
pub trait SmallArraySet: Copy {
fn contains(self, b: u8) -> bool;
fn find_in(self, rhs: &[u8]) -> Option<usize>;
}
// Beware: Rust is cranky about loop unrolling.
// Do not try to be too clever here.
impl SmallArraySet for [u8; 2] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr2(self[0], self[1], rhs)
}
}
impl SmallArraySet for [u8; 3] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr3(self[0], self[1], self[2], rhs)
}
}
impl SmallArraySet for [u8; 4] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2] || b == self[3]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
// TODO.
for (idx, byte) in rhs.iter().enumerate() {
if self.contains(*byte) |
}
None
}
}
// CharSet helper. Avoid branching in the loop to get good unrolling.
#[allow(unused_parens)]
#[inline(always)]
pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool {
let mut result = false;
for &v in set.iter() {
result |= (v == c);
}
result
}
/// A helper function for formatting bitmaps, using - ranges.
fn format_bitmap<Func>(name: &str, f: &mut fmt::Formatter<'_>, contains: Func) -> fmt::Result
where
Func: Fn(u8) -> bool,
{
write!(f, "{}[", name)?;
let mut idx = 0;
let mut maybe_space = "";
while idx <= 256 {
// Compute the next value not contained.
let mut end = idx;
while end <= 256 && contains(end as u8) {
end += 1;
}
match end - idx {
0 => (),
1 => write!(f, "{}{}", maybe_space, idx)?,
_ => write!(f, "{}{}-{}", maybe_space, idx, end - 1)?,
};
if end > idx {
maybe_space = " ";
}
idx = end + 1
}
write!(f, "]")?;
Ok(())
}
/// A bitmap covering ASCII characters.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct AsciiBitmap(pub [u8; 16]);
impl AsciiBitmap {
/// Set a byte val in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
debug_assert!(val <= 127, "Value should be ASCII");
self.0[(val >> 3) as usize] |= 1 << (val & 0x7);
}
}
impl fmt::Debug for AsciiBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("AsciiBitmap", f, |v| self.contains(v))
}
}
impl ByteSet for AsciiBitmap {
/// \return whether this bitmap contains a given value.
/// The value does NOT have to be ASCII.
#[inline(always)]
fn contains(&self, val: u8) -> bool {
// Delicate tricks to avoid branches.
// In general we want to compute the byte via /8, and then mask into the
// byte. But if the value is not ASCII then the byte could be too large.
// So mask off the MSB so that the byte is always in range.
let byte = (val & 0x7F) >> 3;
let bit = val & 0x7;
// Now probe the bitmap. If our sign bit was set, we want the mask to be 0;
// otherwise we want to set only the 'bit' offset.
// Invert the sign bit and reuse it.
let mask = ((val >> 7) ^ 1) << bit;
// Probe the bitmap. We expect the compiler to elide the bounds check.
(self.0[byte as usize] & mask)!= 0
}
}
/// A bitmap covering all bytes.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct ByteBitmap([u16; 16]);
// TODO: the codegen here is pretty horrible; LLVM is emitting a sequence of
// halfword instructions. Consider using a union?
impl ByteBitmap {
/// Construct from a sequence of bytes.
pub fn new(bytes: &[u8]) -> ByteBitmap {
let mut bb = ByteBitmap::default();
for &b in bytes {
bb.set(b)
}
bb
}
/// \return whether this bitmap contains a given byte val.
#[inline(always)]
pub fn contains(&self, val: u8) -> bool {
let byte = val >> 4;
let bit = val & 0xF;
(self.0[byte as usize] & (1 << bit))!= 0
}
/// Set a bit in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
let byte = val >> 4;
let bit = val & 0xF;
self.0[byte as usize] |= 1 << bit;
}
/// Update ourselves from another bitmap, in place.
pub fn bitor(&mut self, rhs: &ByteBitmap) {
for idx in 0..self.0.len() {
self.0[idx] |= rhs.0[idx];
}
}
/// Invert our bits, in place.
pub fn bitnot(&mut self) -> &mut Self {
for val in self.0.iter_mut() {
*val =!*val;
}
self
}
/// Count number of set bits.
pub fn count_bits(&self) -> u32 {
self.0.iter().map(|v| v.count_ones()).sum()
}
/// \return all set bytes, as a vec.
#[allow(clippy::wrong_self_convention)]
pub fn to_vec(&self) -> Vec<u8> {
(0..=255).filter(|b| self.contains(*b)).collect()
}
/// \return the index of the first byte in the slice that is present in this
/// bitmap, using some unsafe tricks.
#[inline(always)]
fn unsafe_find_in_slice(&self, bytes: &[u8]) -> Option<usize> {
type Chunk = u32;
let bm = &self.0;
let mut offset = 0;
let (prefix, body, suffix) = unsafe { bytes.align_to::<Chunk>() };
for &byte in prefix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
for &chunk in body {
// Use LE. Here index 0 is the earliest address.
let byte_idxs = ((chunk >> 4) & 0x0F0F0F0F).to_le_bytes();
let bit_idxs = (chunk & 0x0F0F0F0F).to_le_bytes();
if (bm[byte_idxs[0] as usize] & (1 << bit_idxs[0]))!= 0 {
return Some(offset);
}
if (bm[byte_idxs[1] as usize] & (1 << bit_idxs[1]))!= 0 {
return Some(offset + 1);
}
if (bm[byte_idxs[2] as usize] & (1 << bit_idxs[2]))!= 0 {
return Some(offset + 2);
}
if (bm[byte_idxs[3] as usize] & (1 << bit_idxs[3]))!= 0 {
return Some(offset + 3);
}
offset += 4;
}
for &byte in suffix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
None
}
}
impl ByteSearcher for ByteBitmap {
#[inline(always)]
fn find_in(&self, bytes: &[u8]) -> Option<usize> {
if cfg!(feature = "prohibit-unsafe") {
for (idx, byte) in bytes.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
} else {
self.unsafe_find_in_slice(bytes)
}
}
}
impl fmt::Debug for ByteBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("ByteBitmap", f, |v| self.contains(v))
}
}
/// A trivial ByteSearcher corresponding to the empty string.
#[derive(Debug, Copy, Clone)]
pub struct EmptyString {}
impl ByteSearcher for EmptyString {
#[inline(always)]
fn find_in(&self, _bytes: &[u8]) -> Option<usize> {
Some(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_bitmap(bytes: &[u8]) -> ByteBitmap {
let mut bm = ByteBitmap::default();
for &b in bytes {
bm.set(b)
}
bm
}
#[test]
fn empty_search() {
assert_eq!(EmptyString {}.find_in(&[1, 2, 3]), Some(0));
assert_eq!(EmptyString {}.find_in(&[]), Some(0));
}
#[test]
fn bitmap_search() {
assert_eq!(make_bitmap(&[]).find_in(&[1, 2, 3]), None);
assert_eq!(make_bitmap(&[]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(make_bitmap(&[1]).bitnot().find_in(&[1, 2, 3]), Some(1));
assert_eq!(make_bitmap(&[2]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7])
.find_in(&[8, 9, 10, 11, 12, 13, 4, 14, 6, 15, 7, 16, 17, 18, 19, 20]),
Some(6)
);
}
#[test]
fn literal_search() {
assert_eq!([0, 1, 2, 3].find_in(&[4, 5, 6, 7]), None);
assert_eq!([0, 1, 2, 3].find_in(&[]), None);
}
}
| {
return Some(idx);
} | conditional_block |
bytesearch.rs | use crate::insn::MAX_CHAR_SET_LENGTH;
use core::fmt;
extern crate memchr;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Facilities for searching bytes.
pub trait ByteSearcher {
/// Search for ourselves in a slice of bytes.
/// The length of the slice is unspecified and may be 0.
/// \return the next index of ourselves in the slice, or None.
fn find_in(&self, rhs: &[u8]) -> Option<usize>;
}
/// Helper trait that describes matching against literal bytes.
pub trait ByteSeq: ByteSearcher + core::fmt::Debug + Copy + Clone {
/// Number of bytes.
const LENGTH: usize;
/// Test if a slice is equal.
/// The slice must have exactly LENGTH bytes.
fn equals_known_len(&self, rhs: &[u8]) -> bool;
}
extern "C" {
fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
}
impl<const N: usize> ByteSeq for [u8; N] {
const LENGTH: usize = N;
#[inline(always)]
fn | (&self, rhs: &[u8]) -> bool {
debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length");
if cfg!(feature = "prohibit-unsafe") {
// Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare.
self == rhs
} else {
// Warning: this is delicate. We intend for the compiler to emit optimized bytewise comparisons of unaligned LENGTH bytes,
// where LENGTH is a compile-time constant. Rust's default == on slices will perform a pointer comparison which will always be false,
// and kill any vectorization.
// memcmp() will be optimized to the builtin.
unsafe { memcmp(self.as_ptr(), rhs.as_ptr(), Self::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_len(win) {
// Black magic?
return Some((win.as_ptr() as usize) - (rhs.as_ptr() as usize));
}
}
None
}
}
/// A ByteSet is any set of bytes.
pub trait ByteSet {
/// \return whether the ByteSet contains the byte.
fn contains(&self, b: u8) -> bool;
}
/// A ByteArraySet wraps a small array and uses linear equality.
#[derive(Copy, Clone, Debug)]
#[repr(align(4))]
pub struct ByteArraySet<ArraySet: SmallArraySet>(pub ArraySet);
/// Cover over contains() to avoid bumping into native contains call.
impl<ArraySet: SmallArraySet> ByteArraySet<ArraySet> {
#[inline(always)]
pub fn contains(self, b: u8) -> bool {
self.0.contains(b)
}
}
impl<ArraySet: SmallArraySet> ByteSearcher for ByteArraySet<ArraySet> {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
self.0.find_in(rhs)
}
}
/// A SmallArraySet is a set implemented as a small byte array.
pub trait SmallArraySet: Copy {
fn contains(self, b: u8) -> bool;
fn find_in(self, rhs: &[u8]) -> Option<usize>;
}
// Beware: Rust is cranky about loop unrolling.
// Do not try to be too clever here.
impl SmallArraySet for [u8; 2] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr2(self[0], self[1], rhs)
}
}
impl SmallArraySet for [u8; 3] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr3(self[0], self[1], self[2], rhs)
}
}
impl SmallArraySet for [u8; 4] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2] || b == self[3]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
// TODO.
for (idx, byte) in rhs.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
}
}
// CharSet helper. Avoid branching in the loop to get good unrolling.
#[allow(unused_parens)]
#[inline(always)]
pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool {
let mut result = false;
for &v in set.iter() {
result |= (v == c);
}
result
}
/// A helper function for formatting bitmaps, using - ranges.
fn format_bitmap<Func>(name: &str, f: &mut fmt::Formatter<'_>, contains: Func) -> fmt::Result
where
Func: Fn(u8) -> bool,
{
write!(f, "{}[", name)?;
let mut idx = 0;
let mut maybe_space = "";
while idx <= 256 {
// Compute the next value not contained.
let mut end = idx;
while end <= 256 && contains(end as u8) {
end += 1;
}
match end - idx {
0 => (),
1 => write!(f, "{}{}", maybe_space, idx)?,
_ => write!(f, "{}{}-{}", maybe_space, idx, end - 1)?,
};
if end > idx {
maybe_space = " ";
}
idx = end + 1
}
write!(f, "]")?;
Ok(())
}
/// A bitmap covering ASCII characters.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct AsciiBitmap(pub [u8; 16]);
impl AsciiBitmap {
/// Set a byte val in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
debug_assert!(val <= 127, "Value should be ASCII");
self.0[(val >> 3) as usize] |= 1 << (val & 0x7);
}
}
impl fmt::Debug for AsciiBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("AsciiBitmap", f, |v| self.contains(v))
}
}
impl ByteSet for AsciiBitmap {
/// \return whether this bitmap contains a given value.
/// The value does NOT have to be ASCII.
#[inline(always)]
fn contains(&self, val: u8) -> bool {
// Delicate tricks to avoid branches.
// In general we want to compute the byte via /8, and then mask into the
// byte. But if the value is not ASCII then the byte could be too large.
// So mask off the MSB so that the byte is always in range.
let byte = (val & 0x7F) >> 3;
let bit = val & 0x7;
// Now probe the bitmap. If our sign bit was set, we want the mask to be 0;
// otherwise we want to set only the 'bit' offset.
// Invert the sign bit and reuse it.
let mask = ((val >> 7) ^ 1) << bit;
// Probe the bitmap. We expect the compiler to elide the bounds check.
(self.0[byte as usize] & mask)!= 0
}
}
/// A bitmap covering all bytes.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct ByteBitmap([u16; 16]);
// TODO: the codegen here is pretty horrible; LLVM is emitting a sequence of
// halfword instructions. Consider using a union?
impl ByteBitmap {
/// Construct from a sequence of bytes.
pub fn new(bytes: &[u8]) -> ByteBitmap {
let mut bb = ByteBitmap::default();
for &b in bytes {
bb.set(b)
}
bb
}
/// \return whether this bitmap contains a given byte val.
#[inline(always)]
pub fn contains(&self, val: u8) -> bool {
let byte = val >> 4;
let bit = val & 0xF;
(self.0[byte as usize] & (1 << bit))!= 0
}
/// Set a bit in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
let byte = val >> 4;
let bit = val & 0xF;
self.0[byte as usize] |= 1 << bit;
}
/// Update ourselves from another bitmap, in place.
pub fn bitor(&mut self, rhs: &ByteBitmap) {
for idx in 0..self.0.len() {
self.0[idx] |= rhs.0[idx];
}
}
/// Invert our bits, in place.
pub fn bitnot(&mut self) -> &mut Self {
for val in self.0.iter_mut() {
*val =!*val;
}
self
}
/// Count number of set bits.
pub fn count_bits(&self) -> u32 {
self.0.iter().map(|v| v.count_ones()).sum()
}
/// \return all set bytes, as a vec.
#[allow(clippy::wrong_self_convention)]
pub fn to_vec(&self) -> Vec<u8> {
(0..=255).filter(|b| self.contains(*b)).collect()
}
/// \return the index of the first byte in the slice that is present in this
/// bitmap, using some unsafe tricks.
#[inline(always)]
fn unsafe_find_in_slice(&self, bytes: &[u8]) -> Option<usize> {
type Chunk = u32;
let bm = &self.0;
let mut offset = 0;
let (prefix, body, suffix) = unsafe { bytes.align_to::<Chunk>() };
for &byte in prefix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
for &chunk in body {
// Use LE. Here index 0 is the earliest address.
let byte_idxs = ((chunk >> 4) & 0x0F0F0F0F).to_le_bytes();
let bit_idxs = (chunk & 0x0F0F0F0F).to_le_bytes();
if (bm[byte_idxs[0] as usize] & (1 << bit_idxs[0]))!= 0 {
return Some(offset);
}
if (bm[byte_idxs[1] as usize] & (1 << bit_idxs[1]))!= 0 {
return Some(offset + 1);
}
if (bm[byte_idxs[2] as usize] & (1 << bit_idxs[2]))!= 0 {
return Some(offset + 2);
}
if (bm[byte_idxs[3] as usize] & (1 << bit_idxs[3]))!= 0 {
return Some(offset + 3);
}
offset += 4;
}
for &byte in suffix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
None
}
}
impl ByteSearcher for ByteBitmap {
#[inline(always)]
fn find_in(&self, bytes: &[u8]) -> Option<usize> {
if cfg!(feature = "prohibit-unsafe") {
for (idx, byte) in bytes.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
} else {
self.unsafe_find_in_slice(bytes)
}
}
}
impl fmt::Debug for ByteBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("ByteBitmap", f, |v| self.contains(v))
}
}
/// A trivial ByteSearcher corresponding to the empty string.
#[derive(Debug, Copy, Clone)]
pub struct EmptyString {}
impl ByteSearcher for EmptyString {
#[inline(always)]
fn find_in(&self, _bytes: &[u8]) -> Option<usize> {
Some(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_bitmap(bytes: &[u8]) -> ByteBitmap {
let mut bm = ByteBitmap::default();
for &b in bytes {
bm.set(b)
}
bm
}
#[test]
fn empty_search() {
assert_eq!(EmptyString {}.find_in(&[1, 2, 3]), Some(0));
assert_eq!(EmptyString {}.find_in(&[]), Some(0));
}
#[test]
fn bitmap_search() {
assert_eq!(make_bitmap(&[]).find_in(&[1, 2, 3]), None);
assert_eq!(make_bitmap(&[]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(make_bitmap(&[1]).bitnot().find_in(&[1, 2, 3]), Some(1));
assert_eq!(make_bitmap(&[2]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7])
.find_in(&[8, 9, 10, 11, 12, 13, 4, 14, 6, 15, 7, 16, 17, 18, 19, 20]),
Some(6)
);
}
#[test]
fn literal_search() {
assert_eq!([0, 1, 2, 3].find_in(&[4, 5, 6, 7]), None);
assert_eq!([0, 1, 2, 3].find_in(&[]), None);
}
}
| equals_known_len | identifier_name |
bytesearch.rs | use crate::insn::MAX_CHAR_SET_LENGTH;
use core::fmt;
extern crate memchr;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Facilities for searching bytes.
pub trait ByteSearcher {
/// Search for ourselves in a slice of bytes.
/// The length of the slice is unspecified and may be 0.
/// \return the next index of ourselves in the slice, or None.
fn find_in(&self, rhs: &[u8]) -> Option<usize>;
}
/// Helper trait that describes matching against literal bytes.
pub trait ByteSeq: ByteSearcher + core::fmt::Debug + Copy + Clone {
/// Number of bytes.
const LENGTH: usize;
/// Test if a slice is equal.
/// The slice must have exactly LENGTH bytes.
fn equals_known_len(&self, rhs: &[u8]) -> bool;
}
extern "C" {
fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
}
impl<const N: usize> ByteSeq for [u8; N] {
const LENGTH: usize = N;
#[inline(always)]
fn equals_known_len(&self, rhs: &[u8]) -> bool {
debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length");
if cfg!(feature = "prohibit-unsafe") {
// Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare.
self == rhs
} else {
// Warning: this is delicate. We intend for the compiler to emit optimized bytewise comparisons of unaligned LENGTH bytes,
// where LENGTH is a compile-time constant. Rust's default == on slices will perform a pointer comparison which will always be false,
// and kill any vectorization.
// memcmp() will be optimized to the builtin.
unsafe { memcmp(self.as_ptr(), rhs.as_ptr(), Self::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_len(win) {
// Black magic?
return Some((win.as_ptr() as usize) - (rhs.as_ptr() as usize));
}
}
None
}
}
/// A ByteSet is any set of bytes.
pub trait ByteSet {
/// \return whether the ByteSet contains the byte.
fn contains(&self, b: u8) -> bool;
}
/// A ByteArraySet wraps a small array and uses linear equality.
#[derive(Copy, Clone, Debug)]
#[repr(align(4))]
pub struct ByteArraySet<ArraySet: SmallArraySet>(pub ArraySet);
/// Cover over contains() to avoid bumping into native contains call.
impl<ArraySet: SmallArraySet> ByteArraySet<ArraySet> {
#[inline(always)]
pub fn contains(self, b: u8) -> bool {
self.0.contains(b)
}
}
impl<ArraySet: SmallArraySet> ByteSearcher for ByteArraySet<ArraySet> {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
self.0.find_in(rhs)
}
}
/// A SmallArraySet is a set implemented as a small byte array.
pub trait SmallArraySet: Copy {
fn contains(self, b: u8) -> bool;
fn find_in(self, rhs: &[u8]) -> Option<usize>;
}
// Beware: Rust is cranky about loop unrolling.
// Do not try to be too clever here.
impl SmallArraySet for [u8; 2] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr2(self[0], self[1], rhs)
}
}
impl SmallArraySet for [u8; 3] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr3(self[0], self[1], self[2], rhs)
}
}
impl SmallArraySet for [u8; 4] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2] || b == self[3]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
// TODO.
for (idx, byte) in rhs.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
}
}
// CharSet helper. Avoid branching in the loop to get good unrolling.
#[allow(unused_parens)]
#[inline(always)]
pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool {
let mut result = false;
for &v in set.iter() {
result |= (v == c);
}
result
}
/// A helper function for formatting bitmaps, using - ranges.
fn format_bitmap<Func>(name: &str, f: &mut fmt::Formatter<'_>, contains: Func) -> fmt::Result
where
Func: Fn(u8) -> bool,
{
write!(f, "{}[", name)?;
let mut idx = 0;
let mut maybe_space = "";
while idx <= 256 {
// Compute the next value not contained.
let mut end = idx;
while end <= 256 && contains(end as u8) {
end += 1;
}
match end - idx {
0 => (),
1 => write!(f, "{}{}", maybe_space, idx)?,
_ => write!(f, "{}{}-{}", maybe_space, idx, end - 1)?,
};
if end > idx {
maybe_space = " ";
}
idx = end + 1
}
write!(f, "]")?;
Ok(())
}
/// A bitmap covering ASCII characters.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct AsciiBitmap(pub [u8; 16]);
impl AsciiBitmap {
/// Set a byte val in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
debug_assert!(val <= 127, "Value should be ASCII");
self.0[(val >> 3) as usize] |= 1 << (val & 0x7);
}
}
impl fmt::Debug for AsciiBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("AsciiBitmap", f, |v| self.contains(v))
}
}
impl ByteSet for AsciiBitmap {
/// \return whether this bitmap contains a given value.
/// The value does NOT have to be ASCII.
#[inline(always)]
fn contains(&self, val: u8) -> bool {
// Delicate tricks to avoid branches.
// In general we want to compute the byte via /8, and then mask into the
// byte. But if the value is not ASCII then the byte could be too large.
// So mask off the MSB so that the byte is always in range.
let byte = (val & 0x7F) >> 3;
let bit = val & 0x7;
// Now probe the bitmap. If our sign bit was set, we want the mask to be 0;
// otherwise we want to set only the 'bit' offset.
// Invert the sign bit and reuse it.
let mask = ((val >> 7) ^ 1) << bit;
// Probe the bitmap. We expect the compiler to elide the bounds check.
(self.0[byte as usize] & mask)!= 0
}
}
/// A bitmap covering all bytes.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct ByteBitmap([u16; 16]);
// TODO: the codegen here is pretty horrible; LLVM is emitting a sequence of
// halfword instructions. Consider using a union?
impl ByteBitmap {
/// Construct from a sequence of bytes.
pub fn new(bytes: &[u8]) -> ByteBitmap {
let mut bb = ByteBitmap::default();
for &b in bytes {
bb.set(b)
}
bb
}
/// \return whether this bitmap contains a given byte val.
#[inline(always)]
pub fn contains(&self, val: u8) -> bool {
let byte = val >> 4;
let bit = val & 0xF;
(self.0[byte as usize] & (1 << bit))!= 0
}
/// Set a bit in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
let byte = val >> 4;
let bit = val & 0xF;
self.0[byte as usize] |= 1 << bit;
}
/// Update ourselves from another bitmap, in place.
pub fn bitor(&mut self, rhs: &ByteBitmap) {
for idx in 0..self.0.len() {
self.0[idx] |= rhs.0[idx];
}
}
/// Invert our bits, in place.
pub fn bitnot(&mut self) -> &mut Self {
for val in self.0.iter_mut() {
*val =!*val;
}
self
}
/// Count number of set bits.
pub fn count_bits(&self) -> u32 {
self.0.iter().map(|v| v.count_ones()).sum()
}
/// \return all set bytes, as a vec.
#[allow(clippy::wrong_self_convention)]
pub fn to_vec(&self) -> Vec<u8> {
(0..=255).filter(|b| self.contains(*b)).collect()
}
/// \return the index of the first byte in the slice that is present in this
/// bitmap, using some unsafe tricks.
#[inline(always)]
fn unsafe_find_in_slice(&self, bytes: &[u8]) -> Option<usize> {
type Chunk = u32;
let bm = &self.0;
let mut offset = 0;
let (prefix, body, suffix) = unsafe { bytes.align_to::<Chunk>() };
for &byte in prefix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
for &chunk in body {
// Use LE. Here index 0 is the earliest address.
let byte_idxs = ((chunk >> 4) & 0x0F0F0F0F).to_le_bytes();
let bit_idxs = (chunk & 0x0F0F0F0F).to_le_bytes();
if (bm[byte_idxs[0] as usize] & (1 << bit_idxs[0]))!= 0 {
return Some(offset);
}
if (bm[byte_idxs[1] as usize] & (1 << bit_idxs[1]))!= 0 {
return Some(offset + 1);
}
if (bm[byte_idxs[2] as usize] & (1 << bit_idxs[2]))!= 0 {
return Some(offset + 2);
}
if (bm[byte_idxs[3] as usize] & (1 << bit_idxs[3]))!= 0 {
return Some(offset + 3);
}
offset += 4;
}
for &byte in suffix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
None
}
}
impl ByteSearcher for ByteBitmap {
#[inline(always)]
fn find_in(&self, bytes: &[u8]) -> Option<usize> {
if cfg!(feature = "prohibit-unsafe") {
for (idx, byte) in bytes.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
} else {
self.unsafe_find_in_slice(bytes)
}
}
}
| format_bitmap("ByteBitmap", f, |v| self.contains(v))
}
}
/// A trivial ByteSearcher corresponding to the empty string.
#[derive(Debug, Copy, Clone)]
pub struct EmptyString {}
impl ByteSearcher for EmptyString {
#[inline(always)]
fn find_in(&self, _bytes: &[u8]) -> Option<usize> {
Some(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_bitmap(bytes: &[u8]) -> ByteBitmap {
let mut bm = ByteBitmap::default();
for &b in bytes {
bm.set(b)
}
bm
}
#[test]
fn empty_search() {
assert_eq!(EmptyString {}.find_in(&[1, 2, 3]), Some(0));
assert_eq!(EmptyString {}.find_in(&[]), Some(0));
}
#[test]
fn bitmap_search() {
assert_eq!(make_bitmap(&[]).find_in(&[1, 2, 3]), None);
assert_eq!(make_bitmap(&[]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(make_bitmap(&[1]).bitnot().find_in(&[1, 2, 3]), Some(1));
assert_eq!(make_bitmap(&[2]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7])
.find_in(&[8, 9, 10, 11, 12, 13, 4, 14, 6, 15, 7, 16, 17, 18, 19, 20]),
Some(6)
);
}
#[test]
fn literal_search() {
assert_eq!([0, 1, 2, 3].find_in(&[4, 5, 6, 7]), None);
assert_eq!([0, 1, 2, 3].find_in(&[]), None);
}
} | impl fmt::Debug for ByteBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | random_line_split |
bytesearch.rs | use crate::insn::MAX_CHAR_SET_LENGTH;
use core::fmt;
extern crate memchr;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Facilities for searching bytes.
pub trait ByteSearcher {
/// Search for ourselves in a slice of bytes.
/// The length of the slice is unspecified and may be 0.
/// \return the next index of ourselves in the slice, or None.
fn find_in(&self, rhs: &[u8]) -> Option<usize>;
}
/// Helper trait that describes matching against literal bytes.
pub trait ByteSeq: ByteSearcher + core::fmt::Debug + Copy + Clone {
/// Number of bytes.
const LENGTH: usize;
/// Test if a slice is equal.
/// The slice must have exactly LENGTH bytes.
fn equals_known_len(&self, rhs: &[u8]) -> bool;
}
extern "C" {
fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
}
impl<const N: usize> ByteSeq for [u8; N] {
const LENGTH: usize = N;
#[inline(always)]
fn equals_known_len(&self, rhs: &[u8]) -> bool {
debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length");
if cfg!(feature = "prohibit-unsafe") {
// Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare.
self == rhs
} else {
// Warning: this is delicate. We intend for the compiler to emit optimized bytewise comparisons of unaligned LENGTH bytes,
// where LENGTH is a compile-time constant. Rust's default == on slices will perform a pointer comparison which will always be false,
// and kill any vectorization.
// memcmp() will be optimized to the builtin.
unsafe { memcmp(self.as_ptr(), rhs.as_ptr(), Self::LENGTH) == 0 }
}
}
}
impl<const N: usize> ByteSearcher for [u8; N] {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
if N == 1 {
return memchr::memchr(self[0], rhs);
}
for win in rhs.windows(Self::LENGTH) {
if self.equals_known_len(win) {
// Black magic?
return Some((win.as_ptr() as usize) - (rhs.as_ptr() as usize));
}
}
None
}
}
/// A ByteSet is any set of bytes.
pub trait ByteSet {
/// \return whether the ByteSet contains the byte.
fn contains(&self, b: u8) -> bool;
}
/// A ByteArraySet wraps a small array and uses linear equality.
#[derive(Copy, Clone, Debug)]
#[repr(align(4))]
pub struct ByteArraySet<ArraySet: SmallArraySet>(pub ArraySet);
/// Cover over contains() to avoid bumping into native contains call.
impl<ArraySet: SmallArraySet> ByteArraySet<ArraySet> {
#[inline(always)]
pub fn contains(self, b: u8) -> bool {
self.0.contains(b)
}
}
impl<ArraySet: SmallArraySet> ByteSearcher for ByteArraySet<ArraySet> {
#[inline(always)]
fn find_in(&self, rhs: &[u8]) -> Option<usize> {
self.0.find_in(rhs)
}
}
/// A SmallArraySet is a set implemented as a small byte array.
pub trait SmallArraySet: Copy {
fn contains(self, b: u8) -> bool;
fn find_in(self, rhs: &[u8]) -> Option<usize>;
}
// Beware: Rust is cranky about loop unrolling.
// Do not try to be too clever here.
impl SmallArraySet for [u8; 2] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr2(self[0], self[1], rhs)
}
}
impl SmallArraySet for [u8; 3] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
memchr::memchr3(self[0], self[1], self[2], rhs)
}
}
impl SmallArraySet for [u8; 4] {
#[inline(always)]
fn contains(self, b: u8) -> bool {
b == self[0] || b == self[1] || b == self[2] || b == self[3]
}
#[inline(always)]
fn find_in(self, rhs: &[u8]) -> Option<usize> {
// TODO.
for (idx, byte) in rhs.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
}
}
// CharSet helper. Avoid branching in the loop to get good unrolling.
#[allow(unused_parens)]
#[inline(always)]
pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool {
let mut result = false;
for &v in set.iter() {
result |= (v == c);
}
result
}
/// A helper function for formatting bitmaps, using - ranges.
fn format_bitmap<Func>(name: &str, f: &mut fmt::Formatter<'_>, contains: Func) -> fmt::Result
where
Func: Fn(u8) -> bool,
{
write!(f, "{}[", name)?;
let mut idx = 0;
let mut maybe_space = "";
while idx <= 256 {
// Compute the next value not contained.
let mut end = idx;
while end <= 256 && contains(end as u8) {
end += 1;
}
match end - idx {
0 => (),
1 => write!(f, "{}{}", maybe_space, idx)?,
_ => write!(f, "{}{}-{}", maybe_space, idx, end - 1)?,
};
if end > idx {
maybe_space = " ";
}
idx = end + 1
}
write!(f, "]")?;
Ok(())
}
/// A bitmap covering ASCII characters.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct AsciiBitmap(pub [u8; 16]);
impl AsciiBitmap {
/// Set a byte val in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
debug_assert!(val <= 127, "Value should be ASCII");
self.0[(val >> 3) as usize] |= 1 << (val & 0x7);
}
}
impl fmt::Debug for AsciiBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("AsciiBitmap", f, |v| self.contains(v))
}
}
impl ByteSet for AsciiBitmap {
/// \return whether this bitmap contains a given value.
/// The value does NOT have to be ASCII.
#[inline(always)]
fn contains(&self, val: u8) -> bool {
// Delicate tricks to avoid branches.
// In general we want to compute the byte via /8, and then mask into the
// byte. But if the value is not ASCII then the byte could be too large.
// So mask off the MSB so that the byte is always in range.
let byte = (val & 0x7F) >> 3;
let bit = val & 0x7;
// Now probe the bitmap. If our sign bit was set, we want the mask to be 0;
// otherwise we want to set only the 'bit' offset.
// Invert the sign bit and reuse it.
let mask = ((val >> 7) ^ 1) << bit;
// Probe the bitmap. We expect the compiler to elide the bounds check.
(self.0[byte as usize] & mask)!= 0
}
}
/// A bitmap covering all bytes.
#[derive(Default, Copy, Clone)]
#[repr(align(4))]
pub struct ByteBitmap([u16; 16]);
// TODO: the codegen here is pretty horrible; LLVM is emitting a sequence of
// halfword instructions. Consider using a union?
impl ByteBitmap {
/// Construct from a sequence of bytes.
pub fn new(bytes: &[u8]) -> ByteBitmap {
let mut bb = ByteBitmap::default();
for &b in bytes {
bb.set(b)
}
bb
}
/// \return whether this bitmap contains a given byte val.
#[inline(always)]
pub fn contains(&self, val: u8) -> bool |
/// Set a bit in this bitmap.
#[inline(always)]
pub fn set(&mut self, val: u8) {
let byte = val >> 4;
let bit = val & 0xF;
self.0[byte as usize] |= 1 << bit;
}
/// Update ourselves from another bitmap, in place.
pub fn bitor(&mut self, rhs: &ByteBitmap) {
for idx in 0..self.0.len() {
self.0[idx] |= rhs.0[idx];
}
}
/// Invert our bits, in place.
pub fn bitnot(&mut self) -> &mut Self {
for val in self.0.iter_mut() {
*val =!*val;
}
self
}
/// Count number of set bits.
pub fn count_bits(&self) -> u32 {
self.0.iter().map(|v| v.count_ones()).sum()
}
/// \return all set bytes, as a vec.
#[allow(clippy::wrong_self_convention)]
pub fn to_vec(&self) -> Vec<u8> {
(0..=255).filter(|b| self.contains(*b)).collect()
}
/// \return the index of the first byte in the slice that is present in this
/// bitmap, using some unsafe tricks.
#[inline(always)]
fn unsafe_find_in_slice(&self, bytes: &[u8]) -> Option<usize> {
type Chunk = u32;
let bm = &self.0;
let mut offset = 0;
let (prefix, body, suffix) = unsafe { bytes.align_to::<Chunk>() };
for &byte in prefix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
for &chunk in body {
// Use LE. Here index 0 is the earliest address.
let byte_idxs = ((chunk >> 4) & 0x0F0F0F0F).to_le_bytes();
let bit_idxs = (chunk & 0x0F0F0F0F).to_le_bytes();
if (bm[byte_idxs[0] as usize] & (1 << bit_idxs[0]))!= 0 {
return Some(offset);
}
if (bm[byte_idxs[1] as usize] & (1 << bit_idxs[1]))!= 0 {
return Some(offset + 1);
}
if (bm[byte_idxs[2] as usize] & (1 << bit_idxs[2]))!= 0 {
return Some(offset + 2);
}
if (bm[byte_idxs[3] as usize] & (1 << bit_idxs[3]))!= 0 {
return Some(offset + 3);
}
offset += 4;
}
for &byte in suffix.iter() {
if self.contains(byte) {
return Some(offset);
}
offset += 1;
}
None
}
}
impl ByteSearcher for ByteBitmap {
#[inline(always)]
fn find_in(&self, bytes: &[u8]) -> Option<usize> {
if cfg!(feature = "prohibit-unsafe") {
for (idx, byte) in bytes.iter().enumerate() {
if self.contains(*byte) {
return Some(idx);
}
}
None
} else {
self.unsafe_find_in_slice(bytes)
}
}
}
impl fmt::Debug for ByteBitmap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_bitmap("ByteBitmap", f, |v| self.contains(v))
}
}
/// A trivial ByteSearcher corresponding to the empty string.
#[derive(Debug, Copy, Clone)]
pub struct EmptyString {}
impl ByteSearcher for EmptyString {
#[inline(always)]
fn find_in(&self, _bytes: &[u8]) -> Option<usize> {
Some(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_bitmap(bytes: &[u8]) -> ByteBitmap {
let mut bm = ByteBitmap::default();
for &b in bytes {
bm.set(b)
}
bm
}
#[test]
fn empty_search() {
assert_eq!(EmptyString {}.find_in(&[1, 2, 3]), Some(0));
assert_eq!(EmptyString {}.find_in(&[]), Some(0));
}
#[test]
fn bitmap_search() {
assert_eq!(make_bitmap(&[]).find_in(&[1, 2, 3]), None);
assert_eq!(make_bitmap(&[]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(make_bitmap(&[1]).bitnot().find_in(&[1, 2, 3]), Some(1));
assert_eq!(make_bitmap(&[2]).bitnot().find_in(&[1, 2, 3]), Some(0));
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7]).find_in(&[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),
None
);
assert_eq!(
make_bitmap(&[4, 5, 6, 7])
.find_in(&[8, 9, 10, 11, 12, 13, 4, 14, 6, 15, 7, 16, 17, 18, 19, 20]),
Some(6)
);
}
#[test]
fn literal_search() {
assert_eq!([0, 1, 2, 3].find_in(&[4, 5, 6, 7]), None);
assert_eq!([0, 1, 2, 3].find_in(&[]), None);
}
}
| {
let byte = val >> 4;
let bit = val & 0xF;
(self.0[byte as usize] & (1 << bit)) != 0
} | identifier_body |
texel.rs | ` developers
#![allow(unsafe_code)]
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use core::marker::PhantomData;
use core::{fmt, hash, mem, num, ptr, slice};
use crate::buf::buf;
/// Marker struct to denote a texel type.
///
/// Can be constructed only for types that have expected alignment and no byte invariants. It
/// always implements `Copy` and `Clone`, regardless of the underlying type and is zero-sized.
///
/// This is the central encapsulation of unsafety in this crate. It utilizes `bytemuck` for a safe
/// interface but permits other types with an unsafe interface, and offers the cast operations
/// without a bound on the `Pod` trait. Note that `Pod` is a pure marker trait; its properties must
/// hold even if it is not explicitly mentioned. If all constructors (safely or unsafely) ensure
/// that its properties hold we can use `Texel` as a witness type for the bound and subsequently
/// write interfaces to take an instance instead of having a static type bound. This achieves two
/// effects:
/// * Firstly, it makes the interface independent of the chosen transmutation crate. Potentially we
/// will have a method to construct the `Texel` via a `core` trait.
/// * Secondly, it allows creating texel of third-party types for which the bound can not be
/// implemented. Crucially, this includes SIMD representations that would be a burden to support
/// directly. And conversely you can also deal with arbitrary existing texel without a bound in
/// your own interfaces!
pub struct Texel<P:?Sized>(PhantomData<P>);
/// Marker struct to denote that P is transparently wrapped in O.
///
/// The only way to construct it is by accessing its associated constant which only exists when the
/// bound `bytemuck::TransparentWrapper` holds as required. This encodes a type-level set and is
/// a workaround for such bounds not yet being allowed in `const fn`. Expect this type to be
/// deprecated sooner or later.
pub struct IsTransparentWrapper<P, O>(PhantomData<(P, O)>);
/// Describes a type which can represent a `Texel` and for which this is statically known.
pub trait AsTexel {
/// Get the texel struct for this type.
///
/// The naive implementation of merely unwrapping the result of `Texel::for_type` **panics** on
/// any invalid type. This trait should only be implemented when you know for sure that the
/// type is correct.
fn texel() -> Texel<Self>;
}
macro_rules! def_max_align {
(
$(#[$common_attr:meta])*
$($($arch:literal),* = $num:literal),*
) => {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
$(#[$common_attr])*
$(
#[cfg_attr(
any($(target_arch = $arch),*),
repr(align($num))
)]
)*
pub struct MaxAligned(pub(crate) [u8; MAX_ALIGN]);
$(
#[cfg(
any($(target_arch = $arch),*),
)]
pub(crate) const MAX_ALIGN: usize = $num;
)*
#[cfg(
not(any(
$(any($(target_arch = $arch),*)),*
)),
)]
pub(crate) const MAX_ALIGN: usize = 8;
}
}
def_max_align! {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
#[derive(Clone, Copy)]
#[repr(C)]
"x86", "x86_64" = 32,
"arm" = 16,
"aarch64" = 16,
"wasm32" = 16
}
unsafe impl bytemuck::Zeroable for MaxAligned {}
unsafe impl bytemuck::Pod for MaxAligned {}
macro_rules! builtin_texel {
( $name:ty ) => {
impl AsTexel for $name {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$name>::check_invariants());
};
unsafe { Texel::new_unchecked() }
}
}
};
}
pub(crate) mod constants {
use super::{AsTexel, MaxAligned, Texel};
macro_rules! constant_texel {
($(($name:ident, $type:ty)),*) => {
$(pub const $name: Texel<$type> = Texel(core::marker::PhantomData) ;
impl AsTexel for $type {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$type>::check_invariants());
};
$name
}
}
)*
}
}
constant_texel!(
(I8, i8),
(U8, u8),
(I16, i16),
(U16, u16),
(I32, i32),
(U32, u32),
(F32, f32),
(I64, i64),
(U64, u64),
(F64, f64),
(USIZE, usize),
(ISIZE, isize),
(MAX, MaxAligned)
);
impl<T: AsTexel> AsTexel for [T; 1] {
fn texel() -> Texel<[T; 1]> {
T::texel().array::<1>()
}
}
impl<T: AsTexel> AsTexel for [T; 2] {
fn texel() -> Texel<[T; 2]> {
T::texel().array::<2>()
}
}
impl<T: AsTexel> AsTexel for [T; 3] {
fn texel() -> Texel<[T; 3]> {
T::texel().array::<3>()
}
}
impl<T: AsTexel> AsTexel for [T; 4] {
fn texel() -> Texel<[T; 4]> {
T::texel().array::<4>()
}
}
impl<T: AsTexel> AsTexel for [T; 5] {
fn texel() -> Texel<[T; 5]> {
T::texel().array::<5>()
}
}
impl<T: AsTexel> AsTexel for [T; 6] {
fn | () -> Texel<[T; 6]> {
T::texel().array::<6>()
}
}
impl<T: AsTexel> AsTexel for [T; 7] {
fn texel() -> Texel<[T; 7]> {
T::texel().array::<7>()
}
}
impl<T: AsTexel> AsTexel for [T; 8] {
fn texel() -> Texel<[T; 8]> {
T::texel().array::<8>()
}
}
impl<T: AsTexel> AsTexel for ::core::num::Wrapping<T> {
fn texel() -> Texel<::core::num::Wrapping<T>> {
T::texel().num_wrapping()
}
}
}
#[cfg(target_arch = "x86")]
mod x64 {
use super::{AsTexel, Texel};
use core::arch::x86;
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128d);
builtin_texel!(x86::__m128i);
builtin_texel!(x86::__m256);
builtin_texel!(x86::__m256d);
builtin_texel!(x86::__m256i);
}
#[cfg(target_arch = "x86_64")]
mod x64_64 {
use super::{AsTexel, Texel};
use core::arch::x86_64;
builtin_texel!(x86_64::__m128);
builtin_texel!(x86_64::__m128d);
builtin_texel!(x86_64::__m128i);
builtin_texel!(x86_64::__m256);
builtin_texel!(x86_64::__m256d);
builtin_texel!(x86_64::__m256i);
}
#[cfg(target_arch = "arm")]
mod arm { /* all types unstable */
}
#[cfg(target_arch = "aarch64")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::aarch64;
builtin_texel!(aarch64::float64x1_t);
builtin_texel!(aarch64::float64x1x2_t);
builtin_texel!(aarch64::float64x1x3_t);
builtin_texel!(aarch64::float64x1x4_t);
builtin_texel!(aarch64::float64x2_t);
builtin_texel!(aarch64::float64x2x2_t);
builtin_texel!(aarch64::float64x2x3_t);
builtin_texel!(aarch64::float64x2x4_t);
}
#[cfg(target_arch = "wasm32")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::wasm32;
builtin_texel!(wasm32::v128);
}
impl<P: bytemuck::Pod> Texel<P> {
/// Try to construct an instance of the marker.
///
/// If successful, you can freely use it to access the image buffers. This requires:
/// - The type must have an alignment of *at most* `MAX_ALIGN`.
/// - The type must *not* be a ZST.
/// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
pub const fn for_type() -> Option<Self> {
if Texel::<P>::check_invariants() {
Some(Texel(PhantomData))
} else {
None
}
}
}
impl<P, O: bytemuck::TransparentWrapper<P>> IsTransparentWrapper<P, O> {
pub const CONST: Self = IsTransparentWrapper(PhantomData);
}
/// The **only** ways to construct a `buf`, protecting the alignment invariant.
/// Hint: This is an unsized type so there is no safe way of constructing it.
impl buf {
pub const ALIGNMENT: usize = MAX_ALIGN;
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes(bytes: &[u8]) -> Option<&Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &*(bytes as *const [u8] as *const Self) })
} else {
None
}
}
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &mut *(bytes as *mut [u8] as *mut Self) })
} else {
None
}
}
}
impl<P> Texel<P> {
/// Create a witness certifying `P` as a texel without checks.
///
/// # Safety
///
/// The type `P` must __not__:
/// * have any validity invariants, i.e. is mustn't contain any padding.
/// * have any safety invariants. This implies it can be copied.
/// * have an alignment larger than [`MaxAligned`].
/// * be a zero-size type.
///
/// Furthermore, tentatively, the type must not have any drop glue. That is its members are all
/// simple types without Drop implementations. This requirement exists mainly to avoid code
/// accidentally leaking instances, and ensures that copies created from their byte
/// representation—which is safe according to the other invairants— do not cause unexpected
/// effects.
///
/// Note that the alignment requirement with regards to `MaxAligned` is __architecture
/// dependent__ as the exact bound varies across the `target_arch` feature. Where possible, add
/// static assertions to each call site of this function.
///
/// [`MaxAligned`]: struct.MaxAligned.html
pub const unsafe fn new_unchecked() -> Self {
debug_assert!(Self::check_invariants());
Texel(PhantomData)
}
/// Note this isn't exhaustive. Indeed, we have no way to check for padding.
pub(crate) const fn check_invariants() -> bool {
mem::align_of::<P>() <= MAX_ALIGN && mem::size_of::<P>() > 0 &&!mem::needs_drop::<P>()
}
/// Proxy of `core::mem::align_of`.
pub const fn align(self) -> usize {
mem::align_of::<P>()
}
/// Proxy of `core::mem::size_of`.
pub const fn size(self) -> usize {
mem::size_of::<P>()
}
/// Publicly visible function to use the guarantee of non-ZST.
pub const fn size_nz(self) -> core::num::NonZeroUsize {
match core::num::NonZeroUsize::new(self.size()) {
None => panic!(""),
Some(num) => num,
}
}
// A number of constructors that are technically unsafe. Note that we could write them as safe
// code here to pad our stats but they are not checked by the type system so it's risky. Better
// explain their safety in the code as comments.
/// Construct a texel as an array of no elements.
///
/// # Panics
///
/// This function panics when called with `N` equal to 0.
pub const fn array<const N: usize>(self) -> Texel<[P; N]> {
if N == 0 {
panic!()
}
// Safety:
// * has no validity/safety invariants
// * has the same alignment as P which is not larger then MaxAligned
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by wrapping into a transparent wrapper.
///
/// TODO: a constructor for Texel<O> based on proof of transmutation from &mut P to &mut O,
/// based on the standard transmutation RFC. This is more flexible than bytemuck's
/// TransparentWrapper trait.
pub const fn transparent_wrap<O>(self, _: IsTransparentWrapper<P, O>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by unwrapping a transparent wrapper.
pub const fn transparent_unwrap<O>(self, _: IsTransparentWrapper<O, P>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel that contains a number in the standard `Wrapping` type.
pub const fn num_wrapping(self) -> Texel<num::Wrapping<P>> {
// * Texel<P> = Self certifies the byte properties.
// * `core::num::Wrapping` is `repr(transparent)
unsafe { Texel::new_unchecked() }
}
}
impl<T, const N: usize> Texel<[T; N]> {
/// Construct a texel, from an array of elements.
pub const fn array_element(self) -> Texel<T> {
// Safety:
// We'll see that all properties are implied by _any_ suitable array.
// - The type must have an alignment of *at most* `MAX_ALIGN`. Array and inner type have
// the same alignment.
// - The type must *not* be a ZST. The array would otherwise be a ZST.
// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
// The array would otherwise have Drop-glue.
unsafe { Texel::new_unchecked() }
}
}
/// Operations that can be performed based on the evidence of Texel.
impl<P> Texel<P> {
/// Copy a texel.
///
/// Note that this does not require `Copy` because that requirement was part of the
/// requirements of constructing this `Texel` witness.
pub fn copy_val(self, val: &P) -> P {
// SAFETY: by the constructor, this type can be copied byte-by-byte.
unsafe { ptr::read(val) }
}
/// Reinterpret a slice of aligned bytes as a slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_slice<'buf>(self, buffer: &'buf [MaxAligned]) -> &'buf [P] {
self.cast_buf(buf::new(buffer))
}
/// Reinterpret a slice of aligned bytes as a mutable slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_mut_slice<'buf>(self, buffer: &'buf mut [MaxAligned]) -> &'buf mut [P] {
self.cast_mut_buf(buf::new_mut(buffer))
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice<'buf>(self, bytes: &'buf [u8]) -> Option<&'buf [P]> {
if bytes.as_ptr() as usize % mem::align_of::<P>() == 0 {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P.
// - The total size is at most `bytes` by construction.
let len = bytes.len() / mem::size_of::<P>();
Some(unsafe { &*ptr::slice_from_raw_parts(bytes.as_ptr() as *const P, len) })
} else {
None
}
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> {
if let Some(slice) = self.try_to_slice(bytes) {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P. Conversely, it makes any P valid as bytes.
let len = slice.len();
Some(unsafe { &mut *ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut P, len) })
} else {
None
}
}
/// Reinterpret a slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_ref`].
pub fn to_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
self.cast_bytes(texel)
}
/// Reinterpret a mutable slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_mut`].
pub fn to_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
self.cast_mut_bytes(texel)
}
pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts(
buffer.as_ptr() as *const P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_mut_buf<'buf>(self, buffer: &'buf mut buf) -> &'buf mut [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads and writes as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts_mut(
buffer.as_mut_ptr() as *mut P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity for byte reading checked by Texel constructor
unsafe { slice::from_raw_parts(texel.as_ptr() as *const u8, mem::size_of_val(texel)) }
}
pub(crate) fn cast_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity as bytes checked by Texel constructor
unsafe { slice::from_raw_parts_mut(texel.as_mut_ptr() as *mut u8, mem::size_of_val(texel)) }
}
}
/// This is a pure marker type.
impl<P> Clone for Texel<P> {
fn clone(&self) -> Self {
Texel(PhantomData)
}
}
impl<P> PartialEq for Texel<P> {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl<P> Eq for Texel<P> {}
impl<P> PartialOrd for Texel<P> {
fn partial_cmp(&self, _: &Self) -> Option<Ordering> {
Some(Ordering::Equal)
}
}
impl<P> Ord for Texel<P> {
fn cmp(&self, _: &Self) -> Ordering {
Ordering::Equal
}
}
/// This is a pure marker type.
impl<P> Copy for Texel<P> {}
impl<P> fmt::Debug for Texel<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Texel")
.field("size", &self.size())
.field("align", &self.align())
| texel | identifier_name |
texel.rs | rs` developers
#![allow(unsafe_code)]
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use core::marker::PhantomData;
use core::{fmt, hash, mem, num, ptr, slice};
use crate::buf::buf;
/// Marker struct to denote a texel type.
///
/// Can be constructed only for types that have expected alignment and no byte invariants. It
/// always implements `Copy` and `Clone`, regardless of the underlying type and is zero-sized.
///
/// This is the central encapsulation of unsafety in this crate. It utilizes `bytemuck` for a safe
/// interface but permits other types with an unsafe interface, and offers the cast operations
/// without a bound on the `Pod` trait. Note that `Pod` is a pure marker trait; its properties must
/// hold even if it is not explicitly mentioned. If all constructors (safely or unsafely) ensure
/// that its properties hold we can use `Texel` as a witness type for the bound and subsequently
/// write interfaces to take an instance instead of having a static type bound. This achieves two
/// effects:
/// * Firstly, it makes the interface independent of the chosen transmutation crate. Potentially we
/// will have a method to construct the `Texel` via a `core` trait.
/// * Secondly, it allows creating texel of third-party types for which the bound can not be
/// implemented. Crucially, this includes SIMD representations that would be a burden to support
/// directly. And conversely you can also deal with arbitrary existing texel without a bound in
/// your own interfaces!
pub struct Texel<P:?Sized>(PhantomData<P>);
/// Marker struct to denote that P is transparently wrapped in O.
///
/// The only way to construct it is by accessing its associated constant which only exists when the
/// bound `bytemuck::TransparentWrapper` holds as required. This encodes a type-level set and is
/// a workaround for such bounds not yet being allowed in `const fn`. Expect this type to be
/// deprecated sooner or later.
pub struct IsTransparentWrapper<P, O>(PhantomData<(P, O)>);
/// Describes a type which can represent a `Texel` and for which this is statically known.
pub trait AsTexel {
/// Get the texel struct for this type.
///
/// The naive implementation of merely unwrapping the result of `Texel::for_type` **panics** on
/// any invalid type. This trait should only be implemented when you know for sure that the
/// type is correct.
fn texel() -> Texel<Self>;
}
macro_rules! def_max_align {
(
$(#[$common_attr:meta])*
$($($arch:literal),* = $num:literal),*
) => {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
$(#[$common_attr])*
$(
#[cfg_attr(
any($(target_arch = $arch),*),
repr(align($num))
)]
)*
pub struct MaxAligned(pub(crate) [u8; MAX_ALIGN]);
$(
#[cfg(
any($(target_arch = $arch),*),
)]
pub(crate) const MAX_ALIGN: usize = $num;
)*
#[cfg(
not(any(
$(any($(target_arch = $arch),*)),*
)),
)]
pub(crate) const MAX_ALIGN: usize = 8;
}
}
def_max_align! {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
#[derive(Clone, Copy)]
#[repr(C)]
"x86", "x86_64" = 32,
"arm" = 16,
"aarch64" = 16,
"wasm32" = 16
}
unsafe impl bytemuck::Zeroable for MaxAligned {}
unsafe impl bytemuck::Pod for MaxAligned {}
macro_rules! builtin_texel {
( $name:ty ) => {
impl AsTexel for $name {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$name>::check_invariants());
};
unsafe { Texel::new_unchecked() }
}
}
};
}
pub(crate) mod constants {
use super::{AsTexel, MaxAligned, Texel};
macro_rules! constant_texel {
($(($name:ident, $type:ty)),*) => {
$(pub const $name: Texel<$type> = Texel(core::marker::PhantomData) ;
impl AsTexel for $type {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$type>::check_invariants());
};
$name
}
}
)*
}
}
constant_texel!(
(I8, i8),
(U8, u8),
(I16, i16),
(U16, u16),
(I32, i32),
(U32, u32),
(F32, f32),
(I64, i64),
(U64, u64),
(F64, f64),
(USIZE, usize),
(ISIZE, isize),
(MAX, MaxAligned)
);
impl<T: AsTexel> AsTexel for [T; 1] {
fn texel() -> Texel<[T; 1]> {
T::texel().array::<1>()
}
}
impl<T: AsTexel> AsTexel for [T; 2] {
fn texel() -> Texel<[T; 2]> {
T::texel().array::<2>()
}
}
impl<T: AsTexel> AsTexel for [T; 3] {
fn texel() -> Texel<[T; 3]> {
T::texel().array::<3>()
}
}
impl<T: AsTexel> AsTexel for [T; 4] {
fn texel() -> Texel<[T; 4]> {
T::texel().array::<4>()
}
}
impl<T: AsTexel> AsTexel for [T; 5] {
fn texel() -> Texel<[T; 5]> {
T::texel().array::<5>()
}
}
impl<T: AsTexel> AsTexel for [T; 6] {
fn texel() -> Texel<[T; 6]> {
T::texel().array::<6>()
}
}
impl<T: AsTexel> AsTexel for [T; 7] {
fn texel() -> Texel<[T; 7]> {
T::texel().array::<7>()
}
}
impl<T: AsTexel> AsTexel for [T; 8] {
fn texel() -> Texel<[T; 8]> {
T::texel().array::<8>()
}
}
impl<T: AsTexel> AsTexel for ::core::num::Wrapping<T> {
fn texel() -> Texel<::core::num::Wrapping<T>> {
T::texel().num_wrapping()
}
}
}
#[cfg(target_arch = "x86")]
mod x64 {
use super::{AsTexel, Texel};
use core::arch::x86;
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128d);
builtin_texel!(x86::__m128i);
builtin_texel!(x86::__m256);
builtin_texel!(x86::__m256d);
builtin_texel!(x86::__m256i);
}
#[cfg(target_arch = "x86_64")]
mod x64_64 {
use super::{AsTexel, Texel};
use core::arch::x86_64;
builtin_texel!(x86_64::__m128);
builtin_texel!(x86_64::__m128d);
builtin_texel!(x86_64::__m128i);
builtin_texel!(x86_64::__m256);
builtin_texel!(x86_64::__m256d);
builtin_texel!(x86_64::__m256i);
}
#[cfg(target_arch = "arm")]
mod arm { /* all types unstable */
}
#[cfg(target_arch = "aarch64")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::aarch64;
builtin_texel!(aarch64::float64x1_t);
builtin_texel!(aarch64::float64x1x2_t);
builtin_texel!(aarch64::float64x1x3_t);
builtin_texel!(aarch64::float64x1x4_t);
builtin_texel!(aarch64::float64x2_t);
builtin_texel!(aarch64::float64x2x2_t);
builtin_texel!(aarch64::float64x2x3_t);
builtin_texel!(aarch64::float64x2x4_t);
}
#[cfg(target_arch = "wasm32")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::wasm32;
builtin_texel!(wasm32::v128);
}
impl<P: bytemuck::Pod> Texel<P> {
/// Try to construct an instance of the marker.
///
/// If successful, you can freely use it to access the image buffers. This requires:
/// - The type must have an alignment of *at most* `MAX_ALIGN`.
/// - The type must *not* be a ZST.
/// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
pub const fn for_type() -> Option<Self> {
if Texel::<P>::check_invariants() {
Some(Texel(PhantomData))
} else {
None
}
}
}
impl<P, O: bytemuck::TransparentWrapper<P>> IsTransparentWrapper<P, O> {
pub const CONST: Self = IsTransparentWrapper(PhantomData);
}
/// The **only** ways to construct a `buf`, protecting the alignment invariant.
/// Hint: This is an unsized type so there is no safe way of constructing it.
impl buf {
pub const ALIGNMENT: usize = MAX_ALIGN;
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes(bytes: &[u8]) -> Option<&Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &*(bytes as *const [u8] as *const Self) })
} else {
None
}
}
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &mut *(bytes as *mut [u8] as *mut Self) })
} else {
None
}
}
}
impl<P> Texel<P> {
/// Create a witness certifying `P` as a texel without checks.
///
/// # Safety
///
/// The type `P` must __not__:
/// * have any validity invariants, i.e. is mustn't contain any padding.
/// * have any safety invariants. This implies it can be copied.
/// * have an alignment larger than [`MaxAligned`].
/// * be a zero-size type.
///
/// Furthermore, tentatively, the type must not have any drop glue. That is its members are all
/// simple types without Drop implementations. This requirement exists mainly to avoid code
/// accidentally leaking instances, and ensures that copies created from their byte
/// representation—which is safe according to the other invairants— do not cause unexpected
/// effects.
///
/// Note that the alignment requirement with regards to `MaxAligned` is __architecture
/// dependent__ as the exact bound varies across the `target_arch` feature. Where possible, add
/// static assertions to each call site of this function.
///
/// [`MaxAligned`]: struct.MaxAligned.html
pub const unsafe fn new_unchecked() -> Self {
debug_assert!(Self::check_invariants());
Texel(PhantomData)
}
/// Note this isn't exhaustive. Indeed, we have no way to check for padding.
pub(crate) const fn check_invariants() -> bool {
mem::align_of::<P>() <= MAX_ALIGN && mem::size_of::<P>() > 0 &&!mem::needs_drop::<P>()
}
/// Proxy of `core::mem::align_of`.
pub const fn align(self) -> usize {
mem::align_of::<P>()
}
/// Proxy of `core::mem::size_of`.
pub const fn size(self) -> usize {
mem::size_of::<P>()
}
/// Publicly visible function to use the guarantee of non-ZST.
pub const fn size_nz(self) -> core::num::NonZeroUsize {
match core::num::NonZeroUsize::new(self.size()) {
None => panic!(""),
Some(num) => num,
}
}
// A number of constructors that are technically unsafe. Note that we could write them as safe
// code here to pad our stats but they are not checked by the type system so it's risky. Better
// explain their safety in the code as comments.
/// Construct a texel as an array of no elements.
///
/// # Panics
///
/// This function panics when called with `N` equal to 0.
pub const fn array<const N: usize>(self) -> Texel<[P; N]> {
if N == 0 {
panic!()
}
// Safety:
// * has no validity/safety invariants
// * has the same alignment as P which is not larger then MaxAligned
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by wrapping into a transparent wrapper.
///
/// TODO: a constructor for Texel<O> based on proof of transmutation from &mut P to &mut O,
/// based on the standard transmutation RFC. This is more flexible than bytemuck's
/// TransparentWrapper trait.
pub const fn transparent_wrap<O>(self, _: IsTransparentWrapper<P, O>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by unwrapping a transparent wrapper.
pub const fn transparent_unwrap<O>(self, _: IsTransparentWrapper<O, P>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel that contains a number in the standard `Wrapping` type.
pub const fn num_wrapping(self) -> Texel<num::Wrapping<P>> {
// * Texel<P> = Self certifies the byte properties.
// * `core::num::Wrapping` is `repr(transparent)
unsafe { Texel::new_unchecked() }
}
}
impl<T, const N: usize> Texel<[T; N]> {
/// Construct a texel, from an array of elements.
pub const fn array_element(self) -> Texel<T> {
// Safety:
// We'll see that all properties are implied by _any_ suitable array.
// - The type must have an alignment of *at most* `MAX_ALIGN`. Array and inner type have
// the same alignment.
// - The type must *not* be a ZST. The array would otherwise be a ZST.
// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
// The array would otherwise have Drop-glue.
unsafe { Texel::new_unchecked() }
}
}
/// Operations that can be performed based on the evidence of Texel.
impl<P> Texel<P> {
/// Copy a texel.
///
/// Note that this does not require `Copy` because that requirement was part of the
/// requirements of constructing this `Texel` witness.
pub fn copy_val(self, val: &P) -> P {
// SAFETY: by the constructor, this type can be copied byte-by-byte.
unsafe { ptr::read(val) }
}
/// Reinterpret a slice of aligned bytes as a slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_slice<'buf>(self, buffer: &'buf [MaxAligned]) -> &'buf [P] {
self.cast_buf(buf::new(buffer))
}
/// Reinterpret a slice of aligned bytes as a mutable slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_mut_slice<'buf>(self, buffer: &'buf mut [MaxAligned]) -> &'buf mut [P] {
self.cast_mut_buf(buf::new_mut(buffer))
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice<'buf>(self, bytes: &'buf [u8]) -> Option<&'buf [P]> {
if bytes.as_ptr() as usize % mem::align_of::<P>() == 0 {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P.
// - The total size is at most `bytes` by construction.
let len = bytes.len() / mem::size_of::<P>();
Some(unsafe { &*ptr::slice_from_raw_parts(bytes.as_ptr() as *const P, len) })
} else {
None
}
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> {
if let Some(slice) = self.try_to_slice(bytes) {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P. Conversely, it makes any P valid as bytes.
let len = slice.len();
Some(unsafe { &mut *ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut P, len) })
} else {
None
}
}
/// Reinterpret a slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_ref`].
pub fn to_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
self.cast_bytes(texel)
}
/// Reinterpret a mutable slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_mut`].
pub fn to_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
| pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts(
buffer.as_ptr() as *const P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_mut_buf<'buf>(self, buffer: &'buf mut buf) -> &'buf mut [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads and writes as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts_mut(
buffer.as_mut_ptr() as *mut P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity for byte reading checked by Texel constructor
unsafe { slice::from_raw_parts(texel.as_ptr() as *const u8, mem::size_of_val(texel)) }
}
pub(crate) fn cast_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity as bytes checked by Texel constructor
unsafe { slice::from_raw_parts_mut(texel.as_mut_ptr() as *mut u8, mem::size_of_val(texel)) }
}
}
/// This is a pure marker type.
impl<P> Clone for Texel<P> {
fn clone(&self) -> Self {
Texel(PhantomData)
}
}
impl<P> PartialEq for Texel<P> {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl<P> Eq for Texel<P> {}
impl<P> PartialOrd for Texel<P> {
fn partial_cmp(&self, _: &Self) -> Option<Ordering> {
Some(Ordering::Equal)
}
}
impl<P> Ord for Texel<P> {
fn cmp(&self, _: &Self) -> Ordering {
Ordering::Equal
}
}
/// This is a pure marker type.
impl<P> Copy for Texel<P> {}
impl<P> fmt::Debug for Texel<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Texel")
.field("size", &self.size())
.field("align", &self.align())
| self.cast_mut_bytes(texel)
}
| identifier_body |
texel.rs | rs` developers
#![allow(unsafe_code)]
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use core::marker::PhantomData;
use core::{fmt, hash, mem, num, ptr, slice};
use crate::buf::buf;
/// Marker struct to denote a texel type.
///
/// Can be constructed only for types that have expected alignment and no byte invariants. It
/// always implements `Copy` and `Clone`, regardless of the underlying type and is zero-sized.
///
/// This is the central encapsulation of unsafety in this crate. It utilizes `bytemuck` for a safe
/// interface but permits other types with an unsafe interface, and offers the cast operations
/// without a bound on the `Pod` trait. Note that `Pod` is a pure marker trait; its properties must
/// hold even if it is not explicitly mentioned. If all constructors (safely or unsafely) ensure
/// that its properties hold we can use `Texel` as a witness type for the bound and subsequently
/// write interfaces to take an instance instead of having a static type bound. This achieves two
/// effects:
/// * Firstly, it makes the interface independent of the chosen transmutation crate. Potentially we
/// will have a method to construct the `Texel` via a `core` trait.
/// * Secondly, it allows creating texel of third-party types for which the bound can not be
/// implemented. Crucially, this includes SIMD representations that would be a burden to support
/// directly. And conversely you can also deal with arbitrary existing texel without a bound in
/// your own interfaces!
pub struct Texel<P:?Sized>(PhantomData<P>);
/// Marker struct to denote that P is transparently wrapped in O.
///
/// The only way to construct it is by accessing its associated constant which only exists when the
/// bound `bytemuck::TransparentWrapper` holds as required. This encodes a type-level set and is
/// a workaround for such bounds not yet being allowed in `const fn`. Expect this type to be
/// deprecated sooner or later.
pub struct IsTransparentWrapper<P, O>(PhantomData<(P, O)>);
/// Describes a type which can represent a `Texel` and for which this is statically known.
pub trait AsTexel {
/// Get the texel struct for this type.
///
/// The naive implementation of merely unwrapping the result of `Texel::for_type` **panics** on
/// any invalid type. This trait should only be implemented when you know for sure that the
/// type is correct.
fn texel() -> Texel<Self>;
}
macro_rules! def_max_align {
(
$(#[$common_attr:meta])*
$($($arch:literal),* = $num:literal),*
) => {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
$(#[$common_attr])*
$(
#[cfg_attr(
any($(target_arch = $arch),*),
repr(align($num))
)]
)*
pub struct MaxAligned(pub(crate) [u8; MAX_ALIGN]);
$(
#[cfg(
any($(target_arch = $arch),*),
)]
pub(crate) const MAX_ALIGN: usize = $num;
)*
#[cfg(
not(any(
$(any($(target_arch = $arch),*)),*
)),
)]
pub(crate) const MAX_ALIGN: usize = 8;
}
}
def_max_align! {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
#[derive(Clone, Copy)]
#[repr(C)]
"x86", "x86_64" = 32,
"arm" = 16,
"aarch64" = 16,
"wasm32" = 16
}
unsafe impl bytemuck::Zeroable for MaxAligned {}
unsafe impl bytemuck::Pod for MaxAligned {}
macro_rules! builtin_texel {
( $name:ty ) => {
impl AsTexel for $name {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$name>::check_invariants());
};
unsafe { Texel::new_unchecked() }
}
}
};
}
pub(crate) mod constants {
use super::{AsTexel, MaxAligned, Texel};
macro_rules! constant_texel {
($(($name:ident, $type:ty)),*) => {
$(pub const $name: Texel<$type> = Texel(core::marker::PhantomData) ;
impl AsTexel for $type {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$type>::check_invariants());
};
$name
}
}
)*
}
}
constant_texel!(
(I8, i8),
(U8, u8),
(I16, i16),
(U16, u16),
(I32, i32),
(U32, u32),
(F32, f32),
(I64, i64),
(U64, u64),
(F64, f64),
(USIZE, usize),
(ISIZE, isize),
(MAX, MaxAligned)
);
impl<T: AsTexel> AsTexel for [T; 1] {
fn texel() -> Texel<[T; 1]> {
T::texel().array::<1>()
}
}
impl<T: AsTexel> AsTexel for [T; 2] {
fn texel() -> Texel<[T; 2]> {
T::texel().array::<2>()
}
}
impl<T: AsTexel> AsTexel for [T; 3] {
fn texel() -> Texel<[T; 3]> {
T::texel().array::<3>()
}
}
impl<T: AsTexel> AsTexel for [T; 4] {
fn texel() -> Texel<[T; 4]> {
T::texel().array::<4>()
}
}
impl<T: AsTexel> AsTexel for [T; 5] {
fn texel() -> Texel<[T; 5]> {
T::texel().array::<5>()
}
}
impl<T: AsTexel> AsTexel for [T; 6] {
fn texel() -> Texel<[T; 6]> {
T::texel().array::<6>()
}
}
impl<T: AsTexel> AsTexel for [T; 7] {
fn texel() -> Texel<[T; 7]> {
T::texel().array::<7>()
}
}
impl<T: AsTexel> AsTexel for [T; 8] {
fn texel() -> Texel<[T; 8]> {
T::texel().array::<8>()
}
}
impl<T: AsTexel> AsTexel for ::core::num::Wrapping<T> {
fn texel() -> Texel<::core::num::Wrapping<T>> {
T::texel().num_wrapping()
}
}
}
#[cfg(target_arch = "x86")]
mod x64 {
use super::{AsTexel, Texel};
use core::arch::x86;
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128d);
builtin_texel!(x86::__m128i);
builtin_texel!(x86::__m256);
builtin_texel!(x86::__m256d);
builtin_texel!(x86::__m256i);
}
#[cfg(target_arch = "x86_64")]
mod x64_64 {
use super::{AsTexel, Texel};
use core::arch::x86_64;
builtin_texel!(x86_64::__m128);
builtin_texel!(x86_64::__m128d);
builtin_texel!(x86_64::__m128i);
builtin_texel!(x86_64::__m256);
builtin_texel!(x86_64::__m256d);
builtin_texel!(x86_64::__m256i);
}
#[cfg(target_arch = "arm")]
mod arm { /* all types unstable */
}
#[cfg(target_arch = "aarch64")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::aarch64;
builtin_texel!(aarch64::float64x1_t);
builtin_texel!(aarch64::float64x1x2_t);
builtin_texel!(aarch64::float64x1x3_t);
builtin_texel!(aarch64::float64x1x4_t);
builtin_texel!(aarch64::float64x2_t);
builtin_texel!(aarch64::float64x2x2_t);
builtin_texel!(aarch64::float64x2x3_t);
builtin_texel!(aarch64::float64x2x4_t);
}
#[cfg(target_arch = "wasm32")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::wasm32;
builtin_texel!(wasm32::v128);
}
impl<P: bytemuck::Pod> Texel<P> {
/// Try to construct an instance of the marker.
///
/// If successful, you can freely use it to access the image buffers. This requires:
/// - The type must have an alignment of *at most* `MAX_ALIGN`.
/// - The type must *not* be a ZST.
/// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
pub const fn for_type() -> Option<Self> {
if Texel::<P>::check_invariants() {
Some(Texel(PhantomData))
} else {
None
}
}
}
impl<P, O: bytemuck::TransparentWrapper<P>> IsTransparentWrapper<P, O> {
pub const CONST: Self = IsTransparentWrapper(PhantomData);
}
/// The **only** ways to construct a `buf`, protecting the alignment invariant.
/// Hint: This is an unsized type so there is no safe way of constructing it.
impl buf {
pub const ALIGNMENT: usize = MAX_ALIGN;
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes(bytes: &[u8]) -> Option<&Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &*(bytes as *const [u8] as *const Self) })
} else {
None
}
}
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &mut *(bytes as *mut [u8] as *mut Self) })
} else {
None
}
}
}
impl<P> Texel<P> {
/// Create a witness certifying `P` as a texel without checks.
///
/// # Safety
///
/// The type `P` must __not__:
/// * have any validity invariants, i.e. is mustn't contain any padding.
/// * have any safety invariants. This implies it can be copied.
/// * have an alignment larger than [`MaxAligned`].
/// * be a zero-size type.
///
/// Furthermore, tentatively, the type must not have any drop glue. That is its members are all
/// simple types without Drop implementations. This requirement exists mainly to avoid code
/// accidentally leaking instances, and ensures that copies created from their byte
/// representation—which is safe according to the other invairants— do not cause unexpected
/// effects.
///
/// Note that the alignment requirement with regards to `MaxAligned` is __architecture
/// dependent__ as the exact bound varies across the `target_arch` feature. Where possible, add
/// static assertions to each call site of this function.
///
/// [`MaxAligned`]: struct.MaxAligned.html
pub const unsafe fn new_unchecked() -> Self {
debug_assert!(Self::check_invariants());
Texel(PhantomData)
}
/// Note this isn't exhaustive. Indeed, we have no way to check for padding.
pub(crate) const fn check_invariants() -> bool {
mem::align_of::<P>() <= MAX_ALIGN && mem::size_of::<P>() > 0 &&!mem::needs_drop::<P>()
}
/// Proxy of `core::mem::align_of`.
pub const fn align(self) -> usize {
mem::align_of::<P>()
}
/// Proxy of `core::mem::size_of`.
pub const fn size(self) -> usize {
mem::size_of::<P>()
}
/// Publicly visible function to use the guarantee of non-ZST.
pub const fn size_nz(self) -> core::num::NonZeroUsize {
match core::num::NonZeroUsize::new(self.size()) {
None => panic!(""),
Some(num) => num,
}
}
// A number of constructors that are technically unsafe. Note that we could write them as safe
// code here to pad our stats but they are not checked by the type system so it's risky. Better
// explain their safety in the code as comments.
/// Construct a texel as an array of no elements.
///
/// # Panics
///
/// This function panics when called with `N` equal to 0.
pub const fn array<const N: usize>(self) -> Texel<[P; N]> {
if N == 0 {
panic!()
}
// Safety:
// * has no validity/safety invariants
// * has the same alignment as P which is not larger then MaxAligned
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by wrapping into a transparent wrapper.
///
/// TODO: a constructor for Texel<O> based on proof of transmutation from &mut P to &mut O,
/// based on the standard transmutation RFC. This is more flexible than bytemuck's
/// TransparentWrapper trait.
pub const fn transparent_wrap<O>(self, _: IsTransparentWrapper<P, O>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by unwrapping a transparent wrapper.
pub const fn transparent_unwrap<O>(self, _: IsTransparentWrapper<O, P>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel that contains a number in the standard `Wrapping` type.
pub const fn num_wrapping(self) -> Texel<num::Wrapping<P>> {
// * Texel<P> = Self certifies the byte properties.
// * `core::num::Wrapping` is `repr(transparent)
unsafe { Texel::new_unchecked() }
}
}
impl<T, const N: usize> Texel<[T; N]> {
/// Construct a texel, from an array of elements.
pub const fn array_element(self) -> Texel<T> {
// Safety:
// We'll see that all properties are implied by _any_ suitable array.
// - The type must have an alignment of *at most* `MAX_ALIGN`. Array and inner type have
// the same alignment.
// - The type must *not* be a ZST. The array would otherwise be a ZST.
// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
// The array would otherwise have Drop-glue.
unsafe { Texel::new_unchecked() }
}
}
/// Operations that can be performed based on the evidence of Texel.
impl<P> Texel<P> {
/// Copy a texel.
///
/// Note that this does not require `Copy` because that requirement was part of the
/// requirements of constructing this `Texel` witness.
pub fn copy_val(self, val: &P) -> P {
// SAFETY: by the constructor, this type can be copied byte-by-byte.
unsafe { ptr::read(val) }
}
/// Reinterpret a slice of aligned bytes as a slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_slice<'buf>(self, buffer: &'buf [MaxAligned]) -> &'buf [P] {
self.cast_buf(buf::new(buffer))
}
/// Reinterpret a slice of aligned bytes as a mutable slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_mut_slice<'buf>(self, buffer: &'buf mut [MaxAligned]) -> &'buf mut [P] {
self.cast_mut_buf(buf::new_mut(buffer))
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice<'buf>(self, bytes: &'buf [u8]) -> Option<&'buf [P]> {
if bytes.as_ptr() as usize % mem::align_of::<P>() == 0 {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P.
// - The total size is at most `bytes` by construction.
let len = bytes.len() / mem::size_of::<P>();
Some(unsafe { &*ptr::slice_from_raw_parts(bytes.as_ptr() as *const P, len) })
} else {
| }
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> {
if let Some(slice) = self.try_to_slice(bytes) {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P. Conversely, it makes any P valid as bytes.
let len = slice.len();
Some(unsafe { &mut *ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut P, len) })
} else {
None
}
}
/// Reinterpret a slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_ref`].
pub fn to_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
self.cast_bytes(texel)
}
/// Reinterpret a mutable slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_mut`].
pub fn to_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
self.cast_mut_bytes(texel)
}
pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts(
buffer.as_ptr() as *const P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_mut_buf<'buf>(self, buffer: &'buf mut buf) -> &'buf mut [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads and writes as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts_mut(
buffer.as_mut_ptr() as *mut P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity for byte reading checked by Texel constructor
unsafe { slice::from_raw_parts(texel.as_ptr() as *const u8, mem::size_of_val(texel)) }
}
pub(crate) fn cast_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity as bytes checked by Texel constructor
unsafe { slice::from_raw_parts_mut(texel.as_mut_ptr() as *mut u8, mem::size_of_val(texel)) }
}
}
/// This is a pure marker type.
impl<P> Clone for Texel<P> {
fn clone(&self) -> Self {
Texel(PhantomData)
}
}
impl<P> PartialEq for Texel<P> {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl<P> Eq for Texel<P> {}
impl<P> PartialOrd for Texel<P> {
fn partial_cmp(&self, _: &Self) -> Option<Ordering> {
Some(Ordering::Equal)
}
}
impl<P> Ord for Texel<P> {
fn cmp(&self, _: &Self) -> Ordering {
Ordering::Equal
}
}
/// This is a pure marker type.
impl<P> Copy for Texel<P> {}
impl<P> fmt::Debug for Texel<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Texel")
.field("size", &self.size())
.field("align", &self.align())
| None
}
| conditional_block |
texel.rs | rs` developers | #![allow(unsafe_code)]
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use core::marker::PhantomData;
use core::{fmt, hash, mem, num, ptr, slice};
use crate::buf::buf;
/// Marker struct to denote a texel type.
///
/// Can be constructed only for types that have expected alignment and no byte invariants. It
/// always implements `Copy` and `Clone`, regardless of the underlying type and is zero-sized.
///
/// This is the central encapsulation of unsafety in this crate. It utilizes `bytemuck` for a safe
/// interface but permits other types with an unsafe interface, and offers the cast operations
/// without a bound on the `Pod` trait. Note that `Pod` is a pure marker trait; its properties must
/// hold even if it is not explicitly mentioned. If all constructors (safely or unsafely) ensure
/// that its properties hold we can use `Texel` as a witness type for the bound and subsequently
/// write interfaces to take an instance instead of having a static type bound. This achieves two
/// effects:
/// * Firstly, it makes the interface independent of the chosen transmutation crate. Potentially we
/// will have a method to construct the `Texel` via a `core` trait.
/// * Secondly, it allows creating texel of third-party types for which the bound can not be
/// implemented. Crucially, this includes SIMD representations that would be a burden to support
/// directly. And conversely you can also deal with arbitrary existing texel without a bound in
/// your own interfaces!
pub struct Texel<P:?Sized>(PhantomData<P>);
/// Marker struct to denote that P is transparently wrapped in O.
///
/// The only way to construct it is by accessing its associated constant which only exists when the
/// bound `bytemuck::TransparentWrapper` holds as required. This encodes a type-level set and is
/// a workaround for such bounds not yet being allowed in `const fn`. Expect this type to be
/// deprecated sooner or later.
pub struct IsTransparentWrapper<P, O>(PhantomData<(P, O)>);
/// Describes a type which can represent a `Texel` and for which this is statically known.
pub trait AsTexel {
/// Get the texel struct for this type.
///
/// The naive implementation of merely unwrapping the result of `Texel::for_type` **panics** on
/// any invalid type. This trait should only be implemented when you know for sure that the
/// type is correct.
fn texel() -> Texel<Self>;
}
macro_rules! def_max_align {
(
$(#[$common_attr:meta])*
$($($arch:literal),* = $num:literal),*
) => {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
$(#[$common_attr])*
$(
#[cfg_attr(
any($(target_arch = $arch),*),
repr(align($num))
)]
)*
pub struct MaxAligned(pub(crate) [u8; MAX_ALIGN]);
$(
#[cfg(
any($(target_arch = $arch),*),
)]
pub(crate) const MAX_ALIGN: usize = $num;
)*
#[cfg(
not(any(
$(any($(target_arch = $arch),*)),*
)),
)]
pub(crate) const MAX_ALIGN: usize = 8;
}
}
def_max_align! {
/// A byte-like-type that is aligned to the required max alignment.
///
/// This type does not contain padding and implements `Pod`. Generally, the alignment and size
/// requirement is kept small to avoid overhead.
#[derive(Clone, Copy)]
#[repr(C)]
"x86", "x86_64" = 32,
"arm" = 16,
"aarch64" = 16,
"wasm32" = 16
}
unsafe impl bytemuck::Zeroable for MaxAligned {}
unsafe impl bytemuck::Pod for MaxAligned {}
macro_rules! builtin_texel {
( $name:ty ) => {
impl AsTexel for $name {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$name>::check_invariants());
};
unsafe { Texel::new_unchecked() }
}
}
};
}
pub(crate) mod constants {
use super::{AsTexel, MaxAligned, Texel};
macro_rules! constant_texel {
($(($name:ident, $type:ty)),*) => {
$(pub const $name: Texel<$type> = Texel(core::marker::PhantomData) ;
impl AsTexel for $type {
fn texel() -> Texel<Self> {
const _: () = {
assert!(Texel::<$type>::check_invariants());
};
$name
}
}
)*
}
}
constant_texel!(
(I8, i8),
(U8, u8),
(I16, i16),
(U16, u16),
(I32, i32),
(U32, u32),
(F32, f32),
(I64, i64),
(U64, u64),
(F64, f64),
(USIZE, usize),
(ISIZE, isize),
(MAX, MaxAligned)
);
impl<T: AsTexel> AsTexel for [T; 1] {
fn texel() -> Texel<[T; 1]> {
T::texel().array::<1>()
}
}
impl<T: AsTexel> AsTexel for [T; 2] {
fn texel() -> Texel<[T; 2]> {
T::texel().array::<2>()
}
}
impl<T: AsTexel> AsTexel for [T; 3] {
fn texel() -> Texel<[T; 3]> {
T::texel().array::<3>()
}
}
impl<T: AsTexel> AsTexel for [T; 4] {
fn texel() -> Texel<[T; 4]> {
T::texel().array::<4>()
}
}
impl<T: AsTexel> AsTexel for [T; 5] {
fn texel() -> Texel<[T; 5]> {
T::texel().array::<5>()
}
}
impl<T: AsTexel> AsTexel for [T; 6] {
fn texel() -> Texel<[T; 6]> {
T::texel().array::<6>()
}
}
impl<T: AsTexel> AsTexel for [T; 7] {
fn texel() -> Texel<[T; 7]> {
T::texel().array::<7>()
}
}
impl<T: AsTexel> AsTexel for [T; 8] {
fn texel() -> Texel<[T; 8]> {
T::texel().array::<8>()
}
}
impl<T: AsTexel> AsTexel for ::core::num::Wrapping<T> {
fn texel() -> Texel<::core::num::Wrapping<T>> {
T::texel().num_wrapping()
}
}
}
#[cfg(target_arch = "x86")]
mod x64 {
use super::{AsTexel, Texel};
use core::arch::x86;
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128);
builtin_texel!(x86::__m128d);
builtin_texel!(x86::__m128i);
builtin_texel!(x86::__m256);
builtin_texel!(x86::__m256d);
builtin_texel!(x86::__m256i);
}
#[cfg(target_arch = "x86_64")]
mod x64_64 {
use super::{AsTexel, Texel};
use core::arch::x86_64;
builtin_texel!(x86_64::__m128);
builtin_texel!(x86_64::__m128d);
builtin_texel!(x86_64::__m128i);
builtin_texel!(x86_64::__m256);
builtin_texel!(x86_64::__m256d);
builtin_texel!(x86_64::__m256i);
}
#[cfg(target_arch = "arm")]
mod arm { /* all types unstable */
}
#[cfg(target_arch = "aarch64")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::aarch64;
builtin_texel!(aarch64::float64x1_t);
builtin_texel!(aarch64::float64x1x2_t);
builtin_texel!(aarch64::float64x1x3_t);
builtin_texel!(aarch64::float64x1x4_t);
builtin_texel!(aarch64::float64x2_t);
builtin_texel!(aarch64::float64x2x2_t);
builtin_texel!(aarch64::float64x2x3_t);
builtin_texel!(aarch64::float64x2x4_t);
}
#[cfg(target_arch = "wasm32")]
mod arm {
use super::{AsTexel, Texel};
use core::arch::wasm32;
builtin_texel!(wasm32::v128);
}
impl<P: bytemuck::Pod> Texel<P> {
/// Try to construct an instance of the marker.
///
/// If successful, you can freely use it to access the image buffers. This requires:
/// - The type must have an alignment of *at most* `MAX_ALIGN`.
/// - The type must *not* be a ZST.
/// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
pub const fn for_type() -> Option<Self> {
if Texel::<P>::check_invariants() {
Some(Texel(PhantomData))
} else {
None
}
}
}
impl<P, O: bytemuck::TransparentWrapper<P>> IsTransparentWrapper<P, O> {
pub const CONST: Self = IsTransparentWrapper(PhantomData);
}
/// The **only** ways to construct a `buf`, protecting the alignment invariant.
/// Hint: This is an unsized type so there is no safe way of constructing it.
impl buf {
pub const ALIGNMENT: usize = MAX_ALIGN;
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes(bytes: &[u8]) -> Option<&Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &*(bytes as *const [u8] as *const Self) })
} else {
None
}
}
/// Wrap bytes in a `buf`.
///
/// The bytes need to be aligned to `ALIGNMENT`.
pub fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self> {
if bytes.as_ptr() as usize % Self::ALIGNMENT == 0 {
// SAFETY: this is an almost trivial cast of unsized references. Additionally, we still
// guarantee that this is at least aligned to `MAX_ALIGN`.
Some(unsafe { &mut *(bytes as *mut [u8] as *mut Self) })
} else {
None
}
}
}
impl<P> Texel<P> {
/// Create a witness certifying `P` as a texel without checks.
///
/// # Safety
///
/// The type `P` must __not__:
/// * have any validity invariants, i.e. is mustn't contain any padding.
/// * have any safety invariants. This implies it can be copied.
/// * have an alignment larger than [`MaxAligned`].
/// * be a zero-size type.
///
/// Furthermore, tentatively, the type must not have any drop glue. That is its members are all
/// simple types without Drop implementations. This requirement exists mainly to avoid code
/// accidentally leaking instances, and ensures that copies created from their byte
/// representation—which is safe according to the other invairants— do not cause unexpected
/// effects.
///
/// Note that the alignment requirement with regards to `MaxAligned` is __architecture
/// dependent__ as the exact bound varies across the `target_arch` feature. Where possible, add
/// static assertions to each call site of this function.
///
/// [`MaxAligned`]: struct.MaxAligned.html
pub const unsafe fn new_unchecked() -> Self {
debug_assert!(Self::check_invariants());
Texel(PhantomData)
}
/// Note this isn't exhaustive. Indeed, we have no way to check for padding.
pub(crate) const fn check_invariants() -> bool {
mem::align_of::<P>() <= MAX_ALIGN && mem::size_of::<P>() > 0 &&!mem::needs_drop::<P>()
}
/// Proxy of `core::mem::align_of`.
pub const fn align(self) -> usize {
mem::align_of::<P>()
}
/// Proxy of `core::mem::size_of`.
pub const fn size(self) -> usize {
mem::size_of::<P>()
}
/// Publicly visible function to use the guarantee of non-ZST.
pub const fn size_nz(self) -> core::num::NonZeroUsize {
match core::num::NonZeroUsize::new(self.size()) {
None => panic!(""),
Some(num) => num,
}
}
// A number of constructors that are technically unsafe. Note that we could write them as safe
// code here to pad our stats but they are not checked by the type system so it's risky. Better
// explain their safety in the code as comments.
/// Construct a texel as an array of no elements.
///
/// # Panics
///
/// This function panics when called with `N` equal to 0.
pub const fn array<const N: usize>(self) -> Texel<[P; N]> {
if N == 0 {
panic!()
}
// Safety:
// * has no validity/safety invariants
// * has the same alignment as P which is not larger then MaxAligned
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by wrapping into a transparent wrapper.
///
/// TODO: a constructor for Texel<O> based on proof of transmutation from &mut P to &mut O,
/// based on the standard transmutation RFC. This is more flexible than bytemuck's
/// TransparentWrapper trait.
pub const fn transparent_wrap<O>(self, _: IsTransparentWrapper<P, O>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel by unwrapping a transparent wrapper.
pub const fn transparent_unwrap<O>(self, _: IsTransparentWrapper<O, P>) -> Texel<O> {
// Safety:
// * P and O must have the same invariants, none
// * P and O have the same alignment
unsafe { Texel::new_unchecked() }
}
/// Construct a texel that contains a number in the standard `Wrapping` type.
pub const fn num_wrapping(self) -> Texel<num::Wrapping<P>> {
// * Texel<P> = Self certifies the byte properties.
// * `core::num::Wrapping` is `repr(transparent)
unsafe { Texel::new_unchecked() }
}
}
impl<T, const N: usize> Texel<[T; N]> {
/// Construct a texel, from an array of elements.
pub const fn array_element(self) -> Texel<T> {
// Safety:
// We'll see that all properties are implied by _any_ suitable array.
// - The type must have an alignment of *at most* `MAX_ALIGN`. Array and inner type have
// the same alignment.
// - The type must *not* be a ZST. The array would otherwise be a ZST.
// - The type must *not* have any Drop-glue (no drop, any contain not part that is Drop).
// The array would otherwise have Drop-glue.
unsafe { Texel::new_unchecked() }
}
}
/// Operations that can be performed based on the evidence of Texel.
impl<P> Texel<P> {
/// Copy a texel.
///
/// Note that this does not require `Copy` because that requirement was part of the
/// requirements of constructing this `Texel` witness.
pub fn copy_val(self, val: &P) -> P {
// SAFETY: by the constructor, this type can be copied byte-by-byte.
unsafe { ptr::read(val) }
}
/// Reinterpret a slice of aligned bytes as a slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_slice<'buf>(self, buffer: &'buf [MaxAligned]) -> &'buf [P] {
self.cast_buf(buf::new(buffer))
}
/// Reinterpret a slice of aligned bytes as a mutable slice of the texel.
///
/// Note that the size (in bytes) of the slice will be shortened if the size of `P` is not a
/// divisor of the input slice's size.
pub fn to_mut_slice<'buf>(self, buffer: &'buf mut [MaxAligned]) -> &'buf mut [P] {
self.cast_mut_buf(buf::new_mut(buffer))
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice<'buf>(self, bytes: &'buf [u8]) -> Option<&'buf [P]> {
if bytes.as_ptr() as usize % mem::align_of::<P>() == 0 {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P.
// - The total size is at most `bytes` by construction.
let len = bytes.len() / mem::size_of::<P>();
Some(unsafe { &*ptr::slice_from_raw_parts(bytes.as_ptr() as *const P, len) })
} else {
None
}
}
/// Try to reinterpret a slice of bytes as a slice of the texel.
///
/// This returns `Some` if the buffer is suitably aligned, and `None` otherwise.
pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> {
if let Some(slice) = self.try_to_slice(bytes) {
// SAFETY:
// - The `pod`-ness is certified by `self`, which makes the bytes a valid
// representation of P. Conversely, it makes any P valid as bytes.
let len = slice.len();
Some(unsafe { &mut *ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut P, len) })
} else {
None
}
}
/// Reinterpret a slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_ref`].
pub fn to_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
self.cast_bytes(texel)
}
/// Reinterpret a mutable slice of texel as memory.
///
/// Note that you can convert a reference to a single value by [`core::slice::from_mut`].
pub fn to_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
self.cast_mut_bytes(texel)
}
pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts(
buffer.as_ptr() as *const P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_mut_buf<'buf>(self, buffer: &'buf mut buf) -> &'buf mut [P] {
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0);
debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0);
// Safety:
// * data is valid for reads and writes as memory size is not enlarged
// * lifetime is not changed
// * validity for arbitrary data as required by Texel constructor
// * alignment checked by Texel constructor
// * the size fits in an allocation, see first bullet point.
unsafe {
slice::from_raw_parts_mut(
buffer.as_mut_ptr() as *mut P,
buffer.len() / self.size_nz().get(),
)
}
}
pub(crate) fn cast_bytes<'buf>(self, texel: &'buf [P]) -> &'buf [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity for byte reading checked by Texel constructor
unsafe { slice::from_raw_parts(texel.as_ptr() as *const u8, mem::size_of_val(texel)) }
}
pub(crate) fn cast_mut_bytes<'buf>(self, texel: &'buf mut [P]) -> &'buf mut [u8] {
// Safety:
// * lifetime is not changed
// * keeps the exact same size
// * validity as bytes checked by Texel constructor
unsafe { slice::from_raw_parts_mut(texel.as_mut_ptr() as *mut u8, mem::size_of_val(texel)) }
}
}
/// This is a pure marker type.
impl<P> Clone for Texel<P> {
fn clone(&self) -> Self {
Texel(PhantomData)
}
}
impl<P> PartialEq for Texel<P> {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl<P> Eq for Texel<P> {}
impl<P> PartialOrd for Texel<P> {
fn partial_cmp(&self, _: &Self) -> Option<Ordering> {
Some(Ordering::Equal)
}
}
impl<P> Ord for Texel<P> {
fn cmp(&self, _: &Self) -> Ordering {
Ordering::Equal
}
}
/// This is a pure marker type.
impl<P> Copy for Texel<P> {}
impl<P> fmt::Debug for Texel<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Texel")
.field("size", &self.size())
.field("align", &self.align())
| random_line_split |
|
lib.rs | #![warn(
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::map_unwrap_or,
clippy::unseparated_literal_suffix,
clippy::cargo,
clippy::unwrap_used
)]
#![allow(clippy::upper_case_acronyms)]
use jsonschema::{paths::JSONPointer, Draft};
use pyo3::{
exceptions::{self, PyValueError},
prelude::*,
types::{PyAny, PyList, PyType},
wrap_pyfunction, AsPyPointer, PyIterProtocol, PyObjectProtocol,
};
mod ser;
mod string;
mod types;
const DRAFT7: u8 = 7;
const DRAFT6: u8 = 6;
const DRAFT4: u8 = 4;
/// An instance is invalid under a provided schema.
#[pyclass(extends=exceptions::PyValueError, module="jsonschema_rs")]
#[derive(Debug)]
struct ValidationError {
#[pyo3(get)]
message: String,
verbose_message: String,
#[pyo3(get)]
schema_path: Py<PyList>,
#[pyo3(get)]
instance_path: Py<PyList>,
}
#[pymethods]
impl ValidationError {
#[new]
fn new(
message: String,
long_message: String,
schema_path: Py<PyList>,
instance_path: Py<PyList>,
) -> Self {
ValidationError {
message,
verbose_message: long_message,
schema_path,
instance_path,
}
}
}
#[pyproto]
impl<'p> PyObjectProtocol<'p> for ValidationError {
fn __str__(&'p self) -> PyResult<String> {
Ok(self.verbose_message.clone())
}
fn __repr__(&'p self) -> PyResult<String> {
Ok(format!("<ValidationError: '{}'>", self.message))
}
}
#[pyclass]
struct ValidationErrorIter {
iter: Box<dyn Iterator<Item = PyErr> + Send>,
}
#[pyproto]
impl PyIterProtocol for ValidationErrorIter {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyErr> {
slf.iter.next()
}
}
fn into_py_err(py: Python, error: jsonschema::ValidationError) -> PyResult<PyErr> {
let pyerror_type = PyType::new::<ValidationError>(py);
let message = error.to_string();
let verbose_message = to_error_message(&error);
let schema_path = into_path(py, error.schema_path)?;
let instance_path = into_path(py, error.instance_path)?;
Ok(PyErr::from_type(
pyerror_type,
(message, verbose_message, schema_path, instance_path),
))
}
fn into_path(py: Python, pointer: JSONPointer) -> PyResult<Py<PyList>> {
let path = PyList::empty(py);
for chunk in pointer {
match chunk {
jsonschema::paths::PathChunk::Property(property) => {
path.append(property.into_string())?
}
jsonschema::paths::PathChunk::Index(index) => path.append(index)?,
jsonschema::paths::PathChunk::Keyword(keyword) => path.append(keyword)?,
};
}
Ok(path.into_py(py))
}
fn get_draft(draft: u8) -> PyResult<Draft> {
match draft {
DRAFT4 => Ok(jsonschema::Draft::Draft4),
DRAFT6 => Ok(jsonschema::Draft::Draft6),
DRAFT7 => Ok(jsonschema::Draft::Draft7),
_ => Err(exceptions::PyValueError::new_err(format!(
"Unknown draft: {}",
draft
))),
}
}
fn make_options(
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<jsonschema::CompilationOptions> {
let mut options = jsonschema::JSONSchema::options();
if let Some(raw_draft_version) = draft {
options.with_draft(get_draft(raw_draft_version)?);
}
if let Some(true) = with_meta_schemas {
options.with_meta_schemas();
}
Ok(options)
}
fn iter_on_error(
py: Python,
compiled: &jsonschema::JSONSchema,
instance: &PyAny,
) -> PyResult<ValidationErrorIter> {
let instance = ser::to_value(instance)?;
let mut pyerrors = vec![];
if let Err(errors) = compiled.validate(&instance) {
for error in errors {
pyerrors.push(into_py_err(py, error)?);
}
};
Ok(ValidationErrorIter {
iter: Box::new(pyerrors.into_iter()),
})
}
fn raise_on_error(py: Python, compiled: &jsonschema::JSONSchema, instance: &PyAny) -> PyResult<()> {
let instance = ser::to_value(instance)?;
let result = compiled.validate(&instance);
let error = result
.err()
.map(|mut errors| errors.next().expect("Iterator should not be empty"));
error.map_or_else(|| Ok(()), |err| Err(into_py_err(py, err)?))
}
fn to_error_message(error: &jsonschema::ValidationError) -> String {
let mut message = error.to_string();
message.push('\n');
message.push('\n');
message.push_str("Failed validating");
let push_quoted = |m: &mut String, s: &str| {
m.push('"');
m.push_str(s);
m.push('"');
};
let push_chunk = |m: &mut String, chunk: &jsonschema::paths::PathChunk| {
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(m, property),
jsonschema::paths::PathChunk::Index(index) => m.push_str(&index.to_string()),
jsonschema::paths::PathChunk::Keyword(keyword) => push_quoted(m, keyword),
};
};
if let Some(last) = error.schema_path.last() {
message.push(' ');
push_chunk(&mut message, last)
}
message.push_str(" in schema");
let mut chunks = error.schema_path.iter().peekable();
while let Some(chunk) = chunks.next() {
// Skip the last element as it is already mentioned in the message
if chunks.peek().is_none() {
break;
}
message.push('[');
push_chunk(&mut message, chunk);
message.push(']');
}
message.push('\n');
message.push('\n');
message.push_str("On instance");
for chunk in &error.instance_path {
message.push('[');
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(&mut message, property),
jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()),
// Keywords are not used for instances
jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"),
};
message.push(']');
}
message.push(':');
message.push_str("\n ");
message.push_str(&error.instance.to_string());
message
}
/// is_valid(schema, instance, draft=None, with_meta_schemas=False)
///
/// A shortcut for validating the input instance against the schema.
///
/// >>> is_valid({"minimum": 5}, 3)
/// False
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.is_valid`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn is_valid(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<bool> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => {
let instance = ser::to_value(instance)?;
Ok(compiled.is_valid(&instance))
}
Err(error) => Err(into_py_err(py, error)?),
}
}
/// validate(schema, instance, draft=None, with_meta_schemas=False)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> validate({"minimum": 5}, 3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
/// If your workflow implies validating against the same schema, consider using `JSONSchema.validate`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn validate(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<()> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => raise_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// iter_errors(schema, instance, draft=None, with_meta_schemas=False)
///
/// Iterate the validation errors of the input instance
///
/// >>> next(iter_errors({"minimum": 5}, 3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.iter_errors`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn iter_errors(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<ValidationErrorIter> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => iter_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// JSONSchema(schema, draft=None, with_meta_schemas=False)
///
/// JSON Schema compiled into a validation tree.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// By default Draft 7 will be used for compilation.
#[pyclass(module = "jsonschema_rs")]
#[pyo3(text_signature = "(schema, draft=None, with_meta_schemas=False)")]
struct JSONSchema {
schema: jsonschema::JSONSchema,
repr: String,
}
fn get_schema_repr(schema: &serde_json::Value) -> String {
// It could be more efficient, without converting the whole Value to a string
let mut repr = schema.to_string();
if repr.len() > SCHEMA_LENGTH_LIMIT {
repr.truncate(SCHEMA_LENGTH_LIMIT);
repr.push_str("...}");
}
repr
}
#[pymethods]
impl JSONSchema {
#[new]
fn new(
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let options = make_options(draft, with_meta_schemas)?;
let raw_schema = ser::to_value(pyschema)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// from_str(string, draft=None, with_meta_schemas=False)
///
/// Create `JSONSchema` from a serialized JSON string.
///
/// >>> compiled = JSONSchema.from_str('{"minimum": 5}')
///
/// Use it if you have your schema as a string and want to utilize Rust JSON parsing.
#[classmethod]
#[pyo3(text_signature = "(string, draft=None, with_meta_schemas=False)")]
fn | (
_: &PyType,
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let obj_ptr = pyschema.as_ptr();
let object_type = unsafe { pyo3::ffi::Py_TYPE(obj_ptr) };
if unsafe { object_type!= types::STR_TYPE } {
let type_name =
unsafe { std::ffi::CStr::from_ptr((*object_type).tp_name).to_string_lossy() };
Err(PyValueError::new_err(format!(
"Expected string, got {}",
type_name
)))
} else {
let mut str_size: pyo3::ffi::Py_ssize_t = 0;
let uni = unsafe { string::read_utf8_from_str(obj_ptr, &mut str_size) };
let slice = unsafe { std::slice::from_raw_parts(uni, str_size as usize) };
let raw_schema = serde_json::from_slice(slice)
.map_err(|error| PyValueError::new_err(format!("Invalid string: {}", error)))?;
let options = make_options(draft, with_meta_schemas)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
}
/// is_valid(instance)
///
/// Perform fast validation against the compiled schema.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// The output is a boolean value, that indicates whether the instance is valid or not.
#[pyo3(text_signature = "(instance)")]
fn is_valid(&self, instance: &PyAny) -> PyResult<bool> {
let instance = ser::to_value(instance)?;
Ok(self.schema.is_valid(&instance))
}
/// validate(instance)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.validate(3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
#[pyo3(text_signature = "(instance)")]
fn validate(&self, py: Python, instance: &PyAny) -> PyResult<()> {
raise_on_error(py, &self.schema, instance)
}
/// iter_errors(instance)
///
/// Iterate the validation errors of the input instance
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> next(compiled.iter_errors(3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
#[pyo3(text_signature = "(instance)")]
fn iter_errors(&self, py: Python, instance: &PyAny) -> PyResult<ValidationErrorIter> {
iter_on_error(py, &self.schema, instance)
}
}
const SCHEMA_LENGTH_LIMIT: usize = 32;
#[pyproto]
impl<'p> PyObjectProtocol<'p> for JSONSchema {
fn __repr__(&self) -> PyResult<String> {
Ok(format!("<JSONSchema: {}>", self.repr))
}
}
#[allow(dead_code)]
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// JSON Schema validation for Python written in Rust.
#[pymodule]
fn jsonschema_rs(py: Python, module: &PyModule) -> PyResult<()> {
// To provide proper signatures for PyCharm, all the functions have their signatures as the
// first line in docstrings. The idea is taken from NumPy.
types::init();
module.add_wrapped(wrap_pyfunction!(is_valid))?;
module.add_wrapped(wrap_pyfunction!(validate))?;
module.add_wrapped(wrap_pyfunction!(iter_errors))?;
module.add_class::<JSONSchema>()?;
module.add("ValidationError", py.get_type::<ValidationError>())?;
module.add("Draft4", DRAFT4)?;
module.add("Draft6", DRAFT6)?;
module.add("Draft7", DRAFT7)?;
// Allow deprecated, unless `pyo3-built` is updated
#[allow(deprecated)]
// Add build metadata to ease triaging incoming issues
module.add("__build__", pyo3_built::pyo3_built!(py, build))?;
Ok(())
}
| from_str | identifier_name |
lib.rs | #![warn(
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::map_unwrap_or,
clippy::unseparated_literal_suffix,
clippy::cargo,
clippy::unwrap_used
)]
#![allow(clippy::upper_case_acronyms)]
use jsonschema::{paths::JSONPointer, Draft};
use pyo3::{
exceptions::{self, PyValueError},
prelude::*,
types::{PyAny, PyList, PyType},
wrap_pyfunction, AsPyPointer, PyIterProtocol, PyObjectProtocol,
};
mod ser;
mod string;
mod types;
const DRAFT7: u8 = 7;
const DRAFT6: u8 = 6;
const DRAFT4: u8 = 4;
/// An instance is invalid under a provided schema.
#[pyclass(extends=exceptions::PyValueError, module="jsonschema_rs")]
#[derive(Debug)]
struct ValidationError {
#[pyo3(get)]
message: String,
verbose_message: String,
#[pyo3(get)]
schema_path: Py<PyList>,
#[pyo3(get)]
instance_path: Py<PyList>,
}
#[pymethods]
impl ValidationError {
#[new]
fn new(
message: String,
long_message: String,
schema_path: Py<PyList>,
instance_path: Py<PyList>,
) -> Self {
ValidationError {
message,
verbose_message: long_message,
schema_path,
instance_path,
}
}
}
#[pyproto]
impl<'p> PyObjectProtocol<'p> for ValidationError {
fn __str__(&'p self) -> PyResult<String> {
Ok(self.verbose_message.clone())
}
fn __repr__(&'p self) -> PyResult<String> {
Ok(format!("<ValidationError: '{}'>", self.message))
}
}
#[pyclass]
struct ValidationErrorIter {
iter: Box<dyn Iterator<Item = PyErr> + Send>,
}
#[pyproto]
impl PyIterProtocol for ValidationErrorIter {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyErr> {
slf.iter.next()
}
}
fn into_py_err(py: Python, error: jsonschema::ValidationError) -> PyResult<PyErr> {
let pyerror_type = PyType::new::<ValidationError>(py);
let message = error.to_string();
let verbose_message = to_error_message(&error);
let schema_path = into_path(py, error.schema_path)?;
let instance_path = into_path(py, error.instance_path)?;
Ok(PyErr::from_type(
pyerror_type,
(message, verbose_message, schema_path, instance_path),
))
}
fn into_path(py: Python, pointer: JSONPointer) -> PyResult<Py<PyList>> {
let path = PyList::empty(py);
for chunk in pointer {
match chunk {
jsonschema::paths::PathChunk::Property(property) => {
path.append(property.into_string())?
}
jsonschema::paths::PathChunk::Index(index) => path.append(index)?,
jsonschema::paths::PathChunk::Keyword(keyword) => path.append(keyword)?,
};
}
Ok(path.into_py(py))
}
fn get_draft(draft: u8) -> PyResult<Draft> {
match draft {
DRAFT4 => Ok(jsonschema::Draft::Draft4),
DRAFT6 => Ok(jsonschema::Draft::Draft6),
DRAFT7 => Ok(jsonschema::Draft::Draft7),
_ => Err(exceptions::PyValueError::new_err(format!(
"Unknown draft: {}",
draft
))),
}
}
fn make_options(
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<jsonschema::CompilationOptions> {
let mut options = jsonschema::JSONSchema::options();
if let Some(raw_draft_version) = draft {
options.with_draft(get_draft(raw_draft_version)?);
}
if let Some(true) = with_meta_schemas {
options.with_meta_schemas();
}
Ok(options)
}
fn iter_on_error(
py: Python,
compiled: &jsonschema::JSONSchema,
instance: &PyAny,
) -> PyResult<ValidationErrorIter> {
let instance = ser::to_value(instance)?;
let mut pyerrors = vec![];
if let Err(errors) = compiled.validate(&instance) {
for error in errors {
pyerrors.push(into_py_err(py, error)?);
}
};
Ok(ValidationErrorIter {
iter: Box::new(pyerrors.into_iter()),
})
}
fn raise_on_error(py: Python, compiled: &jsonschema::JSONSchema, instance: &PyAny) -> PyResult<()> {
let instance = ser::to_value(instance)?;
let result = compiled.validate(&instance);
let error = result
.err()
.map(|mut errors| errors.next().expect("Iterator should not be empty"));
error.map_or_else(|| Ok(()), |err| Err(into_py_err(py, err)?))
}
fn to_error_message(error: &jsonschema::ValidationError) -> String {
let mut message = error.to_string();
message.push('\n');
message.push('\n');
message.push_str("Failed validating");
let push_quoted = |m: &mut String, s: &str| {
m.push('"');
m.push_str(s);
m.push('"');
};
let push_chunk = |m: &mut String, chunk: &jsonschema::paths::PathChunk| {
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(m, property),
jsonschema::paths::PathChunk::Index(index) => m.push_str(&index.to_string()),
jsonschema::paths::PathChunk::Keyword(keyword) => push_quoted(m, keyword),
};
};
if let Some(last) = error.schema_path.last() {
message.push(' ');
push_chunk(&mut message, last)
}
message.push_str(" in schema");
let mut chunks = error.schema_path.iter().peekable();
while let Some(chunk) = chunks.next() {
// Skip the last element as it is already mentioned in the message
if chunks.peek().is_none() {
break;
}
message.push('[');
push_chunk(&mut message, chunk);
message.push(']');
}
message.push('\n');
message.push('\n');
message.push_str("On instance");
for chunk in &error.instance_path {
message.push('[');
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(&mut message, property), | message.push(']');
}
message.push(':');
message.push_str("\n ");
message.push_str(&error.instance.to_string());
message
}
/// is_valid(schema, instance, draft=None, with_meta_schemas=False)
///
/// A shortcut for validating the input instance against the schema.
///
/// >>> is_valid({"minimum": 5}, 3)
/// False
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.is_valid`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn is_valid(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<bool> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => {
let instance = ser::to_value(instance)?;
Ok(compiled.is_valid(&instance))
}
Err(error) => Err(into_py_err(py, error)?),
}
}
/// validate(schema, instance, draft=None, with_meta_schemas=False)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> validate({"minimum": 5}, 3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
/// If your workflow implies validating against the same schema, consider using `JSONSchema.validate`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn validate(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<()> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => raise_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// iter_errors(schema, instance, draft=None, with_meta_schemas=False)
///
/// Iterate the validation errors of the input instance
///
/// >>> next(iter_errors({"minimum": 5}, 3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.iter_errors`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn iter_errors(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<ValidationErrorIter> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => iter_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// JSONSchema(schema, draft=None, with_meta_schemas=False)
///
/// JSON Schema compiled into a validation tree.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// By default Draft 7 will be used for compilation.
#[pyclass(module = "jsonschema_rs")]
#[pyo3(text_signature = "(schema, draft=None, with_meta_schemas=False)")]
struct JSONSchema {
schema: jsonschema::JSONSchema,
repr: String,
}
fn get_schema_repr(schema: &serde_json::Value) -> String {
// It could be more efficient, without converting the whole Value to a string
let mut repr = schema.to_string();
if repr.len() > SCHEMA_LENGTH_LIMIT {
repr.truncate(SCHEMA_LENGTH_LIMIT);
repr.push_str("...}");
}
repr
}
#[pymethods]
impl JSONSchema {
#[new]
fn new(
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let options = make_options(draft, with_meta_schemas)?;
let raw_schema = ser::to_value(pyschema)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// from_str(string, draft=None, with_meta_schemas=False)
///
/// Create `JSONSchema` from a serialized JSON string.
///
/// >>> compiled = JSONSchema.from_str('{"minimum": 5}')
///
/// Use it if you have your schema as a string and want to utilize Rust JSON parsing.
#[classmethod]
#[pyo3(text_signature = "(string, draft=None, with_meta_schemas=False)")]
fn from_str(
_: &PyType,
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let obj_ptr = pyschema.as_ptr();
let object_type = unsafe { pyo3::ffi::Py_TYPE(obj_ptr) };
if unsafe { object_type!= types::STR_TYPE } {
let type_name =
unsafe { std::ffi::CStr::from_ptr((*object_type).tp_name).to_string_lossy() };
Err(PyValueError::new_err(format!(
"Expected string, got {}",
type_name
)))
} else {
let mut str_size: pyo3::ffi::Py_ssize_t = 0;
let uni = unsafe { string::read_utf8_from_str(obj_ptr, &mut str_size) };
let slice = unsafe { std::slice::from_raw_parts(uni, str_size as usize) };
let raw_schema = serde_json::from_slice(slice)
.map_err(|error| PyValueError::new_err(format!("Invalid string: {}", error)))?;
let options = make_options(draft, with_meta_schemas)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
}
/// is_valid(instance)
///
/// Perform fast validation against the compiled schema.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// The output is a boolean value, that indicates whether the instance is valid or not.
#[pyo3(text_signature = "(instance)")]
fn is_valid(&self, instance: &PyAny) -> PyResult<bool> {
let instance = ser::to_value(instance)?;
Ok(self.schema.is_valid(&instance))
}
/// validate(instance)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.validate(3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
#[pyo3(text_signature = "(instance)")]
fn validate(&self, py: Python, instance: &PyAny) -> PyResult<()> {
raise_on_error(py, &self.schema, instance)
}
/// iter_errors(instance)
///
/// Iterate the validation errors of the input instance
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> next(compiled.iter_errors(3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
#[pyo3(text_signature = "(instance)")]
fn iter_errors(&self, py: Python, instance: &PyAny) -> PyResult<ValidationErrorIter> {
iter_on_error(py, &self.schema, instance)
}
}
const SCHEMA_LENGTH_LIMIT: usize = 32;
#[pyproto]
impl<'p> PyObjectProtocol<'p> for JSONSchema {
fn __repr__(&self) -> PyResult<String> {
Ok(format!("<JSONSchema: {}>", self.repr))
}
}
#[allow(dead_code)]
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// JSON Schema validation for Python written in Rust.
#[pymodule]
fn jsonschema_rs(py: Python, module: &PyModule) -> PyResult<()> {
// To provide proper signatures for PyCharm, all the functions have their signatures as the
// first line in docstrings. The idea is taken from NumPy.
types::init();
module.add_wrapped(wrap_pyfunction!(is_valid))?;
module.add_wrapped(wrap_pyfunction!(validate))?;
module.add_wrapped(wrap_pyfunction!(iter_errors))?;
module.add_class::<JSONSchema>()?;
module.add("ValidationError", py.get_type::<ValidationError>())?;
module.add("Draft4", DRAFT4)?;
module.add("Draft6", DRAFT6)?;
module.add("Draft7", DRAFT7)?;
// Allow deprecated, unless `pyo3-built` is updated
#[allow(deprecated)]
// Add build metadata to ease triaging incoming issues
module.add("__build__", pyo3_built::pyo3_built!(py, build))?;
Ok(())
} | jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()),
// Keywords are not used for instances
jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"),
}; | random_line_split |
lib.rs | #![warn(
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::map_unwrap_or,
clippy::unseparated_literal_suffix,
clippy::cargo,
clippy::unwrap_used
)]
#![allow(clippy::upper_case_acronyms)]
use jsonschema::{paths::JSONPointer, Draft};
use pyo3::{
exceptions::{self, PyValueError},
prelude::*,
types::{PyAny, PyList, PyType},
wrap_pyfunction, AsPyPointer, PyIterProtocol, PyObjectProtocol,
};
mod ser;
mod string;
mod types;
const DRAFT7: u8 = 7;
const DRAFT6: u8 = 6;
const DRAFT4: u8 = 4;
/// An instance is invalid under a provided schema.
#[pyclass(extends=exceptions::PyValueError, module="jsonschema_rs")]
#[derive(Debug)]
struct ValidationError {
#[pyo3(get)]
message: String,
verbose_message: String,
#[pyo3(get)]
schema_path: Py<PyList>,
#[pyo3(get)]
instance_path: Py<PyList>,
}
#[pymethods]
impl ValidationError {
#[new]
fn new(
message: String,
long_message: String,
schema_path: Py<PyList>,
instance_path: Py<PyList>,
) -> Self {
ValidationError {
message,
verbose_message: long_message,
schema_path,
instance_path,
}
}
}
#[pyproto]
impl<'p> PyObjectProtocol<'p> for ValidationError {
fn __str__(&'p self) -> PyResult<String> {
Ok(self.verbose_message.clone())
}
fn __repr__(&'p self) -> PyResult<String> {
Ok(format!("<ValidationError: '{}'>", self.message))
}
}
#[pyclass]
struct ValidationErrorIter {
iter: Box<dyn Iterator<Item = PyErr> + Send>,
}
#[pyproto]
impl PyIterProtocol for ValidationErrorIter {
fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
slf
}
fn __next__(mut slf: PyRefMut<Self>) -> Option<PyErr> {
slf.iter.next()
}
}
fn into_py_err(py: Python, error: jsonschema::ValidationError) -> PyResult<PyErr> {
let pyerror_type = PyType::new::<ValidationError>(py);
let message = error.to_string();
let verbose_message = to_error_message(&error);
let schema_path = into_path(py, error.schema_path)?;
let instance_path = into_path(py, error.instance_path)?;
Ok(PyErr::from_type(
pyerror_type,
(message, verbose_message, schema_path, instance_path),
))
}
fn into_path(py: Python, pointer: JSONPointer) -> PyResult<Py<PyList>> {
let path = PyList::empty(py);
for chunk in pointer {
match chunk {
jsonschema::paths::PathChunk::Property(property) => {
path.append(property.into_string())?
}
jsonschema::paths::PathChunk::Index(index) => path.append(index)?,
jsonschema::paths::PathChunk::Keyword(keyword) => path.append(keyword)?,
};
}
Ok(path.into_py(py))
}
fn get_draft(draft: u8) -> PyResult<Draft> {
match draft {
DRAFT4 => Ok(jsonschema::Draft::Draft4),
DRAFT6 => Ok(jsonschema::Draft::Draft6),
DRAFT7 => Ok(jsonschema::Draft::Draft7),
_ => Err(exceptions::PyValueError::new_err(format!(
"Unknown draft: {}",
draft
))),
}
}
fn make_options(
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<jsonschema::CompilationOptions> {
let mut options = jsonschema::JSONSchema::options();
if let Some(raw_draft_version) = draft {
options.with_draft(get_draft(raw_draft_version)?);
}
if let Some(true) = with_meta_schemas {
options.with_meta_schemas();
}
Ok(options)
}
fn iter_on_error(
py: Python,
compiled: &jsonschema::JSONSchema,
instance: &PyAny,
) -> PyResult<ValidationErrorIter> {
let instance = ser::to_value(instance)?;
let mut pyerrors = vec![];
if let Err(errors) = compiled.validate(&instance) {
for error in errors {
pyerrors.push(into_py_err(py, error)?);
}
};
Ok(ValidationErrorIter {
iter: Box::new(pyerrors.into_iter()),
})
}
fn raise_on_error(py: Python, compiled: &jsonschema::JSONSchema, instance: &PyAny) -> PyResult<()> {
let instance = ser::to_value(instance)?;
let result = compiled.validate(&instance);
let error = result
.err()
.map(|mut errors| errors.next().expect("Iterator should not be empty"));
error.map_or_else(|| Ok(()), |err| Err(into_py_err(py, err)?))
}
fn to_error_message(error: &jsonschema::ValidationError) -> String {
let mut message = error.to_string();
message.push('\n');
message.push('\n');
message.push_str("Failed validating");
let push_quoted = |m: &mut String, s: &str| {
m.push('"');
m.push_str(s);
m.push('"');
};
let push_chunk = |m: &mut String, chunk: &jsonschema::paths::PathChunk| {
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(m, property),
jsonschema::paths::PathChunk::Index(index) => m.push_str(&index.to_string()),
jsonschema::paths::PathChunk::Keyword(keyword) => push_quoted(m, keyword),
};
};
if let Some(last) = error.schema_path.last() {
message.push(' ');
push_chunk(&mut message, last)
}
message.push_str(" in schema");
let mut chunks = error.schema_path.iter().peekable();
while let Some(chunk) = chunks.next() {
// Skip the last element as it is already mentioned in the message
if chunks.peek().is_none() {
break;
}
message.push('[');
push_chunk(&mut message, chunk);
message.push(']');
}
message.push('\n');
message.push('\n');
message.push_str("On instance");
for chunk in &error.instance_path {
message.push('[');
match chunk {
jsonschema::paths::PathChunk::Property(property) => push_quoted(&mut message, property),
jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()),
// Keywords are not used for instances
jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"),
};
message.push(']');
}
message.push(':');
message.push_str("\n ");
message.push_str(&error.instance.to_string());
message
}
/// is_valid(schema, instance, draft=None, with_meta_schemas=False)
///
/// A shortcut for validating the input instance against the schema.
///
/// >>> is_valid({"minimum": 5}, 3)
/// False
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.is_valid`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn is_valid(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<bool> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => {
let instance = ser::to_value(instance)?;
Ok(compiled.is_valid(&instance))
}
Err(error) => Err(into_py_err(py, error)?),
}
}
/// validate(schema, instance, draft=None, with_meta_schemas=False)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> validate({"minimum": 5}, 3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
/// If your workflow implies validating against the same schema, consider using `JSONSchema.validate`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn validate(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<()> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => raise_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// iter_errors(schema, instance, draft=None, with_meta_schemas=False)
///
/// Iterate the validation errors of the input instance
///
/// >>> next(iter_errors({"minimum": 5}, 3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If your workflow implies validating against the same schema, consider using `JSONSchema.iter_errors`
/// instead.
#[pyfunction]
#[pyo3(text_signature = "(schema, instance, draft=None, with_meta_schemas=False)")]
fn iter_errors(
py: Python,
schema: &PyAny,
instance: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<ValidationErrorIter> {
let options = make_options(draft, with_meta_schemas)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => iter_on_error(py, &compiled, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// JSONSchema(schema, draft=None, with_meta_schemas=False)
///
/// JSON Schema compiled into a validation tree.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// By default Draft 7 will be used for compilation.
#[pyclass(module = "jsonschema_rs")]
#[pyo3(text_signature = "(schema, draft=None, with_meta_schemas=False)")]
struct JSONSchema {
schema: jsonschema::JSONSchema,
repr: String,
}
fn get_schema_repr(schema: &serde_json::Value) -> String {
// It could be more efficient, without converting the whole Value to a string
let mut repr = schema.to_string();
if repr.len() > SCHEMA_LENGTH_LIMIT {
repr.truncate(SCHEMA_LENGTH_LIMIT);
repr.push_str("...}");
}
repr
}
#[pymethods]
impl JSONSchema {
#[new]
fn new(
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let options = make_options(draft, with_meta_schemas)?;
let raw_schema = ser::to_value(pyschema)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
/// from_str(string, draft=None, with_meta_schemas=False)
///
/// Create `JSONSchema` from a serialized JSON string.
///
/// >>> compiled = JSONSchema.from_str('{"minimum": 5}')
///
/// Use it if you have your schema as a string and want to utilize Rust JSON parsing.
#[classmethod]
#[pyo3(text_signature = "(string, draft=None, with_meta_schemas=False)")]
fn from_str(
_: &PyType,
py: Python,
pyschema: &PyAny,
draft: Option<u8>,
with_meta_schemas: Option<bool>,
) -> PyResult<Self> {
let obj_ptr = pyschema.as_ptr();
let object_type = unsafe { pyo3::ffi::Py_TYPE(obj_ptr) };
if unsafe { object_type!= types::STR_TYPE } {
let type_name =
unsafe { std::ffi::CStr::from_ptr((*object_type).tp_name).to_string_lossy() };
Err(PyValueError::new_err(format!(
"Expected string, got {}",
type_name
)))
} else {
let mut str_size: pyo3::ffi::Py_ssize_t = 0;
let uni = unsafe { string::read_utf8_from_str(obj_ptr, &mut str_size) };
let slice = unsafe { std::slice::from_raw_parts(uni, str_size as usize) };
let raw_schema = serde_json::from_slice(slice)
.map_err(|error| PyValueError::new_err(format!("Invalid string: {}", error)))?;
let options = make_options(draft, with_meta_schemas)?;
match options.compile(&raw_schema) {
Ok(schema) => Ok(JSONSchema {
schema,
repr: get_schema_repr(&raw_schema),
}),
Err(error) => Err(into_py_err(py, error)?),
}
}
}
/// is_valid(instance)
///
/// Perform fast validation against the compiled schema.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// False
///
/// The output is a boolean value, that indicates whether the instance is valid or not.
#[pyo3(text_signature = "(instance)")]
fn is_valid(&self, instance: &PyAny) -> PyResult<bool> {
let instance = ser::to_value(instance)?;
Ok(self.schema.is_valid(&instance))
}
/// validate(instance)
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.validate(3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
/// If the input instance is invalid, only the first occurred error is raised.
#[pyo3(text_signature = "(instance)")]
fn validate(&self, py: Python, instance: &PyAny) -> PyResult<()> {
raise_on_error(py, &self.schema, instance)
}
/// iter_errors(instance)
///
/// Iterate the validation errors of the input instance
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> next(compiled.iter_errors(3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
#[pyo3(text_signature = "(instance)")]
fn iter_errors(&self, py: Python, instance: &PyAny) -> PyResult<ValidationErrorIter> |
}
const SCHEMA_LENGTH_LIMIT: usize = 32;
#[pyproto]
impl<'p> PyObjectProtocol<'p> for JSONSchema {
fn __repr__(&self) -> PyResult<String> {
Ok(format!("<JSONSchema: {}>", self.repr))
}
}
#[allow(dead_code)]
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
/// JSON Schema validation for Python written in Rust.
#[pymodule]
fn jsonschema_rs(py: Python, module: &PyModule) -> PyResult<()> {
// To provide proper signatures for PyCharm, all the functions have their signatures as the
// first line in docstrings. The idea is taken from NumPy.
types::init();
module.add_wrapped(wrap_pyfunction!(is_valid))?;
module.add_wrapped(wrap_pyfunction!(validate))?;
module.add_wrapped(wrap_pyfunction!(iter_errors))?;
module.add_class::<JSONSchema>()?;
module.add("ValidationError", py.get_type::<ValidationError>())?;
module.add("Draft4", DRAFT4)?;
module.add("Draft6", DRAFT6)?;
module.add("Draft7", DRAFT7)?;
// Allow deprecated, unless `pyo3-built` is updated
#[allow(deprecated)]
// Add build metadata to ease triaging incoming issues
module.add("__build__", pyo3_built::pyo3_built!(py, build))?;
Ok(())
}
| {
iter_on_error(py, &self.schema, instance)
} | identifier_body |
form_input.rs | use super::error_message::get_error_message;
use crate::styles::{get_palette, get_size, Palette, Size};
use wasm_bindgen_test::*;
use yew::prelude::*;
use yew::{utils, App};
/// # Form Input
///
/// ## Features required
///
/// forms
///
/// ## Example
///
/// ```rust
/// use yew::prelude::*;
/// use yew_styles::forms::form_input::{FormInput, InputType};
/// use yew_styles::styles::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg; | /// type Properties = ();
/// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
/// FormInputExample {
/// link,
/// value: "".to_string(),
/// }
/// }
/// fn update(&mut self, msg: Self::Message) -> ShouldRender {
/// match msg {
/// Msg::Input(value) => {
/// self.value = value;
/// }
/// }
/// true
/// }
/// fn change(&mut self, _props: Self::Properties) -> ShouldRender {
/// false
/// }
///
/// fn view(&self) -> Html {
/// html!{
/// <FormInput
/// input_type=InputType::Text
/// input_palette=Palette::Standard
/// input_size=Size::Medium
/// id="form-input-example"
/// oninput_signal = form_page.link.callback(|e: InputData| Msg::Input(e.value))
/// placeholder="example"
/// underline=false
/// />
/// }
/// }
/// ```
pub struct FormInput {
link: ComponentLink<Self>,
props: Props,
}
/// Different type inputs supported. You can find more information [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
#[derive(Clone, PartialEq)]
pub enum InputType {
Button,
Checkbox,
Color,
Date,
Datetime,
DatetimeLocal,
Email,
Hidden,
Image,
Month,
Number,
Password,
Radio,
Range,
Reset,
Search,
Tel,
Text,
Time,
Url,
Week,
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
/// The input type. Default `InputType::Text`
#[prop_or(InputType::Text)]
pub input_type: InputType,
/// The input style according with the purpose. Default `Palette::Standard`
#[prop_or(Palette::Standard)]
pub input_palette: Palette,
/// The size of the input. Default `Size::Medium`
#[prop_or(Size::Medium)]
pub input_size: Size,
/// Signal to emit the event input
#[prop_or(Callback::noop())]
pub oninput_signal: Callback<InputData>,
/// Signal to emit the event blur
#[prop_or(Callback::noop())]
pub onblur_signal: Callback<FocusEvent>,
/// Signal to emit the event keypress
#[prop_or(Callback::noop())]
pub onkeydown_signal: Callback<KeyboardEvent>,
/// Content to be appear in the form control when the form control is empty
#[prop_or_default]
pub placeholder: String,
/// Whether the command or control is checked
#[prop_or_default]
pub checked: bool,
/// General property to get the ref of the component
#[prop_or_default]
pub code_ref: NodeRef,
/// General property to add keys
#[prop_or_default]
pub key: String,
/// General property to add custom class styles
#[prop_or_default]
pub class_name: String,
/// General property to add custom id
#[prop_or_default]
pub id: String,
/// The name of the input
#[prop_or_default]
pub name: String,
/// Alt attribute for the image type
#[prop_or_default]
pub alt: String,
/// Automatically focus the form control when the page is loaded. Default `false`
#[prop_or(false)]
pub autofocus: bool,
/// Hint for form autofill feature.. Default `false`
#[prop_or(false)]
pub autocomplete: bool,
/// Value of the id attribute of the "datalist" of autocomplete options
#[prop_or_default]
pub list: String,
/// Minimum value
#[prop_or_default]
pub min: u16,
/// Maximum value
#[prop_or_default]
pub max: u16,
/// Minimum length (number of characters) of value
#[prop_or_default]
pub minlength: u16,
/// Maximum length (number of characters) of value. Default `1000`
#[prop_or(1000)]
pub maxlength: u16,
/// Pattern the value must match to be valid. Default `"[\\s\\S]*".to_string()`
#[prop_or("[\\s\\S]*".to_string())]
pub pattern: String,
/// The value is not editable. Default `false`
#[prop_or(false)]
pub readonly: bool,
/// A value is required or must be check for the form to be submittable. Default `false`
#[prop_or(false)]
pub required: bool,
/// Whether the form control is disabled. Default `false`
#[prop_or(false)]
pub disabled: bool,
/// Underline style instead of box, like Material. Default `false`
#[prop_or(false)]
pub underline: bool,
/// Incremental values that are valid
#[prop_or_default]
pub step: i16,
/// Error state for validation. Default `false`
#[prop_or(false)]
pub error_state: bool,
/// Show error message when error_state is true
#[prop_or_default]
pub error_message: String,
}
#[derive(Debug)]
pub enum Msg {
Input(InputData),
Blur(FocusEvent),
KeyPressed(KeyboardEvent),
}
impl Component for FormInput {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { link, props }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Input(input_data) => {
self.props.oninput_signal.emit(input_data);
}
Msg::Blur(focus_event) => {
self.props.onblur_signal.emit(focus_event);
}
Msg::KeyPressed(keyboard_event) => {
self.props.onkeydown_signal.emit(keyboard_event);
}
};
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props!= props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
html! {
<>
<input
id=self.props.id.clone()
class=classes!(
"form-input",
get_palette(self.props.input_palette.clone()),
get_size(self.props.input_size.clone()),
if self.props.underline { "underline" } else { "" },
self.props.class_name.clone(),
)
key=self.props.key.clone()
ref=self.props.code_ref.clone()
type=get_type(self.props.input_type.clone())
oninput=self.link.callback(Msg::Input)
checked=self.props.checked
onblur=self.link.callback(Msg::Blur)
onkeydown=self.link.callback(Msg::KeyPressed)
name=self.props.name.clone()
required=self.props.required
readonly=self.props.readonly
disabled=self.props.disabled
placeholder=self.props.placeholder.clone()
pattern=self.props.pattern.clone()
min=self.props.min.to_string()
minlength=self.props.minlength.to_string()
max=self.props.max.to_string()
maxlength=self.props.maxlength.to_string()
alt=self.props.alt.clone()
autofocus=self.props.autofocus
autocomplete=self.props.autocomplete.to_string()
step=self.props.step.to_string()
list=self.props.list.clone()
/>
{get_error_message(self.props.error_state, self.props.error_message.clone())}
</>
}
}
}
fn get_type(input_type: InputType) -> String {
match input_type {
InputType::Button => "button".to_string(),
InputType::Checkbox => "checkbox".to_string(),
InputType::Color => "color".to_string(),
InputType::Date => "date".to_string(),
InputType::Datetime => "datetime".to_string(),
InputType::DatetimeLocal => "datetime-local".to_string(),
InputType::Email => "email".to_string(),
InputType::Hidden => "hidden".to_string(),
InputType::Image => "image".to_string(),
InputType::Month => "month".to_string(),
InputType::Number => "number".to_string(),
InputType::Password => "password".to_string(),
InputType::Radio => "radio".to_string(),
InputType::Range => "range".to_string(),
InputType::Reset => "reset".to_string(),
InputType::Search => "search".to_string(),
InputType::Tel => "tel".to_string(),
InputType::Text => "text".to_string(),
InputType::Time => "time".to_string(),
InputType::Url => "url".to_string(),
InputType::Week => "week".to_string(),
}
}
#[wasm_bindgen_test]
fn should_create_form_input() {
let props = Props {
key: "".to_string(),
code_ref: NodeRef::default(),
id: "form-input-id-test".to_string(),
class_name: "form-input-class-test".to_string(),
input_type: InputType::Text,
oninput_signal: Callback::noop(),
onblur_signal: Callback::noop(),
onkeydown_signal: Callback::noop(),
checked: false,
error_message: "invalid input".to_string(),
error_state: false,
name: "input-test".to_string(),
input_palette: Palette::Standard,
input_size: Size::Medium,
placeholder: "test input".to_string(),
required: false,
autocomplete: false,
autofocus: false,
alt: "input test".to_string(),
pattern: "".to_string(),
min: 0,
max: 0,
maxlength: 100,
minlength: 0,
readonly: false,
underline: false,
disabled: false,
step: 1,
list: "".to_string(),
};
let form_input: App<FormInput> = App::new();
form_input.mount_with_props(
utils::document().get_element_by_id("output").unwrap(),
props,
);
let form_input_element = utils::document()
.get_element_by_id("form-input-id-test")
.unwrap();
assert_eq!(form_input_element.tag_name(), "INPUT");
} | random_line_split |
|
form_input.rs | use super::error_message::get_error_message;
use crate::styles::{get_palette, get_size, Palette, Size};
use wasm_bindgen_test::*;
use yew::prelude::*;
use yew::{utils, App};
/// # Form Input
///
/// ## Features required
///
/// forms
///
/// ## Example
///
/// ```rust
/// use yew::prelude::*;
/// use yew_styles::forms::form_input::{FormInput, InputType};
/// use yew_styles::styles::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg;
/// type Properties = ();
/// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
/// FormInputExample {
/// link,
/// value: "".to_string(),
/// }
/// }
/// fn update(&mut self, msg: Self::Message) -> ShouldRender {
/// match msg {
/// Msg::Input(value) => {
/// self.value = value;
/// }
/// }
/// true
/// }
/// fn change(&mut self, _props: Self::Properties) -> ShouldRender {
/// false
/// }
///
/// fn view(&self) -> Html {
/// html!{
/// <FormInput
/// input_type=InputType::Text
/// input_palette=Palette::Standard
/// input_size=Size::Medium
/// id="form-input-example"
/// oninput_signal = form_page.link.callback(|e: InputData| Msg::Input(e.value))
/// placeholder="example"
/// underline=false
/// />
/// }
/// }
/// ```
pub struct FormInput {
link: ComponentLink<Self>,
props: Props,
}
/// Different type inputs supported. You can find more information [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
#[derive(Clone, PartialEq)]
pub enum InputType {
Button,
Checkbox,
Color,
Date,
Datetime,
DatetimeLocal,
Email,
Hidden,
Image,
Month,
Number,
Password,
Radio,
Range,
Reset,
Search,
Tel,
Text,
Time,
Url,
Week,
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
/// The input type. Default `InputType::Text`
#[prop_or(InputType::Text)]
pub input_type: InputType,
/// The input style according with the purpose. Default `Palette::Standard`
#[prop_or(Palette::Standard)]
pub input_palette: Palette,
/// The size of the input. Default `Size::Medium`
#[prop_or(Size::Medium)]
pub input_size: Size,
/// Signal to emit the event input
#[prop_or(Callback::noop())]
pub oninput_signal: Callback<InputData>,
/// Signal to emit the event blur
#[prop_or(Callback::noop())]
pub onblur_signal: Callback<FocusEvent>,
/// Signal to emit the event keypress
#[prop_or(Callback::noop())]
pub onkeydown_signal: Callback<KeyboardEvent>,
/// Content to be appear in the form control when the form control is empty
#[prop_or_default]
pub placeholder: String,
/// Whether the command or control is checked
#[prop_or_default]
pub checked: bool,
/// General property to get the ref of the component
#[prop_or_default]
pub code_ref: NodeRef,
/// General property to add keys
#[prop_or_default]
pub key: String,
/// General property to add custom class styles
#[prop_or_default]
pub class_name: String,
/// General property to add custom id
#[prop_or_default]
pub id: String,
/// The name of the input
#[prop_or_default]
pub name: String,
/// Alt attribute for the image type
#[prop_or_default]
pub alt: String,
/// Automatically focus the form control when the page is loaded. Default `false`
#[prop_or(false)]
pub autofocus: bool,
/// Hint for form autofill feature.. Default `false`
#[prop_or(false)]
pub autocomplete: bool,
/// Value of the id attribute of the "datalist" of autocomplete options
#[prop_or_default]
pub list: String,
/// Minimum value
#[prop_or_default]
pub min: u16,
/// Maximum value
#[prop_or_default]
pub max: u16,
/// Minimum length (number of characters) of value
#[prop_or_default]
pub minlength: u16,
/// Maximum length (number of characters) of value. Default `1000`
#[prop_or(1000)]
pub maxlength: u16,
/// Pattern the value must match to be valid. Default `"[\\s\\S]*".to_string()`
#[prop_or("[\\s\\S]*".to_string())]
pub pattern: String,
/// The value is not editable. Default `false`
#[prop_or(false)]
pub readonly: bool,
/// A value is required or must be check for the form to be submittable. Default `false`
#[prop_or(false)]
pub required: bool,
/// Whether the form control is disabled. Default `false`
#[prop_or(false)]
pub disabled: bool,
/// Underline style instead of box, like Material. Default `false`
#[prop_or(false)]
pub underline: bool,
/// Incremental values that are valid
#[prop_or_default]
pub step: i16,
/// Error state for validation. Default `false`
#[prop_or(false)]
pub error_state: bool,
/// Show error message when error_state is true
#[prop_or_default]
pub error_message: String,
}
#[derive(Debug)]
pub enum Msg {
Input(InputData),
Blur(FocusEvent),
KeyPressed(KeyboardEvent),
}
impl Component for FormInput {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { link, props }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Input(input_data) => {
self.props.oninput_signal.emit(input_data);
}
Msg::Blur(focus_event) => {
self.props.onblur_signal.emit(focus_event);
}
Msg::KeyPressed(keyboard_event) => {
self.props.onkeydown_signal.emit(keyboard_event);
}
};
true
}
fn | (&mut self, props: Self::Properties) -> ShouldRender {
if self.props!= props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
html! {
<>
<input
id=self.props.id.clone()
class=classes!(
"form-input",
get_palette(self.props.input_palette.clone()),
get_size(self.props.input_size.clone()),
if self.props.underline { "underline" } else { "" },
self.props.class_name.clone(),
)
key=self.props.key.clone()
ref=self.props.code_ref.clone()
type=get_type(self.props.input_type.clone())
oninput=self.link.callback(Msg::Input)
checked=self.props.checked
onblur=self.link.callback(Msg::Blur)
onkeydown=self.link.callback(Msg::KeyPressed)
name=self.props.name.clone()
required=self.props.required
readonly=self.props.readonly
disabled=self.props.disabled
placeholder=self.props.placeholder.clone()
pattern=self.props.pattern.clone()
min=self.props.min.to_string()
minlength=self.props.minlength.to_string()
max=self.props.max.to_string()
maxlength=self.props.maxlength.to_string()
alt=self.props.alt.clone()
autofocus=self.props.autofocus
autocomplete=self.props.autocomplete.to_string()
step=self.props.step.to_string()
list=self.props.list.clone()
/>
{get_error_message(self.props.error_state, self.props.error_message.clone())}
</>
}
}
}
fn get_type(input_type: InputType) -> String {
match input_type {
InputType::Button => "button".to_string(),
InputType::Checkbox => "checkbox".to_string(),
InputType::Color => "color".to_string(),
InputType::Date => "date".to_string(),
InputType::Datetime => "datetime".to_string(),
InputType::DatetimeLocal => "datetime-local".to_string(),
InputType::Email => "email".to_string(),
InputType::Hidden => "hidden".to_string(),
InputType::Image => "image".to_string(),
InputType::Month => "month".to_string(),
InputType::Number => "number".to_string(),
InputType::Password => "password".to_string(),
InputType::Radio => "radio".to_string(),
InputType::Range => "range".to_string(),
InputType::Reset => "reset".to_string(),
InputType::Search => "search".to_string(),
InputType::Tel => "tel".to_string(),
InputType::Text => "text".to_string(),
InputType::Time => "time".to_string(),
InputType::Url => "url".to_string(),
InputType::Week => "week".to_string(),
}
}
#[wasm_bindgen_test]
fn should_create_form_input() {
let props = Props {
key: "".to_string(),
code_ref: NodeRef::default(),
id: "form-input-id-test".to_string(),
class_name: "form-input-class-test".to_string(),
input_type: InputType::Text,
oninput_signal: Callback::noop(),
onblur_signal: Callback::noop(),
onkeydown_signal: Callback::noop(),
checked: false,
error_message: "invalid input".to_string(),
error_state: false,
name: "input-test".to_string(),
input_palette: Palette::Standard,
input_size: Size::Medium,
placeholder: "test input".to_string(),
required: false,
autocomplete: false,
autofocus: false,
alt: "input test".to_string(),
pattern: "".to_string(),
min: 0,
max: 0,
maxlength: 100,
minlength: 0,
readonly: false,
underline: false,
disabled: false,
step: 1,
list: "".to_string(),
};
let form_input: App<FormInput> = App::new();
form_input.mount_with_props(
utils::document().get_element_by_id("output").unwrap(),
props,
);
let form_input_element = utils::document()
.get_element_by_id("form-input-id-test")
.unwrap();
assert_eq!(form_input_element.tag_name(), "INPUT");
}
| change | identifier_name |
form_input.rs | use super::error_message::get_error_message;
use crate::styles::{get_palette, get_size, Palette, Size};
use wasm_bindgen_test::*;
use yew::prelude::*;
use yew::{utils, App};
/// # Form Input
///
/// ## Features required
///
/// forms
///
/// ## Example
///
/// ```rust
/// use yew::prelude::*;
/// use yew_styles::forms::form_input::{FormInput, InputType};
/// use yew_styles::styles::{Palette, Size};
///
/// pub struct FormInputExample {
/// pub link: ComponentLink<Self>,
/// pub value: String,
/// }
///
/// pub enum Msg {
/// Input(String),
/// }
///
/// impl Component for FormInputExample {
/// type Message = Msg;
/// type Properties = ();
/// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
/// FormInputExample {
/// link,
/// value: "".to_string(),
/// }
/// }
/// fn update(&mut self, msg: Self::Message) -> ShouldRender {
/// match msg {
/// Msg::Input(value) => {
/// self.value = value;
/// }
/// }
/// true
/// }
/// fn change(&mut self, _props: Self::Properties) -> ShouldRender {
/// false
/// }
///
/// fn view(&self) -> Html {
/// html!{
/// <FormInput
/// input_type=InputType::Text
/// input_palette=Palette::Standard
/// input_size=Size::Medium
/// id="form-input-example"
/// oninput_signal = form_page.link.callback(|e: InputData| Msg::Input(e.value))
/// placeholder="example"
/// underline=false
/// />
/// }
/// }
/// ```
pub struct FormInput {
link: ComponentLink<Self>,
props: Props,
}
/// Different type inputs supported. You can find more information [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
#[derive(Clone, PartialEq)]
pub enum InputType {
Button,
Checkbox,
Color,
Date,
Datetime,
DatetimeLocal,
Email,
Hidden,
Image,
Month,
Number,
Password,
Radio,
Range,
Reset,
Search,
Tel,
Text,
Time,
Url,
Week,
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
/// The input type. Default `InputType::Text`
#[prop_or(InputType::Text)]
pub input_type: InputType,
/// The input style according with the purpose. Default `Palette::Standard`
#[prop_or(Palette::Standard)]
pub input_palette: Palette,
/// The size of the input. Default `Size::Medium`
#[prop_or(Size::Medium)]
pub input_size: Size,
/// Signal to emit the event input
#[prop_or(Callback::noop())]
pub oninput_signal: Callback<InputData>,
/// Signal to emit the event blur
#[prop_or(Callback::noop())]
pub onblur_signal: Callback<FocusEvent>,
/// Signal to emit the event keypress
#[prop_or(Callback::noop())]
pub onkeydown_signal: Callback<KeyboardEvent>,
/// Content to be appear in the form control when the form control is empty
#[prop_or_default]
pub placeholder: String,
/// Whether the command or control is checked
#[prop_or_default]
pub checked: bool,
/// General property to get the ref of the component
#[prop_or_default]
pub code_ref: NodeRef,
/// General property to add keys
#[prop_or_default]
pub key: String,
/// General property to add custom class styles
#[prop_or_default]
pub class_name: String,
/// General property to add custom id
#[prop_or_default]
pub id: String,
/// The name of the input
#[prop_or_default]
pub name: String,
/// Alt attribute for the image type
#[prop_or_default]
pub alt: String,
/// Automatically focus the form control when the page is loaded. Default `false`
#[prop_or(false)]
pub autofocus: bool,
/// Hint for form autofill feature.. Default `false`
#[prop_or(false)]
pub autocomplete: bool,
/// Value of the id attribute of the "datalist" of autocomplete options
#[prop_or_default]
pub list: String,
/// Minimum value
#[prop_or_default]
pub min: u16,
/// Maximum value
#[prop_or_default]
pub max: u16,
/// Minimum length (number of characters) of value
#[prop_or_default]
pub minlength: u16,
/// Maximum length (number of characters) of value. Default `1000`
#[prop_or(1000)]
pub maxlength: u16,
/// Pattern the value must match to be valid. Default `"[\\s\\S]*".to_string()`
#[prop_or("[\\s\\S]*".to_string())]
pub pattern: String,
/// The value is not editable. Default `false`
#[prop_or(false)]
pub readonly: bool,
/// A value is required or must be check for the form to be submittable. Default `false`
#[prop_or(false)]
pub required: bool,
/// Whether the form control is disabled. Default `false`
#[prop_or(false)]
pub disabled: bool,
/// Underline style instead of box, like Material. Default `false`
#[prop_or(false)]
pub underline: bool,
/// Incremental values that are valid
#[prop_or_default]
pub step: i16,
/// Error state for validation. Default `false`
#[prop_or(false)]
pub error_state: bool,
/// Show error message when error_state is true
#[prop_or_default]
pub error_message: String,
}
#[derive(Debug)]
pub enum Msg {
Input(InputData),
Blur(FocusEvent),
KeyPressed(KeyboardEvent),
}
impl Component for FormInput {
type Message = Msg;
type Properties = Props;
fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
Self { link, props }
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Input(input_data) => {
self.props.oninput_signal.emit(input_data);
}
Msg::Blur(focus_event) => {
self.props.onblur_signal.emit(focus_event);
}
Msg::KeyPressed(keyboard_event) => {
self.props.onkeydown_signal.emit(keyboard_event);
}
};
true
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
if self.props!= props {
self.props = props;
true
} else {
false
}
}
fn view(&self) -> Html {
html! {
<>
<input
id=self.props.id.clone()
class=classes!(
"form-input",
get_palette(self.props.input_palette.clone()),
get_size(self.props.input_size.clone()),
if self.props.underline { "underline" } else { "" },
self.props.class_name.clone(),
)
key=self.props.key.clone()
ref=self.props.code_ref.clone()
type=get_type(self.props.input_type.clone())
oninput=self.link.callback(Msg::Input)
checked=self.props.checked
onblur=self.link.callback(Msg::Blur)
onkeydown=self.link.callback(Msg::KeyPressed)
name=self.props.name.clone()
required=self.props.required
readonly=self.props.readonly
disabled=self.props.disabled
placeholder=self.props.placeholder.clone()
pattern=self.props.pattern.clone()
min=self.props.min.to_string()
minlength=self.props.minlength.to_string()
max=self.props.max.to_string()
maxlength=self.props.maxlength.to_string()
alt=self.props.alt.clone()
autofocus=self.props.autofocus
autocomplete=self.props.autocomplete.to_string()
step=self.props.step.to_string()
list=self.props.list.clone()
/>
{get_error_message(self.props.error_state, self.props.error_message.clone())}
</>
}
}
}
fn get_type(input_type: InputType) -> String | InputType::Time => "time".to_string(),
InputType::Url => "url".to_string(),
InputType::Week => "week".to_string(),
}
}
#[wasm_bindgen_test]
fn should_create_form_input() {
let props = Props {
key: "".to_string(),
code_ref: NodeRef::default(),
id: "form-input-id-test".to_string(),
class_name: "form-input-class-test".to_string(),
input_type: InputType::Text,
oninput_signal: Callback::noop(),
onblur_signal: Callback::noop(),
onkeydown_signal: Callback::noop(),
checked: false,
error_message: "invalid input".to_string(),
error_state: false,
name: "input-test".to_string(),
input_palette: Palette::Standard,
input_size: Size::Medium,
placeholder: "test input".to_string(),
required: false,
autocomplete: false,
autofocus: false,
alt: "input test".to_string(),
pattern: "".to_string(),
min: 0,
max: 0,
maxlength: 100,
minlength: 0,
readonly: false,
underline: false,
disabled: false,
step: 1,
list: "".to_string(),
};
let form_input: App<FormInput> = App::new();
form_input.mount_with_props(
utils::document().get_element_by_id("output").unwrap(),
props,
);
let form_input_element = utils::document()
.get_element_by_id("form-input-id-test")
.unwrap();
assert_eq!(form_input_element.tag_name(), "INPUT");
}
| {
match input_type {
InputType::Button => "button".to_string(),
InputType::Checkbox => "checkbox".to_string(),
InputType::Color => "color".to_string(),
InputType::Date => "date".to_string(),
InputType::Datetime => "datetime".to_string(),
InputType::DatetimeLocal => "datetime-local".to_string(),
InputType::Email => "email".to_string(),
InputType::Hidden => "hidden".to_string(),
InputType::Image => "image".to_string(),
InputType::Month => "month".to_string(),
InputType::Number => "number".to_string(),
InputType::Password => "password".to_string(),
InputType::Radio => "radio".to_string(),
InputType::Range => "range".to_string(),
InputType::Reset => "reset".to_string(),
InputType::Search => "search".to_string(),
InputType::Tel => "tel".to_string(),
InputType::Text => "text".to_string(), | identifier_body |
main.rs | extern crate clap;
use clap::{App, Arg};
use std::io::{stderr, stdin, stdout, Write, Read};
use std::time::{Duration, Instant};
use std::net::{SocketAddr, TcpListener, IpAddr};
const DEFAULT_BUFFER_SIZE: usize = 4096;
const DEFAULT_ITERATION_COUNT: usize = 1;
const DEFAULT_ADDRESS: &'static str = "127.0.0.1";
macro_rules! print_err_into {
($err_write: expr, $fmt:expr) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($err_write: expr, $fmt:expr, $($arg:tt)*) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
macro_rules! print_err {
($fmt:expr) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($fmt:expr, $($arg:tt)*) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
#[derive(Default)]
struct TransferInfo {
/// The total number of bytes transferred.
total_bytes_transferred: usize,
/// The number of times the Bytes Per Second has been measured.
total_measures: usize,
/// Accumulation of all of the Bytes Per Second measures.
total_bps: f64,
/// The Bytes Per Second during the last measure.
last_bps: f64,
/// The number of bytes transferred during the last measure.
last_bytes_transferred: usize,
}
#[inline]
fn exit_err() ->! {
std::process::exit(1);
}
fn main() {
let matches = App::new("Throughput")
.version("1.1")
.author("Adolph C.")
.about("Measures the throughput of stdin or a socket.")
.arg(Arg::with_name("address")
.short("l")
.long("addr")
.value_name("IP Address")
.help("IP address to listen to. Defaults to 127.0.0.1. Must specify port.")
.takes_value(true))
.arg(Arg::with_name("buffer_size")
.short("b")
.long("bufsize")
.value_name("BYTES")
.help("The size of the buffer used to read from the stream in bytes. Defaults to 4096.")
.takes_value(true))
.arg(Arg::with_name("iterations")
.short("i")
.long("iterations")
.help("The number of times the buffer should be filled before a measure is taken. Defaults to 1.")
.takes_value(true))
.arg(Arg::with_name("port")
.short("p")
.long("port")
.value_name("PORT_NUMBER")
.help("Port to listen on. Must be specified if address is given.")
.takes_value(true))
.arg(Arg::with_name("pass")
.long("pass")
.help("If present, throughput will print to stderr and pass input to stdout.")
.takes_value(false))
.after_help("If a port/address is not specified, throughput will read from stdin.")
.get_matches();
let passthrough = matches.is_present("pass");
let buffer_size: usize;
let iterations: usize;
if let Some(buf_size_str) = matches.value_of("buffer_size") {
if let Ok(bsize) = buf_size_str.parse() {
buffer_size = bsize;
} else {
print_err!("Buffer size must be a valid number.");
exit_err();
}
} else {
buffer_size = DEFAULT_BUFFER_SIZE;
}
if let Some(iterations_str) = matches.value_of("iterations") {
if let Ok(it) = iterations_str.parse() {
iterations = it;
} else {
print_err!("Iterations must be a valid number.");
exit_err();
}
} else {
iterations = DEFAULT_ITERATION_COUNT;
}
let address_present = matches.is_present("address");
let port_present = matches.is_present("port");
if address_present || port_present {
if!port_present {
print_err!("A port must be speicified alongside a address.");
exit_err();
} else {
let address = matches.value_of("address").unwrap_or(DEFAULT_ADDRESS);
let port = matches.value_of("port").expect("Expected port arg to have value.");
if let Ok(parsed_port) = port.parse() {
measure_tcp_stream(address, parsed_port, buffer_size, iterations, passthrough);
} else {
print_err!("Port must be a valid number from 0 to 65535");
exit_err();
}
}
} else {
measure_stdin(buffer_size, iterations, passthrough);
}
}
fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) {
let parsed_addr: IpAddr = match address.parse() {
Ok(parsed) => parsed,
Err(_) => {
print_err!("Bad IP address {}", address);
exit_err();
}
};
let socket_addr = SocketAddr::new(parsed_addr, port);
match TcpListener::bind(socket_addr) {
Ok(listener) => {
println!("Listening at {}", socket_addr);
match listener.accept() {
Ok((stream, incoming_addr)) => {
println!("Reading incoming data from {}", incoming_addr);
println!();
measure_reader(stream, buffer_size, iterations, passthrough);
},
Err(err) => {
print_err!("There was an error accepting a connection.");
print_err!("ERROR: {}", err);
exit_err();
}
}
},
Err(err) => {
print_err!("There was an error connecting to {}", socket_addr);
print_err!("ERROR: {}", err);
exit_err();
}
};
}
fn measure_stdin(buffer_size: usize, iterations: usize, passthrough: bool) {
let input = stdin();
measure_reader(input.lock(), buffer_size, iterations, passthrough);
}
fn measure_reader<R: Read>(mut reader: R, buffer_size: usize, iterations: usize, passthrough: bool) {
let output = stdout();
let mut locked_output = output.lock();
let err_out = stderr();
let mut locked_error = err_out.lock();
let mut buffer = Vec::with_capacity(buffer_size);
buffer.resize(buffer_size, 0);
let mut last_measured = Instant::now();
let mut transfer_info = TransferInfo::default();
loop {
let mut end_loop = false;
for _ in 0..iterations {
match reader.read(&mut buffer) {
Ok(bytes_read) => {
transfer_info.last_bytes_transferred += bytes_read;
transfer_info.total_bytes_transferred += bytes_read;
if bytes_read == 0 {
end_loop = true;
break;
} else if passthrough {
if let Err(err) = locked_output.write_all(&buffer[0..bytes_read]) {
print_err_into!(locked_error, "Error while writing buffer into stdout: {}", err);
exit_err();
}
}
}
Err(err) => {
print_err_into!(locked_error, "Error while reading into buffer: {}", err);
}
}
}
let measure_end = Instant::now();
let duration = measure_end.duration_since(last_measured);
if duration.as_secs() > 0 || end_loop {
transfer_info.last_bps = bytes_per_second(transfer_info.last_bytes_transferred, duration);
transfer_info.total_measures += 1;
transfer_info.total_bps += transfer_info.last_bps;
let _print_result = if passthrough {
print_info(&mut locked_error, &mut transfer_info)
} else {
print_info(&mut locked_output, &mut transfer_info)
};
match _print_result {
Ok(_) => {},
Err(err) => {
print_err_into!(locked_error, "Error while printing output: {}", err);
exit_err();
}
}
last_measured = measure_end;
transfer_info.last_bps = 0.0;
transfer_info.last_bytes_transferred = 0;
}
if end_loop { return; }
}
}
fn print_info<W: Write>(output: &mut W, transfer_info: &mut TransferInfo) -> Result<(), std::io::Error> {
if transfer_info.total_measures > 1 { term_move_up(output, 3)?; }
let (mem_total_transfer, unit_total_transfer) = byte_to_mem_units(transfer_info.total_bytes_transferred as f64);
print_fixed_width(output, "Data Transferred:", 24);
write!(output, "{:.3} {} ({} cycles)",
mem_total_transfer, unit_total_transfer, transfer_info.total_measures)?;
term_clear_line(output)?;
let (mem_single, unit_single) = byte_to_mem_units(transfer_info.last_bps);
print_fixed_width(output, "Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_single, unit_single)?;
term_clear_line(output)?;
let avg_bps = transfer_info.total_bps / transfer_info.total_measures as f64;
let (mem_avg, unit_avg) = byte_to_mem_units(avg_bps);
print_fixed_width(output, "Average Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_avg, unit_avg)?;
term_clear_line(output)?;
Ok(())
}
fn print_fixed_width<W: Write>(output: &mut W, text: &str, columns: usize) {
if let Err(err) = output.write(text.as_bytes()) {
panic!("[print_fixed_width] Error while writing to stream: {}", err);
}
if text.len() < columns {
let remaining = columns - text.len();
let pad = [b' '];
for _ in 0..remaining {
if let Err(err) = output.write(&pad) {
panic!("[print_fixed_width] Error while padding output: {}", err);
}
}
}
}
/// Clears to the end of the current line.
#[inline]
fn term_clear_line<W: Write>(output: &mut W) -> Result<(), std::io::Error> {
writeln!(output, "\x1b[K")?;
Ok(())
}
/// Moves the cursor up one line.
#[inline]
fn term_move_up<W: Write>(output: &mut W, lines: usize) -> Result<(), std::io::Error> |
fn byte_to_mem_units(bytes: f64) -> (f64, &'static str) {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
const TB: f64 = GB * 1024.0;
if bytes >= TB { (bytes / TB, "TB") }
else if bytes >= GB { (bytes / GB, "GB") }
else if bytes >= MB { (bytes / MB, "MB") }
else if bytes >= KB { (bytes / KB, "KB") }
else { (bytes, "Bytes") }
}
fn bytes_per_second(bytes_read: usize, duration: Duration) -> f64 {
let duration_seconds =
duration.as_secs() as f64 +
duration.subsec_nanos() as f64 / 1000000000.0;
return bytes_read as f64 / duration_seconds;
} | {
write!(output, "\x1b[{}A", lines)?;
Ok(())
} | identifier_body |
main.rs | extern crate clap;
use clap::{App, Arg};
use std::io::{stderr, stdin, stdout, Write, Read};
use std::time::{Duration, Instant};
use std::net::{SocketAddr, TcpListener, IpAddr};
const DEFAULT_BUFFER_SIZE: usize = 4096;
const DEFAULT_ITERATION_COUNT: usize = 1;
const DEFAULT_ADDRESS: &'static str = "127.0.0.1";
macro_rules! print_err_into {
($err_write: expr, $fmt:expr) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($err_write: expr, $fmt:expr, $($arg:tt)*) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
macro_rules! print_err {
($fmt:expr) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($fmt:expr, $($arg:tt)*) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
#[derive(Default)]
struct TransferInfo {
/// The total number of bytes transferred.
total_bytes_transferred: usize,
/// The number of times the Bytes Per Second has been measured.
total_measures: usize,
/// Accumulation of all of the Bytes Per Second measures.
total_bps: f64,
/// The Bytes Per Second during the last measure.
last_bps: f64,
/// The number of bytes transferred during the last measure.
last_bytes_transferred: usize,
}
#[inline]
fn exit_err() ->! {
std::process::exit(1);
}
fn main() {
let matches = App::new("Throughput")
.version("1.1")
.author("Adolph C.")
.about("Measures the throughput of stdin or a socket.")
.arg(Arg::with_name("address")
.short("l")
.long("addr")
.value_name("IP Address")
.help("IP address to listen to. Defaults to 127.0.0.1. Must specify port.")
.takes_value(true))
.arg(Arg::with_name("buffer_size")
.short("b")
.long("bufsize")
.value_name("BYTES")
.help("The size of the buffer used to read from the stream in bytes. Defaults to 4096.")
.takes_value(true))
.arg(Arg::with_name("iterations")
.short("i")
.long("iterations")
.help("The number of times the buffer should be filled before a measure is taken. Defaults to 1.")
.takes_value(true))
.arg(Arg::with_name("port")
.short("p")
.long("port")
.value_name("PORT_NUMBER")
.help("Port to listen on. Must be specified if address is given.")
.takes_value(true))
.arg(Arg::with_name("pass")
.long("pass")
.help("If present, throughput will print to stderr and pass input to stdout.")
.takes_value(false))
.after_help("If a port/address is not specified, throughput will read from stdin.")
.get_matches();
let passthrough = matches.is_present("pass");
let buffer_size: usize;
let iterations: usize;
if let Some(buf_size_str) = matches.value_of("buffer_size") {
if let Ok(bsize) = buf_size_str.parse() {
buffer_size = bsize;
} else {
print_err!("Buffer size must be a valid number.");
exit_err();
}
} else {
buffer_size = DEFAULT_BUFFER_SIZE;
}
if let Some(iterations_str) = matches.value_of("iterations") {
if let Ok(it) = iterations_str.parse() {
iterations = it;
} else {
print_err!("Iterations must be a valid number.");
exit_err();
}
} else {
iterations = DEFAULT_ITERATION_COUNT;
}
let address_present = matches.is_present("address");
let port_present = matches.is_present("port");
if address_present || port_present {
if!port_present {
print_err!("A port must be speicified alongside a address.");
exit_err();
} else {
let address = matches.value_of("address").unwrap_or(DEFAULT_ADDRESS);
let port = matches.value_of("port").expect("Expected port arg to have value.");
if let Ok(parsed_port) = port.parse() {
measure_tcp_stream(address, parsed_port, buffer_size, iterations, passthrough);
} else {
print_err!("Port must be a valid number from 0 to 65535");
exit_err();
} | } else {
measure_stdin(buffer_size, iterations, passthrough);
}
}
fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) {
let parsed_addr: IpAddr = match address.parse() {
Ok(parsed) => parsed,
Err(_) => {
print_err!("Bad IP address {}", address);
exit_err();
}
};
let socket_addr = SocketAddr::new(parsed_addr, port);
match TcpListener::bind(socket_addr) {
Ok(listener) => {
println!("Listening at {}", socket_addr);
match listener.accept() {
Ok((stream, incoming_addr)) => {
println!("Reading incoming data from {}", incoming_addr);
println!();
measure_reader(stream, buffer_size, iterations, passthrough);
},
Err(err) => {
print_err!("There was an error accepting a connection.");
print_err!("ERROR: {}", err);
exit_err();
}
}
},
Err(err) => {
print_err!("There was an error connecting to {}", socket_addr);
print_err!("ERROR: {}", err);
exit_err();
}
};
}
fn measure_stdin(buffer_size: usize, iterations: usize, passthrough: bool) {
let input = stdin();
measure_reader(input.lock(), buffer_size, iterations, passthrough);
}
fn measure_reader<R: Read>(mut reader: R, buffer_size: usize, iterations: usize, passthrough: bool) {
let output = stdout();
let mut locked_output = output.lock();
let err_out = stderr();
let mut locked_error = err_out.lock();
let mut buffer = Vec::with_capacity(buffer_size);
buffer.resize(buffer_size, 0);
let mut last_measured = Instant::now();
let mut transfer_info = TransferInfo::default();
loop {
let mut end_loop = false;
for _ in 0..iterations {
match reader.read(&mut buffer) {
Ok(bytes_read) => {
transfer_info.last_bytes_transferred += bytes_read;
transfer_info.total_bytes_transferred += bytes_read;
if bytes_read == 0 {
end_loop = true;
break;
} else if passthrough {
if let Err(err) = locked_output.write_all(&buffer[0..bytes_read]) {
print_err_into!(locked_error, "Error while writing buffer into stdout: {}", err);
exit_err();
}
}
}
Err(err) => {
print_err_into!(locked_error, "Error while reading into buffer: {}", err);
}
}
}
let measure_end = Instant::now();
let duration = measure_end.duration_since(last_measured);
if duration.as_secs() > 0 || end_loop {
transfer_info.last_bps = bytes_per_second(transfer_info.last_bytes_transferred, duration);
transfer_info.total_measures += 1;
transfer_info.total_bps += transfer_info.last_bps;
let _print_result = if passthrough {
print_info(&mut locked_error, &mut transfer_info)
} else {
print_info(&mut locked_output, &mut transfer_info)
};
match _print_result {
Ok(_) => {},
Err(err) => {
print_err_into!(locked_error, "Error while printing output: {}", err);
exit_err();
}
}
last_measured = measure_end;
transfer_info.last_bps = 0.0;
transfer_info.last_bytes_transferred = 0;
}
if end_loop { return; }
}
}
fn print_info<W: Write>(output: &mut W, transfer_info: &mut TransferInfo) -> Result<(), std::io::Error> {
if transfer_info.total_measures > 1 { term_move_up(output, 3)?; }
let (mem_total_transfer, unit_total_transfer) = byte_to_mem_units(transfer_info.total_bytes_transferred as f64);
print_fixed_width(output, "Data Transferred:", 24);
write!(output, "{:.3} {} ({} cycles)",
mem_total_transfer, unit_total_transfer, transfer_info.total_measures)?;
term_clear_line(output)?;
let (mem_single, unit_single) = byte_to_mem_units(transfer_info.last_bps);
print_fixed_width(output, "Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_single, unit_single)?;
term_clear_line(output)?;
let avg_bps = transfer_info.total_bps / transfer_info.total_measures as f64;
let (mem_avg, unit_avg) = byte_to_mem_units(avg_bps);
print_fixed_width(output, "Average Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_avg, unit_avg)?;
term_clear_line(output)?;
Ok(())
}
fn print_fixed_width<W: Write>(output: &mut W, text: &str, columns: usize) {
if let Err(err) = output.write(text.as_bytes()) {
panic!("[print_fixed_width] Error while writing to stream: {}", err);
}
if text.len() < columns {
let remaining = columns - text.len();
let pad = [b' '];
for _ in 0..remaining {
if let Err(err) = output.write(&pad) {
panic!("[print_fixed_width] Error while padding output: {}", err);
}
}
}
}
/// Clears to the end of the current line.
#[inline]
fn term_clear_line<W: Write>(output: &mut W) -> Result<(), std::io::Error> {
writeln!(output, "\x1b[K")?;
Ok(())
}
/// Moves the cursor up one line.
#[inline]
fn term_move_up<W: Write>(output: &mut W, lines: usize) -> Result<(), std::io::Error> {
write!(output, "\x1b[{}A", lines)?;
Ok(())
}
fn byte_to_mem_units(bytes: f64) -> (f64, &'static str) {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
const TB: f64 = GB * 1024.0;
if bytes >= TB { (bytes / TB, "TB") }
else if bytes >= GB { (bytes / GB, "GB") }
else if bytes >= MB { (bytes / MB, "MB") }
else if bytes >= KB { (bytes / KB, "KB") }
else { (bytes, "Bytes") }
}
fn bytes_per_second(bytes_read: usize, duration: Duration) -> f64 {
let duration_seconds =
duration.as_secs() as f64 +
duration.subsec_nanos() as f64 / 1000000000.0;
return bytes_read as f64 / duration_seconds;
} | } | random_line_split |
main.rs | extern crate clap;
use clap::{App, Arg};
use std::io::{stderr, stdin, stdout, Write, Read};
use std::time::{Duration, Instant};
use std::net::{SocketAddr, TcpListener, IpAddr};
const DEFAULT_BUFFER_SIZE: usize = 4096;
const DEFAULT_ITERATION_COUNT: usize = 1;
const DEFAULT_ADDRESS: &'static str = "127.0.0.1";
macro_rules! print_err_into {
($err_write: expr, $fmt:expr) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($err_write: expr, $fmt:expr, $($arg:tt)*) => ({
use std::io::Write;
if let Err(e) = writeln!($err_write, $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
macro_rules! print_err {
($fmt:expr) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt) {
panic!("Error while writing to stderr: {}", e);
}
});
($fmt:expr, $($arg:tt)*) => ({
use std::io::{stderr, Write};
if let Err(e) = writeln!(stderr(), $fmt, $($arg)*) {
panic!("Error while writing to stderr: {}", e);
}
});
}
#[derive(Default)]
struct TransferInfo {
/// The total number of bytes transferred.
total_bytes_transferred: usize,
/// The number of times the Bytes Per Second has been measured.
total_measures: usize,
/// Accumulation of all of the Bytes Per Second measures.
total_bps: f64,
/// The Bytes Per Second during the last measure.
last_bps: f64,
/// The number of bytes transferred during the last measure.
last_bytes_transferred: usize,
}
#[inline]
fn exit_err() ->! {
std::process::exit(1);
}
fn main() {
let matches = App::new("Throughput")
.version("1.1")
.author("Adolph C.")
.about("Measures the throughput of stdin or a socket.")
.arg(Arg::with_name("address")
.short("l")
.long("addr")
.value_name("IP Address")
.help("IP address to listen to. Defaults to 127.0.0.1. Must specify port.")
.takes_value(true))
.arg(Arg::with_name("buffer_size")
.short("b")
.long("bufsize")
.value_name("BYTES")
.help("The size of the buffer used to read from the stream in bytes. Defaults to 4096.")
.takes_value(true))
.arg(Arg::with_name("iterations")
.short("i")
.long("iterations")
.help("The number of times the buffer should be filled before a measure is taken. Defaults to 1.")
.takes_value(true))
.arg(Arg::with_name("port")
.short("p")
.long("port")
.value_name("PORT_NUMBER")
.help("Port to listen on. Must be specified if address is given.")
.takes_value(true))
.arg(Arg::with_name("pass")
.long("pass")
.help("If present, throughput will print to stderr and pass input to stdout.")
.takes_value(false))
.after_help("If a port/address is not specified, throughput will read from stdin.")
.get_matches();
let passthrough = matches.is_present("pass");
let buffer_size: usize;
let iterations: usize;
if let Some(buf_size_str) = matches.value_of("buffer_size") {
if let Ok(bsize) = buf_size_str.parse() {
buffer_size = bsize;
} else {
print_err!("Buffer size must be a valid number.");
exit_err();
}
} else {
buffer_size = DEFAULT_BUFFER_SIZE;
}
if let Some(iterations_str) = matches.value_of("iterations") {
if let Ok(it) = iterations_str.parse() {
iterations = it;
} else {
print_err!("Iterations must be a valid number.");
exit_err();
}
} else {
iterations = DEFAULT_ITERATION_COUNT;
}
let address_present = matches.is_present("address");
let port_present = matches.is_present("port");
if address_present || port_present {
if!port_present {
print_err!("A port must be speicified alongside a address.");
exit_err();
} else {
let address = matches.value_of("address").unwrap_or(DEFAULT_ADDRESS);
let port = matches.value_of("port").expect("Expected port arg to have value.");
if let Ok(parsed_port) = port.parse() {
measure_tcp_stream(address, parsed_port, buffer_size, iterations, passthrough);
} else {
print_err!("Port must be a valid number from 0 to 65535");
exit_err();
}
}
} else {
measure_stdin(buffer_size, iterations, passthrough);
}
}
fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) {
let parsed_addr: IpAddr = match address.parse() {
Ok(parsed) => parsed,
Err(_) => {
print_err!("Bad IP address {}", address);
exit_err();
}
};
let socket_addr = SocketAddr::new(parsed_addr, port);
match TcpListener::bind(socket_addr) {
Ok(listener) => {
println!("Listening at {}", socket_addr);
match listener.accept() {
Ok((stream, incoming_addr)) => {
println!("Reading incoming data from {}", incoming_addr);
println!();
measure_reader(stream, buffer_size, iterations, passthrough);
},
Err(err) => {
print_err!("There was an error accepting a connection.");
print_err!("ERROR: {}", err);
exit_err();
}
}
},
Err(err) => {
print_err!("There was an error connecting to {}", socket_addr);
print_err!("ERROR: {}", err);
exit_err();
}
};
}
fn measure_stdin(buffer_size: usize, iterations: usize, passthrough: bool) {
let input = stdin();
measure_reader(input.lock(), buffer_size, iterations, passthrough);
}
fn measure_reader<R: Read>(mut reader: R, buffer_size: usize, iterations: usize, passthrough: bool) {
let output = stdout();
let mut locked_output = output.lock();
let err_out = stderr();
let mut locked_error = err_out.lock();
let mut buffer = Vec::with_capacity(buffer_size);
buffer.resize(buffer_size, 0);
let mut last_measured = Instant::now();
let mut transfer_info = TransferInfo::default();
loop {
let mut end_loop = false;
for _ in 0..iterations {
match reader.read(&mut buffer) {
Ok(bytes_read) => {
transfer_info.last_bytes_transferred += bytes_read;
transfer_info.total_bytes_transferred += bytes_read;
if bytes_read == 0 {
end_loop = true;
break;
} else if passthrough {
if let Err(err) = locked_output.write_all(&buffer[0..bytes_read]) {
print_err_into!(locked_error, "Error while writing buffer into stdout: {}", err);
exit_err();
}
}
}
Err(err) => {
print_err_into!(locked_error, "Error while reading into buffer: {}", err);
}
}
}
let measure_end = Instant::now();
let duration = measure_end.duration_since(last_measured);
if duration.as_secs() > 0 || end_loop {
transfer_info.last_bps = bytes_per_second(transfer_info.last_bytes_transferred, duration);
transfer_info.total_measures += 1;
transfer_info.total_bps += transfer_info.last_bps;
let _print_result = if passthrough {
print_info(&mut locked_error, &mut transfer_info)
} else {
print_info(&mut locked_output, &mut transfer_info)
};
match _print_result {
Ok(_) => {},
Err(err) => {
print_err_into!(locked_error, "Error while printing output: {}", err);
exit_err();
}
}
last_measured = measure_end;
transfer_info.last_bps = 0.0;
transfer_info.last_bytes_transferred = 0;
}
if end_loop { return; }
}
}
fn print_info<W: Write>(output: &mut W, transfer_info: &mut TransferInfo) -> Result<(), std::io::Error> {
if transfer_info.total_measures > 1 { term_move_up(output, 3)?; }
let (mem_total_transfer, unit_total_transfer) = byte_to_mem_units(transfer_info.total_bytes_transferred as f64);
print_fixed_width(output, "Data Transferred:", 24);
write!(output, "{:.3} {} ({} cycles)",
mem_total_transfer, unit_total_transfer, transfer_info.total_measures)?;
term_clear_line(output)?;
let (mem_single, unit_single) = byte_to_mem_units(transfer_info.last_bps);
print_fixed_width(output, "Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_single, unit_single)?;
term_clear_line(output)?;
let avg_bps = transfer_info.total_bps / transfer_info.total_measures as f64;
let (mem_avg, unit_avg) = byte_to_mem_units(avg_bps);
print_fixed_width(output, "Average Transfer Speed:", 24);
write!(output, "{:.3} {}/sec", mem_avg, unit_avg)?;
term_clear_line(output)?;
Ok(())
}
fn print_fixed_width<W: Write>(output: &mut W, text: &str, columns: usize) {
if let Err(err) = output.write(text.as_bytes()) {
panic!("[print_fixed_width] Error while writing to stream: {}", err);
}
if text.len() < columns {
let remaining = columns - text.len();
let pad = [b' '];
for _ in 0..remaining {
if let Err(err) = output.write(&pad) {
panic!("[print_fixed_width] Error while padding output: {}", err);
}
}
}
}
/// Clears to the end of the current line.
#[inline]
fn term_clear_line<W: Write>(output: &mut W) -> Result<(), std::io::Error> {
writeln!(output, "\x1b[K")?;
Ok(())
}
/// Moves the cursor up one line.
#[inline]
fn term_move_up<W: Write>(output: &mut W, lines: usize) -> Result<(), std::io::Error> {
write!(output, "\x1b[{}A", lines)?;
Ok(())
}
fn | (bytes: f64) -> (f64, &'static str) {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
const TB: f64 = GB * 1024.0;
if bytes >= TB { (bytes / TB, "TB") }
else if bytes >= GB { (bytes / GB, "GB") }
else if bytes >= MB { (bytes / MB, "MB") }
else if bytes >= KB { (bytes / KB, "KB") }
else { (bytes, "Bytes") }
}
fn bytes_per_second(bytes_read: usize, duration: Duration) -> f64 {
let duration_seconds =
duration.as_secs() as f64 +
duration.subsec_nanos() as f64 / 1000000000.0;
return bytes_read as f64 / duration_seconds;
} | byte_to_mem_units | identifier_name |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position, given `edge` length of grid.
#[must_use]
pub fn index_for(&self, edge: i32) -> usize {
let mut i = 0_i32;
for c in &self.coords {
i = i * edge + c;
}
usize::try_from(i).unwrap()
}
#[must_use]
/// Construct from n-dimensional coordinates.
pub fn from(coords: &[i32]) -> Self {
Self { coords: coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => ConwayCube::Inactive,
'#' => ConwayCube::Active,
_ => {
let e = format!("invalid cube character {}", cube);
panic!(e);
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InfiniteGrid {
cubes: Vec<ConwayCube>,
dim: usize,
edge: i32,
}
impl fmt::Display for InfiniteGrid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let half_edge = self.edge / 2;
let mut s = String::new();
for coords in (0..self.dim).map(|_i| 0..self.edge).multi_cartesian_product() {
if coords[self.dim - 2] == 0 && coords[self.dim - 1] == 0 {
let axes = vec!['z', 'w', 'v', 'u'];
for d in 2..self.dim {
if d > 2 {
s += ", ";
}
let label = format!("{}={}", axes[d - 2], coords[self.dim - d - 1] - half_edge);
s += &label;
}
s += "\n";
}
let pos = Position::from(&coords);
s += match self.cube_at(&pos) {
ConwayCube::Void => "_",
ConwayCube::Inactive => ".",
ConwayCube::Active => "#",
};
if coords[self.dim - 1] >= self.edge - 1 {
s += "\n";
}
}
write!(f, "{}", s)
}
}
pub struct InfiniteGridIter {
layout: InfiniteGrid,
}
impl Iterator for InfiniteGridIter {
type Item = InfiniteGrid;
fn next(&mut self) -> Option<Self::Item> {
let prev_layout = self.layout.clone();
self.layout = prev_layout.cube_round();
Some(self.layout.clone())
}
}
impl InfiniteGrid {
/// Return edge length.
#[must_use]
pub fn edge(&self) -> i32 {
self.edge
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from file at `path`.
///
/// # Errors
///
/// Returns `Err` if the input file cannot be opened, or if line is
/// found with invalid format.
pub fn read_from_file(path: &str, dim: usize) -> Result<InfiniteGrid> {
let s: String = fs::read_to_string(path)?;
InfiniteGrid::from_input(&s, dim)
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from `input` string.
///
/// # Errors
///
/// Returns `Err` if a line is found with invalid format.
pub fn from_input(input: &str, dim: usize) -> Result<InfiniteGrid> {
let edge = i32::try_from(input.lines().next().unwrap().len()).unwrap();
let half_edge = edge / 2;
// parse and store initial 2D grid plane:
let cubes_2d: Vec<ConwayCube> = input
.lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect();
// create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edge {
let from_i = usize::try_from(y * edge + x).unwrap();
let mut dims = vec![half_edge; dim];
dims[dim-1] = x;
dims[dim-2] = y;
let to_i = Position::from(&dims).index_for(edge);
cubes[to_i] = cubes_2d[from_i];
}
}
Ok(Self { cubes, dim, edge })
}
#[must_use]
fn index_size(edge: i32, dim: usize) -> usize {
let mut s = 1_i32;
for _i in 0..dim {
s *= edge;
}
usize::try_from(s).unwrap()
}
#[must_use]
pub fn iter(&self) -> InfiniteGridIter {
InfiniteGridIter {
layout: self.clone(),
}
}
/// Return `ConwayCube` at the given position.
#[must_use]
pub fn cube_at(&self, pos: &Position) -> ConwayCube {
for c in &pos.coords {
if *c < 0 || *c >= self.edge {
return ConwayCube::Void;
}
}
self.cubes[pos.index_for(self.edge)]
}
/// Return count of active cubes.
#[must_use]
pub fn active_cubes(&self) -> usize {
self.cubes.iter().filter(|&c| *c == ConwayCube::Active).count()
}
/// Return count of active neighbor cubes of the cube at the given
/// position.
#[must_use]
pub fn active_neighbors_at(&self, pos: &Position) -> usize {
let mut n_active: usize = 0;
for deltas in (0..self.dim).map(|_i| -1..=1).multi_cartesian_product() {
if deltas.iter().all(|dc| *dc == 0) {
continue;
}
let d_coords: Vec<i32> = pos.coords
.iter()
.enumerate()
.map(|(i, dc)| *dc + deltas[i])
.collect();
let d_pos = Position::from(&d_coords);
if self.cube_at(&d_pos) == ConwayCube::Active {
n_active += 1;
}
}
n_active
}
/// Do one round of cube life. Returns a new grid which is one unit
/// bigger in all directions (its edge increases by 2 in all
/// dimensions).
#[must_use]
pub fn cube_round(&self) -> InfiniteGrid {
let edge = self.edge + 2;
let max_i = InfiniteGrid::index_size(edge, self.dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for coords in (0..self.dim).map(|_i| 0..edge).multi_cartesian_product() {
let from_coords: Vec<i32> = coords.iter().map(|c| c - 1).collect();
let from_pos = Position::from(&from_coords);
let pos = Position::from(&coords);
cubes[pos.index_for(edge)] = self.new_cube_at(&from_pos);
}
InfiniteGrid { cubes, dim: self.dim, edge }
}
fn new_cube_at(&self, pos: &Position) -> ConwayCube {
match self.cube_at(&pos) {
ConwayCube::Active => {
let n = self.active_neighbors_at(&pos);
if n == 2 || n == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
_ => {
if self.active_neighbors_at(&pos) == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const TINY_LAYOUT: &'static str = ".#.\n..#\n###\n";
#[test]
fn test_from_input() |
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(&pos));
let pos = Position::from(&[0, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_z() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[-1, 0, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[3, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_y() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, -1, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 3, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_x() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, -1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 3]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_6_rounds() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= N_ROUNDS - 1 {
n_active = g.active_cubes();
break;
}
}
assert_eq!(112, n_active);
}
#[test]
fn test_6_rounds_4d() {
// the full N_ROUNDS takes a while so:
let n_rounds = 1; // = N_ROUNDS;
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= n_rounds - 1 {
n_active = g.active_cubes();
break;
}
}
let expect = if n_rounds == 1 { 3*4 + 5 + 3*4 } else { 848 };
assert_eq!(expect, n_active);
}
}
| {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
} | identifier_body |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position, given `edge` length of grid.
#[must_use]
pub fn index_for(&self, edge: i32) -> usize {
let mut i = 0_i32;
for c in &self.coords {
i = i * edge + c;
}
usize::try_from(i).unwrap()
}
#[must_use]
/// Construct from n-dimensional coordinates.
pub fn from(coords: &[i32]) -> Self {
Self { coords: coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => ConwayCube::Inactive,
'#' => ConwayCube::Active,
_ => {
let e = format!("invalid cube character {}", cube);
panic!(e);
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InfiniteGrid {
cubes: Vec<ConwayCube>,
dim: usize,
edge: i32,
}
impl fmt::Display for InfiniteGrid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let half_edge = self.edge / 2;
let mut s = String::new();
for coords in (0..self.dim).map(|_i| 0..self.edge).multi_cartesian_product() {
if coords[self.dim - 2] == 0 && coords[self.dim - 1] == 0 {
let axes = vec!['z', 'w', 'v', 'u'];
for d in 2..self.dim {
if d > 2 {
s += ", ";
}
let label = format!("{}={}", axes[d - 2], coords[self.dim - d - 1] - half_edge);
s += &label;
}
s += "\n";
}
let pos = Position::from(&coords);
s += match self.cube_at(&pos) {
ConwayCube::Void => "_",
ConwayCube::Inactive => ".",
ConwayCube::Active => "#",
};
if coords[self.dim - 1] >= self.edge - 1 {
s += "\n";
}
}
write!(f, "{}", s)
}
}
pub struct InfiniteGridIter {
layout: InfiniteGrid,
}
impl Iterator for InfiniteGridIter {
type Item = InfiniteGrid;
fn next(&mut self) -> Option<Self::Item> {
let prev_layout = self.layout.clone();
self.layout = prev_layout.cube_round();
Some(self.layout.clone())
}
}
impl InfiniteGrid {
/// Return edge length.
#[must_use]
pub fn edge(&self) -> i32 {
self.edge
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from file at `path`.
///
/// # Errors
///
/// Returns `Err` if the input file cannot be opened, or if line is
/// found with invalid format.
pub fn read_from_file(path: &str, dim: usize) -> Result<InfiniteGrid> {
let s: String = fs::read_to_string(path)?;
InfiniteGrid::from_input(&s, dim)
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from `input` string.
///
/// # Errors
///
/// Returns `Err` if a line is found with invalid format.
pub fn from_input(input: &str, dim: usize) -> Result<InfiniteGrid> {
let edge = i32::try_from(input.lines().next().unwrap().len()).unwrap();
let half_edge = edge / 2;
// parse and store initial 2D grid plane:
let cubes_2d: Vec<ConwayCube> = input | // create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edge {
let from_i = usize::try_from(y * edge + x).unwrap();
let mut dims = vec![half_edge; dim];
dims[dim-1] = x;
dims[dim-2] = y;
let to_i = Position::from(&dims).index_for(edge);
cubes[to_i] = cubes_2d[from_i];
}
}
Ok(Self { cubes, dim, edge })
}
#[must_use]
fn index_size(edge: i32, dim: usize) -> usize {
let mut s = 1_i32;
for _i in 0..dim {
s *= edge;
}
usize::try_from(s).unwrap()
}
#[must_use]
pub fn iter(&self) -> InfiniteGridIter {
InfiniteGridIter {
layout: self.clone(),
}
}
/// Return `ConwayCube` at the given position.
#[must_use]
pub fn cube_at(&self, pos: &Position) -> ConwayCube {
for c in &pos.coords {
if *c < 0 || *c >= self.edge {
return ConwayCube::Void;
}
}
self.cubes[pos.index_for(self.edge)]
}
/// Return count of active cubes.
#[must_use]
pub fn active_cubes(&self) -> usize {
self.cubes.iter().filter(|&c| *c == ConwayCube::Active).count()
}
/// Return count of active neighbor cubes of the cube at the given
/// position.
#[must_use]
pub fn active_neighbors_at(&self, pos: &Position) -> usize {
let mut n_active: usize = 0;
for deltas in (0..self.dim).map(|_i| -1..=1).multi_cartesian_product() {
if deltas.iter().all(|dc| *dc == 0) {
continue;
}
let d_coords: Vec<i32> = pos.coords
.iter()
.enumerate()
.map(|(i, dc)| *dc + deltas[i])
.collect();
let d_pos = Position::from(&d_coords);
if self.cube_at(&d_pos) == ConwayCube::Active {
n_active += 1;
}
}
n_active
}
/// Do one round of cube life. Returns a new grid which is one unit
/// bigger in all directions (its edge increases by 2 in all
/// dimensions).
#[must_use]
pub fn cube_round(&self) -> InfiniteGrid {
let edge = self.edge + 2;
let max_i = InfiniteGrid::index_size(edge, self.dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for coords in (0..self.dim).map(|_i| 0..edge).multi_cartesian_product() {
let from_coords: Vec<i32> = coords.iter().map(|c| c - 1).collect();
let from_pos = Position::from(&from_coords);
let pos = Position::from(&coords);
cubes[pos.index_for(edge)] = self.new_cube_at(&from_pos);
}
InfiniteGrid { cubes, dim: self.dim, edge }
}
fn new_cube_at(&self, pos: &Position) -> ConwayCube {
match self.cube_at(&pos) {
ConwayCube::Active => {
let n = self.active_neighbors_at(&pos);
if n == 2 || n == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
_ => {
if self.active_neighbors_at(&pos) == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const TINY_LAYOUT: &'static str = ".#.\n..#\n###\n";
#[test]
fn test_from_input() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
}
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(&pos));
let pos = Position::from(&[0, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_z() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[-1, 0, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[3, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_y() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, -1, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 3, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_x() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, -1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 3]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_6_rounds() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= N_ROUNDS - 1 {
n_active = g.active_cubes();
break;
}
}
assert_eq!(112, n_active);
}
#[test]
fn test_6_rounds_4d() {
// the full N_ROUNDS takes a while so:
let n_rounds = 1; // = N_ROUNDS;
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= n_rounds - 1 {
n_active = g.active_cubes();
break;
}
}
let expect = if n_rounds == 1 { 3*4 + 5 + 3*4 } else { 848 };
assert_eq!(expect, n_active);
}
} | .lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect(); | random_line_split |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position, given `edge` length of grid.
#[must_use]
pub fn index_for(&self, edge: i32) -> usize {
let mut i = 0_i32;
for c in &self.coords {
i = i * edge + c;
}
usize::try_from(i).unwrap()
}
#[must_use]
/// Construct from n-dimensional coordinates.
pub fn from(coords: &[i32]) -> Self {
Self { coords: coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => ConwayCube::Inactive,
'#' => ConwayCube::Active,
_ => {
let e = format!("invalid cube character {}", cube);
panic!(e);
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InfiniteGrid {
cubes: Vec<ConwayCube>,
dim: usize,
edge: i32,
}
impl fmt::Display for InfiniteGrid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let half_edge = self.edge / 2;
let mut s = String::new();
for coords in (0..self.dim).map(|_i| 0..self.edge).multi_cartesian_product() {
if coords[self.dim - 2] == 0 && coords[self.dim - 1] == 0 {
let axes = vec!['z', 'w', 'v', 'u'];
for d in 2..self.dim {
if d > 2 {
s += ", ";
}
let label = format!("{}={}", axes[d - 2], coords[self.dim - d - 1] - half_edge);
s += &label;
}
s += "\n";
}
let pos = Position::from(&coords);
s += match self.cube_at(&pos) {
ConwayCube::Void => "_",
ConwayCube::Inactive => ".",
ConwayCube::Active => "#",
};
if coords[self.dim - 1] >= self.edge - 1 {
s += "\n";
}
}
write!(f, "{}", s)
}
}
pub struct InfiniteGridIter {
layout: InfiniteGrid,
}
impl Iterator for InfiniteGridIter {
type Item = InfiniteGrid;
fn next(&mut self) -> Option<Self::Item> {
let prev_layout = self.layout.clone();
self.layout = prev_layout.cube_round();
Some(self.layout.clone())
}
}
impl InfiniteGrid {
/// Return edge length.
#[must_use]
pub fn edge(&self) -> i32 {
self.edge
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from file at `path`.
///
/// # Errors
///
/// Returns `Err` if the input file cannot be opened, or if line is
/// found with invalid format.
pub fn read_from_file(path: &str, dim: usize) -> Result<InfiniteGrid> {
let s: String = fs::read_to_string(path)?;
InfiniteGrid::from_input(&s, dim)
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from `input` string.
///
/// # Errors
///
/// Returns `Err` if a line is found with invalid format.
pub fn from_input(input: &str, dim: usize) -> Result<InfiniteGrid> {
let edge = i32::try_from(input.lines().next().unwrap().len()).unwrap();
let half_edge = edge / 2;
// parse and store initial 2D grid plane:
let cubes_2d: Vec<ConwayCube> = input
.lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect();
// create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edge {
let from_i = usize::try_from(y * edge + x).unwrap();
let mut dims = vec![half_edge; dim];
dims[dim-1] = x;
dims[dim-2] = y;
let to_i = Position::from(&dims).index_for(edge);
cubes[to_i] = cubes_2d[from_i];
}
}
Ok(Self { cubes, dim, edge })
}
#[must_use]
fn index_size(edge: i32, dim: usize) -> usize {
let mut s = 1_i32;
for _i in 0..dim {
s *= edge;
}
usize::try_from(s).unwrap()
}
#[must_use]
pub fn iter(&self) -> InfiniteGridIter {
InfiniteGridIter {
layout: self.clone(),
}
}
/// Return `ConwayCube` at the given position.
#[must_use]
pub fn cube_at(&self, pos: &Position) -> ConwayCube {
for c in &pos.coords {
if *c < 0 || *c >= self.edge {
return ConwayCube::Void;
}
}
self.cubes[pos.index_for(self.edge)]
}
/// Return count of active cubes.
#[must_use]
pub fn active_cubes(&self) -> usize {
self.cubes.iter().filter(|&c| *c == ConwayCube::Active).count()
}
/// Return count of active neighbor cubes of the cube at the given
/// position.
#[must_use]
pub fn active_neighbors_at(&self, pos: &Position) -> usize {
let mut n_active: usize = 0;
for deltas in (0..self.dim).map(|_i| -1..=1).multi_cartesian_product() {
if deltas.iter().all(|dc| *dc == 0) {
continue;
}
let d_coords: Vec<i32> = pos.coords
.iter()
.enumerate()
.map(|(i, dc)| *dc + deltas[i])
.collect();
let d_pos = Position::from(&d_coords);
if self.cube_at(&d_pos) == ConwayCube::Active {
n_active += 1;
}
}
n_active
}
/// Do one round of cube life. Returns a new grid which is one unit
/// bigger in all directions (its edge increases by 2 in all
/// dimensions).
#[must_use]
pub fn cube_round(&self) -> InfiniteGrid {
let edge = self.edge + 2;
let max_i = InfiniteGrid::index_size(edge, self.dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for coords in (0..self.dim).map(|_i| 0..edge).multi_cartesian_product() {
let from_coords: Vec<i32> = coords.iter().map(|c| c - 1).collect();
let from_pos = Position::from(&from_coords);
let pos = Position::from(&coords);
cubes[pos.index_for(edge)] = self.new_cube_at(&from_pos);
}
InfiniteGrid { cubes, dim: self.dim, edge }
}
fn new_cube_at(&self, pos: &Position) -> ConwayCube {
match self.cube_at(&pos) {
ConwayCube::Active => {
let n = self.active_neighbors_at(&pos);
if n == 2 || n == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
_ => {
if self.active_neighbors_at(&pos) == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const TINY_LAYOUT: &'static str = ".#.\n..#\n###\n";
#[test]
fn test_from_input() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
}
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(&pos));
let pos = Position::from(&[0, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_z() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[-1, 0, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[3, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_y() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, -1, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 3, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_x() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, -1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 3]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_6_rounds() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= N_ROUNDS - 1 {
n_active = g.active_cubes();
break;
}
}
assert_eq!(112, n_active);
}
#[test]
fn | () {
// the full N_ROUNDS takes a while so:
let n_rounds = 1; // = N_ROUNDS;
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= n_rounds - 1 {
n_active = g.active_cubes();
break;
}
}
let expect = if n_rounds == 1 { 3*4 + 5 + 3*4 } else { 848 };
assert_eq!(expect, n_active);
}
}
| test_6_rounds_4d | identifier_name |
lib.rs | use itertools::Itertools;
use std::convert::TryFrom;
use std::fmt;
use std::fs;
pub const N_ROUNDS: usize = 6;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
coords: Vec<i32>,
}
impl Position {
/// Return linear index of position, given `edge` length of grid.
#[must_use]
pub fn index_for(&self, edge: i32) -> usize {
let mut i = 0_i32;
for c in &self.coords {
i = i * edge + c;
}
usize::try_from(i).unwrap()
}
#[must_use]
/// Construct from n-dimensional coordinates.
pub fn from(coords: &[i32]) -> Self {
Self { coords: coords.iter().copied().collect() }
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ConwayCube {
Void,
Inactive,
Active,
}
impl ConwayCube {
/// Construct cube from input character.
#[must_use]
pub fn from_char(cube: char) -> ConwayCube {
match cube {
'.' => ConwayCube::Inactive,
'#' => ConwayCube::Active,
_ => {
let e = format!("invalid cube character {}", cube);
panic!(e);
}
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InfiniteGrid {
cubes: Vec<ConwayCube>,
dim: usize,
edge: i32,
}
impl fmt::Display for InfiniteGrid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let half_edge = self.edge / 2;
let mut s = String::new();
for coords in (0..self.dim).map(|_i| 0..self.edge).multi_cartesian_product() {
if coords[self.dim - 2] == 0 && coords[self.dim - 1] == 0 {
let axes = vec!['z', 'w', 'v', 'u'];
for d in 2..self.dim {
if d > 2 {
s += ", ";
}
let label = format!("{}={}", axes[d - 2], coords[self.dim - d - 1] - half_edge);
s += &label;
}
s += "\n";
}
let pos = Position::from(&coords);
s += match self.cube_at(&pos) {
ConwayCube::Void => "_",
ConwayCube::Inactive => ".",
ConwayCube::Active => "#",
};
if coords[self.dim - 1] >= self.edge - 1 {
s += "\n";
}
}
write!(f, "{}", s)
}
}
pub struct InfiniteGridIter {
layout: InfiniteGrid,
}
impl Iterator for InfiniteGridIter {
type Item = InfiniteGrid;
fn next(&mut self) -> Option<Self::Item> {
let prev_layout = self.layout.clone();
self.layout = prev_layout.cube_round();
Some(self.layout.clone())
}
}
impl InfiniteGrid {
/// Return edge length.
#[must_use]
pub fn edge(&self) -> i32 {
self.edge
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from file at `path`.
///
/// # Errors
///
/// Returns `Err` if the input file cannot be opened, or if line is
/// found with invalid format.
pub fn read_from_file(path: &str, dim: usize) -> Result<InfiniteGrid> {
let s: String = fs::read_to_string(path)?;
InfiniteGrid::from_input(&s, dim)
}
/// Construct `InfiniteGrid` of dimension `dim` by reading initial grid
/// plane from `input` string.
///
/// # Errors
///
/// Returns `Err` if a line is found with invalid format.
pub fn from_input(input: &str, dim: usize) -> Result<InfiniteGrid> {
let edge = i32::try_from(input.lines().next().unwrap().len()).unwrap();
let half_edge = edge / 2;
// parse and store initial 2D grid plane:
let cubes_2d: Vec<ConwayCube> = input
.lines()
.flat_map(|line| line.trim().chars().map(ConwayCube::from_char))
.collect();
// create empty nD grid, and copy initial 2D grid plane to it
// (in the middle of each dimension beyond the first two):
let max_i = InfiniteGrid::index_size(edge, dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for y in 0..edge {
for x in 0..edge {
let from_i = usize::try_from(y * edge + x).unwrap();
let mut dims = vec![half_edge; dim];
dims[dim-1] = x;
dims[dim-2] = y;
let to_i = Position::from(&dims).index_for(edge);
cubes[to_i] = cubes_2d[from_i];
}
}
Ok(Self { cubes, dim, edge })
}
#[must_use]
fn index_size(edge: i32, dim: usize) -> usize {
let mut s = 1_i32;
for _i in 0..dim {
s *= edge;
}
usize::try_from(s).unwrap()
}
#[must_use]
pub fn iter(&self) -> InfiniteGridIter {
InfiniteGridIter {
layout: self.clone(),
}
}
/// Return `ConwayCube` at the given position.
#[must_use]
pub fn cube_at(&self, pos: &Position) -> ConwayCube {
for c in &pos.coords {
if *c < 0 || *c >= self.edge {
return ConwayCube::Void;
}
}
self.cubes[pos.index_for(self.edge)]
}
/// Return count of active cubes.
#[must_use]
pub fn active_cubes(&self) -> usize {
self.cubes.iter().filter(|&c| *c == ConwayCube::Active).count()
}
/// Return count of active neighbor cubes of the cube at the given
/// position.
#[must_use]
pub fn active_neighbors_at(&self, pos: &Position) -> usize {
let mut n_active: usize = 0;
for deltas in (0..self.dim).map(|_i| -1..=1).multi_cartesian_product() {
if deltas.iter().all(|dc| *dc == 0) {
continue;
}
let d_coords: Vec<i32> = pos.coords
.iter()
.enumerate()
.map(|(i, dc)| *dc + deltas[i])
.collect();
let d_pos = Position::from(&d_coords);
if self.cube_at(&d_pos) == ConwayCube::Active {
n_active += 1;
}
}
n_active
}
/// Do one round of cube life. Returns a new grid which is one unit
/// bigger in all directions (its edge increases by 2 in all
/// dimensions).
#[must_use]
pub fn cube_round(&self) -> InfiniteGrid {
let edge = self.edge + 2;
let max_i = InfiniteGrid::index_size(edge, self.dim);
let mut cubes: Vec<ConwayCube> = vec![ConwayCube::Void; max_i];
for coords in (0..self.dim).map(|_i| 0..edge).multi_cartesian_product() {
let from_coords: Vec<i32> = coords.iter().map(|c| c - 1).collect();
let from_pos = Position::from(&from_coords);
let pos = Position::from(&coords);
cubes[pos.index_for(edge)] = self.new_cube_at(&from_pos);
}
InfiniteGrid { cubes, dim: self.dim, edge }
}
fn new_cube_at(&self, pos: &Position) -> ConwayCube {
match self.cube_at(&pos) {
ConwayCube::Active => {
let n = self.active_neighbors_at(&pos);
if n == 2 || n == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
_ => {
if self.active_neighbors_at(&pos) == 3 {
ConwayCube::Active
} else {
ConwayCube::Inactive
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const TINY_LAYOUT: &'static str = ".#.\n..#\n###\n";
#[test]
fn test_from_input() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
assert_eq!(3, grid.edge);
assert_eq!(5, grid.active_cubes());
}
#[test]
fn test_grid_indexing() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, 1]);
assert_eq!(ConwayCube::Active, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 0]);
assert_eq!(ConwayCube::Inactive, grid.cube_at(&pos));
let pos = Position::from(&[0, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_z() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[-1, 0, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[3, 1, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_y() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, -1, 1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 3, 0]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_grid_indexing_void_x() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let pos = Position::from(&[1, 0, -1]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
let pos = Position::from(&[1, 1, 3]);
assert_eq!(ConwayCube::Void, grid.cube_at(&pos));
}
#[test]
fn test_6_rounds() {
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 3).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= N_ROUNDS - 1 {
n_active = g.active_cubes();
break;
}
}
assert_eq!(112, n_active);
}
#[test]
fn test_6_rounds_4d() {
// the full N_ROUNDS takes a while so:
let n_rounds = 1; // = N_ROUNDS;
let grid = InfiniteGrid::from_input(TINY_LAYOUT, 4).unwrap();
let mut n_active: usize = 0;
for (i, g) in grid.iter().enumerate() {
if i >= n_rounds - 1 {
n_active = g.active_cubes();
break;
}
}
let expect = if n_rounds == 1 | else { 848 };
assert_eq!(expect, n_active);
}
}
| { 3*4 + 5 + 3*4 } | conditional_block |
encoder.rs | common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use av_data::pixel::formats::YUV420;
use av_data::pixel::Formaton;
#[derive(Clone, Debug, PartialEq)]
pub struct PSNR {
pub samples: [u32; 4],
pub sse: [u64; 4],
pub psnr: [f64; 4],
}
/// Safe wrapper around `aom_codec_cx_pkt`
#[derive(Clone, Debug)]
pub enum AOMPacket {
Packet(Packet),
Stats(Vec<u8>),
MBStats(Vec<u8>),
PSNR(PSNR),
Custom(Vec<u8>),
}
fn to_buffer(buf: aom_fixed_buf_t) -> Vec<u8> {
let mut v: Vec<u8> = Vec::with_capacity(buf.sz);
unsafe {
ptr::copy_nonoverlapping(buf.buf as *const u8, v.as_mut_ptr(), buf.sz);
v.set_len(buf.sz);
}
v
}
impl AOMPacket {
fn new(pkt: aom_codec_cx_pkt) -> AOMPacket {
match pkt.kind {
aom_codec_cx_pkt_kind::AOM_CODEC_CX_FRAME_PKT => {
let f = unsafe { pkt.data.frame };
let mut p = Packet::with_capacity(f.sz);
unsafe {
ptr::copy_nonoverlapping(f.buf as *const u8, p.data.as_mut_ptr(), f.sz);
p.data.set_len(f.sz);
}
p.t.pts = Some(f.pts);
p.is_key = (f.flags & AOM_FRAME_IS_KEY)!= 0;
AOMPacket::Packet(p)
}
aom_codec_cx_pkt_kind::AOM_CODEC_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.twopass_stats });
AOMPacket::Stats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_FPMB_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.firstpass_mb_stats });
AOMPacket::MBStats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_PSNR_PKT => {
let p = unsafe { pkt.data.psnr };
AOMPacket::PSNR(PSNR {
samples: p.samples,
sse: p.sse,
psnr: p.psnr,
})
}
aom_codec_cx_pkt_kind::AOM_CODEC_CUSTOM_PKT => {
let b = to_buffer(unsafe { pkt.data.raw });
AOMPacket::Custom(b)
}
_ => panic!("No packet defined"),
}
}
}
#[cfg(target_os = "windows")]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as i32;
img.tc = fmt.get_xfer() as i32;
img.mc = fmt.get_matrix() as i32;
}
#[cfg(not(target_os = "windows"))]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as u32;
img.tc = fmt.get_xfer() as u32;
img.mc = fmt.get_matrix() as u32;
}
// TODO: Extend
fn map_formaton(img: &mut aom_image, fmt: &Formaton) {
if fmt == YUV420 {
img.fmt = aom_img_fmt::AOM_IMG_FMT_I420;
} else {
unimplemented!();
}
img.bit_depth = 8;
img.bps = 12;
img.x_chroma_shift = 1;
img.y_chroma_shift = 1;
map_fmt_to_img(img, fmt);
}
fn img_from_frame(frame: &Frame) -> aom_image {
let mut img: aom_image = unsafe { mem::zeroed() };
if let MediaKind::Video(ref v) = frame.kind {
map_formaton(&mut img, &v.format);
img.w = v.width as u32;
img.h = v.height as u32;
img.d_w = v.width as u32;
img.d_h = v.height as u32;
}
// populate the buffers
for i in 0..frame.buf.count() {
let s: &[u8] = frame.buf.as_slice(i).unwrap();
img.planes[i] = s.as_ptr() as *mut u8;
img.stride[i] = frame.buf.linesize(i).unwrap() as i32;
}
img
}
/// AV1 Encoder
pub struct AV1Encoder {
pub(crate) ctx: aom_codec_ctx_t,
pub(crate) iter: aom_codec_iter_t,
}
unsafe impl Send for AV1Encoder {} // TODO: Make sure it cannot be abused
impl AV1Encoder {
/// Create a new encoder using the provided configuration
///
/// You may use `get_encoder` instead.
pub fn new(cfg: &mut AV1EncoderConfig) -> Result<AV1Encoder, aom_codec_err_t::Type> {
let mut ctx = MaybeUninit::uninit();
let ret = unsafe {
aom_codec_enc_init_ver(
ctx.as_mut_ptr(),
aom_codec_av1_cx(),
cfg.cfg(),
0,
AOM_ENCODER_ABI_VERSION as i32,
)
};
match ret {
aom_codec_err_t::AOM_CODEC_OK => {
let ctx = unsafe { ctx.assume_init() };
let mut enc = AV1Encoder {
ctx,
iter: ptr::null(),
};
// Apparently aom 2.0 would crash if a CPUUSED is not set explicitly.
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.expect("Cannot set CPUUSED");
Ok(enc)
}
_ => Err(ret),
}
}
/// Update the encoder parameters after-creation
///
/// It calls `aom_codec_control_`
pub fn control(
&mut self,
id: aome_enc_control_id::Type,
val: i32,
) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_control(&mut self.ctx, id as i32, val) };
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
// TODO: Cache the image information
//
/// Send an uncompressed frame to the encoder
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode`.
///
/// [`get_packet`]: #method.get_packet
pub fn encode(&mut self, frame: &Frame) -> Result<(), aom_codec_err_t::Type> {
let img = img_from_frame(frame);
let ret = unsafe { aom_codec_encode(&mut self.ctx, &img, frame.t.pts.unwrap(), 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Notify the encoder that no more data will be sent
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode` with NULL arguments.
///
/// [`get_packet`]: #method.get_packet
pub fn flush(&mut self) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_encode(&mut self.ctx, ptr::null_mut(), 0, 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Retrieve the compressed data
///
/// To be called until it returns `None`.
///
/// It calls `aom_codec_get_cx_data`.
pub fn get_packet(&mut self) -> Option<AOMPacket> {
let pkt = unsafe { aom_codec_get_cx_data(&mut self.ctx, &mut self.iter) };
if pkt.is_null() {
None
} else {
Some(AOMPacket::new(unsafe { *pkt }))
}
}
}
impl Drop for AV1Encoder {
fn drop(&mut self) {
unsafe { aom_codec_destroy(&mut self.ctx) };
}
}
impl AOMCodec for AV1Encoder {
fn get_context(&mut self) -> &mut aom_codec_ctx {
&mut self.ctx
}
}
#[cfg(feature = "codec-trait")]
mod encoder_trait {
use super::*;
use av_codec::encoder::*;
use av_codec::error::*;
use av_data::frame::ArcFrame;
use av_data::params::{CodecParams, MediaKind, VideoInfo};
use av_data::value::Value;
pub struct Des {
descr: Descr,
}
pub struct Enc {
cfg: AV1EncoderConfig,
enc: Option<AV1Encoder>,
}
impl Descriptor for Des {
type OutputEncoder = Enc;
fn create(&self) -> Self::OutputEncoder {
Enc {
cfg: AV1EncoderConfig::new().unwrap(),
enc: None,
}
}
fn describe(&self) -> &Descr {
&self.descr
}
}
impl Encoder for Enc {
fn | (&mut self) -> Result<()> {
if self.enc.is_none() {
self.cfg
.get_encoder()
.map(|enc| {
self.enc = Some(enc);
})
.map_err(|_err| Error::ConfigurationIncomplete)
} else {
unimplemented!()
}
}
// TODO: have it as default impl?
fn get_extradata(&self) -> Option<Vec<u8>> {
None
}
fn send_frame(&mut self, frame: &ArcFrame) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.encode(frame).map_err(|_| unimplemented!())
}
fn receive_packet(&mut self) -> Result<Packet> {
let enc = self.enc.as_mut().unwrap();
if let Some(p) = enc.get_packet() {
match p {
AOMPacket::Packet(pkt) => Ok(pkt),
_ => unimplemented!(),
}
} else {
Err(Error::MoreDataNeeded)
}
}
fn flush(&mut self) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.flush().map_err(|_| unimplemented!())
}
fn set_option<'a>(&mut self, key: &str, val: Value<'a>) -> Result<()> {
match (key, val) {
("w", Value::U64(v)) => self.cfg.g_w = v as u32,
("h", Value::U64(v)) => self.cfg.g_h = v as u32,
("qmin", Value::U64(v)) => self.cfg.rc_min_quantizer = v as u32,
("qmax", Value::U64(v)) => self.cfg.rc_max_quantizer = v as u32,
("timebase", Value::Pair(num, den)) => {
self.cfg.g_timebase.num = num as i32;
self.cfg.g_timebase.den = den as i32;
}
_ => unimplemented!(),
}
Ok(())
}
fn get_params(&self) -> Result<CodecParams> {
use std::sync::Arc;
Ok(CodecParams {
kind: Some(MediaKind::Video(VideoInfo {
height: self.cfg.g_h as usize,
width: self.cfg.g_w as usize,
format: Some(Arc::new(*YUV420)), // TODO: support more formats
})),
codec_id: Some("av1".to_owned()),
extradata: None,
bit_rate: 0, // TODO: expose the information
convergence_window: 0,
delay: 0,
})
}
fn set_params(&mut self, params: &CodecParams) -> Result<()> {
if let Some(MediaKind::Video(ref info)) = params.kind {
self.cfg.g_w = info.width as u32;
self.cfg.g_h = info.height as u32;
}
Ok(())
}
}
/// AV1 Encoder
///
/// To be used with [av-codec](https://docs.rs/av-codec) `Encoder Context`.
pub const AV1_DESCR: &Des = &Des {
descr: Descr {
codec: "av1",
name: "aom",
desc: "libaom AV1 encoder",
mime: "video/AV1",
},
};
}
#[cfg(feature = "codec-trait")]
pub use self::encoder_trait::AV1_DESCR;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
#[test]
fn init() {
let mut c = AV1EncoderConfig::new().unwrap();
let mut e = c.get_encoder().unwrap();
println!("{}", e.error_to_str());
}
use av_data::rational::*;
use av_data::timeinfo::TimeInfo;
pub fn setup(w: u32, h: u32, t: &TimeInfo) -> AV1Encoder {
if (w % 2)!= 0 || (h % 2)!= 0 {
panic!("Invalid frame size: w: {} h: {}", w, h);
}
let mut cfg = AV1EncoderConfig::new()
.unwrap()
.width(w)
.height(h)
.timebase(t.timebase.unwrap())
.rc_min_quantizer(0)
.rc_min_quantizer(0)
.threads(4)
.pass(aom_enc_pass::AOM_RC_ONE_PASS)
.rc_end_usage(aom_rc_mode::AOM_CQ);
let mut enc = cfg.get_encoder().unwrap();
enc.control(aome_enc_control_id::AOME_SET_CQ_LEVEL, 4)
.unwrap();
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.unwrap();
enc
}
pub fn setup_frame(w: u32, h: u32, t: &TimeInfo) -> Frame {
use av_data::frame::*;
use av_data::pixel::formats;
use std::sync::Arc;
let v = VideoInfo::new(
w as usize,
h as usize,
false,
FrameType::OTHER,
Arc::new(*formats::YUV420),
);
Frame::new_default_frame(v, Some(t.clone()))
}
#[test]
fn encode() {
let w = 200;
let h = 200;
let t = TimeInfo {
pts: Some(0),
dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
};
let mut e = setup(w, h, &t);
let mut f = setup_frame(w, h, &t);
let mut out = 0;
// TODO write some pattern
for i in 0..100 {
e.encode(&f).unwrap();
f.t.pts = Some(i);
// println!("{:#?}", f);
loop {
let p = e.get_packet();
if p.is_none() {
break;
} else {
out = 1;
// println!("{:#?}", p.unwrap());
}
}
}
if out!= 1 {
panic!("No packet produced");
}
}
#[cfg(all(test, feature = "codec-trait"))]
#[test]
fn encode_codec_trait() {
use super::AV1_DESCR;
use av_codec::common::CodecList;
use av_codec::encoder::*;
use av_codec::error::*;
use std::sync::Arc;
let encoders = Codecs::from_list(&[AV1_DESCR]);
let mut ctx = Context::by_name(&encoders, "av1").unwrap();
let w = 200;
let h = 200;
ctx.set_option("w", u64::from(w)).unwrap();
ctx.set_option("h", u64::from(h)).unwrap();
ctx.set_option("timebase", (1, 1000)).unwrap();
ctx.set_option("qmin", 0u64).unwrap();
ctx.set_option("qmax", 0u64).unwrap();
let t = TimeInfo {
pts: Some(0),
dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
};
ctx.configure().unwrap();
let mut f = Arc::new(setup_frame(w, h, &t));
let mut out = 0;
for i in 0..100 {
Arc::get_mut(&mut f).unwrap().t.pts = Some(i);
println!("Sending {}", i);
ctx.send_frame(&f).unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => unimplemented!(),
},
}
}
}
ctx.flush().unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => | configure | identifier_name |
encoder.rs | common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use av_data::pixel::formats::YUV420;
use av_data::pixel::Formaton;
#[derive(Clone, Debug, PartialEq)]
pub struct PSNR {
pub samples: [u32; 4],
pub sse: [u64; 4],
pub psnr: [f64; 4],
}
/// Safe wrapper around `aom_codec_cx_pkt`
#[derive(Clone, Debug)]
pub enum AOMPacket {
Packet(Packet),
Stats(Vec<u8>),
MBStats(Vec<u8>),
PSNR(PSNR),
Custom(Vec<u8>),
}
fn to_buffer(buf: aom_fixed_buf_t) -> Vec<u8> {
let mut v: Vec<u8> = Vec::with_capacity(buf.sz);
unsafe {
ptr::copy_nonoverlapping(buf.buf as *const u8, v.as_mut_ptr(), buf.sz);
v.set_len(buf.sz);
}
v
}
impl AOMPacket {
fn new(pkt: aom_codec_cx_pkt) -> AOMPacket {
match pkt.kind {
aom_codec_cx_pkt_kind::AOM_CODEC_CX_FRAME_PKT => {
let f = unsafe { pkt.data.frame };
let mut p = Packet::with_capacity(f.sz);
unsafe {
ptr::copy_nonoverlapping(f.buf as *const u8, p.data.as_mut_ptr(), f.sz);
p.data.set_len(f.sz);
}
p.t.pts = Some(f.pts);
p.is_key = (f.flags & AOM_FRAME_IS_KEY)!= 0;
AOMPacket::Packet(p)
}
aom_codec_cx_pkt_kind::AOM_CODEC_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.twopass_stats });
AOMPacket::Stats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_FPMB_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.firstpass_mb_stats });
AOMPacket::MBStats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_PSNR_PKT => {
let p = unsafe { pkt.data.psnr };
AOMPacket::PSNR(PSNR {
samples: p.samples,
sse: p.sse,
psnr: p.psnr,
})
}
aom_codec_cx_pkt_kind::AOM_CODEC_CUSTOM_PKT => {
let b = to_buffer(unsafe { pkt.data.raw });
AOMPacket::Custom(b)
}
_ => panic!("No packet defined"),
}
}
}
#[cfg(target_os = "windows")]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as i32;
img.tc = fmt.get_xfer() as i32;
img.mc = fmt.get_matrix() as i32;
}
#[cfg(not(target_os = "windows"))]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as u32;
img.tc = fmt.get_xfer() as u32;
img.mc = fmt.get_matrix() as u32;
}
// TODO: Extend
fn map_formaton(img: &mut aom_image, fmt: &Formaton) {
if fmt == YUV420 {
img.fmt = aom_img_fmt::AOM_IMG_FMT_I420;
} else {
unimplemented!();
}
img.bit_depth = 8;
img.bps = 12;
img.x_chroma_shift = 1;
img.y_chroma_shift = 1;
map_fmt_to_img(img, fmt);
}
fn img_from_frame(frame: &Frame) -> aom_image {
let mut img: aom_image = unsafe { mem::zeroed() };
if let MediaKind::Video(ref v) = frame.kind {
map_formaton(&mut img, &v.format);
img.w = v.width as u32;
img.h = v.height as u32;
img.d_w = v.width as u32;
img.d_h = v.height as u32;
}
// populate the buffers
for i in 0..frame.buf.count() {
let s: &[u8] = frame.buf.as_slice(i).unwrap();
img.planes[i] = s.as_ptr() as *mut u8;
img.stride[i] = frame.buf.linesize(i).unwrap() as i32;
}
img
}
/// AV1 Encoder
pub struct AV1Encoder {
pub(crate) ctx: aom_codec_ctx_t,
pub(crate) iter: aom_codec_iter_t,
}
unsafe impl Send for AV1Encoder {} // TODO: Make sure it cannot be abused
impl AV1Encoder {
/// Create a new encoder using the provided configuration
///
/// You may use `get_encoder` instead.
pub fn new(cfg: &mut AV1EncoderConfig) -> Result<AV1Encoder, aom_codec_err_t::Type> {
let mut ctx = MaybeUninit::uninit();
let ret = unsafe {
aom_codec_enc_init_ver(
ctx.as_mut_ptr(),
aom_codec_av1_cx(),
cfg.cfg(),
0,
AOM_ENCODER_ABI_VERSION as i32,
)
};
match ret {
aom_codec_err_t::AOM_CODEC_OK => {
let ctx = unsafe { ctx.assume_init() };
let mut enc = AV1Encoder {
ctx,
iter: ptr::null(),
};
// Apparently aom 2.0 would crash if a CPUUSED is not set explicitly.
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.expect("Cannot set CPUUSED");
Ok(enc)
}
_ => Err(ret),
}
}
/// Update the encoder parameters after-creation
///
/// It calls `aom_codec_control_`
pub fn control(
&mut self,
id: aome_enc_control_id::Type,
val: i32,
) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_control(&mut self.ctx, id as i32, val) };
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
// TODO: Cache the image information
//
/// Send an uncompressed frame to the encoder
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode`.
///
/// [`get_packet`]: #method.get_packet
pub fn encode(&mut self, frame: &Frame) -> Result<(), aom_codec_err_t::Type> {
let img = img_from_frame(frame);
let ret = unsafe { aom_codec_encode(&mut self.ctx, &img, frame.t.pts.unwrap(), 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Notify the encoder that no more data will be sent
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode` with NULL arguments.
///
/// [`get_packet`]: #method.get_packet
pub fn flush(&mut self) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_encode(&mut self.ctx, ptr::null_mut(), 0, 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Retrieve the compressed data
///
/// To be called until it returns `None`.
///
/// It calls `aom_codec_get_cx_data`.
pub fn get_packet(&mut self) -> Option<AOMPacket> {
let pkt = unsafe { aom_codec_get_cx_data(&mut self.ctx, &mut self.iter) };
if pkt.is_null() {
None
} else {
Some(AOMPacket::new(unsafe { *pkt }))
}
}
}
impl Drop for AV1Encoder {
fn drop(&mut self) {
unsafe { aom_codec_destroy(&mut self.ctx) };
}
}
impl AOMCodec for AV1Encoder {
fn get_context(&mut self) -> &mut aom_codec_ctx {
&mut self.ctx
}
}
#[cfg(feature = "codec-trait")]
mod encoder_trait {
use super::*;
use av_codec::encoder::*;
use av_codec::error::*;
use av_data::frame::ArcFrame;
use av_data::params::{CodecParams, MediaKind, VideoInfo};
use av_data::value::Value;
pub struct Des {
descr: Descr,
}
pub struct Enc {
cfg: AV1EncoderConfig,
enc: Option<AV1Encoder>,
}
impl Descriptor for Des {
type OutputEncoder = Enc;
fn create(&self) -> Self::OutputEncoder {
Enc {
cfg: AV1EncoderConfig::new().unwrap(),
enc: None,
}
}
fn describe(&self) -> &Descr {
&self.descr
}
}
impl Encoder for Enc {
fn configure(&mut self) -> Result<()> {
if self.enc.is_none() {
self.cfg
.get_encoder()
.map(|enc| {
self.enc = Some(enc);
})
.map_err(|_err| Error::ConfigurationIncomplete)
} else {
unimplemented!()
}
}
// TODO: have it as default impl?
fn get_extradata(&self) -> Option<Vec<u8>> {
None
}
fn send_frame(&mut self, frame: &ArcFrame) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.encode(frame).map_err(|_| unimplemented!())
}
fn receive_packet(&mut self) -> Result<Packet> {
let enc = self.enc.as_mut().unwrap();
if let Some(p) = enc.get_packet() {
match p {
AOMPacket::Packet(pkt) => Ok(pkt),
_ => unimplemented!(),
}
} else {
Err(Error::MoreDataNeeded)
}
}
fn flush(&mut self) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.flush().map_err(|_| unimplemented!())
}
fn set_option<'a>(&mut self, key: &str, val: Value<'a>) -> Result<()> {
match (key, val) {
("w", Value::U64(v)) => self.cfg.g_w = v as u32,
("h", Value::U64(v)) => self.cfg.g_h = v as u32,
("qmin", Value::U64(v)) => self.cfg.rc_min_quantizer = v as u32,
("qmax", Value::U64(v)) => self.cfg.rc_max_quantizer = v as u32,
("timebase", Value::Pair(num, den)) => {
self.cfg.g_timebase.num = num as i32;
self.cfg.g_timebase.den = den as i32;
}
_ => unimplemented!(),
}
Ok(())
}
fn get_params(&self) -> Result<CodecParams> {
use std::sync::Arc;
Ok(CodecParams {
kind: Some(MediaKind::Video(VideoInfo {
height: self.cfg.g_h as usize,
width: self.cfg.g_w as usize,
format: Some(Arc::new(*YUV420)), // TODO: support more formats
})),
codec_id: Some("av1".to_owned()),
extradata: None,
bit_rate: 0, // TODO: expose the information
convergence_window: 0,
delay: 0,
})
}
fn set_params(&mut self, params: &CodecParams) -> Result<()> {
if let Some(MediaKind::Video(ref info)) = params.kind {
self.cfg.g_w = info.width as u32;
self.cfg.g_h = info.height as u32;
}
Ok(())
}
}
/// AV1 Encoder
///
/// To be used with [av-codec](https://docs.rs/av-codec) `Encoder Context`.
pub const AV1_DESCR: &Des = &Des {
descr: Descr {
codec: "av1",
name: "aom",
desc: "libaom AV1 encoder",
mime: "video/AV1",
},
};
}
#[cfg(feature = "codec-trait")]
pub use self::encoder_trait::AV1_DESCR;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
#[test]
fn init() {
let mut c = AV1EncoderConfig::new().unwrap();
let mut e = c.get_encoder().unwrap();
println!("{}", e.error_to_str());
}
use av_data::rational::*;
use av_data::timeinfo::TimeInfo;
pub fn setup(w: u32, h: u32, t: &TimeInfo) -> AV1Encoder {
if (w % 2)!= 0 || (h % 2)!= 0 {
panic!("Invalid frame size: w: {} h: {}", w, h);
}
let mut cfg = AV1EncoderConfig::new()
.unwrap()
.width(w)
.height(h)
.timebase(t.timebase.unwrap())
.rc_min_quantizer(0)
.rc_min_quantizer(0)
.threads(4)
.pass(aom_enc_pass::AOM_RC_ONE_PASS)
.rc_end_usage(aom_rc_mode::AOM_CQ);
let mut enc = cfg.get_encoder().unwrap();
enc.control(aome_enc_control_id::AOME_SET_CQ_LEVEL, 4)
.unwrap();
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.unwrap();
enc
}
pub fn setup_frame(w: u32, h: u32, t: &TimeInfo) -> Frame {
use av_data::frame::*;
use av_data::pixel::formats;
use std::sync::Arc;
let v = VideoInfo::new(
w as usize,
h as usize,
false,
FrameType::OTHER,
Arc::new(*formats::YUV420),
);
Frame::new_default_frame(v, Some(t.clone()))
}
#[test]
fn encode() {
let w = 200;
let h = 200;
let t = TimeInfo {
pts: Some(0),
dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
};
let mut e = setup(w, h, &t);
let mut f = setup_frame(w, h, &t);
let mut out = 0;
// TODO write some pattern
for i in 0..100 {
e.encode(&f).unwrap();
f.t.pts = Some(i);
// println!("{:#?}", f);
loop {
let p = e.get_packet();
if p.is_none() {
break;
} else {
out = 1;
// println!("{:#?}", p.unwrap());
}
}
}
if out!= 1 {
panic!("No packet produced");
}
}
#[cfg(all(test, feature = "codec-trait"))]
#[test]
fn encode_codec_trait() | dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
};
ctx.configure().unwrap();
let mut f = Arc::new(setup_frame(w, h, &t));
let mut out = 0;
for i in 0..100 {
Arc::get_mut(&mut f).unwrap().t.pts = Some(i);
println!("Sending {}", i);
ctx.send_frame(&f).unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => unimplemented!(),
},
}
}
}
ctx.flush().unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => unimplemented | {
use super::AV1_DESCR;
use av_codec::common::CodecList;
use av_codec::encoder::*;
use av_codec::error::*;
use std::sync::Arc;
let encoders = Codecs::from_list(&[AV1_DESCR]);
let mut ctx = Context::by_name(&encoders, "av1").unwrap();
let w = 200;
let h = 200;
ctx.set_option("w", u64::from(w)).unwrap();
ctx.set_option("h", u64::from(h)).unwrap();
ctx.set_option("timebase", (1, 1000)).unwrap();
ctx.set_option("qmin", 0u64).unwrap();
ctx.set_option("qmax", 0u64).unwrap();
let t = TimeInfo {
pts: Some(0), | identifier_body |
encoder.rs | ::common::AOMCodec;
use crate::ffi::*;
use std::mem::{self, MaybeUninit};
use std::ptr;
use av_data::frame::{Frame, FrameBufferConv, MediaKind};
use av_data::packet::Packet;
use av_data::pixel::formats::YUV420;
use av_data::pixel::Formaton;
#[derive(Clone, Debug, PartialEq)]
pub struct PSNR {
pub samples: [u32; 4],
pub sse: [u64; 4],
pub psnr: [f64; 4],
}
/// Safe wrapper around `aom_codec_cx_pkt`
#[derive(Clone, Debug)]
pub enum AOMPacket {
Packet(Packet),
Stats(Vec<u8>),
MBStats(Vec<u8>),
PSNR(PSNR),
Custom(Vec<u8>),
}
fn to_buffer(buf: aom_fixed_buf_t) -> Vec<u8> {
let mut v: Vec<u8> = Vec::with_capacity(buf.sz);
unsafe {
ptr::copy_nonoverlapping(buf.buf as *const u8, v.as_mut_ptr(), buf.sz);
v.set_len(buf.sz);
}
v
}
impl AOMPacket {
fn new(pkt: aom_codec_cx_pkt) -> AOMPacket {
match pkt.kind {
aom_codec_cx_pkt_kind::AOM_CODEC_CX_FRAME_PKT => {
let f = unsafe { pkt.data.frame };
let mut p = Packet::with_capacity(f.sz);
unsafe {
ptr::copy_nonoverlapping(f.buf as *const u8, p.data.as_mut_ptr(), f.sz);
p.data.set_len(f.sz);
}
p.t.pts = Some(f.pts);
p.is_key = (f.flags & AOM_FRAME_IS_KEY)!= 0;
AOMPacket::Packet(p)
}
aom_codec_cx_pkt_kind::AOM_CODEC_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.twopass_stats });
AOMPacket::Stats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_FPMB_STATS_PKT => {
let b = to_buffer(unsafe { pkt.data.firstpass_mb_stats });
AOMPacket::MBStats(b)
}
aom_codec_cx_pkt_kind::AOM_CODEC_PSNR_PKT => {
let p = unsafe { pkt.data.psnr };
AOMPacket::PSNR(PSNR {
samples: p.samples,
sse: p.sse,
psnr: p.psnr,
})
}
aom_codec_cx_pkt_kind::AOM_CODEC_CUSTOM_PKT => {
let b = to_buffer(unsafe { pkt.data.raw });
AOMPacket::Custom(b)
}
_ => panic!("No packet defined"),
}
}
}
#[cfg(target_os = "windows")]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as i32;
img.tc = fmt.get_xfer() as i32;
img.mc = fmt.get_matrix() as i32;
}
#[cfg(not(target_os = "windows"))]
fn map_fmt_to_img(img: &mut aom_image, fmt: &Formaton) {
img.cp = fmt.get_primaries() as u32;
img.tc = fmt.get_xfer() as u32;
img.mc = fmt.get_matrix() as u32;
}
// TODO: Extend
fn map_formaton(img: &mut aom_image, fmt: &Formaton) {
if fmt == YUV420 {
img.fmt = aom_img_fmt::AOM_IMG_FMT_I420;
} else {
unimplemented!();
}
img.bit_depth = 8;
img.bps = 12;
img.x_chroma_shift = 1;
img.y_chroma_shift = 1;
map_fmt_to_img(img, fmt);
}
fn img_from_frame(frame: &Frame) -> aom_image {
let mut img: aom_image = unsafe { mem::zeroed() };
if let MediaKind::Video(ref v) = frame.kind {
map_formaton(&mut img, &v.format);
img.w = v.width as u32;
img.h = v.height as u32;
img.d_w = v.width as u32;
img.d_h = v.height as u32;
}
// populate the buffers
for i in 0..frame.buf.count() {
let s: &[u8] = frame.buf.as_slice(i).unwrap();
img.planes[i] = s.as_ptr() as *mut u8;
img.stride[i] = frame.buf.linesize(i).unwrap() as i32;
}
img
}
/// AV1 Encoder
pub struct AV1Encoder {
pub(crate) ctx: aom_codec_ctx_t,
pub(crate) iter: aom_codec_iter_t,
}
unsafe impl Send for AV1Encoder {} // TODO: Make sure it cannot be abused
impl AV1Encoder {
/// Create a new encoder using the provided configuration
///
/// You may use `get_encoder` instead.
pub fn new(cfg: &mut AV1EncoderConfig) -> Result<AV1Encoder, aom_codec_err_t::Type> {
let mut ctx = MaybeUninit::uninit();
let ret = unsafe {
aom_codec_enc_init_ver(
ctx.as_mut_ptr(),
aom_codec_av1_cx(),
cfg.cfg(),
0,
AOM_ENCODER_ABI_VERSION as i32,
)
};
match ret {
aom_codec_err_t::AOM_CODEC_OK => {
let ctx = unsafe { ctx.assume_init() };
let mut enc = AV1Encoder {
ctx,
iter: ptr::null(),
};
// Apparently aom 2.0 would crash if a CPUUSED is not set explicitly.
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.expect("Cannot set CPUUSED");
Ok(enc)
}
_ => Err(ret),
}
}
/// Update the encoder parameters after-creation
///
/// It calls `aom_codec_control_`
pub fn control(
&mut self,
id: aome_enc_control_id::Type,
val: i32,
) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_control(&mut self.ctx, id as i32, val) };
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
// TODO: Cache the image information
//
/// Send an uncompressed frame to the encoder
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode`.
///
/// [`get_packet`]: #method.get_packet
pub fn encode(&mut self, frame: &Frame) -> Result<(), aom_codec_err_t::Type> {
let img = img_from_frame(frame);
let ret = unsafe { aom_codec_encode(&mut self.ctx, &img, frame.t.pts.unwrap(), 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Notify the encoder that no more data will be sent
///
/// Call [`get_packet`] to receive the compressed data.
///
/// It calls `aom_codec_encode` with NULL arguments.
///
/// [`get_packet`]: #method.get_packet
pub fn flush(&mut self) -> Result<(), aom_codec_err_t::Type> {
let ret = unsafe { aom_codec_encode(&mut self.ctx, ptr::null_mut(), 0, 1, 0) };
self.iter = ptr::null();
match ret {
aom_codec_err_t::AOM_CODEC_OK => Ok(()),
_ => Err(ret),
}
}
/// Retrieve the compressed data
///
/// To be called until it returns `None`.
///
/// It calls `aom_codec_get_cx_data`.
pub fn get_packet(&mut self) -> Option<AOMPacket> {
let pkt = unsafe { aom_codec_get_cx_data(&mut self.ctx, &mut self.iter) };
if pkt.is_null() {
None
} else {
Some(AOMPacket::new(unsafe { *pkt }))
}
}
}
impl Drop for AV1Encoder {
fn drop(&mut self) {
unsafe { aom_codec_destroy(&mut self.ctx) };
}
}
impl AOMCodec for AV1Encoder {
fn get_context(&mut self) -> &mut aom_codec_ctx {
&mut self.ctx
}
}
#[cfg(feature = "codec-trait")]
mod encoder_trait {
use super::*;
use av_codec::encoder::*;
use av_codec::error::*;
use av_data::frame::ArcFrame;
use av_data::params::{CodecParams, MediaKind, VideoInfo};
use av_data::value::Value;
pub struct Des {
descr: Descr,
}
pub struct Enc {
cfg: AV1EncoderConfig,
enc: Option<AV1Encoder>,
}
impl Descriptor for Des {
type OutputEncoder = Enc;
fn create(&self) -> Self::OutputEncoder {
Enc {
cfg: AV1EncoderConfig::new().unwrap(),
enc: None,
}
}
fn describe(&self) -> &Descr {
&self.descr
}
}
impl Encoder for Enc {
fn configure(&mut self) -> Result<()> {
if self.enc.is_none() {
self.cfg
.get_encoder()
.map(|enc| {
self.enc = Some(enc);
})
.map_err(|_err| Error::ConfigurationIncomplete)
} else {
unimplemented!()
}
}
// TODO: have it as default impl?
fn get_extradata(&self) -> Option<Vec<u8>> {
None
}
fn send_frame(&mut self, frame: &ArcFrame) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.encode(frame).map_err(|_| unimplemented!())
}
fn receive_packet(&mut self) -> Result<Packet> {
let enc = self.enc.as_mut().unwrap();
if let Some(p) = enc.get_packet() {
match p {
AOMPacket::Packet(pkt) => Ok(pkt),
_ => unimplemented!(),
}
} else {
Err(Error::MoreDataNeeded)
}
}
fn flush(&mut self) -> Result<()> {
let enc = self.enc.as_mut().unwrap();
enc.flush().map_err(|_| unimplemented!())
}
fn set_option<'a>(&mut self, key: &str, val: Value<'a>) -> Result<()> {
match (key, val) {
("w", Value::U64(v)) => self.cfg.g_w = v as u32,
("h", Value::U64(v)) => self.cfg.g_h = v as u32,
("qmin", Value::U64(v)) => self.cfg.rc_min_quantizer = v as u32,
("qmax", Value::U64(v)) => self.cfg.rc_max_quantizer = v as u32,
("timebase", Value::Pair(num, den)) => {
self.cfg.g_timebase.num = num as i32;
self.cfg.g_timebase.den = den as i32;
}
_ => unimplemented!(),
}
Ok(())
}
fn get_params(&self) -> Result<CodecParams> {
use std::sync::Arc;
Ok(CodecParams {
kind: Some(MediaKind::Video(VideoInfo {
height: self.cfg.g_h as usize,
width: self.cfg.g_w as usize,
format: Some(Arc::new(*YUV420)), // TODO: support more formats
})),
codec_id: Some("av1".to_owned()),
extradata: None,
bit_rate: 0, // TODO: expose the information
convergence_window: 0,
delay: 0,
})
}
fn set_params(&mut self, params: &CodecParams) -> Result<()> {
if let Some(MediaKind::Video(ref info)) = params.kind {
self.cfg.g_w = info.width as u32;
self.cfg.g_h = info.height as u32;
}
Ok(())
}
}
/// AV1 Encoder
///
/// To be used with [av-codec](https://docs.rs/av-codec) `Encoder Context`.
pub const AV1_DESCR: &Des = &Des {
descr: Descr {
codec: "av1",
name: "aom",
desc: "libaom AV1 encoder",
mime: "video/AV1",
},
};
}
#[cfg(feature = "codec-trait")]
pub use self::encoder_trait::AV1_DESCR;
#[cfg(test)]
pub(crate) mod tests {
use super::*;
#[test]
fn init() {
let mut c = AV1EncoderConfig::new().unwrap();
let mut e = c.get_encoder().unwrap();
println!("{}", e.error_to_str());
}
use av_data::rational::*;
use av_data::timeinfo::TimeInfo;
pub fn setup(w: u32, h: u32, t: &TimeInfo) -> AV1Encoder {
if (w % 2)!= 0 || (h % 2)!= 0 {
panic!("Invalid frame size: w: {} h: {}", w, h);
}
let mut cfg = AV1EncoderConfig::new()
.unwrap()
.width(w)
.height(h)
.timebase(t.timebase.unwrap())
.rc_min_quantizer(0)
.rc_min_quantizer(0)
.threads(4)
.pass(aom_enc_pass::AOM_RC_ONE_PASS)
.rc_end_usage(aom_rc_mode::AOM_CQ);
let mut enc = cfg.get_encoder().unwrap();
enc.control(aome_enc_control_id::AOME_SET_CQ_LEVEL, 4)
.unwrap();
enc.control(aome_enc_control_id::AOME_SET_CPUUSED, 2)
.unwrap();
enc
}
pub fn setup_frame(w: u32, h: u32, t: &TimeInfo) -> Frame {
use av_data::frame::*;
use av_data::pixel::formats;
use std::sync::Arc;
let v = VideoInfo::new(
w as usize,
h as usize,
false,
FrameType::OTHER,
Arc::new(*formats::YUV420),
);
Frame::new_default_frame(v, Some(t.clone()))
}
#[test]
fn encode() {
let w = 200;
let h = 200;
let t = TimeInfo {
pts: Some(0),
dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
}; |
let mut e = setup(w, h, &t);
let mut f = setup_frame(w, h, &t);
let mut out = 0;
// TODO write some pattern
for i in 0..100 {
e.encode(&f).unwrap();
f.t.pts = Some(i);
// println!("{:#?}", f);
loop {
let p = e.get_packet();
if p.is_none() {
break;
} else {
out = 1;
// println!("{:#?}", p.unwrap());
}
}
}
if out!= 1 {
panic!("No packet produced");
}
}
#[cfg(all(test, feature = "codec-trait"))]
#[test]
fn encode_codec_trait() {
use super::AV1_DESCR;
use av_codec::common::CodecList;
use av_codec::encoder::*;
use av_codec::error::*;
use std::sync::Arc;
let encoders = Codecs::from_list(&[AV1_DESCR]);
let mut ctx = Context::by_name(&encoders, "av1").unwrap();
let w = 200;
let h = 200;
ctx.set_option("w", u64::from(w)).unwrap();
ctx.set_option("h", u64::from(h)).unwrap();
ctx.set_option("timebase", (1, 1000)).unwrap();
ctx.set_option("qmin", 0u64).unwrap();
ctx.set_option("qmax", 0u64).unwrap();
let t = TimeInfo {
pts: Some(0),
dts: Some(0),
duration: Some(1),
timebase: Some(Rational64::new(1, 1000)),
user_private: None,
};
ctx.configure().unwrap();
let mut f = Arc::new(setup_frame(w, h, &t));
let mut out = 0;
for i in 0..100 {
Arc::get_mut(&mut f).unwrap().t.pts = Some(i);
println!("Sending {}", i);
ctx.send_frame(&f).unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => unimplemented!(),
},
}
}
}
ctx.flush().unwrap();
loop {
match ctx.receive_packet() {
Ok(p) => {
println!("{:#?}", p);
out = 1
}
Err(e) => match e {
Error::MoreDataNeeded => break,
_ => unimplemented | random_line_split |
|
main.rs | Find a better way.
let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) };
let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref());
unsafe { std::mem::forget(temporary_process); }
ret
})?;
println!("Open /dev/nvhost-as-gpu");
let (nvasgpu, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvhost-as-gpu"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Open /dev/nvmap");
let (nvmap, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvmap"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Initialize vi");
let vi_m = nn::visrv::sf::IManagerRootService::new()?;
println!("get_display_service");
let disp_svc = vi_m.get_display_service(1)?;
println!("get_relay_service");
let relay_svc = disp_svc.get_relay_service()?;
println!("get_system_display_service");
let system_disp_svc = disp_svc.get_system_display_service()?;
println!("get_manager_display_service");
let manager_disp_svc = disp_svc.get_manager_display_service()?;
println!("Open display");
let display_id = {
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
disp_svc.open_display(display)?
};
println!("Open a layer");
let layer_id = manager_disp_svc.create_managed_layer(1, display_id, 0)?;
let binder_id = {
let mut parcel = RawParcel::default();
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
let _window_size = disp_svc.open_layer(display, layer_id, 0, parcel.as_bytes_mut())?;
let mut reader = parcel.into_parcel_reader();
let fbo = FlatBinderObject::from_parcel(&mut reader);
let binder = fbo.inner as i32;
relay_svc.adjust_refcount(binder, 1, 0)?;
relay_svc.adjust_refcount(binder, 1, 1)?;
binder
};
// Connect to the IGBP. Take a look at the following link for reference.
// https://android.googlesource.com/platform/frameworks/native/+/e2786ea5aec3a12d948feb85ffbb535fc89c0fe6/libs/gui/IGraphicBufferProducer.cpp#297
println!("Connect to the IGBP");
let queue_buffer_output = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(0); // IProducerListener is null because we don't support it in MegatonHammer (nor in libt) yet.
parcel.write_u32(2); // API
parcel.write_u32(0); // ProducerControlledByApp.
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, CONNECT, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut reader = parcel_out.into_parcel_reader();
let qbo = QueueBufferOutput::from_parcel(&mut reader);
if reader.read_u32()!= 0 {
println!("Failed to connect to igbp");
return Ok(());
}
qbo
};
println!("Allocate framebuffers");
let mut mem : Vec<BufferMemory> = Vec::with_capacity(3);
unsafe { mem.set_len(3); }
// Disables caching when talking to the gpu.
unsafe { svc::set_memory_attribute(mem.as_mut_ptr() as _, mem.len() * std::mem::size_of::<BufferMemory>(), 0x8, 0x8).expect("Failed to set memory attribute"); }
let gpu_buffer = {
let mut create = NvMapIocCreateArgs {
size: (mem.len() * std::mem::size_of::<BufferMemory>()) as u32,
handle: 0
};
println!("NVMAP_IOC_CREATE {:?} ({:?})", create, unsafe { std::mem::transmute::<&NvMapIocCreateArgs, &[u8; std::mem::size_of::<NvMapIocCreateArgs>()]>(&create) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_CREATE,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&create as *const NvMapIocCreateArgs as *const u8, std::mem::size_of::<NvMapIocCreateArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut create as *mut NvMapIocCreateArgs as *mut u8, std::mem::size_of::<NvMapIocCreateArgs>()) })?;
if ret!= 0 |
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
heapmask: 0,
flags: 0,
align: gpu_buffer.alignment,
kind: gpu_buffer.kind,
pad: [0; 7],
addr: mem.as_mut_ptr() as u64
};
println!("NVMAP_IOC_ALLOC {:?} ({:?})", alloc, unsafe { std::mem::transmute::<&NvMapIocAllocArgs, &[u8; std::mem::size_of::<NvMapIocAllocArgs>()]>(&alloc) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_ALLOC,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&alloc as *const NvMapIocAllocArgs as *const u8, std::mem::size_of::<NvMapIocAllocArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut alloc as *mut NvMapIocAllocArgs as *mut u8, std::mem::size_of::<NvMapIocAllocArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
let mut buffers = Vec::with_capacity(3);
for i in 0..3 {
buffers.push(GraphicBuffer {
width: queue_buffer_output.width,
height: queue_buffer_output.height,
stride: queue_buffer_output.width,
format: 1, // RGBA_8888
usage: 0xb00, // TODO: Wat?
gpu_buffer: &gpu_buffer,
index: i,
offset_gpu_buffer: 0x3c0000 * i
});
}
buffers
};
println!("Tell IGBP about the buffers");
for (i, buf) in buffers.iter().enumerate() {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(i as u32); // slot
parcel.write_u32(1); // Unknown
parcel.write_u32(0x16c); // Flattened GraphicsBuffer length
parcel.write_u32(0); // Unknown
buf.write_to_parcel(&mut parcel);
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, SET_PREALLOCATED_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
}
println!("Set scaling mode");
disp_svc.set_layer_scaling_mode(2, layer_id)?;
println!("Add layer to stack");
for stack in [0x0, 0x2, 0x4, 0x5, 0xA].iter() {
manager_disp_svc.add_to_layer_stack(*stack, layer_id)?;
}
println!("Set Z layer");
system_disp_svc.set_layer_z(layer_id, 2)?;
println!("Loading image from FERRIS");
let image = BMPDecoder::new(Cursor::new(&FERRIS[..]));
println!("Getting frame");
let frame = image.into_frames()?.next().unwrap().into_buffer();
//println!("Resizing FERRIS");
//let frame = image::imageops::resize(&image.into_frames()?.next().unwrap().into_buffer(), 1280, 760, image::FilterType::Lanczos3);
let vevent = unsafe { Event::from_kobject(disp_svc.get_display_vsync_event(display_id)?) };
for _ in 0..60 {
println!("Dequeue buffer");
let slot = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(1); // Pixel format
parcel.write_u32(1280); // width
parcel.write_u32(720); // height
parcel.write_u32(0); // get_frame_timestamp
parcel.write_u32(0xb00); // usage
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, DEQUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
let mut parcel_out = parcel_out.into_parcel_reader();
let slot = parcel_out.read_u32();
// Read fence
parcel_out.0.seek(SeekFrom::Current(44));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
slot
};
// Request buffer if it hasn't been requested already.
println!("Request buffer {}", slot);
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, REQUEST_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
let non_null = parcel_out.read_u32()!= 0;
if non_null {
let len = parcel_out.read_u32();
if len!= 0x16c {
println!("Invalid length: {}", len);
return Ok(())
}
let unk = parcel_out.read_u32();
// TODO: Get graphicbuffer.
parcel_out.0.seek(SeekFrom::Current(0x16c));
}
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
// Blit
println!("Blit");
{
fn pdep(mask: u32, mut value: u32) -> u32 {
let mut out = 0;
for shift in 0..32 {
let bit = 1 << shift;
if mask & bit!= 0 {
if value & 1!= 0 {
out |= bit
}
value >>= 1;
}
}
out
}
fn swizzle_x(v: u32) -> u32 { pdep(!0x7B4, v) }
fn swizzle_y(v: u32) -> u32 { pdep(0x7B4, v) }
let x0 = 0;
let y0 = 0;
let mut offs_x0 = swizzle_x(x0);
let mut offs_y = swizzle_y(y0);
let x_mask = swizzle_x(!0);
let y_mask = swizzle_y(!0);
let incr_y = swizzle_x(128 * 10);
let tile_height = 128;
offs_x0 += incr_y * (y0 / tile_height);
// TODO: Add clipping.
for y in 0..frame.height() {
let mut offs_x = offs_x0;
for x in 0..frame.width() {
let pixel = frame.get_pixel(x, y);
mem[slot as usize][offs_y as usize + offs_x as usize] = LE::read_u32(pixel.channels());
offs_x = offs_x.wrapping_sub(x_mask) & x_mask;
}
offs_y = offs_y.wrapping_sub(y_mask) & y_mask;
if offs_y == 0 {
offs_x0 += incr_y; // wrap into next tile row
}
}
}
// Enqueue buffer
println!("Enqueue buffer");
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values
parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64
parcel.write_u32(1); // unknown, but always those values
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // sometimes zero
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // Also seen 2
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(1); // fence?
parcel.write_u32(1);
parcel.write_u32(0xa3);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, QUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
println!("{:?}", QueueBufferOutput::from_parcel(&mut parcel_out));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
vevent.wait()?;
vevent.reset()?;
}
Ok(())
}
//static FERRIS : &'static [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
//static FERRIS: &'static [u8; 33061] = include_bytes!("../img/ferris.png");
static FERRIS: &'static [u8; 153718] = include_bytes!("../img/ferris.bmp");
// Graphic buffer stuff
//struct IGraphicBufferProducer(Arc<IHOSBinderDriver>, u32);
//
//impl IGraphicBufferProducer {
// pub fn dequeue_buffer(&self) {
//
// }
//}
//struct Display(Arc<IManagerDisplayService>, u64);
//
//impl Drop for Display {
// fn drop(&mut self) {
// self.0.close_display(self.1);
// }
//}
// TODO: Layer trait?
//struct ManagedLayer(Arc<IManagerDisplayService>, u64);
//
//impl Drop for ManagedLayer {
// fn drop(&mut self) {
// self.0.destroy_managed_layer(self.1);
// }
//}
/// Binder object in a parcel
#[repr(C)]
#[derive(Debug)]
struct FlatBinderObject {
ty: u32,
flags: u32,
inner: usize, // Can either be a void *binder or a u32 handle
cookie: usize
}
impl FlatBinderObject {
fn from_parcel(parcel: &mut ParcelReader) -> FlatBinderObject {
FlatBinderObject {
ty: parcel.read_u32(),
flags: parcel.read_u32(),
inner: parcel.read_u64() as usize,
cookie: parcel.read_u64() as usize
}
}
}
// Returned by igbp_connect
#[repr(C)]
#[derive(Debug)]
struct QueueBufferOutput {
width: u32,
height: u32,
transform_hint: u32,
num_pending_buffers: u32
}
impl QueueBufferOutput {
fn from_parcel(parcel: &mut ParcelReader) -> QueueBufferOutput {
let width = parcel.read_u32();
let height = parcel.read_u32();
let transform_hint = parcel.read_u32();
let num_pending_buffers = parcel.read_u32();
QueueBufferOutput {
width, height, transform_hint, num_pending_buffers
}
}
}
#[repr(C)]
struct GraphicBuffer<'a> {
width: u32,
height: u32,
stride: u32,
format: u32,
usage: u32,
gpu_buffer: &'a GpuBuffer,
index: u32,
offset_gpu_buffer: u32,
}
impl<'a> GraphicBuffer<'a> {
fn write_to_parcel(&self, parcel: &mut OwnedParcel) {
}
}
#[repr(C)]
struct GpuBuffer {
nvmap_handle: u32,
size: usize,
alignment: u32,
kind: u8
}
// nvmap stuff
#[repr(C, align(4096))]
struct BufferMemory([u32; 0x3c0000/4]);
impl std::ops::Deref for BufferMemory {
type Target = [u32];
fn deref(&self) -> &[u32] {
&self.0[..]
}
}
impl std::ops::DerefMut for BufferMemory {
fn deref_mut(&mut self) -> &mut [u32] {
&mut self.0[..]
}
}
const NVMAP_IOC_CREATE: u32 = 0xC0080101;
const NVMAP_IOC_FROM_ID: u32 = 0xC0080103;
const NVMAP_IOC_ALLOC: u32 = 0xC0200104;
const NVMAP_IOC_FREE: u32 = 0xC0180105;
const NVMAP_IOC_PARAM: u32 = 0xC00C0109;
const NVMAP_IOC_GET_ID: u32 = 0xC008010E;
#[repr(C)]
#[derive(Debug)]
struct NvMapIocCreateArgs{
/// In, size of the buffer in bytes
size: u32,
/// Out, handle to use for other operations
handle: u32
}
#[repr(C)]
#[derive(Debug)]
struct NvMapIocAllocArgs {
handle: u32,
heapmask: u32,
/// (0=read-only, 1=read-write)
flags: u32,
align: u32,
kind: u8,
pad: [u8; 7],
addr: u64,
}
// vi stuff. I should reuse some code from rust-binder, instead of rolling my
// own again.
const REQUEST_BUFFER: u32 = 0x1;
const SET_BUFFER_COUNT: u32 = 0x2;
const DEQUEUE_BUFFER: u32 = 0x3;
const DETACH_BUFFER: u32 = 0x4;
const DETACH_NEXT_BUFFER: u32 = 0x5;
const ATTACH_BUFFER: u32 = 0x6;
const QUEUE_BUFFER: u32 = 0x7;
const CANCEL_BUFFER: u32 = 0x8;
const QUERY: u32 = 0x9;
const CONNECT: u32 = 0xA;
const DISCONNECT: u32 = 0xB;
// 0xC might be SET_SIDEBAND_STREAM but I'm not sure
const ALLOCATE_BUFFERS: u32 = 0xD;
const SET_PREALLOCATED_BUFFER: u32 = 0xE;
#[derive(Debug)]
struct OwnedParcel(Vec<u8>);
impl OwnedParcel {
pub fn new() -> OwnedParcel {
OwnedParcel(Vec::new())
}
pub fn write_u32(&mut self, data: u32) {
self.0.write_u32::< | {
return Err(MyError::IoctlError(ret));
} | conditional_block |
main.rs | Find a better way.
let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) };
let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref());
unsafe { std::mem::forget(temporary_process); }
ret
})?;
println!("Open /dev/nvhost-as-gpu");
let (nvasgpu, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvhost-as-gpu"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Open /dev/nvmap");
let (nvmap, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvmap"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Initialize vi");
let vi_m = nn::visrv::sf::IManagerRootService::new()?;
println!("get_display_service");
let disp_svc = vi_m.get_display_service(1)?;
println!("get_relay_service");
let relay_svc = disp_svc.get_relay_service()?;
println!("get_system_display_service");
let system_disp_svc = disp_svc.get_system_display_service()?;
println!("get_manager_display_service");
let manager_disp_svc = disp_svc.get_manager_display_service()?;
println!("Open display");
let display_id = {
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
disp_svc.open_display(display)?
};
println!("Open a layer");
let layer_id = manager_disp_svc.create_managed_layer(1, display_id, 0)?;
let binder_id = {
let mut parcel = RawParcel::default();
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
let _window_size = disp_svc.open_layer(display, layer_id, 0, parcel.as_bytes_mut())?;
let mut reader = parcel.into_parcel_reader();
let fbo = FlatBinderObject::from_parcel(&mut reader);
let binder = fbo.inner as i32;
relay_svc.adjust_refcount(binder, 1, 0)?;
relay_svc.adjust_refcount(binder, 1, 1)?;
binder
};
// Connect to the IGBP. Take a look at the following link for reference.
// https://android.googlesource.com/platform/frameworks/native/+/e2786ea5aec3a12d948feb85ffbb535fc89c0fe6/libs/gui/IGraphicBufferProducer.cpp#297
println!("Connect to the IGBP");
let queue_buffer_output = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(0); // IProducerListener is null because we don't support it in MegatonHammer (nor in libt) yet.
parcel.write_u32(2); // API
parcel.write_u32(0); // ProducerControlledByApp.
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, CONNECT, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut reader = parcel_out.into_parcel_reader();
let qbo = QueueBufferOutput::from_parcel(&mut reader);
if reader.read_u32()!= 0 {
println!("Failed to connect to igbp");
return Ok(());
}
qbo
};
println!("Allocate framebuffers");
let mut mem : Vec<BufferMemory> = Vec::with_capacity(3);
unsafe { mem.set_len(3); }
// Disables caching when talking to the gpu.
unsafe { svc::set_memory_attribute(mem.as_mut_ptr() as _, mem.len() * std::mem::size_of::<BufferMemory>(), 0x8, 0x8).expect("Failed to set memory attribute"); }
let gpu_buffer = {
let mut create = NvMapIocCreateArgs {
size: (mem.len() * std::mem::size_of::<BufferMemory>()) as u32,
handle: 0
};
println!("NVMAP_IOC_CREATE {:?} ({:?})", create, unsafe { std::mem::transmute::<&NvMapIocCreateArgs, &[u8; std::mem::size_of::<NvMapIocCreateArgs>()]>(&create) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_CREATE,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&create as *const NvMapIocCreateArgs as *const u8, std::mem::size_of::<NvMapIocCreateArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut create as *mut NvMapIocCreateArgs as *mut u8, std::mem::size_of::<NvMapIocCreateArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
heapmask: 0,
flags: 0,
align: gpu_buffer.alignment,
kind: gpu_buffer.kind,
pad: [0; 7],
addr: mem.as_mut_ptr() as u64
};
println!("NVMAP_IOC_ALLOC {:?} ({:?})", alloc, unsafe { std::mem::transmute::<&NvMapIocAllocArgs, &[u8; std::mem::size_of::<NvMapIocAllocArgs>()]>(&alloc) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_ALLOC,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&alloc as *const NvMapIocAllocArgs as *const u8, std::mem::size_of::<NvMapIocAllocArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut alloc as *mut NvMapIocAllocArgs as *mut u8, std::mem::size_of::<NvMapIocAllocArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
let mut buffers = Vec::with_capacity(3);
for i in 0..3 {
buffers.push(GraphicBuffer {
width: queue_buffer_output.width,
height: queue_buffer_output.height,
stride: queue_buffer_output.width,
format: 1, // RGBA_8888
usage: 0xb00, // TODO: Wat?
gpu_buffer: &gpu_buffer,
index: i,
offset_gpu_buffer: 0x3c0000 * i
});
}
buffers
};
println!("Tell IGBP about the buffers");
for (i, buf) in buffers.iter().enumerate() {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(i as u32); // slot
parcel.write_u32(1); // Unknown
parcel.write_u32(0x16c); // Flattened GraphicsBuffer length
parcel.write_u32(0); // Unknown
buf.write_to_parcel(&mut parcel);
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, SET_PREALLOCATED_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
}
println!("Set scaling mode");
disp_svc.set_layer_scaling_mode(2, layer_id)?;
println!("Add layer to stack");
for stack in [0x0, 0x2, 0x4, 0x5, 0xA].iter() {
manager_disp_svc.add_to_layer_stack(*stack, layer_id)?;
}
println!("Set Z layer");
system_disp_svc.set_layer_z(layer_id, 2)?;
println!("Loading image from FERRIS");
let image = BMPDecoder::new(Cursor::new(&FERRIS[..]));
println!("Getting frame");
let frame = image.into_frames()?.next().unwrap().into_buffer();
//println!("Resizing FERRIS");
//let frame = image::imageops::resize(&image.into_frames()?.next().unwrap().into_buffer(), 1280, 760, image::FilterType::Lanczos3);
let vevent = unsafe { Event::from_kobject(disp_svc.get_display_vsync_event(display_id)?) };
for _ in 0..60 {
println!("Dequeue buffer");
let slot = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(1); // Pixel format
parcel.write_u32(1280); // width
parcel.write_u32(720); // height
parcel.write_u32(0); // get_frame_timestamp
parcel.write_u32(0xb00); // usage
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, DEQUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
let mut parcel_out = parcel_out.into_parcel_reader();
let slot = parcel_out.read_u32();
// Read fence
parcel_out.0.seek(SeekFrom::Current(44));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
slot
};
// Request buffer if it hasn't been requested already.
println!("Request buffer {}", slot);
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, REQUEST_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
let non_null = parcel_out.read_u32()!= 0;
if non_null {
let len = parcel_out.read_u32();
if len!= 0x16c {
println!("Invalid length: {}", len);
return Ok(())
}
let unk = parcel_out.read_u32();
// TODO: Get graphicbuffer.
parcel_out.0.seek(SeekFrom::Current(0x16c));
}
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
// Blit
println!("Blit");
{
fn pdep(mask: u32, mut value: u32) -> u32 {
let mut out = 0;
for shift in 0..32 {
let bit = 1 << shift;
if mask & bit!= 0 {
if value & 1!= 0 {
out |= bit
}
value >>= 1;
}
}
out
}
fn swizzle_x(v: u32) -> u32 { pdep(!0x7B4, v) }
fn swizzle_y(v: u32) -> u32 { pdep(0x7B4, v) }
let x0 = 0;
let y0 = 0;
let mut offs_x0 = swizzle_x(x0);
let mut offs_y = swizzle_y(y0);
let x_mask = swizzle_x(!0);
let y_mask = swizzle_y(!0);
let incr_y = swizzle_x(128 * 10);
let tile_height = 128;
offs_x0 += incr_y * (y0 / tile_height);
// TODO: Add clipping.
for y in 0..frame.height() {
let mut offs_x = offs_x0;
for x in 0..frame.width() {
let pixel = frame.get_pixel(x, y);
mem[slot as usize][offs_y as usize + offs_x as usize] = LE::read_u32(pixel.channels());
offs_x = offs_x.wrapping_sub(x_mask) & x_mask;
}
offs_y = offs_y.wrapping_sub(y_mask) & y_mask;
if offs_y == 0 {
offs_x0 += incr_y; // wrap into next tile row
}
}
}
// Enqueue buffer
println!("Enqueue buffer");
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values
parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64
parcel.write_u32(1); // unknown, but always those values
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // sometimes zero
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // Also seen 2
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(1); // fence?
parcel.write_u32(1);
parcel.write_u32(0xa3);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, QUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
println!("{:?}", QueueBufferOutput::from_parcel(&mut parcel_out));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
vevent.wait()?;
vevent.reset()?;
}
Ok(())
}
//static FERRIS : &'static [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
//static FERRIS: &'static [u8; 33061] = include_bytes!("../img/ferris.png");
static FERRIS: &'static [u8; 153718] = include_bytes!("../img/ferris.bmp");
// Graphic buffer stuff
//struct IGraphicBufferProducer(Arc<IHOSBinderDriver>, u32);
//
//impl IGraphicBufferProducer {
// pub fn dequeue_buffer(&self) {
//
// }
//}
//struct Display(Arc<IManagerDisplayService>, u64);
//
//impl Drop for Display {
// fn drop(&mut self) {
// self.0.close_display(self.1);
// }
//}
// TODO: Layer trait?
//struct ManagedLayer(Arc<IManagerDisplayService>, u64);
//
//impl Drop for ManagedLayer {
// fn drop(&mut self) {
// self.0.destroy_managed_layer(self.1);
// }
//}
/// Binder object in a parcel
#[repr(C)]
#[derive(Debug)]
struct FlatBinderObject {
ty: u32,
flags: u32,
inner: usize, // Can either be a void *binder or a u32 handle
cookie: usize
}
impl FlatBinderObject {
fn from_parcel(parcel: &mut ParcelReader) -> FlatBinderObject {
FlatBinderObject {
ty: parcel.read_u32(),
flags: parcel.read_u32(),
inner: parcel.read_u64() as usize,
cookie: parcel.read_u64() as usize
}
}
}
// Returned by igbp_connect
#[repr(C)]
#[derive(Debug)]
struct QueueBufferOutput {
width: u32,
height: u32,
transform_hint: u32,
num_pending_buffers: u32
}
impl QueueBufferOutput {
fn from_parcel(parcel: &mut ParcelReader) -> QueueBufferOutput {
let width = parcel.read_u32();
let height = parcel.read_u32();
let transform_hint = parcel.read_u32();
let num_pending_buffers = parcel.read_u32();
QueueBufferOutput {
width, height, transform_hint, num_pending_buffers
}
}
}
#[repr(C)]
struct GraphicBuffer<'a> {
width: u32,
height: u32,
stride: u32,
format: u32,
usage: u32,
gpu_buffer: &'a GpuBuffer,
index: u32,
offset_gpu_buffer: u32,
}
impl<'a> GraphicBuffer<'a> {
fn write_to_parcel(&self, parcel: &mut OwnedParcel) {
}
}
#[repr(C)]
struct GpuBuffer {
nvmap_handle: u32,
size: usize,
alignment: u32,
kind: u8
}
// nvmap stuff
#[repr(C, align(4096))]
struct BufferMemory([u32; 0x3c0000/4]);
impl std::ops::Deref for BufferMemory {
type Target = [u32];
fn | (&self) -> &[u32] {
&self.0[..]
}
}
impl std::ops::DerefMut for BufferMemory {
fn deref_mut(&mut self) -> &mut [u32] {
&mut self.0[..]
}
}
const NVMAP_IOC_CREATE: u32 = 0xC0080101;
const NVMAP_IOC_FROM_ID: u32 = 0xC0080103;
const NVMAP_IOC_ALLOC: u32 = 0xC0200104;
const NVMAP_IOC_FREE: u32 = 0xC0180105;
const NVMAP_IOC_PARAM: u32 = 0xC00C0109;
const NVMAP_IOC_GET_ID: u32 = 0xC008010E;
#[repr(C)]
#[derive(Debug)]
struct NvMapIocCreateArgs{
/// In, size of the buffer in bytes
size: u32,
/// Out, handle to use for other operations
handle: u32
}
#[repr(C)]
#[derive(Debug)]
struct NvMapIocAllocArgs {
handle: u32,
heapmask: u32,
/// (0=read-only, 1=read-write)
flags: u32,
align: u32,
kind: u8,
pad: [u8; 7],
addr: u64,
}
// vi stuff. I should reuse some code from rust-binder, instead of rolling my
// own again.
const REQUEST_BUFFER: u32 = 0x1;
const SET_BUFFER_COUNT: u32 = 0x2;
const DEQUEUE_BUFFER: u32 = 0x3;
const DETACH_BUFFER: u32 = 0x4;
const DETACH_NEXT_BUFFER: u32 = 0x5;
const ATTACH_BUFFER: u32 = 0x6;
const QUEUE_BUFFER: u32 = 0x7;
const CANCEL_BUFFER: u32 = 0x8;
const QUERY: u32 = 0x9;
const CONNECT: u32 = 0xA;
const DISCONNECT: u32 = 0xB;
// 0xC might be SET_SIDEBAND_STREAM but I'm not sure
const ALLOCATE_BUFFERS: u32 = 0xD;
const SET_PREALLOCATED_BUFFER: u32 = 0xE;
#[derive(Debug)]
struct OwnedParcel(Vec<u8>);
impl OwnedParcel {
pub fn new() -> OwnedParcel {
OwnedParcel(Vec::new())
}
pub fn write_u32(&mut self, data: u32) {
self.0.write_u32::< | deref | identifier_name |
main.rs | : Find a better way.
let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) };
let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref());
unsafe { std::mem::forget(temporary_process); }
ret
})?;
println!("Open /dev/nvhost-as-gpu");
let (nvasgpu, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvhost-as-gpu"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Open /dev/nvmap");
let (nvmap, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvmap"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Initialize vi");
let vi_m = nn::visrv::sf::IManagerRootService::new()?;
println!("get_display_service");
let disp_svc = vi_m.get_display_service(1)?;
println!("get_relay_service");
let relay_svc = disp_svc.get_relay_service()?;
println!("get_system_display_service");
let system_disp_svc = disp_svc.get_system_display_service()?;
println!("get_manager_display_service");
let manager_disp_svc = disp_svc.get_manager_display_service()?;
println!("Open display");
let display_id = {
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
disp_svc.open_display(display)?
};
println!("Open a layer");
let layer_id = manager_disp_svc.create_managed_layer(1, display_id, 0)?;
let binder_id = {
let mut parcel = RawParcel::default();
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
let _window_size = disp_svc.open_layer(display, layer_id, 0, parcel.as_bytes_mut())?;
let mut reader = parcel.into_parcel_reader();
let fbo = FlatBinderObject::from_parcel(&mut reader);
let binder = fbo.inner as i32;
relay_svc.adjust_refcount(binder, 1, 0)?;
relay_svc.adjust_refcount(binder, 1, 1)?;
binder
};
// Connect to the IGBP. Take a look at the following link for reference.
// https://android.googlesource.com/platform/frameworks/native/+/e2786ea5aec3a12d948feb85ffbb535fc89c0fe6/libs/gui/IGraphicBufferProducer.cpp#297
println!("Connect to the IGBP");
let queue_buffer_output = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(0); // IProducerListener is null because we don't support it in MegatonHammer (nor in libt) yet.
parcel.write_u32(2); // API
parcel.write_u32(0); // ProducerControlledByApp.
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, CONNECT, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut reader = parcel_out.into_parcel_reader();
let qbo = QueueBufferOutput::from_parcel(&mut reader);
if reader.read_u32()!= 0 {
println!("Failed to connect to igbp");
return Ok(());
}
qbo
};
println!("Allocate framebuffers");
let mut mem : Vec<BufferMemory> = Vec::with_capacity(3);
unsafe { mem.set_len(3); }
// Disables caching when talking to the gpu.
unsafe { svc::set_memory_attribute(mem.as_mut_ptr() as _, mem.len() * std::mem::size_of::<BufferMemory>(), 0x8, 0x8).expect("Failed to set memory attribute"); }
let gpu_buffer = {
let mut create = NvMapIocCreateArgs {
size: (mem.len() * std::mem::size_of::<BufferMemory>()) as u32,
handle: 0
};
println!("NVMAP_IOC_CREATE {:?} ({:?})", create, unsafe { std::mem::transmute::<&NvMapIocCreateArgs, &[u8; std::mem::size_of::<NvMapIocCreateArgs>()]>(&create) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_CREATE,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&create as *const NvMapIocCreateArgs as *const u8, std::mem::size_of::<NvMapIocCreateArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut create as *mut NvMapIocCreateArgs as *mut u8, std::mem::size_of::<NvMapIocCreateArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
heapmask: 0,
flags: 0,
align: gpu_buffer.alignment,
kind: gpu_buffer.kind,
pad: [0; 7],
addr: mem.as_mut_ptr() as u64
};
println!("NVMAP_IOC_ALLOC {:?} ({:?})", alloc, unsafe { std::mem::transmute::<&NvMapIocAllocArgs, &[u8; std::mem::size_of::<NvMapIocAllocArgs>()]>(&alloc) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_ALLOC,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&alloc as *const NvMapIocAllocArgs as *const u8, std::mem::size_of::<NvMapIocAllocArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut alloc as *mut NvMapIocAllocArgs as *mut u8, std::mem::size_of::<NvMapIocAllocArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
let mut buffers = Vec::with_capacity(3);
for i in 0..3 {
buffers.push(GraphicBuffer {
width: queue_buffer_output.width,
height: queue_buffer_output.height,
stride: queue_buffer_output.width,
format: 1, // RGBA_8888
usage: 0xb00, // TODO: Wat?
gpu_buffer: &gpu_buffer,
index: i,
offset_gpu_buffer: 0x3c0000 * i
});
}
buffers
};
println!("Tell IGBP about the buffers");
for (i, buf) in buffers.iter().enumerate() {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(i as u32); // slot
parcel.write_u32(1); // Unknown
parcel.write_u32(0x16c); // Flattened GraphicsBuffer length
parcel.write_u32(0); // Unknown
buf.write_to_parcel(&mut parcel);
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, SET_PREALLOCATED_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
}
println!("Set scaling mode");
disp_svc.set_layer_scaling_mode(2, layer_id)?;
println!("Add layer to stack");
for stack in [0x0, 0x2, 0x4, 0x5, 0xA].iter() {
manager_disp_svc.add_to_layer_stack(*stack, layer_id)?;
}
println!("Set Z layer");
system_disp_svc.set_layer_z(layer_id, 2)?;
println!("Loading image from FERRIS");
let image = BMPDecoder::new(Cursor::new(&FERRIS[..]));
println!("Getting frame");
let frame = image.into_frames()?.next().unwrap().into_buffer();
//println!("Resizing FERRIS");
//let frame = image::imageops::resize(&image.into_frames()?.next().unwrap().into_buffer(), 1280, 760, image::FilterType::Lanczos3);
let vevent = unsafe { Event::from_kobject(disp_svc.get_display_vsync_event(display_id)?) };
for _ in 0..60 {
println!("Dequeue buffer");
let slot = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(1); // Pixel format
parcel.write_u32(1280); // width
parcel.write_u32(720); // height
parcel.write_u32(0); // get_frame_timestamp
parcel.write_u32(0xb00); // usage
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, DEQUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
let mut parcel_out = parcel_out.into_parcel_reader();
let slot = parcel_out.read_u32();
// Read fence
parcel_out.0.seek(SeekFrom::Current(44));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
slot
};
// Request buffer if it hasn't been requested already.
println!("Request buffer {}", slot);
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, REQUEST_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
let non_null = parcel_out.read_u32()!= 0;
if non_null {
let len = parcel_out.read_u32();
if len!= 0x16c {
println!("Invalid length: {}", len);
return Ok(())
}
let unk = parcel_out.read_u32();
// TODO: Get graphicbuffer.
parcel_out.0.seek(SeekFrom::Current(0x16c));
}
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
// Blit
println!("Blit");
{
fn pdep(mask: u32, mut value: u32) -> u32 {
let mut out = 0;
for shift in 0..32 {
let bit = 1 << shift;
if mask & bit!= 0 {
if value & 1!= 0 {
out |= bit
}
value >>= 1;
}
}
out
}
fn swizzle_x(v: u32) -> u32 { pdep(!0x7B4, v) }
fn swizzle_y(v: u32) -> u32 { pdep(0x7B4, v) }
let x0 = 0;
let y0 = 0;
let mut offs_x0 = swizzle_x(x0);
let mut offs_y = swizzle_y(y0);
let x_mask = swizzle_x(!0);
let y_mask = swizzle_y(!0);
let incr_y = swizzle_x(128 * 10);
let tile_height = 128;
offs_x0 += incr_y * (y0 / tile_height);
// TODO: Add clipping.
for y in 0..frame.height() {
let mut offs_x = offs_x0;
for x in 0..frame.width() {
let pixel = frame.get_pixel(x, y);
mem[slot as usize][offs_y as usize + offs_x as usize] = LE::read_u32(pixel.channels());
offs_x = offs_x.wrapping_sub(x_mask) & x_mask;
}
offs_y = offs_y.wrapping_sub(y_mask) & y_mask;
if offs_y == 0 {
offs_x0 += incr_y; // wrap into next tile row
}
}
}
// Enqueue buffer
println!("Enqueue buffer");
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot | parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values
parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64
parcel.write_u32(1); // unknown, but always those values
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // sometimes zero
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // Also seen 2
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(1); // fence?
parcel.write_u32(1);
parcel.write_u32(0xa3);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, QUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
println!("{:?}", QueueBufferOutput::from_parcel(&mut parcel_out));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
vevent.wait()?;
vevent.reset()?;
}
Ok(())
}
//static FERRIS : &'static [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
//static FERRIS: &'static [u8; 33061] = include_bytes!("../img/ferris.png");
static FERRIS: &'static [u8; 153718] = include_bytes!("../img/ferris.bmp");
// Graphic buffer stuff
//struct IGraphicBufferProducer(Arc<IHOSBinderDriver>, u32);
//
//impl IGraphicBufferProducer {
// pub fn dequeue_buffer(&self) {
//
// }
//}
//struct Display(Arc<IManagerDisplayService>, u64);
//
//impl Drop for Display {
// fn drop(&mut self) {
// self.0.close_display(self.1);
// }
//}
// TODO: Layer trait?
//struct ManagedLayer(Arc<IManagerDisplayService>, u64);
//
//impl Drop for ManagedLayer {
// fn drop(&mut self) {
// self.0.destroy_managed_layer(self.1);
// }
//}
/// Binder object in a parcel
#[repr(C)]
#[derive(Debug)]
struct FlatBinderObject {
ty: u32,
flags: u32,
inner: usize, // Can either be a void *binder or a u32 handle
cookie: usize
}
impl FlatBinderObject {
fn from_parcel(parcel: &mut ParcelReader) -> FlatBinderObject {
FlatBinderObject {
ty: parcel.read_u32(),
flags: parcel.read_u32(),
inner: parcel.read_u64() as usize,
cookie: parcel.read_u64() as usize
}
}
}
// Returned by igbp_connect
#[repr(C)]
#[derive(Debug)]
struct QueueBufferOutput {
width: u32,
height: u32,
transform_hint: u32,
num_pending_buffers: u32
}
impl QueueBufferOutput {
fn from_parcel(parcel: &mut ParcelReader) -> QueueBufferOutput {
let width = parcel.read_u32();
let height = parcel.read_u32();
let transform_hint = parcel.read_u32();
let num_pending_buffers = parcel.read_u32();
QueueBufferOutput {
width, height, transform_hint, num_pending_buffers
}
}
}
#[repr(C)]
struct GraphicBuffer<'a> {
width: u32,
height: u32,
stride: u32,
format: u32,
usage: u32,
gpu_buffer: &'a GpuBuffer,
index: u32,
offset_gpu_buffer: u32,
}
impl<'a> GraphicBuffer<'a> {
fn write_to_parcel(&self, parcel: &mut OwnedParcel) {
}
}
#[repr(C)]
struct GpuBuffer {
nvmap_handle: u32,
size: usize,
alignment: u32,
kind: u8
}
// nvmap stuff
#[repr(C, align(4096))]
struct BufferMemory([u32; 0x3c0000/4]);
impl std::ops::Deref for BufferMemory {
type Target = [u32];
fn deref(&self) -> &[u32] {
&self.0[..]
}
}
impl std::ops::DerefMut for BufferMemory {
fn deref_mut(&mut self) -> &mut [u32] {
&mut self.0[..]
}
}
const NVMAP_IOC_CREATE: u32 = 0xC0080101;
const NVMAP_IOC_FROM_ID: u32 = 0xC0080103;
const NVMAP_IOC_ALLOC: u32 = 0xC0200104;
const NVMAP_IOC_FREE: u32 = 0xC0180105;
const NVMAP_IOC_PARAM: u32 = 0xC00C0109;
const NVMAP_IOC_GET_ID: u32 = 0xC008010E;
#[repr(C)]
#[derive(Debug)]
struct NvMapIocCreateArgs{
/// In, size of the buffer in bytes
size: u32,
/// Out, handle to use for other operations
handle: u32
}
#[repr(C)]
#[derive(Debug)]
struct NvMapIocAllocArgs {
handle: u32,
heapmask: u32,
/// (0=read-only, 1=read-write)
flags: u32,
align: u32,
kind: u8,
pad: [u8; 7],
addr: u64,
}
// vi stuff. I should reuse some code from rust-binder, instead of rolling my
// own again.
const REQUEST_BUFFER: u32 = 0x1;
const SET_BUFFER_COUNT: u32 = 0x2;
const DEQUEUE_BUFFER: u32 = 0x3;
const DETACH_BUFFER: u32 = 0x4;
const DETACH_NEXT_BUFFER: u32 = 0x5;
const ATTACH_BUFFER: u32 = 0x6;
const QUEUE_BUFFER: u32 = 0x7;
const CANCEL_BUFFER: u32 = 0x8;
const QUERY: u32 = 0x9;
const CONNECT: u32 = 0xA;
const DISCONNECT: u32 = 0xB;
// 0xC might be SET_SIDEBAND_STREAM but I'm not sure
const ALLOCATE_BUFFERS: u32 = 0xD;
const SET_PREALLOCATED_BUFFER: u32 = 0xE;
#[derive(Debug)]
struct OwnedParcel(Vec<u8>);
impl OwnedParcel {
pub fn new() -> OwnedParcel {
OwnedParcel(Vec::new())
}
pub fn write_u32(&mut self, data: u32) {
self.0.write_u32::<LE | random_line_split |
|
main.rs |
}
impl From<megaton_hammer::error::Error> for MyError {
fn from(err: megaton_hammer::error::Error) -> MyError {
MyError::MegatonError(err)
}
}
fn main() -> std::result::Result<(), MyError> {
// Let's get ferris to show up on my switch.
println!("Initialize NV");
let nvdrv = nns::nvdrv::INvDrvServices::new_nvdrv_a(|cb| {
println!("Create transfer memory");
let transfer_mem = TransferMemory::new(0x30000)?;
// TODO: Find a better way.
let temporary_process = unsafe { KObject::new(megaton_hammer::kernel::svc::CURRENT_PROCESS) };
let ret = cb(0x30000, &temporary_process, transfer_mem.as_ref());
unsafe { std::mem::forget(temporary_process); }
ret
})?;
println!("Open /dev/nvhost-as-gpu");
let (nvasgpu, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvhost-as-gpu"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Open /dev/nvmap");
let (nvmap, err) = nvdrv.open(u8_slice_to_i8_slice(&b"/dev/nvmap"[..]))?;
if err!= 0 {
panic!("Failed to open");
}
println!("Initialize vi");
let vi_m = nn::visrv::sf::IManagerRootService::new()?;
println!("get_display_service");
let disp_svc = vi_m.get_display_service(1)?;
println!("get_relay_service");
let relay_svc = disp_svc.get_relay_service()?;
println!("get_system_display_service");
let system_disp_svc = disp_svc.get_system_display_service()?;
println!("get_manager_display_service");
let manager_disp_svc = disp_svc.get_manager_display_service()?;
println!("Open display");
let display_id = {
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
disp_svc.open_display(display)?
};
println!("Open a layer");
let layer_id = manager_disp_svc.create_managed_layer(1, display_id, 0)?;
let binder_id = {
let mut parcel = RawParcel::default();
let mut display = [0u8; 64];
display[..b"Default".len()].copy_from_slice(b"Default");
let _window_size = disp_svc.open_layer(display, layer_id, 0, parcel.as_bytes_mut())?;
let mut reader = parcel.into_parcel_reader();
let fbo = FlatBinderObject::from_parcel(&mut reader);
let binder = fbo.inner as i32;
relay_svc.adjust_refcount(binder, 1, 0)?;
relay_svc.adjust_refcount(binder, 1, 1)?;
binder
};
// Connect to the IGBP. Take a look at the following link for reference.
// https://android.googlesource.com/platform/frameworks/native/+/e2786ea5aec3a12d948feb85ffbb535fc89c0fe6/libs/gui/IGraphicBufferProducer.cpp#297
println!("Connect to the IGBP");
let queue_buffer_output = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(0); // IProducerListener is null because we don't support it in MegatonHammer (nor in libt) yet.
parcel.write_u32(2); // API
parcel.write_u32(0); // ProducerControlledByApp.
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, CONNECT, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut reader = parcel_out.into_parcel_reader();
let qbo = QueueBufferOutput::from_parcel(&mut reader);
if reader.read_u32()!= 0 {
println!("Failed to connect to igbp");
return Ok(());
}
qbo
};
println!("Allocate framebuffers");
let mut mem : Vec<BufferMemory> = Vec::with_capacity(3);
unsafe { mem.set_len(3); }
// Disables caching when talking to the gpu.
unsafe { svc::set_memory_attribute(mem.as_mut_ptr() as _, mem.len() * std::mem::size_of::<BufferMemory>(), 0x8, 0x8).expect("Failed to set memory attribute"); }
let gpu_buffer = {
let mut create = NvMapIocCreateArgs {
size: (mem.len() * std::mem::size_of::<BufferMemory>()) as u32,
handle: 0
};
println!("NVMAP_IOC_CREATE {:?} ({:?})", create, unsafe { std::mem::transmute::<&NvMapIocCreateArgs, &[u8; std::mem::size_of::<NvMapIocCreateArgs>()]>(&create) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_CREATE,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&create as *const NvMapIocCreateArgs as *const u8, std::mem::size_of::<NvMapIocCreateArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut create as *mut NvMapIocCreateArgs as *mut u8, std::mem::size_of::<NvMapIocCreateArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
GpuBuffer {
nvmap_handle: create.handle,
size: mem.len() * std::mem::size_of::<BufferMemory>(),
alignment: 0x1000,
kind: 0
}
};
let buffers = {
let mut alloc = NvMapIocAllocArgs {
handle: gpu_buffer.nvmap_handle,
heapmask: 0,
flags: 0,
align: gpu_buffer.alignment,
kind: gpu_buffer.kind,
pad: [0; 7],
addr: mem.as_mut_ptr() as u64
};
println!("NVMAP_IOC_ALLOC {:?} ({:?})", alloc, unsafe { std::mem::transmute::<&NvMapIocAllocArgs, &[u8; std::mem::size_of::<NvMapIocAllocArgs>()]>(&alloc) });
let ret = nvdrv.ioctl(nvmap, NVMAP_IOC_ALLOC,
// TODO: This is unsafe. And illegal. Rust assumes aliasing
// doesn't happen with references, which is exactly what we're
// doing. In theory, because we never *read* the content of
// those, I believe this is, erm, "mostly OK"? But I should
// find a better way to deal with it.
unsafe { std::slice::from_raw_parts(&alloc as *const NvMapIocAllocArgs as *const u8, std::mem::size_of::<NvMapIocAllocArgs>()) },
unsafe { std::slice::from_raw_parts_mut(&mut alloc as *mut NvMapIocAllocArgs as *mut u8, std::mem::size_of::<NvMapIocAllocArgs>()) })?;
if ret!= 0 {
return Err(MyError::IoctlError(ret));
}
let mut buffers = Vec::with_capacity(3);
for i in 0..3 {
buffers.push(GraphicBuffer {
width: queue_buffer_output.width,
height: queue_buffer_output.height,
stride: queue_buffer_output.width,
format: 1, // RGBA_8888
usage: 0xb00, // TODO: Wat?
gpu_buffer: &gpu_buffer,
index: i,
offset_gpu_buffer: 0x3c0000 * i
});
}
buffers
};
println!("Tell IGBP about the buffers");
for (i, buf) in buffers.iter().enumerate() {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(i as u32); // slot
parcel.write_u32(1); // Unknown
parcel.write_u32(0x16c); // Flattened GraphicsBuffer length
parcel.write_u32(0); // Unknown
buf.write_to_parcel(&mut parcel);
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, SET_PREALLOCATED_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
}
println!("Set scaling mode");
disp_svc.set_layer_scaling_mode(2, layer_id)?;
println!("Add layer to stack");
for stack in [0x0, 0x2, 0x4, 0x5, 0xA].iter() {
manager_disp_svc.add_to_layer_stack(*stack, layer_id)?;
}
println!("Set Z layer");
system_disp_svc.set_layer_z(layer_id, 2)?;
println!("Loading image from FERRIS");
let image = BMPDecoder::new(Cursor::new(&FERRIS[..]));
println!("Getting frame");
let frame = image.into_frames()?.next().unwrap().into_buffer();
//println!("Resizing FERRIS");
//let frame = image::imageops::resize(&image.into_frames()?.next().unwrap().into_buffer(), 1280, 760, image::FilterType::Lanczos3);
let vevent = unsafe { Event::from_kobject(disp_svc.get_display_vsync_event(display_id)?) };
for _ in 0..60 {
println!("Dequeue buffer");
let slot = {
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(1); // Pixel format
parcel.write_u32(1280); // width
parcel.write_u32(720); // height
parcel.write_u32(0); // get_frame_timestamp
parcel.write_u32(0xb00); // usage
let mut parcel_out = RawParcel::default();
relay_svc.transact_parcel(binder_id as i32, DEQUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
println!("{:?}", parcel_out);
let mut parcel_out = parcel_out.into_parcel_reader();
let slot = parcel_out.read_u32();
// Read fence
parcel_out.0.seek(SeekFrom::Current(44));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
slot
};
// Request buffer if it hasn't been requested already.
println!("Request buffer {}", slot);
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, REQUEST_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
let non_null = parcel_out.read_u32()!= 0;
if non_null {
let len = parcel_out.read_u32();
if len!= 0x16c {
println!("Invalid length: {}", len);
return Ok(())
}
let unk = parcel_out.read_u32();
// TODO: Get graphicbuffer.
parcel_out.0.seek(SeekFrom::Current(0x16c));
}
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
// Blit
println!("Blit");
{
fn pdep(mask: u32, mut value: u32) -> u32 {
let mut out = 0;
for shift in 0..32 {
let bit = 1 << shift;
if mask & bit!= 0 {
if value & 1!= 0 {
out |= bit
}
value >>= 1;
}
}
out
}
fn swizzle_x(v: u32) -> u32 { pdep(!0x7B4, v) }
fn swizzle_y(v: u32) -> u32 { pdep(0x7B4, v) }
let x0 = 0;
let y0 = 0;
let mut offs_x0 = swizzle_x(x0);
let mut offs_y = swizzle_y(y0);
let x_mask = swizzle_x(!0);
let y_mask = swizzle_y(!0);
let incr_y = swizzle_x(128 * 10);
let tile_height = 128;
offs_x0 += incr_y * (y0 / tile_height);
// TODO: Add clipping.
for y in 0..frame.height() {
let mut offs_x = offs_x0;
for x in 0..frame.width() {
let pixel = frame.get_pixel(x, y);
mem[slot as usize][offs_y as usize + offs_x as usize] = LE::read_u32(pixel.channels());
offs_x = offs_x.wrapping_sub(x_mask) & x_mask;
}
offs_y = offs_y.wrapping_sub(y_mask) & y_mask;
if offs_y == 0 {
offs_x0 += incr_y; // wrap into next tile row
}
}
}
// Enqueue buffer
println!("Enqueue buffer");
{
let mut parcel = OwnedParcel::new();
parcel.write_interface_token("android.gui.IGraphicBufferProducer");
parcel.write_u32(slot); // Slot
parcel.write_u32(0x54); parcel.write_u32(0); // unknown, but always those values
parcel.write_u32(0x588bbba9); parcel.write_u32(0); // Timestamp, u64
parcel.write_u32(1); // unknown, but always those values
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // sometimes zero
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(0); // Also seen 2
parcel.write_u32(0);
parcel.write_u32(0);
parcel.write_u32(1); // fence?
parcel.write_u32(1);
parcel.write_u32(0xa3);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
parcel.write_u32(-1i32 as u32);
parcel.write_u32(0);
let mut parcel_out = RawParcel::default();
let res = relay_svc.transact_parcel(binder_id as i32, QUEUE_BUFFER, 0, parcel.build().as_bytes(), parcel_out.as_bytes_mut())?;
let mut parcel_out = parcel_out.into_parcel_reader();
println!("{:?}", QueueBufferOutput::from_parcel(&mut parcel_out));
let status = parcel_out.read_u32();
if status!= 0 {
println!("WTF: {}", status);
return Err(MyError::ParcelError(status));
}
}
vevent.wait()?;
vevent.reset()?;
}
Ok(())
}
//static FERRIS : &'static [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
//static FERRIS: &'static [u8; 33061] = include_bytes!("../img/ferris.png");
static FERRIS: &'static [u8; 153718] = include_bytes!("../img/ferris.bmp");
// Graphic buffer stuff
//struct IGraphicBufferProducer(Arc<IHOSBinderDriver>, u32);
//
//impl IGraphicBufferProducer {
// pub fn dequeue_buffer(&self) {
//
// }
//}
//struct Display(Arc<IManagerDisplayService>, u64);
//
//impl Drop for Display {
// fn drop(&mut self) {
// self.0.close_display(self.1);
// }
//}
// TODO: Layer trait?
//struct ManagedLayer(Arc<IManagerDisplayService>, u64);
//
//impl Drop for ManagedLayer {
// fn drop(&mut self) {
// self.0.destroy_managed_layer(self.1);
// }
//}
/// Binder object in a parcel
#[repr(C)]
#[derive(Debug)]
struct FlatBinderObject {
ty: u32,
flags: u32,
inner: usize, // Can either be a void *binder or a u32 handle
cookie: usize
}
impl FlatBinderObject {
fn from_parcel(parcel: &mut ParcelReader) -> FlatBinderObject {
FlatBinderObject {
ty: parcel.read_u32(),
flags: parcel.read_u32(),
inner: parcel.read_u64() as usize,
cookie: parcel.read_u64() as usize
}
}
}
// Returned by igbp_connect
#[repr(C)]
#[derive(Debug)]
struct QueueBufferOutput {
width: u32,
height: u32,
transform_hint: u32,
num_pending_buffers: u32
}
impl QueueBufferOutput {
fn from_parcel(parcel: &mut ParcelReader) -> QueueBufferOutput {
let width = parcel.read_u32();
let height = parcel.read_u32();
let transform_hint = parcel.read_u32();
let num_pending_buffers = parcel.read_u32();
QueueBufferOutput {
width, height, transform_hint, num_pending_buffers
}
}
}
#[repr(C)]
struct GraphicBuffer<'a> {
width: u32,
height: u32,
stride: u32,
format: u32,
usage: u32,
gpu_buffer: &'a GpuBuffer,
index: u32,
offset_gpu_buffer: u32,
}
impl<'a> GraphicBuffer<'a> {
fn write_to_parcel(&self, parcel: &mut OwnedParcel) {
}
}
#[repr(C)]
struct GpuBuffer {
nvmap_handle: u32,
size: usize,
alignment: u32,
kind: u8
}
// nvmap stuff
#[repr(C, align(4096))]
struct BufferMemory([u32; 0x3c0000/4]);
impl std::ops::Deref for BufferMemory {
type Target = [u32];
fn deref(&self) -> &[u32] {
&self.0[..]
}
}
impl std::ops::DerefMut for BufferMemory {
fn deref_mut(&mut self) -> &mut [u32] {
&mut self.0[..]
}
}
const NVMAP_IOC_CREATE: u32 = 0xC0080101;
const NVMAP_IOC_FROM_ID: u32 = 0xC0080103;
const NVMAP_IOC_ALLOC: u32 = 0xC0200104;
const NVMAP_IOC_FREE: u32 = 0xC0180105;
const NVMAP_IOC_PARAM: u32 = 0xC00C0109;
const NVMAP_IOC_GET_ID: u32 = 0xC008010E;
#[repr(C)]
#[derive(Debug)]
struct NvMapIocCreateArgs{
/// In, size of the buffer in bytes
size: u32,
/// Out, handle to use for other operations
handle: u32
}
#[repr(C)]
#[derive(Debug)]
struct NvMapIocAllocArgs {
handle: u32,
heapmask: u32,
/// (0=read-only, 1=read-write)
flags: u32,
align: u32,
kind: u8,
pad: [u8; 7],
addr: u64,
}
// vi stuff. I should reuse some code from rust-binder, instead of rolling my
// own again.
const REQUEST_BUFFER: u32 = 0x1;
const SET_BUFFER_COUNT: u32 = 0x2;
const DEQUEUE_BUFFER: u32 = 0x3;
const DETACH_BUFFER: u32 = 0x4;
const DETACH_NEXT_BUFFER: u32 = 0x5;
const ATTACH_ | {
MyError::ImageError(err)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.